@unbrained/pm-cli 2026.9.6 → 2026.9.8
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/.agents/skills/pm-developer/SKILL.md +12 -4
- package/.agents/skills/pm-developer/references/MULTI_AGENT_MERGE.md +19 -10
- package/.agents/skills/pm-extensions/SKILL.md +6 -0
- package/.agents/skills/pm-sdk/SKILL.md +11 -2
- package/.agents/skills/pm-user/SKILL.md +5 -0
- package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +95 -0
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +218 -182
- package/dist/cli/after-command-context-usage.js +1 -48
- package/dist/cli/argv-utils.js +1 -40
- package/dist/cli/bootstrap-args.js +1 -9
- package/dist/cli/bundle-integrity.js +2 -110
- package/dist/cli/commander-usage.js +11 -771
- package/dist/cli/commands/activity.js +1 -9
- package/dist/cli/commands/aggregate.js +1 -5
- package/dist/cli/commands/append.js +1 -5
- package/dist/cli/commands/claim.js +1 -5
- package/dist/cli/commands/close-many.js +1 -5
- package/dist/cli/commands/close.js +1 -9
- package/dist/cli/commands/comments.js +1 -5
- package/dist/cli/commands/config.js +1 -9
- package/dist/cli/commands/context.js +1 -9
- package/dist/cli/commands/contracts.js +1 -5
- package/dist/cli/commands/copy.js +1 -9
- package/dist/cli/commands/create.js +1 -9
- package/dist/cli/commands/delete.js +1 -9
- package/dist/cli/commands/deps.js +1 -9
- package/dist/cli/commands/docs.js +1 -9
- package/dist/cli/commands/duplicates.js +1 -9
- package/dist/cli/commands/eval.js +1 -9
- package/dist/cli/commands/extension/describe.js +1 -5
- package/dist/cli/commands/extension/scaffold.js +1 -5
- package/dist/cli/commands/extension/shared.js +1 -5
- package/dist/cli/commands/extension.js +1 -9
- package/dist/cli/commands/files.js +1 -9
- package/dist/cli/commands/focus.js +1 -9
- package/dist/cli/commands/gc.js +1 -9
- package/dist/cli/commands/get.js +1 -9
- package/dist/cli/commands/graph.js +1 -10
- package/dist/cli/commands/health.js +1 -9
- package/dist/cli/commands/history-compact.js +1 -10
- package/dist/cli/commands/history-redact.js +1 -11
- package/dist/cli/commands/history-repair.js +1 -10
- package/dist/cli/commands/history.js +1 -5
- package/dist/cli/commands/index.js +1 -58
- package/dist/cli/commands/init-agent-guidance.js +1 -9
- package/dist/cli/commands/init.js +1 -9
- package/dist/cli/commands/learnings.js +1 -5
- package/dist/cli/commands/lifecycle-transitions.js +1 -5
- package/dist/cli/commands/list.js +1 -9
- package/dist/cli/commands/merge.js +1 -11
- package/dist/cli/commands/next.js +1 -9
- package/dist/cli/commands/notes.js +1 -5
- package/dist/cli/commands/plan.js +1 -9
- package/dist/cli/commands/profile.js +1 -9
- package/dist/cli/commands/restore.js +1 -9
- package/dist/cli/commands/scheduling-shortcuts.js +1 -9
- package/dist/cli/commands/schema.js +1 -10
- package/dist/cli/commands/search.js +1 -9
- package/dist/cli/commands/stats.js +1 -9
- package/dist/cli/commands/telemetry.js +1 -9
- package/dist/cli/commands/test-all.js +1 -9
- package/dist/cli/commands/test-runs.js +1 -9
- package/dist/cli/commands/test.js +1 -9
- package/dist/cli/commands/update-many.js +1 -5
- package/dist/cli/commands/update.js +1 -9
- package/dist/cli/commands/upgrade.js +1 -5
- package/dist/cli/commands/validate.js +1 -15
- package/dist/cli/context-intent-invocation.js +1 -20
- package/dist/cli/description-stdin.js +1 -17
- package/dist/cli/error-guidance.js +1 -1353
- package/dist/cli/extension-command-help.js +5 -636
- package/dist/cli/extension-command-options.js +1 -427
- package/dist/cli/extension-recovery.js +1 -126
- package/dist/cli/help-content.js +2 -1001
- package/dist/cli/help-json-payload.js +4 -570
- package/dist/cli/main.d.ts +4 -0
- package/dist/cli/main.js +5 -2573
- package/dist/cli/migration-gates.js +1 -289
- package/dist/cli/public.js +1 -20
- package/dist/cli/register-annotations.js +1 -270
- package/dist/cli/register-assurance.js +1 -62
- package/dist/cli/register-files-lookup.js +1 -56
- package/dist/cli/register-history-activity.d.ts +8 -0
- package/dist/cli/register-history-activity.js +2 -0
- package/dist/cli/register-history-author.js +1 -38
- package/dist/cli/register-history-maintenance.d.ts +9 -0
- package/dist/cli/register-history-maintenance.js +2 -0
- package/dist/cli/register-list-query.js +10 -943
- package/dist/cli/register-mutation-options.js +1 -9
- package/dist/cli/register-mutation.js +19 -1893
- package/dist/cli/register-operations.js +1 -920
- package/dist/cli/register-setup.js +1 -716
- package/dist/cli/register-structured-mutation.js +1 -196
- package/dist/cli/registration-helpers.js +1 -5
- package/dist/cli/runtime-compatibility-boundary.js +4 -42
- package/dist/cli/schema-registration-helpers.js +1 -73
- package/dist/cli/search-refresh.js +1 -13
- package/dist/cli/stats-analytics-json.js +1 -68
- package/dist/cli/telemetry-flush.js +1 -10
- package/dist/cli-bundle/bundle-manifest.json +164 -156
- package/dist/cli-bundle/chunks/chunk-3BZZA6A3.js +5 -0
- package/dist/cli-bundle/chunks/chunk-AMRDVX36.js +235 -0
- package/dist/cli-bundle/chunks/chunk-DAM4CBBR.js +2202 -0
- package/dist/cli-bundle/chunks/{chunk-WYRZZ5ZE.js → chunk-DEZPZOQ7.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-FLDWYEND.js +77 -0
- package/dist/cli-bundle/chunks/{chunk-NPN5I67J.js → chunk-G5ADGQ2D.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-JAAEYHUA.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-JX4DH4WC.js → chunk-KR3RP4FH.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-LEZOUXG6.js +2 -0
- package/dist/cli-bundle/chunks/chunk-NSAPNEYH.js +2 -0
- package/dist/cli-bundle/chunks/chunk-QOEKOECV.js +29 -0
- package/dist/cli-bundle/chunks/chunk-RHSFOMHU.js +2 -0
- package/dist/cli-bundle/chunks/chunk-XOD2PCB6.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-JT6XF6GE.js → chunk-YVEQ2AMO.js} +4 -4
- package/dist/cli-bundle/chunks/register-list-query-KSK3R63M.js +11 -0
- package/dist/cli-bundle/chunks/register-mutation-IQ5C7U6O.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-I5W3KMGB.js → register-operations-DWVHR2NC.js} +2 -2
- package/dist/cli-bundle/chunks/register-setup-BQ5SVD4B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-3WRPWLA7.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-7MBUII7U.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-COPBO5HW.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-DUN4IXYN.js +20 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LIJIA4TY.js → chunk-EE5QSM4Z.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-HJVARYM3.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-IAUOUGVR.js +177 -0
- package/dist/cli-bundle/focused-chunks/chunk-KOOMJ54F.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-MZDXX7JY.js +56 -0
- package/dist/cli-bundle/focused-chunks/{chunk-M6PBRFSH.js → chunk-OPFHFGDD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QHNETP77.js +9 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3BZEOXLT.js → chunk-RMWES4M6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-RXT4P5QH.js +10 -0
- package/dist/cli-bundle/focused-chunks/chunk-SDOL6FM2.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-SQV4AAUC.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PEFABF7E.js → chunk-WE3IUNIW.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-YALOUBWJ.js +2 -0
- package/dist/cli-bundle/main.js +20 -20
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +29 -29
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +42 -42
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/cli.js +1 -104
- package/dist/core/checkpoint/checkpoint-gc.js +1 -169
- package/dist/core/checkpoint/mutation-checkpoint.js +2 -133
- package/dist/core/config/nested-settings.js +1 -534
- package/dist/core/config/positional-value.js +1 -109
- package/dist/core/diagnostics/remediation.js +1 -506
- package/dist/core/extensions/activation-summary-markdown.js +2 -145
- package/dist/core/extensions/activation-summary.js +1 -92
- package/dist/core/extensions/activation-transaction.js +1 -46
- package/dist/core/extensions/capability-usage.js +1 -173
- package/dist/core/extensions/command-hook-context.js +1 -13
- package/dist/core/extensions/command-metadata-contract.js +1 -22
- package/dist/core/extensions/command-visibility-tier.js +1 -29
- package/dist/core/extensions/contribution-inventory.js +1 -173
- package/dist/core/extensions/exporter-output-contract.js +1 -66
- package/dist/core/extensions/extension-candidate.js +1 -18
- package/dist/core/extensions/extension-capability-aliases.js +1 -158
- package/dist/core/extensions/extension-hook-runtime.js +1 -699
- package/dist/core/extensions/extension-policy.js +1 -599
- package/dist/core/extensions/extension-registries.js +1 -62
- package/dist/core/extensions/extension-runtime-helpers.js +1 -33
- package/dist/core/extensions/extension-types.js +1 -102
- package/dist/core/extensions/flag-definition-validation.js +1 -52
- package/dist/core/extensions/flag-value-types.js +1 -64
- package/dist/core/extensions/index.js +1 -526
- package/dist/core/extensions/item-field-types.js +1 -39
- package/dist/core/extensions/item-fields.js +1 -261
- package/dist/core/extensions/loader.js +1 -2223
- package/dist/core/extensions/manifest-schema.js +1 -69
- package/dist/core/extensions/module-graph-snapshot.js +1 -33
- package/dist/core/extensions/preflight-ownership.js +1 -41
- package/dist/core/extensions/registration-validation.js +1 -82
- package/dist/core/extensions/registration-values.js +1 -209
- package/dist/core/extensions/reserved-host-flags.js +1 -36
- package/dist/core/extensions/runtime-registrations.js +1 -67
- package/dist/core/extensions/service-ownership.js +1 -19
- package/dist/core/extensions/version-compat.js +1 -216
- package/dist/core/fs/fs-utils.js +2 -158
- package/dist/core/fs/host-environment-errors.js +1 -141
- package/dist/core/fs/index.js +1 -9
- package/dist/core/fs/path-utils.js +1 -17
- package/dist/core/governance/content-fields.js +1 -160
- package/dist/core/governance/issue-codes.js +1 -151
- package/dist/core/governance/metadata-coverage.js +1 -358
- package/dist/core/history/drift-cache.js +3 -72
- package/dist/core/history/drift-scan.js +1 -342
- package/dist/core/history/event-classification.js +1 -109
- package/dist/core/history/event-index.js +8 -784
- package/dist/core/history/history-compact-bulk.js +1 -104
- package/dist/core/history/history-diff.js +1 -158
- package/dist/core/history/history-rewrite.d.ts +6 -1
- package/dist/core/history/history-rewrite.js +1 -107
- package/dist/core/history/history-storage-stats.js +1 -102
- package/dist/core/history/history-stream-policy.js +1 -62
- package/dist/core/history/history.js +2 -617
- package/dist/core/history/identity.js +1 -30
- package/dist/core/history/index.js +1 -9
- package/dist/core/history/projection.js +1 -196
- package/dist/core/history/read.d.ts +9 -0
- package/dist/core/history/read.js +1 -57
- package/dist/core/history/replay.js +2 -439
- package/dist/core/history/version-address.js +1 -32
- package/dist/core/history/workspace-history.js +2 -433
- package/dist/core/io/body-file.js +1 -62
- package/dist/core/io/bulk-ids-input.js +1 -112
- package/dist/core/item/actionability.js +1 -327
- package/dist/core/item/dependency-reference.js +1 -20
- package/dist/core/item/id.js +1 -112
- package/dist/core/item/index.js +1 -12
- package/dist/core/item/item-format-version.js +1 -78
- package/dist/core/item/item-format.js +5 -1473
- package/dist/core/item/item-record.js +1 -23
- package/dist/core/item/item-type-definition.js +1 -133
- package/dist/core/item/parent-reference-policy.js +1 -57
- package/dist/core/item/parse.js +2 -603
- package/dist/core/item/plan-lifecycle.js +1 -19
- package/dist/core/item/priority.js +1 -61
- package/dist/core/item/sprint-release-format.js +1 -38
- package/dist/core/item/status-filter.js +1 -115
- package/dist/core/item/status.js +1 -43
- package/dist/core/item/toon-decode.js +1 -29
- package/dist/core/item/type-registry.js +1 -715
- package/dist/core/item/type-synonyms.js +1 -38
- package/dist/core/lock/index.js +1 -9
- package/dist/core/lock/lock-gc.js +1 -240
- package/dist/core/lock/lock.js +3 -590
- package/dist/core/output/mutation-projection.js +1 -217
- package/dist/core/output/output-control.js +1 -25
- package/dist/core/output/output.js +11 -494
- package/dist/core/output/query-summary.js +1 -58
- package/dist/core/output/tabular.js +1 -77
- package/dist/core/packages/manifest.js +1 -244
- package/dist/core/packages/root.js +1 -84
- package/dist/core/profile/profile-describe.js +1 -83
- package/dist/core/profile/profile-lint.js +1 -415
- package/dist/core/profile/profile-plan.js +0 -0
- package/dist/core/profile/profile-presets.js +1 -370
- package/dist/core/reproducibility/context.js +1 -82
- package/dist/core/schema/fields-file.js +2 -288
- package/dist/core/schema/item-types-file.js +2 -296
- package/dist/core/schema/runtime-field-filters.js +1 -49
- package/dist/core/schema/runtime-field-values.js +1 -313
- package/dist/core/schema/runtime-schema.js +2 -826
- package/dist/core/schema/status-defs-file.js +2 -227
- package/dist/core/schema/status-token.js +1 -31
- package/dist/core/schema/type-inference.js +1 -95
- package/dist/core/schema/type-presets.js +1 -87
- package/dist/core/schema/type-workflows.js +1 -104
- package/dist/core/search/background-refresh.js +2 -286
- package/dist/core/search/bm25.js +1 -146
- package/dist/core/search/cache.js +2 -534
- package/dist/core/search/corpus.js +1 -311
- package/dist/core/search/embedding-batches.js +1 -163
- package/dist/core/search/eval.js +1 -225
- package/dist/core/search/http-client.js +1 -75
- package/dist/core/search/providers.js +1 -242
- package/dist/core/search/relevance.js +1 -244
- package/dist/core/search/semantic-defaults.js +1 -199
- package/dist/core/search/staleness.js +1 -30
- package/dist/core/search/vector-stores.js +2 -664
- package/dist/core/search/vectorization-metadata.js +1 -81
- package/dist/core/sentry/helpers.js +1 -272
- package/dist/core/sentry/instrument.js +1 -387
- package/dist/core/session/session-state.js +1 -260
- package/dist/core/shared/agent-session-context.js +1 -133
- package/dist/core/shared/author.js +1 -1172
- package/dist/core/shared/command-types.js +1 -4
- package/dist/core/shared/conflict-markers.js +1 -31
- package/dist/core/shared/constants.js +1 -405
- package/dist/core/shared/errors.js +1 -20
- package/dist/core/shared/html-entity-decode.js +1 -131
- package/dist/core/shared/index.js +1 -12
- package/dist/core/shared/item-metadata-contract.js +1 -89
- package/dist/core/shared/lazy-module.js +1 -16
- package/dist/core/shared/levenshtein.js +1 -61
- package/dist/core/shared/memo.js +1 -19
- package/dist/core/shared/numeric-parsers.js +1 -20
- package/dist/core/shared/option-alias-visibility.js +1 -67
- package/dist/core/shared/primitives.js +1 -127
- package/dist/core/shared/serial-queue.js +1 -79
- package/dist/core/shared/serialization.js +1 -210
- package/dist/core/shared/split-comma-list.js +1 -30
- package/dist/core/shared/text-normalization.js +1 -38
- package/dist/core/shared/time.js +1 -306
- package/dist/core/store/index.js +1 -12
- package/dist/core/store/item-format-migration.js +1 -125
- package/dist/core/store/item-metadata-cache.js +1 -1116
- package/dist/core/store/item-metadata-query-index.js +9 -394
- package/dist/core/store/item-metadata-read-work.js +1 -43
- package/dist/core/store/item-store.js +1 -693
- package/dist/core/store/paths.d.ts +1 -1
- package/dist/core/store/paths.js +1 -214
- package/dist/core/store/settings-read-cache.js +1 -85
- package/dist/core/store/settings-validator.js +1 -421
- package/dist/core/store/settings.js +3 -1309
- package/dist/core/store/tracker-preflight.js +1 -141
- package/dist/core/telemetry/consent.js +5 -108
- package/dist/core/telemetry/observability.js +1 -246
- package/dist/core/telemetry/runtime.js +4 -1988
- package/dist/core/test/background-runs.js +4 -945
- package/dist/core/test/item-test-run-tracking.js +1 -63
- package/dist/core/test/run-selectors.js +1 -120
- package/dist/core/validate/estimate-defaults.js +1 -89
- package/dist/core/validate/fix-planning.js +1 -189
- package/dist/core/validate/linked-artifact-reference.js +1 -36
- package/dist/core/validate/missing-by-type.js +1 -34
- package/dist/core/validate/missing-link-owners.js +1 -95
- package/dist/core/validate/stale-file-classification.js +1 -82
- package/dist/mcp/http-server.js +5 -448
- package/dist/mcp/legacy-adapter.js +1 -77
- package/dist/mcp/runtime-capabilities.js +1 -200
- package/dist/mcp/server.js +4 -1233
- package/dist/mcp/tool-definitions.js +1 -804
- package/dist/sdk/actionability.js +1 -13
- package/dist/sdk/agent/closed-domain-contracts.js +1 -161
- package/dist/sdk/agent/command-recovery.js +1 -59
- package/dist/sdk/agent/command-suggestions.js +1 -66
- package/dist/sdk/agent/create-option-policy.js +1 -31
- package/dist/sdk/agent/identity-config.js +1 -106
- package/dist/sdk/agent/item-addressing.js +1 -207
- package/dist/sdk/agent/refusal-closure-census.js +1 -151
- package/dist/sdk/agent/refusal-closure.js +1 -133
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -193
- package/dist/sdk/agent/refusal-reachability.js +1 -593
- package/dist/sdk/agent/subcommand-recovery.js +1 -83
- package/dist/sdk/agent/task-transcript-contracts.js +1 -197
- package/dist/sdk/agent/tracker-preflight-contracts.js +1 -126
- package/dist/sdk/agent-capability-contracts.js +1 -428
- package/dist/sdk/agent-session-context.js +1 -9
- package/dist/sdk/annotations.js +1 -448
- package/dist/sdk/author-attribution.js +1 -468
- package/dist/sdk/authoring.js +1 -20
- package/dist/sdk/cli-bootstrap.js +1 -838
- package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +4 -476
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -79
- package/dist/sdk/cli-contracts/command-aliases.d.ts +4 -0
- package/dist/sdk/cli-contracts/command-aliases.js +1 -107
- package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -151
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1081
- package/dist/sdk/cli-contracts/commander-types.js +1 -159
- package/dist/sdk/cli-contracts/completeness.js +1 -393
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -222
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1947
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -347
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -986
- package/dist/sdk/cli-contracts/registration-helpers.js +7 -990
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +5 -0
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -2090
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -324
- package/dist/sdk/cli-contracts/string-lists.js +1 -16
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -461
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -2167
- package/dist/sdk/cli-contracts/tool-schema.d.ts +3 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1664
- package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -4
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -17
- package/dist/sdk/cli-program.js +1 -49
- package/dist/sdk/command-line.d.ts +2 -5
- package/dist/sdk/command-line.js +1 -78
- package/dist/sdk/comments.js +1 -133
- package/dist/sdk/compile-cache.js +1 -73
- package/dist/sdk/completion.js +157 -837
- package/dist/sdk/compose.js +1 -1090
- package/dist/sdk/config.js +1 -1204
- package/dist/sdk/context/recency.js +1 -33
- package/dist/sdk/context/semantic-session-attribution.js +1 -82
- package/dist/sdk/context/usage-egress.js +1 -29
- package/dist/sdk/context/usage-ledger.js +3 -185
- package/dist/sdk/context-intent-contracts.js +1 -709
- package/dist/sdk/context-intent-runtime.js +1 -115
- package/dist/sdk/context-packing.js +1 -218
- package/dist/sdk/context-relevance.js +1 -503
- package/dist/sdk/context-signal-store.js +2 -426
- package/dist/sdk/context-usage.js +1 -367
- package/dist/sdk/contracts.js +1 -23
- package/dist/sdk/core-governance.js +1 -14
- package/dist/sdk/core.js +1 -14
- package/dist/sdk/corpus-shape.js +1 -401
- package/dist/sdk/define.js +1 -220
- package/dist/sdk/dependencies.js +1 -718
- package/dist/sdk/dependency-flag-validation.js +1 -156
- package/dist/sdk/dependency-provenance.js +1 -135
- package/dist/sdk/docs.js +1 -14
- package/dist/sdk/duplicates.js +1 -40
- package/dist/sdk/environment/agent-environment.js +1 -466
- package/dist/sdk/environment/host-environment-errors.js +1 -8
- package/dist/sdk/environment/project-runtime-compatibility.js +1 -481
- package/dist/sdk/environment/source-context.js +1 -28
- package/dist/sdk/environment/tracker-preflight.js +1 -9
- package/dist/sdk/error-code-catalog.js +1 -153
- package/dist/sdk/error-runtime.js +1 -58
- package/dist/sdk/errors.js +1 -58
- package/dist/sdk/eval.js +1 -190
- package/dist/sdk/extension/author-manifest.js +1 -92
- package/dist/sdk/extension/bundled-catalog.js +1 -332
- package/dist/sdk/extension/concurrency.js +1 -25
- package/dist/sdk/extension/copy-scope.d.ts +2 -0
- package/dist/sdk/extension/copy-scope.js +2 -0
- package/dist/sdk/extension/custom-field-collisions.js +1 -30
- package/dist/sdk/extension/describe.js +3 -189
- package/dist/sdk/extension/doctor.js +1 -606
- package/dist/sdk/extension/install-plan.d.ts +69 -0
- package/dist/sdk/extension/install-plan.js +2 -0
- package/dist/sdk/extension/install-receipts.d.ts +7 -0
- package/dist/sdk/extension/install-receipts.js +2 -0
- package/dist/sdk/extension/install-runtime.js +3 -313
- package/dist/sdk/extension/install-snapshot.js +1 -66
- package/dist/sdk/extension/install-sources.js +5 -1057
- package/dist/sdk/extension/managed-state.js +2 -252
- package/dist/sdk/extension/migrations.js +2 -174
- package/dist/sdk/extension/output-ownership.js +1 -25
- package/dist/sdk/extension/runtime-summary.js +1 -18
- package/dist/sdk/extension/scaffold.js +4 -2308
- package/dist/sdk/extension/shared.js +1 -147
- package/dist/sdk/extension/source-resolution.js +1 -65
- package/dist/sdk/extension/update-check.js +1 -67
- package/dist/sdk/extension-command-context.js +1 -44
- package/dist/sdk/extension-contracts.js +1 -73
- package/dist/sdk/extension.d.ts +7 -2
- package/dist/sdk/extension.js +1 -2196
- package/dist/sdk/files.js +1 -535
- package/dist/sdk/flag-invocation-contracts.d.ts +0 -5
- package/dist/sdk/flag-invocation-contracts.js +1 -344
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -2224
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -2236
- package/dist/sdk/generated-error-code-catalog.js +1 -16
- package/dist/sdk/governance/assurance-action-contracts.js +1 -4
- package/dist/sdk/governance/assurance-action.js +1 -411
- package/dist/sdk/governance/assurance-limits.js +1 -10
- package/dist/sdk/governance/assurance-mutation-error.js +1 -81
- package/dist/sdk/governance/assurance-presets.js +1 -135
- package/dist/sdk/governance/assurance-runtime.js +1 -238
- package/dist/sdk/governance/assurance.js +4 -1182
- package/dist/sdk/governance/boundary-fixtures.js +1 -200
- package/dist/sdk/governance/coverage-assurance.js +1 -60
- package/dist/sdk/governance/defect-recurrence-coverage.js +1 -188
- package/dist/sdk/governance/defect-recurrence-graph.js +1 -120
- package/dist/sdk/governance/defect-recurrence-signals.js +1 -24
- package/dist/sdk/governance/defect-recurrence.js +1 -623
- package/dist/sdk/governance/extension-host-version.js +1 -115
- package/dist/sdk/governance/gc.js +1 -368
- package/dist/sdk/governance/health.js +1 -2367
- package/dist/sdk/governance/hierarchy-validation.js +1 -108
- package/dist/sdk/governance/linked-file-report.js +1 -71
- package/dist/sdk/governance/merge-receipt-history.js +1 -206
- package/dist/sdk/governance/provenance-health.js +1 -282
- package/dist/sdk/governance/reindex.js +4 -761
- package/dist/sdk/governance/stale-work.js +1 -82
- package/dist/sdk/governance/status-role-diagnostics.js +1 -35
- package/dist/sdk/governance/storage-integrity.js +1 -280
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -106
- package/dist/sdk/governance/upgrade.js +2 -327
- package/dist/sdk/governance/validate-history-drift.js +1 -81
- package/dist/sdk/governance/validate-item-reader.js +1 -17
- package/dist/sdk/governance/validate-normalization.js +1 -36
- package/dist/sdk/governance/validate.js +1 -2261
- package/dist/sdk/governance/workspace-position.js +1 -163
- package/dist/sdk/governance.d.ts +1 -0
- package/dist/sdk/governance.js +1 -31
- package/dist/sdk/graph/adapter.js +1 -181
- package/dist/sdk/graph/analytics.js +1 -474
- package/dist/sdk/graph/assembly.js +1 -377
- package/dist/sdk/graph/cache.js +1 -160
- package/dist/sdk/graph/centrality.js +1 -258
- package/dist/sdk/graph/conformance.js +1 -130
- package/dist/sdk/graph/deadline-scheduling.d.ts +90 -0
- package/dist/sdk/graph/deadline-scheduling.js +2 -0
- package/dist/sdk/graph/durable-cache.d.ts +1 -1
- package/dist/sdk/graph/durable-cache.js +1 -361
- package/dist/sdk/graph/governance-contracts.js +1 -34
- package/dist/sdk/graph/governance.d.ts +13 -1
- package/dist/sdk/graph/governance.js +1 -735
- package/dist/sdk/graph/hierarchy-integrity.js +1 -310
- package/dist/sdk/graph/index.d.ts +3 -2
- package/dist/sdk/graph/index.js +1 -26
- package/dist/sdk/graph/lifecycle-coverage.d.ts +32 -0
- package/dist/sdk/graph/lifecycle-coverage.js +2 -0
- package/dist/sdk/graph/mutation-advisory.js +1 -176
- package/dist/sdk/graph/remediation.js +1 -197
- package/dist/sdk/graph/run.d.ts +15 -1
- package/dist/sdk/graph/run.js +1 -768
- package/dist/sdk/graph/scheduling.js +1 -124
- package/dist/sdk/graph/traversal.js +1 -284
- package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -27
- package/dist/sdk/graph.js +1 -15
- package/dist/sdk/guide-topics.js +1 -707
- package/dist/sdk/guide.js +1 -279
- package/dist/sdk/history/maintenance.d.ts +71 -0
- package/dist/sdk/history/maintenance.js +2 -0
- package/dist/sdk/history/salvage.js +2 -247
- package/dist/sdk/history/subject.d.ts +19 -0
- package/dist/sdk/history/subject.js +2 -0
- package/dist/sdk/history-analytics.js +1 -282
- package/dist/sdk/history-compact.js +1 -527
- package/dist/sdk/history-mcp.js +1 -68
- package/dist/sdk/history-provenance.js +1 -182
- package/dist/sdk/history-read.js +1 -96
- package/dist/sdk/history-redact.d.ts +1 -14
- package/dist/sdk/history-redact.js +1 -643
- package/dist/sdk/history-repair.d.ts +5 -0
- package/dist/sdk/history-repair.js +1 -657
- package/dist/sdk/improvement-ledger-validation.js +1 -62
- package/dist/sdk/improvement-ledger.js +2 -257
- package/dist/sdk/index.d.ts +4 -0
- package/dist/sdk/index.js +1 -183
- package/dist/sdk/init-agent-guidance.js +2 -496
- package/dist/sdk/init.js +2 -820
- package/dist/sdk/invocation-author.js +1 -39
- package/dist/sdk/item-children.js +1 -90
- package/dist/sdk/item-metadata-index.js +1 -15
- package/dist/sdk/item-schedule.js +1 -27
- package/dist/sdk/item-transaction.js +1 -396
- package/dist/sdk/learnings.js +1 -29
- package/dist/sdk/lifecycle/append.js +2 -53
- package/dist/sdk/lifecycle/claim.d.ts +2 -0
- package/dist/sdk/lifecycle/claim.js +1 -242
- package/dist/sdk/lifecycle/close-many.js +1 -438
- package/dist/sdk/lifecycle/close.js +1 -468
- package/dist/sdk/lifecycle/copy.js +1 -212
- package/dist/sdk/lifecycle/create.js +1 -1949
- package/dist/sdk/lifecycle/delete.js +1 -45
- package/dist/sdk/lifecycle/event-validation-messages.js +1 -91
- package/dist/sdk/lifecycle/focus.js +1 -91
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -24
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -149
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -40
- package/dist/sdk/lifecycle/mcp-actions.d.ts +2 -0
- package/dist/sdk/lifecycle/mcp-actions.js +1 -51
- package/dist/sdk/lifecycle/metadata-normalizers.js +1 -46
- package/dist/sdk/lifecycle/mutation-command-options.js +1 -9
- package/dist/sdk/lifecycle/plan.js +1 -1606
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -147
- package/dist/sdk/lifecycle/reopen.js +1 -68
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +1 -143
- package/dist/sdk/lifecycle/restore.d.ts +1 -0
- package/dist/sdk/lifecycle/restore.js +1 -330
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -295
- package/dist/sdk/lifecycle/update-many.js +1 -861
- package/dist/sdk/lifecycle/update.js +1 -2136
- package/dist/sdk/lifecycle-completion.js +1 -92
- package/dist/sdk/lifecycle-policy.js +1 -120
- package/dist/sdk/linked-artifacts.js +1 -530
- package/dist/sdk/mcp/apps.js +4 -133
- package/dist/sdk/mcp/authorization.js +1 -404
- package/dist/sdk/mcp/discovery.js +1 -494
- package/dist/sdk/mcp/interactions.js +1 -336
- package/dist/sdk/mcp/protocol.d.ts +7 -0
- package/dist/sdk/mcp/protocol.js +1 -184
- package/dist/sdk/mcp/skills.js +1 -389
- package/dist/sdk/mcp/subscriptions.js +1 -211
- package/dist/sdk/mcp/tasks.js +2 -430
- package/dist/sdk/mcp/transport.js +1 -260
- package/dist/sdk/merge/abandoned-receipts.js +1 -46
- package/dist/sdk/merge/driver.js +1 -212
- package/dist/sdk/merge/index.js +1 -16
- package/dist/sdk/merge/install.js +3 -561
- package/dist/sdk/merge/receipt-file-boundary.js +1 -46
- package/dist/sdk/merge/receipt-operation.js +1 -96
- package/dist/sdk/merge/receipt-schema.js +1 -397
- package/dist/sdk/merge/receipts.js +4 -525
- package/dist/sdk/merge/reconcile.js +1 -352
- package/dist/sdk/merge/three-way.js +3 -775
- package/dist/sdk/merge.js +1 -10
- package/dist/sdk/mutation-events.js +1 -292
- package/dist/sdk/mutation-guard.js +1 -216
- package/dist/sdk/notes.js +1 -139
- package/dist/sdk/output-contracts.js +1 -172
- package/dist/sdk/output-projection.js +1 -430
- package/dist/sdk/output-token-accounting.js +1 -140
- package/dist/sdk/output.js +1 -64
- package/dist/sdk/ownership-source.js +1 -21
- package/dist/sdk/package-import-adapters.js +1 -442
- package/dist/sdk/package-migrations.js +1 -20
- package/dist/sdk/package-runtime-options.js +1 -80
- package/dist/sdk/pagination.js +1 -162
- package/dist/sdk/profile.js +1 -454
- package/dist/sdk/provenance.js +1 -258
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.js +1 -401
- package/dist/sdk/query/aggregate.d.ts +16 -0
- package/dist/sdk/query/aggregate.js +1 -390
- package/dist/sdk/query/calendar.js +1 -964
- package/dist/sdk/query/complete-list.js +1 -215
- package/dist/sdk/query/context.js +1 -1702
- package/dist/sdk/query/duplicate-candidates.js +1 -70
- package/dist/sdk/query/get.js +1 -450
- package/dist/sdk/query/history.js +1 -186
- package/dist/sdk/query/item-filter-options.js +1 -9
- package/dist/sdk/query/light-metadata.js +1 -18
- package/dist/sdk/query/list-filter-shared.js +1 -81
- package/dist/sdk/query/list.js +1 -1304
- package/dist/sdk/query/multi-value-filters.js +1 -78
- package/dist/sdk/query/next.js +1 -513
- package/dist/sdk/query/parsers.js +1 -44
- package/dist/sdk/query/projection-contracts.js +1 -184
- package/dist/sdk/query/search-contracts.js +1 -230
- package/dist/sdk/query/search-pagination.js +1 -35
- package/dist/sdk/query/search-rendering.js +1 -105
- package/dist/sdk/query/search.js +2 -1987
- package/dist/sdk/query.js +1 -35
- package/dist/sdk/read-output/continuation.js +1 -194
- package/dist/sdk/read-output-budget.js +1 -135
- package/dist/sdk/read-output-contracts.js +1 -1225
- package/dist/sdk/read-output-rows.js +1 -186
- package/dist/sdk/read-output-session.js +1 -208
- package/dist/sdk/relationship-analytics.js +1 -410
- package/dist/sdk/relationship-context.js +1 -284
- package/dist/sdk/relationship-history.js +4 -519
- package/dist/sdk/relationship-kinds/contract.js +1 -22
- package/dist/sdk/relationship-migration.js +1 -77
- package/dist/sdk/relationships.js +1 -579
- package/dist/sdk/reproducibility/process.js +1 -87
- package/dist/sdk/runtime-action-aliases.js +1 -59
- package/dist/sdk/runtime-extended-actions.js +1 -177
- package/dist/sdk/runtime-input.js +1 -614
- package/dist/sdk/runtime-primitives.js +1 -84
- package/dist/sdk/runtime-public-contracts.js +1 -4
- package/dist/sdk/runtime-stats-options.js +1 -38
- package/dist/sdk/runtime.js +1 -1928
- package/dist/sdk/scheduling-shortcuts.js +1 -63
- package/dist/sdk/schema-migration.js +3 -856
- package/dist/sdk/schema.js +1 -1376
- package/dist/sdk/search-refresh-worker.js +1 -18
- package/dist/sdk/similarity-scoring.js +1 -53
- package/dist/sdk/similarity.js +1 -326
- package/dist/sdk/start-task-status.js +1 -14
- package/dist/sdk/stats.js +1 -270
- package/dist/sdk/structured-mutations.js +1 -580
- package/dist/sdk/telemetry-flush.js +1 -13
- package/dist/sdk/telemetry.js +1 -405
- package/dist/sdk/templates.js +2 -292
- package/dist/sdk/test/batch.js +2 -509
- package/dist/sdk/test/entry.js +1 -70
- package/dist/sdk/test/execution.js +6 -2211
- package/dist/sdk/test/linked-command-detection.js +1 -546
- package/dist/sdk/test/measurements.js +1 -91
- package/dist/sdk/test/parsers.js +1 -545
- package/dist/sdk/test/runs.js +1 -193
- package/dist/sdk/test/trust.js +2 -206
- package/dist/sdk/testing.js +4 -1391
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -32
- package/dist/sdk/traceability/source-traceability.js +1 -292
- package/dist/sdk/tracker-root-discovery.js +1 -9
- package/dist/sdk/workspace-contracts-cache.js +1 -28
- package/dist/sdk/workspace-contracts.js +1 -33
- package/dist/sdk/workspace-memory.js +2 -318
- package/dist/sdk/workspace-recipe.js +1 -71
- package/dist/sdk/workspace-snapshot.js +4 -613
- package/dist/sdk/workspace-transaction-gc.js +1 -149
- package/dist/sdk/workspace-transaction.js +2 -363
- package/dist/sdk/workspace.js +3 -127
- package/dist/types/index.js +1 -9
- package/dist/types.js +1 -245
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +167 -0
- package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +9 -3
- package/docs/EXTENSIONS.md +1 -0
- package/docs/HISTORY_MAINTENANCE.md +125 -0
- package/docs/MCP_2026_07_28_CONFORMANCE.md +20 -10
- package/docs/PACKAGE_EVIDENCE.md +92 -0
- package/docs/PLANNING_MEASUREMENTS.md +183 -0
- package/docs/README.md +3 -0
- package/docs/RELEASING.md +1 -0
- package/docs/SCRIPTING.md +21 -0
- package/docs/TESTING.md +23 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +5 -5
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +2 -2
- package/marketplace.json +2 -2
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/scripts/finalize-build.mjs +45 -3
- package/dist/cli-bundle/chunks/chunk-AZDFJGH6.js +0 -9
- package/dist/cli-bundle/chunks/chunk-BAX2BYUW.js +0 -2111
- package/dist/cli-bundle/chunks/chunk-CKOL5U7J.js +0 -77
- package/dist/cli-bundle/chunks/chunk-OF76PSDQ.js +0 -5
- package/dist/cli-bundle/chunks/chunk-QUWFABDM.js +0 -232
- package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +0 -2
- package/dist/cli-bundle/chunks/chunk-RWWBOWJ5.js +0 -2
- package/dist/cli-bundle/chunks/chunk-WGAOYSYH.js +0 -40
- package/dist/cli-bundle/chunks/chunk-WI2AYPA7.js +0 -2
- package/dist/cli-bundle/chunks/register-list-query-5JL52D33.js +0 -11
- package/dist/cli-bundle/chunks/register-mutation-ZPG7KMVP.js +0 -20
- package/dist/cli-bundle/chunks/register-setup-H4SVAVX7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-AL5ON6K6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CHC2IDXA.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-CK6QFAPZ.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-EZR3GHFE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-H2WJWK7L.js +0 -56
- package/dist/cli-bundle/focused-chunks/chunk-NTPY5GSO.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-P5O7MP5Y.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-PDMW2E36.js +0 -177
- package/dist/cli-bundle/focused-chunks/chunk-QTVCLMSZ.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-QTZRBUYA.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-SGQST3PQ.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-UKHASMMP.js +0 -10
- package/dist/cli-bundle/focused-chunks/chunk-ZPEKQHOC.js +0 -2
|
@@ -1,1989 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
* @module core/telemetry/runtime
|
|
3
|
-
|
|
4
|
-
* Captures consent-aware telemetry and observability events for Runtime.
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="26ea62d9-874d-5826-9822-83c5523b673b")}catch(e){}}();
|
|
8
|
-
import crypto from "node:crypto";
|
|
9
|
-
import { spawn } from "node:child_process";
|
|
10
|
-
import { mkdirSync, rmSync, statSync } from "node:fs";
|
|
11
|
-
import { mkdir, readdir, rm, stat } from "node:fs/promises";
|
|
12
|
-
import { request as httpRequest } from "node:http";
|
|
13
|
-
import { request as httpsRequest } from "node:https";
|
|
14
|
-
import os from "node:os";
|
|
15
|
-
import path from "node:path";
|
|
16
|
-
import { resolvePmPackageRootFromModule } from "../packages/root.js";
|
|
17
|
-
import { isFileMissingError, appendLineAtomic, readFileIfExists, writeFileAtomic, } from "../fs/fs-utils.js";
|
|
18
|
-
import { resolveTelemetryErrorCategory, } from "../shared/constants.js";
|
|
19
|
-
import { nowIso } from "../shared/time.js";
|
|
20
|
-
import { detectAgentIdentity, readAuthorEnvironment, } from "../shared/author.js";
|
|
21
|
-
import { resolveGlobalPmRoot } from "../store/paths.js";
|
|
22
|
-
import { readSettings, writeSettings } from "../store/settings.js";
|
|
23
|
-
import { deriveTelemetryCommandResolution, deriveTelemetryCommandTaxonomy, inferTelemetryErrorCode, } from "./observability.js";
|
|
24
|
-
const TELEMETRY_QUEUE_RELATIVE_PATH = path.join("runtime", "telemetry", "events.jsonl");
|
|
25
|
-
const TELEMETRY_STATE_RELATIVE_PATH = path.join("runtime", "telemetry", "state.json");
|
|
26
|
-
const TELEMETRY_OTEL_SPANS_RELATIVE_PATH = path.join("runtime", "telemetry", "otel-spans.jsonl");
|
|
27
|
-
// OTLP requests run concurrently, while event and OTLP phases run sequentially.
|
|
28
|
-
// The maximum configurable HTTP timeout therefore keeps two worst-case network
|
|
29
|
-
// phases below TELEMETRY_FLUSH_LOCK_STALE_MS (60s), preventing a later command
|
|
30
|
-
// from treating a live worker's lock as stale and starting a second worker.
|
|
31
|
-
const TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE = 8;
|
|
32
|
-
const TELEMETRY_OTEL_SPANS_MAX_PENDING = 500;
|
|
33
|
-
/** Public contract for telemetry schema version, shared by SDK and presentation-layer consumers. */
|
|
34
|
-
export const TELEMETRY_SCHEMA_VERSION = 1;
|
|
35
|
-
const TELEMETRY_CLIENT_SCHEMA_VERSION = 1;
|
|
36
|
-
const TELEMETRY_FLUSH_BATCH_SIZE = 100;
|
|
37
|
-
const TELEMETRY_MAX_RETRY_DELAY_MS = 3_600_000;
|
|
38
|
-
const TELEMETRY_RETRY_BASE_DELAY_MS = 30_000;
|
|
39
|
-
const TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS = 20_000;
|
|
40
|
-
const TELEMETRY_HTTP_TIMEOUT_MIN_MS = 1_000;
|
|
41
|
-
const TELEMETRY_HTTP_TIMEOUT_MAX_MS = 25_000;
|
|
42
|
-
const MILLISECONDS_PER_DAY = 86_400_000;
|
|
43
|
-
const TELEMETRY_MAX_EVENT_BYTES = 65_536;
|
|
44
|
-
const TELEMETRY_SANITIZE_MAX_DEPTH = 6;
|
|
45
|
-
const TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS = 20;
|
|
46
|
-
/** Public contract for telemetry max queue entry attempts, shared by SDK and presentation-layer consumers. */
|
|
47
|
-
export const TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS = 15;
|
|
48
|
-
const TELEMETRY_RESULT_PREVIEW_MAX_BYTES = 8_192;
|
|
49
|
-
const TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS = [25, 50, 100, 200];
|
|
50
|
-
const TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS = 60 * 60 * 1000;
|
|
51
|
-
const TELEMETRY_FLUSH_LOCK_STALE_MS = 60_000;
|
|
52
|
-
const TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS = 60_000;
|
|
53
|
-
const OTEL_TRACES_ENDPOINT_ENV = "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT";
|
|
54
|
-
const OTEL_BASE_ENDPOINT_ENV = "OTEL_EXPORTER_OTLP_ENDPOINT";
|
|
55
|
-
const OTEL_SERVICE_NAME_ENV = "OTEL_SERVICE_NAME";
|
|
56
|
-
const PM_TELEMETRY_DISABLED_ENV = "PM_TELEMETRY_DISABLED";
|
|
57
|
-
const PM_NO_TELEMETRY_ENV = "PM_NO_TELEMETRY";
|
|
58
|
-
const PM_TELEMETRY_DISABLED_VALUES = new Set(["1", "true", "yes", "on"]);
|
|
59
|
-
const PM_TELEMETRY_OTEL_DISABLED_ENV = "PM_TELEMETRY_OTEL_DISABLED";
|
|
60
|
-
const PM_TELEMETRY_OTEL_DISABLED_VALUES = new Set(["1", "true", "yes", "on"]);
|
|
61
|
-
const PM_TELEMETRY_INLINE_FLUSH_ENV = "PM_TELEMETRY_INLINE_FLUSH";
|
|
62
|
-
const PM_TELEMETRY_FLUSH_CHILD_ENV = "PM_TELEMETRY_FLUSH_CHILD";
|
|
63
|
-
const PM_TELEMETRY_SOURCE_CONTEXT_ENV = "PM_TELEMETRY_SOURCE_CONTEXT";
|
|
64
|
-
const PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV = "PM_TELEMETRY_HTTP_TIMEOUT_MS";
|
|
65
|
-
const NATIVE_FETCH = globalThis.fetch;
|
|
66
|
-
/** Supported values accepted by the pm telemetry source context contract. */
|
|
67
|
-
export const PM_TELEMETRY_SOURCE_CONTEXT_VALUES = [
|
|
68
|
-
"user",
|
|
69
|
-
"automation",
|
|
70
|
-
"test",
|
|
71
|
-
"dogfood",
|
|
72
|
-
];
|
|
73
|
-
let _lastFlushPromise = Promise.resolve();
|
|
74
|
-
let _queueMutationPromise = Promise.resolve();
|
|
75
|
-
/** Wait for the most recent background flush to settle. Test-only helper. */
|
|
76
|
-
export async function waitForPendingFlush() {
|
|
77
|
-
await _lastFlushPromise;
|
|
78
|
-
await _queueMutationPromise;
|
|
79
|
-
}
|
|
80
|
-
const PM_TELEMETRY_SOURCE_CONTEXT_SET = new Set(PM_TELEMETRY_SOURCE_CONTEXT_VALUES);
|
|
81
|
-
const BOOLEAN_TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
|
|
82
|
-
const PROCESS_SESSION_ID = crypto.randomUUID();
|
|
83
|
-
const SENSITIVE_KEYWORDS = [
|
|
84
|
-
"token",
|
|
85
|
-
"secret",
|
|
86
|
-
"password",
|
|
87
|
-
"passwd",
|
|
88
|
-
"api_key",
|
|
89
|
-
"apikey",
|
|
90
|
-
"authorization",
|
|
91
|
-
"cookie",
|
|
92
|
-
"session",
|
|
93
|
-
"credentials",
|
|
94
|
-
"bearer",
|
|
95
|
-
];
|
|
96
|
-
const REDACTION_INPUT_KEYS = new Set([
|
|
97
|
-
"literal",
|
|
98
|
-
"literals",
|
|
99
|
-
"regex",
|
|
100
|
-
"regexes",
|
|
101
|
-
"replacement",
|
|
102
|
-
"replacements",
|
|
103
|
-
]);
|
|
104
|
-
const SENSITIVE_INLINE_KEY_PATTERN = "(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)";
|
|
105
|
-
const INLINE_SENSITIVE_ASSIGNMENT_PATTERN = new RegExp(`\\b(${SENSITIVE_INLINE_KEY_PATTERN})\\s*([:=])\\s*([^\\s,;]+)`, "giu");
|
|
106
|
-
const INLINE_SENSITIVE_FLAG_PATTERN = new RegExp(`(--${SENSITIVE_INLINE_KEY_PATTERN})(=|\\s+)([^\\s,;]+)`, "giu");
|
|
107
|
-
const ABSOLUTE_PATH_TOKEN_PATTERN = /(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g;
|
|
108
|
-
const BEARER_TOKEN_PATTERN = /bearer\s+[a-z0-9._=-]+/giu;
|
|
109
|
-
const PRIVATE_IP_PATTERN = /\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;
|
|
110
|
-
function queuePath(globalPmRoot) {
|
|
111
|
-
return path.join(globalPmRoot, TELEMETRY_QUEUE_RELATIVE_PATH);
|
|
112
|
-
}
|
|
113
|
-
function otelSpansQueuePath(globalPmRoot) {
|
|
114
|
-
return path.join(globalPmRoot, TELEMETRY_OTEL_SPANS_RELATIVE_PATH);
|
|
115
|
-
}
|
|
116
|
-
function telemetryRuntimeDirectory(globalPmRoot) {
|
|
117
|
-
return path.dirname(queuePath(globalPmRoot));
|
|
118
|
-
}
|
|
119
|
-
function runtimeStatePath(globalPmRoot) {
|
|
120
|
-
return path.join(globalPmRoot, TELEMETRY_STATE_RELATIVE_PATH);
|
|
121
|
-
}
|
|
122
|
-
function flushLockPath(globalPmRoot) {
|
|
123
|
-
return path.join(globalPmRoot, "runtime", "telemetry", "flush.lock");
|
|
124
|
-
}
|
|
125
|
-
function flushSpawnLockPath(globalPmRoot) {
|
|
126
|
-
return path.join(globalPmRoot, "runtime", "telemetry", "flush.spawn.lock");
|
|
127
|
-
}
|
|
128
|
-
function telemetryFlushRunnerPath() {
|
|
129
|
-
return path.join(resolvePmPackageRootFromModule(import.meta.url, ["../../.."]), "dist", "cli", "telemetry-flush.js");
|
|
130
|
-
}
|
|
131
|
-
function shouldFlushInline() {
|
|
132
|
-
if (parseBooleanTrueLike(process.env[PM_TELEMETRY_INLINE_FLUSH_ENV])) {
|
|
133
|
-
return true;
|
|
134
|
-
}
|
|
135
|
-
if (parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])) {
|
|
136
|
-
return true;
|
|
137
|
-
}
|
|
138
|
-
const nodeEnv = (process.env.NODE_ENV ?? "").trim().toLowerCase();
|
|
139
|
-
return (typeof process.env.VITEST === "string" ||
|
|
140
|
-
typeof process.env.VITEST_WORKER_ID === "string" ||
|
|
141
|
-
nodeEnv === "test");
|
|
142
|
-
}
|
|
143
|
-
async function readRuntimeState(globalPmRoot) {
|
|
144
|
-
const raw = await readFileIfExists(runtimeStatePath(globalPmRoot));
|
|
145
|
-
if (!raw || raw.trim().length === 0) {
|
|
146
|
-
return {};
|
|
147
|
-
}
|
|
148
|
-
try {
|
|
149
|
-
const parsed = JSON.parse(raw);
|
|
150
|
-
if (typeof parsed !== "object" ||
|
|
151
|
-
parsed === null ||
|
|
152
|
-
Array.isArray(parsed)) {
|
|
153
|
-
return {};
|
|
154
|
-
}
|
|
155
|
-
return parsed;
|
|
156
|
-
}
|
|
157
|
-
catch {
|
|
158
|
-
return {};
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
async function writeRuntimeState(globalPmRoot, patch) {
|
|
162
|
-
try {
|
|
163
|
-
const current = await readRuntimeState(globalPmRoot);
|
|
164
|
-
const next = {
|
|
165
|
-
...current,
|
|
166
|
-
...patch,
|
|
167
|
-
};
|
|
168
|
-
const normalized = Object.fromEntries(Object.entries(next)
|
|
169
|
-
.filter(([, value]) => value !== undefined)
|
|
170
|
-
.sort((left, right) => left[0].localeCompare(right[0])));
|
|
171
|
-
await writeFileAtomic(runtimeStatePath(globalPmRoot), `${JSON.stringify(normalized, null, 2)}\n`);
|
|
172
|
-
}
|
|
173
|
-
catch {
|
|
174
|
-
// Runtime state persistence is best effort and must not block command execution.
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
function isSensitiveKey(key) {
|
|
178
|
-
const normalized = key
|
|
179
|
-
.trim()
|
|
180
|
-
.toLowerCase()
|
|
181
|
-
.replaceAll("-", "_")
|
|
182
|
-
.replaceAll(/[^a-z0-9_]+/g, "_");
|
|
183
|
-
const tokens = normalized.split("_").filter((token) => token.length > 0);
|
|
184
|
-
return (REDACTION_INPUT_KEYS.has(normalized) ||
|
|
185
|
-
SENSITIVE_KEYWORDS.some((keyword) => normalized === keyword ||
|
|
186
|
-
normalized.endsWith(`_${keyword}`) ||
|
|
187
|
-
tokens.includes(keyword)));
|
|
188
|
-
}
|
|
189
|
-
function redactInlineSensitiveAssignments(input) {
|
|
190
|
-
const withoutAssignments = input.replaceAll(INLINE_SENSITIVE_ASSIGNMENT_PATTERN, (_match, key, delimiter) => `${key}${delimiter}[redacted]`);
|
|
191
|
-
return withoutAssignments.replaceAll(INLINE_SENSITIVE_FLAG_PATTERN, (_match, flag, delimiter) => `${flag}${delimiter}[redacted]`);
|
|
192
|
-
}
|
|
193
|
-
function redactAbsolutePathTokens(input) {
|
|
194
|
-
return input.replaceAll(ABSOLUTE_PATH_TOKEN_PATTERN, (_match, prefix) => `${prefix}[redacted_path]`);
|
|
195
|
-
}
|
|
196
|
-
function isAsciiLetterOrDigitCode(code) {
|
|
197
|
-
const isUpper = code >= 65 && code <= 90;
|
|
198
|
-
const isLower = code >= 97 && code <= 122;
|
|
199
|
-
const isDigit = code >= 48 && code <= 57;
|
|
200
|
-
return isUpper || isLower || isDigit;
|
|
201
|
-
}
|
|
202
|
-
function isEmailLocalCharacter(character) {
|
|
203
|
-
if (!character) {
|
|
204
|
-
return false;
|
|
205
|
-
}
|
|
206
|
-
const code = character.charCodeAt(0);
|
|
207
|
-
if (isAsciiLetterOrDigitCode(code)) {
|
|
208
|
-
return true;
|
|
209
|
-
}
|
|
210
|
-
return (character === "." ||
|
|
211
|
-
character === "_" ||
|
|
212
|
-
character === "%" ||
|
|
213
|
-
character === "+" ||
|
|
214
|
-
character === "-");
|
|
215
|
-
}
|
|
216
|
-
function isEmailDomainCharacter(character) {
|
|
217
|
-
if (!character) {
|
|
218
|
-
return false;
|
|
219
|
-
}
|
|
220
|
-
const code = character.charCodeAt(0);
|
|
221
|
-
if (isAsciiLetterOrDigitCode(code)) {
|
|
222
|
-
return true;
|
|
223
|
-
}
|
|
224
|
-
return character === "." || character === "-";
|
|
225
|
-
}
|
|
226
|
-
function looksLikeEmailToken(token) {
|
|
227
|
-
const atIndex = token.indexOf("@");
|
|
228
|
-
if (atIndex <= 0 ||
|
|
229
|
-
atIndex !== token.lastIndexOf("@") ||
|
|
230
|
-
atIndex === token.length - 1) {
|
|
231
|
-
return false;
|
|
232
|
-
}
|
|
233
|
-
const localPart = token.slice(0, atIndex);
|
|
234
|
-
const domainPart = token.slice(atIndex + 1);
|
|
235
|
-
const lastDot = domainPart.lastIndexOf(".");
|
|
236
|
-
if (lastDot <= 0 || lastDot === domainPart.length - 1) {
|
|
237
|
-
return false;
|
|
238
|
-
}
|
|
239
|
-
if (domainPart.length - (lastDot + 1) < 2) {
|
|
240
|
-
return false;
|
|
241
|
-
}
|
|
242
|
-
for (const character of localPart) {
|
|
243
|
-
if (!isEmailLocalCharacter(character)) {
|
|
244
|
-
return false;
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
for (const character of domainPart) {
|
|
248
|
-
if (!isEmailDomainCharacter(character)) {
|
|
249
|
-
return false;
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
return true;
|
|
253
|
-
}
|
|
254
|
-
function redactEmailTokens(input) {
|
|
255
|
-
let redacted = "";
|
|
256
|
-
let cursor = 0;
|
|
257
|
-
while (cursor < input.length) {
|
|
258
|
-
const atIndex = input.indexOf("@", cursor);
|
|
259
|
-
if (atIndex < 0) {
|
|
260
|
-
redacted += input.slice(cursor);
|
|
261
|
-
break;
|
|
262
|
-
}
|
|
263
|
-
let start = atIndex - 1;
|
|
264
|
-
while (start >= cursor && isEmailLocalCharacter(input[start])) {
|
|
265
|
-
start -= 1;
|
|
266
|
-
}
|
|
267
|
-
start += 1;
|
|
268
|
-
let end = atIndex + 1;
|
|
269
|
-
while (end < input.length && isEmailDomainCharacter(input[end])) {
|
|
270
|
-
end += 1;
|
|
271
|
-
}
|
|
272
|
-
const candidate = input.slice(start, end);
|
|
273
|
-
if (looksLikeEmailToken(candidate)) {
|
|
274
|
-
redacted += input.slice(cursor, start);
|
|
275
|
-
redacted += "[redacted_email]";
|
|
276
|
-
cursor = end;
|
|
277
|
-
continue;
|
|
278
|
-
}
|
|
279
|
-
redacted += input.slice(cursor, atIndex + 1);
|
|
280
|
-
cursor = atIndex + 1;
|
|
281
|
-
}
|
|
282
|
-
return redacted;
|
|
283
|
-
}
|
|
284
|
-
function sanitizeCommonSensitiveTokens(input) {
|
|
285
|
-
const withoutEmails = redactEmailTokens(input);
|
|
286
|
-
const withoutBearer = withoutEmails.replaceAll(BEARER_TOKEN_PATTERN, "bearer [redacted_token]");
|
|
287
|
-
return withoutBearer.replaceAll(PRIVATE_IP_PATTERN, "[redacted_ip]");
|
|
288
|
-
}
|
|
289
|
-
function sanitizeStringRedacted(input) {
|
|
290
|
-
const withoutCommonSensitiveTokens = sanitizeCommonSensitiveTokens(input);
|
|
291
|
-
const withoutInlineSecrets = redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);
|
|
292
|
-
const withoutAbsolutePaths = redactAbsolutePathTokens(withoutInlineSecrets);
|
|
293
|
-
const trimmed = withoutAbsolutePaths.trim();
|
|
294
|
-
if (trimmed.startsWith("/") && trimmed.length > 1) {
|
|
295
|
-
return "[redacted_path]";
|
|
296
|
-
}
|
|
297
|
-
if (withoutAbsolutePaths.length > 512) {
|
|
298
|
-
return `${withoutAbsolutePaths.slice(0, 509)}...`;
|
|
299
|
-
}
|
|
300
|
-
return withoutAbsolutePaths;
|
|
301
|
-
}
|
|
302
|
-
function sanitizeStringMax(input) {
|
|
303
|
-
const withoutCommonSensitiveTokens = sanitizeCommonSensitiveTokens(input);
|
|
304
|
-
const withoutInlineSecrets = redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);
|
|
305
|
-
const withoutAbsolutePaths = redactAbsolutePathTokens(withoutInlineSecrets);
|
|
306
|
-
const trimmed = withoutAbsolutePaths.trim();
|
|
307
|
-
if (trimmed.startsWith("/") && trimmed.length > 1) {
|
|
308
|
-
return "[redacted_path]";
|
|
309
|
-
}
|
|
310
|
-
if (withoutAbsolutePaths.length > 2048) {
|
|
311
|
-
return `${withoutAbsolutePaths.slice(0, 2045)}...`;
|
|
312
|
-
}
|
|
313
|
-
return withoutAbsolutePaths;
|
|
314
|
-
}
|
|
315
|
-
function sanitizeString(input, captureLevel = "redacted") {
|
|
316
|
-
if (captureLevel === "max") {
|
|
317
|
-
return sanitizeStringMax(input);
|
|
318
|
-
}
|
|
319
|
-
return sanitizeStringRedacted(input);
|
|
320
|
-
}
|
|
321
|
-
function sanitizeValue(value, keyHint, captureLevel = "redacted", depth = 0) {
|
|
322
|
-
if (keyHint && isSensitiveKey(keyHint)) {
|
|
323
|
-
return "[redacted]";
|
|
324
|
-
}
|
|
325
|
-
if (value === null || value === undefined) {
|
|
326
|
-
return value;
|
|
327
|
-
}
|
|
328
|
-
if (typeof value === "string") {
|
|
329
|
-
return sanitizeString(value, captureLevel);
|
|
330
|
-
}
|
|
331
|
-
if (typeof value === "number" || typeof value === "boolean") {
|
|
332
|
-
return value;
|
|
333
|
-
}
|
|
334
|
-
if (depth >= TELEMETRY_SANITIZE_MAX_DEPTH) {
|
|
335
|
-
return "[depth_truncated]";
|
|
336
|
-
}
|
|
337
|
-
if (Array.isArray(value)) {
|
|
338
|
-
return value
|
|
339
|
-
.slice(0, TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS)
|
|
340
|
-
.map((entry) => sanitizeValue(entry, undefined, captureLevel, depth + 1));
|
|
341
|
-
}
|
|
342
|
-
if (typeof value === "object") {
|
|
343
|
-
const record = value;
|
|
344
|
-
const sanitized = {};
|
|
345
|
-
for (const [key, nested] of Object.entries(record)) {
|
|
346
|
-
sanitized[key] = sanitizeValue(nested, key, captureLevel, depth + 1);
|
|
347
|
-
}
|
|
348
|
-
return sanitized;
|
|
349
|
-
}
|
|
350
|
-
return String(value);
|
|
351
|
-
}
|
|
352
|
-
function sanitizeCommandArgs(args, captureLevel = "redacted") {
|
|
353
|
-
const sanitized = [];
|
|
354
|
-
let nextIsSensitiveValue = false;
|
|
355
|
-
for (const rawArg of args) {
|
|
356
|
-
const arg = sanitizeString(rawArg, captureLevel);
|
|
357
|
-
if (nextIsSensitiveValue) {
|
|
358
|
-
sanitized.push("[redacted]");
|
|
359
|
-
nextIsSensitiveValue = false;
|
|
360
|
-
continue;
|
|
361
|
-
}
|
|
362
|
-
if (arg.startsWith("--")) {
|
|
363
|
-
const withoutPrefix = arg.slice(2);
|
|
364
|
-
const delimiterIndex = withoutPrefix.indexOf("=");
|
|
365
|
-
if (delimiterIndex >= 0) {
|
|
366
|
-
const key = withoutPrefix.slice(0, delimiterIndex);
|
|
367
|
-
const value = withoutPrefix.slice(delimiterIndex + 1);
|
|
368
|
-
if (isSensitiveKey(key)) {
|
|
369
|
-
sanitized.push(`--${key}=[redacted]`);
|
|
370
|
-
}
|
|
371
|
-
else {
|
|
372
|
-
sanitized.push(`--${key}=${sanitizeString(value, captureLevel)}`);
|
|
373
|
-
}
|
|
374
|
-
continue;
|
|
375
|
-
}
|
|
376
|
-
if (isSensitiveKey(withoutPrefix)) {
|
|
377
|
-
sanitized.push(`--${withoutPrefix}`);
|
|
378
|
-
nextIsSensitiveValue = true;
|
|
379
|
-
continue;
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
sanitized.push(arg);
|
|
383
|
-
}
|
|
384
|
-
return sanitized;
|
|
385
|
-
}
|
|
386
|
-
function normalizeCaptureLevel(value) {
|
|
387
|
-
const normalized = value?.trim().toLowerCase();
|
|
388
|
-
if (normalized === "minimal" ||
|
|
389
|
-
normalized === "redacted" ||
|
|
390
|
-
normalized === "max") {
|
|
391
|
-
return normalized;
|
|
392
|
-
}
|
|
393
|
-
return "redacted";
|
|
394
|
-
}
|
|
395
|
-
function parseBooleanTrueLike(value) {
|
|
396
|
-
return BOOLEAN_TRUE_VALUES.has((value ?? "").trim().toLowerCase());
|
|
397
|
-
}
|
|
398
|
-
/** Resolve the background event and OTLP request timeout within the flush-lock safety envelope. */
|
|
399
|
-
function resolveTelemetryHttpTimeoutMs() {
|
|
400
|
-
const rawConfigured = process.env[PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV]?.trim();
|
|
401
|
-
if (!rawConfigured) {
|
|
402
|
-
return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS;
|
|
403
|
-
}
|
|
404
|
-
const configured = Number(rawConfigured);
|
|
405
|
-
if (!Number.isFinite(configured)) {
|
|
406
|
-
return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS;
|
|
407
|
-
}
|
|
408
|
-
return Math.min(TELEMETRY_HTTP_TIMEOUT_MAX_MS, Math.max(TELEMETRY_HTTP_TIMEOUT_MIN_MS, Math.trunc(configured)));
|
|
409
|
-
}
|
|
410
|
-
/** POST a JSON payload with one total timeout that covers DNS, connection, TLS, and response completion. */
|
|
411
|
-
async function postTelemetryJson(endpoint, headers, body) {
|
|
412
|
-
const url = new URL(endpoint);
|
|
413
|
-
// A replaced global fetch is an intentional runtime adapter used by the
|
|
414
|
-
// repository's deterministic tests and by embedders that instrument network
|
|
415
|
-
// traffic. Production retains the native HTTP transport below so Node's
|
|
416
|
-
// independent built-in-fetch connect timeout cannot preempt our bound.
|
|
417
|
-
if (globalThis.fetch !== NATIVE_FETCH) {
|
|
418
|
-
const controller = new AbortController();
|
|
419
|
-
let timeout;
|
|
420
|
-
const deadline = new Promise((_resolve, reject) => {
|
|
421
|
-
timeout = setTimeout(() => {
|
|
422
|
-
controller.abort();
|
|
423
|
-
reject(new Error("telemetry_http_timeout"));
|
|
424
|
-
}, resolveTelemetryHttpTimeoutMs());
|
|
425
|
-
});
|
|
426
|
-
try {
|
|
427
|
-
const response = await Promise.race([
|
|
428
|
-
globalThis.fetch(endpoint, {
|
|
429
|
-
method: "POST",
|
|
430
|
-
headers,
|
|
431
|
-
body,
|
|
432
|
-
signal: controller.signal,
|
|
433
|
-
}),
|
|
434
|
-
deadline,
|
|
435
|
-
]);
|
|
436
|
-
return response.status;
|
|
437
|
-
}
|
|
438
|
-
finally {
|
|
439
|
-
clearTimeout(timeout);
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
const request = url.protocol === "https:"
|
|
443
|
-
? httpsRequest
|
|
444
|
-
: url.protocol === "http:"
|
|
445
|
-
? httpRequest
|
|
446
|
-
: undefined;
|
|
447
|
-
if (!request) {
|
|
448
|
-
throw new Error(`telemetry_http_protocol_unsupported_${url.protocol}`);
|
|
449
|
-
}
|
|
450
|
-
return new Promise((resolve, reject) => {
|
|
451
|
-
const timeoutMs = resolveTelemetryHttpTimeoutMs();
|
|
452
|
-
const requestOptions = {
|
|
453
|
-
method: "POST",
|
|
454
|
-
headers: {
|
|
455
|
-
...headers,
|
|
456
|
-
"content-length": Buffer.byteLength(body),
|
|
457
|
-
},
|
|
458
|
-
signal: AbortSignal.timeout(timeoutMs),
|
|
459
|
-
autoSelectFamilyAttemptTimeout: Math.min(5_000, timeoutMs),
|
|
460
|
-
};
|
|
461
|
-
const clientRequest = request(url, requestOptions, (response) => {
|
|
462
|
-
response.once("error", reject);
|
|
463
|
-
// Client responses always carry an HTTP status code; Node's shared
|
|
464
|
-
// IncomingMessage type is also used for server requests where it is absent.
|
|
465
|
-
response.once("end", () => resolve(response.statusCode));
|
|
466
|
-
response.resume();
|
|
467
|
-
});
|
|
468
|
-
clientRequest.once("error", reject);
|
|
469
|
-
clientRequest.end(body);
|
|
470
|
-
});
|
|
471
|
-
}
|
|
472
|
-
function normalizePmVersion(value) {
|
|
473
|
-
const trimmed = typeof value === "string" ? value.trim() : "";
|
|
474
|
-
return trimmed.length > 0 ? trimmed : "0.0.0";
|
|
475
|
-
}
|
|
476
|
-
function normalizeTelemetryErrorCode(value) {
|
|
477
|
-
const normalized = value?.trim();
|
|
478
|
-
return normalized && normalized.length > 0 ? normalized : undefined;
|
|
479
|
-
}
|
|
480
|
-
function normalizeTelemetryExitCode(exitCode, ok) {
|
|
481
|
-
if (Number.isFinite(exitCode)) {
|
|
482
|
-
return Math.max(0, Math.trunc(exitCode));
|
|
483
|
-
}
|
|
484
|
-
return ok ? 0 : 1;
|
|
485
|
-
}
|
|
486
|
-
function normalizeTelemetryErrorCategory(params) {
|
|
487
|
-
if (params.ok) {
|
|
488
|
-
return undefined;
|
|
489
|
-
}
|
|
490
|
-
if (typeof params.errorCategory === "string" &&
|
|
491
|
-
params.errorCategory.trim().length > 0) {
|
|
492
|
-
return params.errorCategory;
|
|
493
|
-
}
|
|
494
|
-
if (typeof params.errorCode === "string" &&
|
|
495
|
-
params.errorCode.trim().length > 0) {
|
|
496
|
-
return resolveTelemetryErrorCategory(params.errorCode);
|
|
497
|
-
}
|
|
498
|
-
return "unknown";
|
|
499
|
-
}
|
|
500
|
-
function resolveTelemetrySourceContext(globalOptions) {
|
|
501
|
-
const override = (process.env[PM_TELEMETRY_SOURCE_CONTEXT_ENV] ?? "")
|
|
502
|
-
.trim()
|
|
503
|
-
.toLowerCase();
|
|
504
|
-
if (PM_TELEMETRY_SOURCE_CONTEXT_SET.has(override)) {
|
|
505
|
-
return {
|
|
506
|
-
source_context: override,
|
|
507
|
-
source_context_source: "env_override",
|
|
508
|
-
};
|
|
509
|
-
}
|
|
510
|
-
const nodeEnv = (process.env.NODE_ENV ?? "").trim().toLowerCase();
|
|
511
|
-
if (typeof process.env.VITEST === "string" ||
|
|
512
|
-
typeof process.env.VITEST_WORKER_ID === "string" ||
|
|
513
|
-
nodeEnv === "test") {
|
|
514
|
-
return {
|
|
515
|
-
source_context: "test",
|
|
516
|
-
source_context_source: "inferred",
|
|
517
|
-
};
|
|
518
|
-
}
|
|
519
|
-
const nonTty = process.stdin.isTTY !== true || process.stdout.isTTY !== true;
|
|
520
|
-
const ci = parseBooleanTrueLike(process.env.CI);
|
|
521
|
-
const scriptLikeMode = globalOptions.json === true || globalOptions.quiet === true;
|
|
522
|
-
if (nonTty || ci || scriptLikeMode) {
|
|
523
|
-
return {
|
|
524
|
-
source_context: "automation",
|
|
525
|
-
source_context_source: "inferred",
|
|
526
|
-
};
|
|
527
|
-
}
|
|
528
|
-
return {
|
|
529
|
-
source_context: "user",
|
|
530
|
-
source_context_source: "inferred",
|
|
531
|
-
};
|
|
532
|
-
}
|
|
533
|
-
function hashWithInstallationId(installationId, value) {
|
|
534
|
-
return crypto
|
|
535
|
-
.createHash("sha256")
|
|
536
|
-
.update(`${installationId}:${value}`)
|
|
537
|
-
.digest("hex");
|
|
538
|
-
}
|
|
539
|
-
/**
|
|
540
|
-
* Builds privacy-bounded author and agent dimensions for a telemetry payload.
|
|
541
|
-
*
|
|
542
|
-
* The raw `PM_AUTHOR` value (e.g. `claude-code-agent`) is never emitted. At
|
|
543
|
-
* non-minimal capture levels a stable `author_context_hash` is attached — the
|
|
544
|
-
* same installation-id-keyed one-way hash used for `pm_root_hash`/`cwd_hash`, so
|
|
545
|
-
* agent-driven invocations can be segmented in Sentry/dashboards while the same
|
|
546
|
-
* author hashes differently across installations. Because the field is a one-way
|
|
547
|
-
* hash, it intentionally bypasses the {@link SENSITIVE_KEYWORDS} redaction path.
|
|
548
|
-
* Harness and model values use the same installation-keyed one-way hashing.
|
|
549
|
-
* Model source is a fixed enum and can be emitted directly. The local
|
|
550
|
-
* invocation/session identifier is deliberately excluded at every capture
|
|
551
|
-
* level. At minimal capture only presence booleans are surfaced.
|
|
552
|
-
*/
|
|
553
|
-
function buildAuthorContextPayloadFields(captureLevel, installationId) {
|
|
554
|
-
const author = (readAuthorEnvironment() ?? "").trim();
|
|
555
|
-
const agent = detectAgentIdentity({
|
|
556
|
-
env: process.env,
|
|
557
|
-
argv: process.argv,
|
|
558
|
-
});
|
|
559
|
-
const hasAgentContext = agent.harness !== undefined || agent.model !== undefined;
|
|
560
|
-
if (captureLevel === "minimal") {
|
|
561
|
-
return {
|
|
562
|
-
has_author_context: author.length > 0,
|
|
563
|
-
has_agent_context: hasAgentContext,
|
|
564
|
-
};
|
|
565
|
-
}
|
|
566
|
-
return {
|
|
567
|
-
...(author.length > 0
|
|
568
|
-
? {
|
|
569
|
-
author_context_hash: hashWithInstallationId(installationId, author),
|
|
570
|
-
}
|
|
571
|
-
: {}),
|
|
572
|
-
...(agent.harness
|
|
573
|
-
? {
|
|
574
|
-
agent_harness_hash: hashWithInstallationId(installationId, agent.harness),
|
|
575
|
-
}
|
|
576
|
-
: {}),
|
|
577
|
-
...(agent.model
|
|
578
|
-
? {
|
|
579
|
-
agent_model_hash: hashWithInstallationId(installationId, agent.model),
|
|
580
|
-
}
|
|
581
|
-
: {}),
|
|
582
|
-
...(agent.model_source
|
|
583
|
-
? { agent_model_source: agent.model_source }
|
|
584
|
-
: {}),
|
|
585
|
-
};
|
|
586
|
-
}
|
|
587
|
-
function normalizeForHash(value, depth = 0) {
|
|
588
|
-
if (value === null || value === undefined) {
|
|
589
|
-
return value;
|
|
590
|
-
}
|
|
591
|
-
if (typeof value === "string" ||
|
|
592
|
-
typeof value === "number" ||
|
|
593
|
-
typeof value === "boolean") {
|
|
594
|
-
return value;
|
|
595
|
-
}
|
|
596
|
-
if (depth >= TELEMETRY_SANITIZE_MAX_DEPTH) {
|
|
597
|
-
return "[depth_truncated]";
|
|
598
|
-
}
|
|
599
|
-
if (Array.isArray(value)) {
|
|
600
|
-
return value
|
|
601
|
-
.slice(0, TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS)
|
|
602
|
-
.map((entry) => normalizeForHash(entry, depth + 1));
|
|
603
|
-
}
|
|
604
|
-
if (typeof value === "object") {
|
|
605
|
-
const record = value;
|
|
606
|
-
const normalized = {};
|
|
607
|
-
const sortedKeys = Object.keys(record).sort((left, right) => left.localeCompare(right));
|
|
608
|
-
for (const key of sortedKeys) {
|
|
609
|
-
normalized[key] = normalizeForHash(record[key], depth + 1);
|
|
610
|
-
}
|
|
611
|
-
return normalized;
|
|
612
|
-
}
|
|
613
|
-
return String(value);
|
|
614
|
-
}
|
|
615
|
-
function hashTelemetryValue(installationId, value) {
|
|
616
|
-
return hashWithInstallationId(installationId, JSON.stringify(normalizeForHash(value)));
|
|
617
|
-
}
|
|
618
|
-
function hashCommandArgs(installationId, args) {
|
|
619
|
-
return {
|
|
620
|
-
hashes: args.map((arg) => hashWithInstallationId(installationId, arg)),
|
|
621
|
-
digest: hashWithInstallationId(installationId, args.join("\u0000")),
|
|
622
|
-
};
|
|
623
|
-
}
|
|
624
|
-
function hashTelemetryErrorFingerprint(installationId, command, errorCode, errorMessage) {
|
|
625
|
-
const normalizedMessage = sanitizeString(typeof errorMessage === "string" ? errorMessage : "", "redacted");
|
|
626
|
-
const normalizedCode = typeof errorCode === "string" && errorCode.length > 0
|
|
627
|
-
? errorCode
|
|
628
|
-
: "unknown_error";
|
|
629
|
-
const fingerprintSource = `${command}\u0000${normalizedCode}\u0000${normalizedMessage}`;
|
|
630
|
-
return hashWithInstallationId(installationId, fingerprintSource);
|
|
631
|
-
}
|
|
632
|
-
function telemetryDisabledByEnvironment() {
|
|
633
|
-
return (PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_TELEMETRY_DISABLED_ENV] ?? "").trim().toLowerCase()) ||
|
|
634
|
-
PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_NO_TELEMETRY_ENV] ?? "").trim().toLowerCase()));
|
|
635
|
-
}
|
|
636
|
-
function resolveOtelTracesEndpoint() {
|
|
637
|
-
if (PM_TELEMETRY_OTEL_DISABLED_VALUES.has((process.env[PM_TELEMETRY_OTEL_DISABLED_ENV] ?? "").trim().toLowerCase())) {
|
|
638
|
-
return null;
|
|
639
|
-
}
|
|
640
|
-
const directEndpoint = (process.env[OTEL_TRACES_ENDPOINT_ENV] ?? "").trim();
|
|
641
|
-
if (directEndpoint.length > 0) {
|
|
642
|
-
try {
|
|
643
|
-
return new URL(directEndpoint).toString();
|
|
644
|
-
}
|
|
645
|
-
catch {
|
|
646
|
-
return null;
|
|
647
|
-
}
|
|
648
|
-
}
|
|
649
|
-
const baseEndpoint = (process.env[OTEL_BASE_ENDPOINT_ENV] ?? "").trim();
|
|
650
|
-
if (baseEndpoint.length === 0) {
|
|
651
|
-
return null;
|
|
652
|
-
}
|
|
653
|
-
try {
|
|
654
|
-
const url = new URL(baseEndpoint);
|
|
655
|
-
const normalizedPath = url.pathname.replace(/\/+$/, "");
|
|
656
|
-
if (!normalizedPath.endsWith("/v1/traces")) {
|
|
657
|
-
url.pathname = `${normalizedPath.length === 0 ? "" : normalizedPath}/v1/traces`;
|
|
658
|
-
}
|
|
659
|
-
return url.toString();
|
|
660
|
-
}
|
|
661
|
-
catch {
|
|
662
|
-
return null;
|
|
663
|
-
}
|
|
664
|
-
}
|
|
665
|
-
function isoToUnixNano(iso) {
|
|
666
|
-
const parsedMs = Date.parse(iso);
|
|
667
|
-
const epochMs = Number.isNaN(parsedMs) ? Date.now() : parsedMs;
|
|
668
|
-
return `${BigInt(epochMs) * 1000000n}`;
|
|
669
|
-
}
|
|
670
|
-
function otlpStringAttribute(key, value) {
|
|
671
|
-
return {
|
|
672
|
-
key,
|
|
673
|
-
value: { stringValue: value },
|
|
674
|
-
};
|
|
675
|
-
}
|
|
676
|
-
function otlpBoolAttribute(key, value) {
|
|
677
|
-
return {
|
|
678
|
-
key,
|
|
679
|
-
value: { boolValue: value },
|
|
680
|
-
};
|
|
681
|
-
}
|
|
682
|
-
function otlpIntAttribute(key, value) {
|
|
683
|
-
return {
|
|
684
|
-
key,
|
|
685
|
-
value: { intValue: String(Math.max(0, Math.trunc(value))) },
|
|
686
|
-
};
|
|
687
|
-
}
|
|
688
|
-
/**
|
|
689
|
-
* Build the OTLP trace-export request for a finished command without performing
|
|
690
|
-
* any network I/O. Returns `null` when OTLP export is not configured (no traces
|
|
691
|
-
* endpoint / trace ids). The actual POST is deferred to the detached flush worker
|
|
692
|
-
* via {@link enqueuePendingOtelSpan} so the foreground command never blocks on a
|
|
693
|
-
* connecting socket (GH-209).
|
|
694
|
-
*/
|
|
695
|
-
function buildOtelSpanRequest(activeCommand, outcome, finishedAtIso, durationMs) {
|
|
696
|
-
if (typeof activeCommand.otel_traces_endpoint !== "string" ||
|
|
697
|
-
activeCommand.otel_traces_endpoint.trim().length === 0 ||
|
|
698
|
-
typeof activeCommand.otel_trace_id !== "string" ||
|
|
699
|
-
activeCommand.otel_trace_id.length === 0 ||
|
|
700
|
-
typeof activeCommand.otel_span_id !== "string" ||
|
|
701
|
-
activeCommand.otel_span_id.length === 0) {
|
|
702
|
-
return null;
|
|
703
|
-
}
|
|
704
|
-
const serviceNameCandidate = sanitizeString((process.env[OTEL_SERVICE_NAME_ENV] ?? "").trim());
|
|
705
|
-
const serviceName = serviceNameCandidate.length > 0 ? serviceNameCandidate : "pm-cli";
|
|
706
|
-
const normalizedExitCode = normalizeTelemetryExitCode(outcome.exit_code, outcome.ok);
|
|
707
|
-
const normalizedErrorCode = normalizeTelemetryErrorCode(outcome.error_code);
|
|
708
|
-
const normalizedErrorCategory = normalizeTelemetryErrorCategory({
|
|
709
|
-
ok: outcome.ok,
|
|
710
|
-
errorCode: normalizedErrorCode,
|
|
711
|
-
errorCategory: outcome.error_category,
|
|
712
|
-
});
|
|
713
|
-
const attributes = [
|
|
714
|
-
otlpStringAttribute("pm.command", sanitizeString(activeCommand.command)),
|
|
715
|
-
otlpStringAttribute("pm.version", activeCommand.pm_version),
|
|
716
|
-
otlpStringAttribute("pm.source_context", activeCommand.source_context),
|
|
717
|
-
otlpStringAttribute("pm.source_context_source", activeCommand.source_context_source),
|
|
718
|
-
otlpStringAttribute("pm.installation_id", activeCommand.installation_id),
|
|
719
|
-
otlpStringAttribute("pm.session_id", PROCESS_SESSION_ID),
|
|
720
|
-
otlpStringAttribute("pm.pm_root_hash", activeCommand.pm_root_hash),
|
|
721
|
-
otlpStringAttribute("pm.cwd_hash", activeCommand.cwd_hash),
|
|
722
|
-
otlpBoolAttribute("pm.ok", outcome.ok),
|
|
723
|
-
otlpIntAttribute("pm.exit_code", normalizedExitCode),
|
|
724
|
-
otlpIntAttribute("pm.duration_ms", durationMs),
|
|
725
|
-
];
|
|
726
|
-
if (typeof normalizedErrorCode === "string") {
|
|
727
|
-
attributes.push(otlpStringAttribute("pm.error_code", normalizedErrorCode));
|
|
728
|
-
}
|
|
729
|
-
if (typeof normalizedErrorCategory === "string") {
|
|
730
|
-
attributes.push(otlpStringAttribute("pm.error_category", normalizedErrorCategory));
|
|
731
|
-
}
|
|
732
|
-
if (typeof outcome.error === "string" && outcome.error.trim().length > 0) {
|
|
733
|
-
attributes.push(otlpStringAttribute("pm.error", sanitizeString(outcome.error)));
|
|
734
|
-
}
|
|
735
|
-
const payload = {
|
|
736
|
-
resourceSpans: [
|
|
737
|
-
{
|
|
738
|
-
resource: {
|
|
739
|
-
attributes: [otlpStringAttribute("service.name", serviceName)],
|
|
740
|
-
},
|
|
741
|
-
scopeSpans: [
|
|
742
|
-
{
|
|
743
|
-
scope: {
|
|
744
|
-
name: "pm-cli.telemetry",
|
|
745
|
-
version: "1",
|
|
746
|
-
},
|
|
747
|
-
spans: [
|
|
748
|
-
{
|
|
749
|
-
traceId: activeCommand.otel_trace_id,
|
|
750
|
-
spanId: activeCommand.otel_span_id,
|
|
751
|
-
name: `pm.command.${sanitizeString(activeCommand.command)}`,
|
|
752
|
-
kind: 1,
|
|
753
|
-
startTimeUnixNano: isoToUnixNano(activeCommand.started_at),
|
|
754
|
-
endTimeUnixNano: isoToUnixNano(finishedAtIso),
|
|
755
|
-
attributes,
|
|
756
|
-
status: {
|
|
757
|
-
code: outcome.ok ? 1 : 2,
|
|
758
|
-
message: outcome.ok
|
|
759
|
-
? ""
|
|
760
|
-
: sanitizeString(typeof outcome.error === "string"
|
|
761
|
-
? outcome.error
|
|
762
|
-
: "command_failed"),
|
|
763
|
-
},
|
|
764
|
-
},
|
|
765
|
-
],
|
|
766
|
-
},
|
|
767
|
-
],
|
|
768
|
-
},
|
|
769
|
-
],
|
|
770
|
-
};
|
|
771
|
-
return { endpoint: activeCommand.otel_traces_endpoint, payload };
|
|
772
|
-
}
|
|
773
|
-
function summarizeResult(result, captureLevel = "redacted") {
|
|
774
|
-
if (result === null || result === undefined) {
|
|
775
|
-
return { type: "nullish" };
|
|
776
|
-
}
|
|
777
|
-
if (typeof result === "string") {
|
|
778
|
-
return { type: "string", value: sanitizeString(result, captureLevel) };
|
|
779
|
-
}
|
|
780
|
-
if (typeof result === "number" || typeof result === "boolean") {
|
|
781
|
-
return { type: typeof result, value: result };
|
|
782
|
-
}
|
|
783
|
-
if (Array.isArray(result)) {
|
|
784
|
-
return {
|
|
785
|
-
type: "array",
|
|
786
|
-
length: result.length,
|
|
787
|
-
sample: result
|
|
788
|
-
.slice(0, 5)
|
|
789
|
-
.map((entry) => sanitizeValue(entry, undefined, captureLevel)),
|
|
790
|
-
};
|
|
791
|
-
}
|
|
792
|
-
if (typeof result === "object") {
|
|
793
|
-
const record = result;
|
|
794
|
-
const keys = Object.keys(record).sort((left, right) => left.localeCompare(right));
|
|
795
|
-
const sanitized = {};
|
|
796
|
-
let previewBytes = 0;
|
|
797
|
-
for (const key of keys.slice(0, 25)) {
|
|
798
|
-
const sanitizedValue = sanitizeValue(record[key], key, captureLevel);
|
|
799
|
-
const entrySize = JSON.stringify(sanitizedValue).length;
|
|
800
|
-
if (previewBytes + entrySize > TELEMETRY_RESULT_PREVIEW_MAX_BYTES) {
|
|
801
|
-
sanitized[key] = "[preview_truncated]";
|
|
802
|
-
break;
|
|
803
|
-
}
|
|
804
|
-
previewBytes += entrySize;
|
|
805
|
-
sanitized[key] = sanitizedValue;
|
|
806
|
-
}
|
|
807
|
-
return {
|
|
808
|
-
type: "object",
|
|
809
|
-
key_count: keys.length,
|
|
810
|
-
keys_preview: keys.slice(0, 50),
|
|
811
|
-
preview: sanitized,
|
|
812
|
-
};
|
|
813
|
-
}
|
|
814
|
-
return { type: typeof result, value: String(result) };
|
|
815
|
-
}
|
|
816
|
-
function buildCommandStartPayload(params) {
|
|
817
|
-
const { captureLevel, context, pmVersion, sourceContext, pmRootHash, cwdHash, installationId, } = params;
|
|
818
|
-
const commandTaxonomy = deriveTelemetryCommandTaxonomy(context.command);
|
|
819
|
-
const hashedArgs = hashCommandArgs(installationId, context.args);
|
|
820
|
-
const commandInvocationDigest = hashWithInstallationId(installationId, `${context.command}\u0000${context.args.join("\u0000")}`);
|
|
821
|
-
const commandOptionsDigest = hashTelemetryValue(installationId, context.options);
|
|
822
|
-
const globalOptionsDigest = hashTelemetryValue(installationId, context.global);
|
|
823
|
-
const authorContextFields = buildAuthorContextPayloadFields(captureLevel, installationId);
|
|
824
|
-
if (captureLevel === "minimal") {
|
|
825
|
-
return {
|
|
826
|
-
capture_level: captureLevel,
|
|
827
|
-
pm_version: pmVersion,
|
|
828
|
-
source_context: sourceContext.source_context,
|
|
829
|
-
source_context_source: sourceContext.source_context_source,
|
|
830
|
-
command_taxonomy: commandTaxonomy,
|
|
831
|
-
command_args_digest: hashedArgs.digest,
|
|
832
|
-
command_invocation_digest: commandInvocationDigest,
|
|
833
|
-
command_options_digest: commandOptionsDigest,
|
|
834
|
-
global_options_digest: globalOptionsDigest,
|
|
835
|
-
...authorContextFields,
|
|
836
|
-
};
|
|
837
|
-
}
|
|
838
|
-
return {
|
|
839
|
-
pm_version: pmVersion,
|
|
840
|
-
source_context: sourceContext.source_context,
|
|
841
|
-
source_context_source: sourceContext.source_context_source,
|
|
842
|
-
command_taxonomy: commandTaxonomy,
|
|
843
|
-
...authorContextFields,
|
|
844
|
-
command_args: sanitizeCommandArgs(context.args, captureLevel),
|
|
845
|
-
command_args_hashes: hashedArgs.hashes,
|
|
846
|
-
command_args_digest: hashedArgs.digest,
|
|
847
|
-
command_invocation_digest: commandInvocationDigest,
|
|
848
|
-
command_options: sanitizeValue(context.options, undefined, captureLevel),
|
|
849
|
-
command_options_digest: commandOptionsDigest,
|
|
850
|
-
global_options: sanitizeValue(context.global, undefined, captureLevel),
|
|
851
|
-
global_options_digest: globalOptionsDigest,
|
|
852
|
-
pm_root_hash: pmRootHash,
|
|
853
|
-
cwd_hash: cwdHash,
|
|
854
|
-
capture_level: captureLevel,
|
|
855
|
-
runtime: {
|
|
856
|
-
node: process.version,
|
|
857
|
-
platform: process.platform,
|
|
858
|
-
arch: process.arch,
|
|
859
|
-
hostname_hash: hashWithInstallationId(installationId, os.hostname()),
|
|
860
|
-
stdin_tty: process.stdin.isTTY === true,
|
|
861
|
-
stdout_tty: process.stdout.isTTY === true,
|
|
862
|
-
},
|
|
863
|
-
};
|
|
864
|
-
}
|
|
865
|
-
function buildCommandFinishPayload(params) {
|
|
866
|
-
const { captureLevel, pmVersion, sourceContext, outcome, durationMs, startedAt, command, installationId, commandTaxonomy, exitCode, errorCode, errorCategory, commandResolution, resolutionStage, } = params;
|
|
867
|
-
const errorFingerprint = outcome.ok === false
|
|
868
|
-
? hashTelemetryErrorFingerprint(installationId, command, errorCode, outcome.error)
|
|
869
|
-
: undefined;
|
|
870
|
-
const authorContextFields = buildAuthorContextPayloadFields(captureLevel, installationId);
|
|
871
|
-
if (captureLevel === "minimal") {
|
|
872
|
-
return {
|
|
873
|
-
capture_level: captureLevel,
|
|
874
|
-
pm_version: pmVersion,
|
|
875
|
-
source_context: sourceContext.source_context,
|
|
876
|
-
source_context_source: sourceContext.source_context_source,
|
|
877
|
-
command_taxonomy: commandTaxonomy,
|
|
878
|
-
command_resolution: commandResolution,
|
|
879
|
-
resolution_stage: resolutionStage,
|
|
880
|
-
ok: outcome.ok,
|
|
881
|
-
exit_code: exitCode,
|
|
882
|
-
error_code: errorCode,
|
|
883
|
-
error_category: errorCategory,
|
|
884
|
-
error: outcome.error
|
|
885
|
-
? sanitizeString(outcome.error, "redacted")
|
|
886
|
-
: undefined,
|
|
887
|
-
error_fingerprint: errorFingerprint,
|
|
888
|
-
duration_ms: durationMs,
|
|
889
|
-
...authorContextFields,
|
|
890
|
-
};
|
|
891
|
-
}
|
|
892
|
-
return {
|
|
893
|
-
capture_level: captureLevel,
|
|
894
|
-
pm_version: pmVersion,
|
|
895
|
-
source_context: sourceContext.source_context,
|
|
896
|
-
source_context_source: sourceContext.source_context_source,
|
|
897
|
-
command_taxonomy: commandTaxonomy,
|
|
898
|
-
command_resolution: commandResolution,
|
|
899
|
-
resolution_stage: resolutionStage,
|
|
900
|
-
...authorContextFields,
|
|
901
|
-
ok: outcome.ok,
|
|
902
|
-
exit_code: exitCode,
|
|
903
|
-
error_code: errorCode,
|
|
904
|
-
error_category: errorCategory,
|
|
905
|
-
error: outcome.error
|
|
906
|
-
? sanitizeString(outcome.error, captureLevel)
|
|
907
|
-
: undefined,
|
|
908
|
-
error_fingerprint: errorFingerprint,
|
|
909
|
-
duration_ms: durationMs,
|
|
910
|
-
started_at: startedAt,
|
|
911
|
-
result_summary: summarizeResult(outcome.result, captureLevel),
|
|
912
|
-
};
|
|
913
|
-
}
|
|
914
|
-
function buildCommandErrorPayload(params) {
|
|
915
|
-
const { captureLevel, pmVersion, sourceContext, command, commandTaxonomy, commandResolution, resolutionStage, args, options, pmRootHash, cwdHash, installationId, errorCode, errorMessage, errorCategory, exitCode, } = params;
|
|
916
|
-
const attemptedArgHashes = hashCommandArgs(installationId, args);
|
|
917
|
-
const attemptedCommandDigest = hashWithInstallationId(installationId, command);
|
|
918
|
-
const attemptedOptionsDigest = hashTelemetryValue(installationId, options);
|
|
919
|
-
const errorFingerprint = hashTelemetryErrorFingerprint(installationId, command, errorCode, errorMessage);
|
|
920
|
-
const authorContextFields = buildAuthorContextPayloadFields(captureLevel, installationId);
|
|
921
|
-
if (captureLevel === "minimal") {
|
|
922
|
-
return {
|
|
923
|
-
capture_level: captureLevel,
|
|
924
|
-
pm_version: pmVersion,
|
|
925
|
-
source_context: sourceContext.source_context,
|
|
926
|
-
source_context_source: sourceContext.source_context_source,
|
|
927
|
-
command_taxonomy: commandTaxonomy,
|
|
928
|
-
command_resolution: commandResolution,
|
|
929
|
-
resolution_stage: resolutionStage,
|
|
930
|
-
attempted_command_digest: attemptedCommandDigest,
|
|
931
|
-
attempted_args_digest: attemptedArgHashes.digest,
|
|
932
|
-
attempted_options_digest: attemptedOptionsDigest,
|
|
933
|
-
error_code: errorCode,
|
|
934
|
-
error_category: errorCategory,
|
|
935
|
-
exit_code: exitCode,
|
|
936
|
-
error: sanitizeString(errorMessage, "redacted"),
|
|
937
|
-
error_fingerprint: errorFingerprint,
|
|
938
|
-
...authorContextFields,
|
|
939
|
-
};
|
|
940
|
-
}
|
|
941
|
-
return {
|
|
942
|
-
capture_level: captureLevel,
|
|
943
|
-
pm_version: pmVersion,
|
|
944
|
-
source_context: sourceContext.source_context,
|
|
945
|
-
source_context_source: sourceContext.source_context_source,
|
|
946
|
-
command_taxonomy: commandTaxonomy,
|
|
947
|
-
command_resolution: commandResolution,
|
|
948
|
-
resolution_stage: resolutionStage,
|
|
949
|
-
...authorContextFields,
|
|
950
|
-
attempted_command: sanitizeString(command, captureLevel),
|
|
951
|
-
attempted_command_digest: attemptedCommandDigest,
|
|
952
|
-
attempted_args: sanitizeCommandArgs(args, captureLevel),
|
|
953
|
-
attempted_args_hashes: attemptedArgHashes.hashes,
|
|
954
|
-
attempted_args_digest: attemptedArgHashes.digest,
|
|
955
|
-
attempted_options: sanitizeValue(options, undefined, captureLevel),
|
|
956
|
-
attempted_options_digest: attemptedOptionsDigest,
|
|
957
|
-
error_code: errorCode,
|
|
958
|
-
error_category: errorCategory,
|
|
959
|
-
exit_code: exitCode,
|
|
960
|
-
error: sanitizeString(errorMessage, captureLevel),
|
|
961
|
-
error_fingerprint: errorFingerprint,
|
|
962
|
-
pm_root_hash: pmRootHash,
|
|
963
|
-
cwd_hash: cwdHash,
|
|
964
|
-
runtime: {
|
|
965
|
-
node: process.version,
|
|
966
|
-
platform: process.platform,
|
|
967
|
-
arch: process.arch,
|
|
968
|
-
hostname_hash: hashWithInstallationId(installationId, os.hostname()),
|
|
969
|
-
stdin_tty: process.stdin.isTTY === true,
|
|
970
|
-
stdout_tty: process.stdout.isTTY === true,
|
|
971
|
-
},
|
|
972
|
-
};
|
|
973
|
-
}
|
|
974
|
-
async function ensureInstallationId(globalPmRoot) {
|
|
975
|
-
const settings = await readSettings(globalPmRoot);
|
|
976
|
-
let changed = false;
|
|
977
|
-
if (settings.telemetry.installation_id.trim().length === 0) {
|
|
978
|
-
settings.telemetry.installation_id = crypto.randomUUID();
|
|
979
|
-
changed = true;
|
|
980
|
-
}
|
|
981
|
-
if (changed) {
|
|
982
|
-
await writeSettings(globalPmRoot, settings, "telemetry:install_id");
|
|
983
|
-
}
|
|
984
|
-
return {
|
|
985
|
-
installationId: settings.telemetry.installation_id,
|
|
986
|
-
endpoint: settings.telemetry.endpoint,
|
|
987
|
-
retentionDays: Math.max(1, Math.trunc(settings.telemetry.retention_days)),
|
|
988
|
-
};
|
|
989
|
-
}
|
|
990
|
-
async function enqueueTelemetryEvent(globalPmRoot, event) {
|
|
991
|
-
const queued = {
|
|
992
|
-
client_schema_version: TELEMETRY_CLIENT_SCHEMA_VERSION,
|
|
993
|
-
event,
|
|
994
|
-
attempts: 0,
|
|
995
|
-
};
|
|
996
|
-
let serialized = JSON.stringify(queued);
|
|
997
|
-
if (serialized.length > TELEMETRY_MAX_EVENT_BYTES) {
|
|
998
|
-
const trimmed = {
|
|
999
|
-
...event,
|
|
1000
|
-
payload: {
|
|
1001
|
-
...event.payload,
|
|
1002
|
-
result_summary: {
|
|
1003
|
-
truncated: true,
|
|
1004
|
-
reason: "payload_size_exceeded",
|
|
1005
|
-
original_bytes: serialized.length,
|
|
1006
|
-
},
|
|
1007
|
-
},
|
|
1008
|
-
};
|
|
1009
|
-
const trimmedQueued = {
|
|
1010
|
-
client_schema_version: TELEMETRY_CLIENT_SCHEMA_VERSION,
|
|
1011
|
-
event: trimmed,
|
|
1012
|
-
attempts: 0,
|
|
1013
|
-
};
|
|
1014
|
-
serialized = JSON.stringify(trimmedQueued);
|
|
1015
|
-
}
|
|
1016
|
-
await withQueueMutation(async () => {
|
|
1017
|
-
await appendLineAtomic(queuePath(globalPmRoot), serialized);
|
|
1018
|
-
});
|
|
1019
|
-
}
|
|
1020
|
-
function parseQueueLines(raw) {
|
|
1021
|
-
const entries = [];
|
|
1022
|
-
for (const line of raw.split("\n")) {
|
|
1023
|
-
const trimmed = line.trim();
|
|
1024
|
-
if (trimmed.length === 0) {
|
|
1025
|
-
continue;
|
|
1026
|
-
}
|
|
1027
|
-
try {
|
|
1028
|
-
const parsed = JSON.parse(trimmed);
|
|
1029
|
-
if (parsed &&
|
|
1030
|
-
typeof parsed === "object" &&
|
|
1031
|
-
parsed.event &&
|
|
1032
|
-
typeof parsed.event === "object" &&
|
|
1033
|
-
typeof parsed.attempts === "number" &&
|
|
1034
|
-
(parsed.client_schema_version === undefined ||
|
|
1035
|
-
(typeof parsed.client_schema_version === "number" &&
|
|
1036
|
-
Number.isFinite(parsed.client_schema_version)))) {
|
|
1037
|
-
entries.push(parsed);
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
catch {
|
|
1041
|
-
// Drop malformed lines to preserve queue forward progress.
|
|
1042
|
-
}
|
|
1043
|
-
}
|
|
1044
|
-
return entries;
|
|
1045
|
-
}
|
|
1046
|
-
function nextRetryIso(attempts) {
|
|
1047
|
-
const delay = Math.min(TELEMETRY_RETRY_BASE_DELAY_MS * 2 ** Math.max(attempts - 1, 0), TELEMETRY_MAX_RETRY_DELAY_MS);
|
|
1048
|
-
return new Date(Date.now() + delay).toISOString();
|
|
1049
|
-
}
|
|
1050
|
-
function isDueForRetryAt(nextAttemptAfter) {
|
|
1051
|
-
if (typeof nextAttemptAfter !== "string" ||
|
|
1052
|
-
nextAttemptAfter.trim().length === 0) {
|
|
1053
|
-
return true;
|
|
1054
|
-
}
|
|
1055
|
-
const dueAtMs = Date.parse(nextAttemptAfter);
|
|
1056
|
-
if (Number.isNaN(dueAtMs)) {
|
|
1057
|
-
return true;
|
|
1058
|
-
}
|
|
1059
|
-
return dueAtMs <= Date.now();
|
|
1060
|
-
}
|
|
1061
|
-
function isDueForRetry(entry) {
|
|
1062
|
-
return isDueForRetryAt(entry.next_attempt_after);
|
|
1063
|
-
}
|
|
1064
|
-
function retentionCutoffMs(retentionDays) {
|
|
1065
|
-
const normalizedDays = Number.isFinite(retentionDays)
|
|
1066
|
-
? Math.max(1, Math.trunc(retentionDays))
|
|
1067
|
-
: 1;
|
|
1068
|
-
return Date.now() - normalizedDays * MILLISECONDS_PER_DAY;
|
|
1069
|
-
}
|
|
1070
|
-
function isExpiredQueueEntry(entry, cutoffMs) {
|
|
1071
|
-
const occurredAt = entry.event?.occurred_at;
|
|
1072
|
-
if (typeof occurredAt !== "string" || occurredAt.trim().length === 0) {
|
|
1073
|
-
return false;
|
|
1074
|
-
}
|
|
1075
|
-
const occurredAtMs = Date.parse(occurredAt);
|
|
1076
|
-
if (Number.isNaN(occurredAtMs)) {
|
|
1077
|
-
return false;
|
|
1078
|
-
}
|
|
1079
|
-
return occurredAtMs < cutoffMs;
|
|
1080
|
-
}
|
|
1081
|
-
function pruneExpiredQueueEntries(entries, retentionDays) {
|
|
1082
|
-
const cutoffMs = retentionCutoffMs(retentionDays);
|
|
1083
|
-
const retained = [];
|
|
1084
|
-
let prunedCount = 0;
|
|
1085
|
-
for (const entry of entries) {
|
|
1086
|
-
const serializedSize = JSON.stringify(entry).length;
|
|
1087
|
-
const oversized = serializedSize > TELEMETRY_MAX_EVENT_BYTES;
|
|
1088
|
-
if (oversized ||
|
|
1089
|
-
isExpiredQueueEntry(entry, cutoffMs) ||
|
|
1090
|
-
entry.attempts >= TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS) {
|
|
1091
|
-
prunedCount += 1;
|
|
1092
|
-
continue;
|
|
1093
|
-
}
|
|
1094
|
-
retained.push(entry);
|
|
1095
|
-
}
|
|
1096
|
-
return { entries: retained, prunedCount };
|
|
1097
|
-
}
|
|
1098
|
-
async function rewriteQueue(globalPmRoot, entries) {
|
|
1099
|
-
const serialized = entries.map((entry) => JSON.stringify(entry)).join("\n");
|
|
1100
|
-
const contents = serialized.length > 0 ? `${serialized}\n` : "";
|
|
1101
|
-
for (let attempt = 0;; attempt += 1) {
|
|
1102
|
-
try {
|
|
1103
|
-
await writeFileAtomic(queuePath(globalPmRoot), contents);
|
|
1104
|
-
return;
|
|
1105
|
-
}
|
|
1106
|
-
catch (error) {
|
|
1107
|
-
const retryDelay = TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];
|
|
1108
|
-
if (retryDelay === undefined || !isRetryableQueueRewriteError(error)) {
|
|
1109
|
-
throw error;
|
|
1110
|
-
}
|
|
1111
|
-
await sleep(retryDelay);
|
|
1112
|
-
}
|
|
1113
|
-
}
|
|
1114
|
-
}
|
|
1115
|
-
function isRetryableQueueRewriteError(error) {
|
|
1116
|
-
if (typeof error !== "object" || error === null || !("code" in error)) {
|
|
1117
|
-
return false;
|
|
1118
|
-
}
|
|
1119
|
-
const code = error.code;
|
|
1120
|
-
return code === "EACCES" || code === "EBUSY" || code === "EPERM";
|
|
1121
|
-
}
|
|
1122
|
-
function sleep(milliseconds) {
|
|
1123
|
-
return new Promise((resolve) => {
|
|
1124
|
-
setTimeout(resolve, milliseconds);
|
|
1125
|
-
});
|
|
1126
|
-
}
|
|
1127
|
-
/** Append a built OTLP span request to the bounded pending-spans queue. The detached flush worker drains and POSTs these so the foreground command never performs OTLP network I/O (GH-209). Best effort: a write failure never blocks the command, and the span is simply not exported. */
|
|
1128
|
-
async function enqueuePendingOtelSpan(globalPmRoot, request) {
|
|
1129
|
-
const pending = {
|
|
1130
|
-
id: crypto.randomUUID(),
|
|
1131
|
-
endpoint: request.endpoint,
|
|
1132
|
-
payload: request.payload,
|
|
1133
|
-
enqueued_at: nowIso(),
|
|
1134
|
-
attempts: 0,
|
|
1135
|
-
};
|
|
1136
|
-
const serialized = JSON.stringify(pending);
|
|
1137
|
-
// Drop oversized spans rather than poison the queue; they would never flush.
|
|
1138
|
-
if (serialized.length > TELEMETRY_MAX_EVENT_BYTES) {
|
|
1139
|
-
return;
|
|
1140
|
-
}
|
|
1141
|
-
await withQueueMutation(async () => {
|
|
1142
|
-
await appendLineAtomic(otelSpansQueuePath(globalPmRoot), serialized);
|
|
1143
|
-
});
|
|
1144
|
-
}
|
|
1145
|
-
/** Derive a stable id for a legacy id-less pending span from its identity fields. Deterministic so the same on-disk line yields the same id across reads, which is what lets reconciliation remove/update it after a flush. */
|
|
1146
|
-
function backfillPendingOtelSpanId(entry) {
|
|
1147
|
-
const material = JSON.stringify([
|
|
1148
|
-
entry.endpoint,
|
|
1149
|
-
entry.enqueued_at,
|
|
1150
|
-
entry.payload,
|
|
1151
|
-
]);
|
|
1152
|
-
return crypto
|
|
1153
|
-
.createHash("sha256")
|
|
1154
|
-
.update(material)
|
|
1155
|
-
.digest("hex")
|
|
1156
|
-
.slice(0, 32);
|
|
1157
|
-
}
|
|
1158
|
-
function parsePendingOtelSpanLines(raw) {
|
|
1159
|
-
const entries = [];
|
|
1160
|
-
for (const line of raw.split("\n")) {
|
|
1161
|
-
const trimmed = line.trim();
|
|
1162
|
-
if (trimmed.length === 0) {
|
|
1163
|
-
continue;
|
|
1164
|
-
}
|
|
1165
|
-
try {
|
|
1166
|
-
const parsed = JSON.parse(trimmed);
|
|
1167
|
-
if (parsed &&
|
|
1168
|
-
typeof parsed === "object" &&
|
|
1169
|
-
typeof parsed.endpoint === "string" &&
|
|
1170
|
-
parsed.endpoint.trim().length > 0 &&
|
|
1171
|
-
"payload" in parsed &&
|
|
1172
|
-
typeof parsed.attempts === "number" &&
|
|
1173
|
-
Number.isFinite(parsed.attempts)) {
|
|
1174
|
-
// Backfill an id for legacy entries written before id tracking existed.
|
|
1175
|
-
// It MUST be deterministic from the entry's content so the post-flush
|
|
1176
|
-
// re-read derives the same id and reconciliation can address the entry;
|
|
1177
|
-
// a random id would differ between reads and strand the span.
|
|
1178
|
-
if (typeof parsed.id !== "string" || parsed.id.length === 0) {
|
|
1179
|
-
parsed.id = backfillPendingOtelSpanId(parsed);
|
|
1180
|
-
}
|
|
1181
|
-
entries.push(parsed);
|
|
1182
|
-
}
|
|
1183
|
-
}
|
|
1184
|
-
catch {
|
|
1185
|
-
// Drop malformed lines to preserve forward progress.
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
return entries;
|
|
1189
|
-
}
|
|
1190
|
-
function isExpiredPendingOtelSpan(entry, cutoffMs) {
|
|
1191
|
-
if (typeof entry.enqueued_at !== "string" ||
|
|
1192
|
-
entry.enqueued_at.trim().length === 0) {
|
|
1193
|
-
return false;
|
|
1194
|
-
}
|
|
1195
|
-
const enqueuedAtMs = Date.parse(entry.enqueued_at);
|
|
1196
|
-
if (Number.isNaN(enqueuedAtMs)) {
|
|
1197
|
-
return false;
|
|
1198
|
-
}
|
|
1199
|
-
return enqueuedAtMs < cutoffMs;
|
|
1200
|
-
}
|
|
1201
|
-
function prunePendingOtelSpans(entries, retentionDays) {
|
|
1202
|
-
const cutoffMs = retentionCutoffMs(retentionDays);
|
|
1203
|
-
const retained = [];
|
|
1204
|
-
let prunedCount = 0;
|
|
1205
|
-
for (const entry of entries) {
|
|
1206
|
-
const oversized = JSON.stringify(entry).length > TELEMETRY_MAX_EVENT_BYTES;
|
|
1207
|
-
if (oversized ||
|
|
1208
|
-
isExpiredPendingOtelSpan(entry, cutoffMs) ||
|
|
1209
|
-
entry.attempts >= TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS) {
|
|
1210
|
-
prunedCount += 1;
|
|
1211
|
-
continue;
|
|
1212
|
-
}
|
|
1213
|
-
retained.push(entry);
|
|
1214
|
-
}
|
|
1215
|
-
if (retained.length > TELEMETRY_OTEL_SPANS_MAX_PENDING) {
|
|
1216
|
-
const overflow = retained.length - TELEMETRY_OTEL_SPANS_MAX_PENDING;
|
|
1217
|
-
prunedCount += overflow;
|
|
1218
|
-
// Keep the most recently enqueued spans; oldest beyond the cap are dropped.
|
|
1219
|
-
return { entries: retained.slice(overflow), prunedCount };
|
|
1220
|
-
}
|
|
1221
|
-
return { entries: retained, prunedCount };
|
|
1222
|
-
}
|
|
1223
|
-
async function rewritePendingOtelSpans(globalPmRoot, entries) {
|
|
1224
|
-
const serialized = entries.map((entry) => JSON.stringify(entry)).join("\n");
|
|
1225
|
-
const contents = serialized.length > 0 ? `${serialized}\n` : "";
|
|
1226
|
-
for (let attempt = 0;; attempt += 1) {
|
|
1227
|
-
try {
|
|
1228
|
-
await writeFileAtomic(otelSpansQueuePath(globalPmRoot), contents);
|
|
1229
|
-
return;
|
|
1230
|
-
}
|
|
1231
|
-
catch (error) {
|
|
1232
|
-
const retryDelay = TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];
|
|
1233
|
-
if (retryDelay === undefined || !isRetryableQueueRewriteError(error)) {
|
|
1234
|
-
throw error;
|
|
1235
|
-
}
|
|
1236
|
-
await sleep(retryDelay);
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
}
|
|
1240
|
-
/** Drain the pending OTLP span queue and POST due spans to their traces endpoint. Runs only inside the flush worker (detached child) or the inline test path, so the foreground command never makes OTLP network calls. Failures increment per-span attempts with backoff and are retried by a later flush; runtime state records OTLP export diagnostics for `pm health` (GH-205). */
|
|
1241
|
-
/** Re-read the spans queue under the mutation serializer and rewrite it with the processed spans removed/updated by id, preserving any spans a concurrent foreground process appended during the (network) flush window. `succeededIds` are dropped; `failedUpdates` patch attempts/next_attempt_after by id; all other (incl. newly-appended) entries are retained, then pruned. Returns the count of spans left in the queue. Mirrors removeFlushedEntriesFromCurrentQueue. */
|
|
1242
|
-
async function reconcilePendingOtelSpansAfterFlush(globalPmRoot, retentionDays, succeededIds, failedUpdates) {
|
|
1243
|
-
return withQueueMutation(async () => {
|
|
1244
|
-
const raw = await readFileIfExists(otelSpansQueuePath(globalPmRoot));
|
|
1245
|
-
const current = raw === null ? [] : parsePendingOtelSpanLines(raw);
|
|
1246
|
-
const reconciled = [];
|
|
1247
|
-
for (const entry of current) {
|
|
1248
|
-
if (succeededIds.has(entry.id)) {
|
|
1249
|
-
continue;
|
|
1250
|
-
}
|
|
1251
|
-
const failure = failedUpdates.get(entry.id);
|
|
1252
|
-
reconciled.push(failure
|
|
1253
|
-
? {
|
|
1254
|
-
...entry,
|
|
1255
|
-
attempts: failure.attempts,
|
|
1256
|
-
next_attempt_after: failure.next_attempt_after,
|
|
1257
|
-
}
|
|
1258
|
-
: entry);
|
|
1259
|
-
}
|
|
1260
|
-
const { entries: retained } = prunePendingOtelSpans(reconciled, retentionDays);
|
|
1261
|
-
await rewritePendingOtelSpans(globalPmRoot, retained);
|
|
1262
|
-
return retained.length;
|
|
1263
|
-
});
|
|
1264
|
-
}
|
|
1265
|
-
async function flushPendingOtelSpans(globalPmRoot, retentionDays) {
|
|
1266
|
-
const raw = await readFileIfExists(otelSpansQueuePath(globalPmRoot));
|
|
1267
|
-
if (raw === null || raw.trim().length === 0) {
|
|
1268
|
-
await writeRuntimeState(globalPmRoot, { pending_otel_spans: 0 });
|
|
1269
|
-
return;
|
|
1270
|
-
}
|
|
1271
|
-
const entries = parsePendingOtelSpanLines(raw);
|
|
1272
|
-
const { entries: retained, prunedCount } = prunePendingOtelSpans(entries, retentionDays);
|
|
1273
|
-
const due = retained
|
|
1274
|
-
.filter((entry) => isDueForRetryAt(entry.next_attempt_after))
|
|
1275
|
-
.slice(0, TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE);
|
|
1276
|
-
if (due.length === 0) {
|
|
1277
|
-
// Nothing to POST. Still reconcile so pruning persists, but only if pruning
|
|
1278
|
-
// actually changed the on-disk set (avoids a redundant rewrite each command).
|
|
1279
|
-
const remaining = prunedCount > 0
|
|
1280
|
-
? await reconcilePendingOtelSpansAfterFlush(globalPmRoot, retentionDays, new Set(), new Map())
|
|
1281
|
-
: retained.length;
|
|
1282
|
-
await writeRuntimeState(globalPmRoot, { pending_otel_spans: remaining });
|
|
1283
|
-
return;
|
|
1284
|
-
}
|
|
1285
|
-
const attemptTime = nowIso();
|
|
1286
|
-
const succeededIds = new Set();
|
|
1287
|
-
const failedUpdates = new Map();
|
|
1288
|
-
let succeededCount = 0;
|
|
1289
|
-
let lastError;
|
|
1290
|
-
// Export the batch concurrently so a slow/blackholed collector caps the worker
|
|
1291
|
-
// at one TELEMETRY_HTTP_TIMEOUT_MS rather than batch-size x timeout — keeping it
|
|
1292
|
-
// well within the flush-lock TTL. The Set/Map/counter mutations are synchronous
|
|
1293
|
-
// and safe under Node's single-threaded event loop.
|
|
1294
|
-
await Promise.all(due.map(async (span) => {
|
|
1295
|
-
try {
|
|
1296
|
-
const status = await postTelemetryJson(span.endpoint, { "content-type": "application/json" }, JSON.stringify(span.payload));
|
|
1297
|
-
if (status < 200 || status >= 300) {
|
|
1298
|
-
throw new Error(`local_otel_export_http_${status}`);
|
|
1299
|
-
}
|
|
1300
|
-
succeededIds.add(span.id);
|
|
1301
|
-
succeededCount += 1;
|
|
1302
|
-
}
|
|
1303
|
-
catch (error) {
|
|
1304
|
-
lastError =
|
|
1305
|
-
error instanceof Error
|
|
1306
|
-
? sanitizeString(error.message, "redacted")
|
|
1307
|
-
: "local_otel_export_failed";
|
|
1308
|
-
const nextAttempts = span.attempts + 1;
|
|
1309
|
-
failedUpdates.set(span.id, {
|
|
1310
|
-
attempts: nextAttempts,
|
|
1311
|
-
next_attempt_after: nextRetryIso(nextAttempts),
|
|
1312
|
-
});
|
|
1313
|
-
}
|
|
1314
|
-
}));
|
|
1315
|
-
const remaining = await reconcilePendingOtelSpansAfterFlush(globalPmRoot, retentionDays, succeededIds, failedUpdates);
|
|
1316
|
-
const statePatch = {
|
|
1317
|
-
pending_otel_spans: remaining,
|
|
1318
|
-
last_otel_attempt_at: attemptTime,
|
|
1319
|
-
};
|
|
1320
|
-
if (succeededCount > 0) {
|
|
1321
|
-
statePatch.last_otel_success_at = attemptTime;
|
|
1322
|
-
}
|
|
1323
|
-
if (lastError !== undefined) {
|
|
1324
|
-
statePatch.last_otel_failure_at = attemptTime;
|
|
1325
|
-
statePatch.last_otel_failure_error = lastError;
|
|
1326
|
-
}
|
|
1327
|
-
else if (remaining === 0) {
|
|
1328
|
-
// Only clear the failure diagnostic once the queue is fully drained. A
|
|
1329
|
-
// clean batch while other (not-yet-due) spans still wait could be hiding
|
|
1330
|
-
// earlier failures; keep the last known failure until nothing is pending.
|
|
1331
|
-
statePatch.last_otel_failure_at = undefined;
|
|
1332
|
-
statePatch.last_otel_failure_error = undefined;
|
|
1333
|
-
}
|
|
1334
|
-
await writeRuntimeState(globalPmRoot, statePatch);
|
|
1335
|
-
}
|
|
1336
|
-
/** Flush both telemetry artifacts under the same worker invocation: the event ingest queue and the pending OTLP span queue. Used by the detached flush worker and the inline (test) path so OTLP export always happens off the foreground command's critical path. */
|
|
1337
|
-
async function flushTelemetryArtifacts(globalPmRoot, endpoint, retentionDays) {
|
|
1338
|
-
// Isolate the two artifacts: a failure flushing the event queue (e.g. a corrupt
|
|
1339
|
-
// queue file) must not strand the OTLP span flush in the same pass, and vice
|
|
1340
|
-
// versa. Both are best effort and retried on the next dispatch.
|
|
1341
|
-
try {
|
|
1342
|
-
await flushQueue(globalPmRoot, endpoint, retentionDays);
|
|
1343
|
-
}
|
|
1344
|
-
catch {
|
|
1345
|
-
// Best effort; event-queue flush is retried on the next dispatch.
|
|
1346
|
-
}
|
|
1347
|
-
try {
|
|
1348
|
-
await flushPendingOtelSpans(globalPmRoot, retentionDays);
|
|
1349
|
-
}
|
|
1350
|
-
catch {
|
|
1351
|
-
// Best effort; span flush is retried on the next dispatch.
|
|
1352
|
-
}
|
|
1353
|
-
}
|
|
1354
|
-
async function cleanupTelemetryQueueTempOrphans(globalPmRoot, maxAgeMs = TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS) {
|
|
1355
|
-
try {
|
|
1356
|
-
const dirPath = telemetryRuntimeDirectory(globalPmRoot);
|
|
1357
|
-
const entries = await readdir(dirPath, { withFileTypes: true });
|
|
1358
|
-
const cutoffMs = Date.now() - Math.max(0, maxAgeMs);
|
|
1359
|
-
await Promise.all(entries
|
|
1360
|
-
.filter((entry) => entry.isFile() &&
|
|
1361
|
-
/^\.events\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(entry.name))
|
|
1362
|
-
.map(async (entry) => {
|
|
1363
|
-
const candidate = path.join(dirPath, entry.name);
|
|
1364
|
-
const candidateStats = await stat(candidate);
|
|
1365
|
-
if (candidateStats.mtimeMs < cutoffMs) {
|
|
1366
|
-
await rm(candidate, { force: true });
|
|
1367
|
-
}
|
|
1368
|
-
}));
|
|
1369
|
-
}
|
|
1370
|
-
catch {
|
|
1371
|
-
// Telemetry cleanup is best-effort and must not affect command execution.
|
|
1372
|
-
}
|
|
1373
|
-
}
|
|
1374
|
-
async function withQueueMutation(operation) {
|
|
1375
|
-
const run = _queueMutationPromise
|
|
1376
|
-
.catch(
|
|
1377
|
-
/* c8 ignore next */
|
|
1378
|
-
() => { })
|
|
1379
|
-
.then(operation);
|
|
1380
|
-
_queueMutationPromise = run.catch(
|
|
1381
|
-
/* c8 ignore next */
|
|
1382
|
-
() => { });
|
|
1383
|
-
return run;
|
|
1384
|
-
}
|
|
1385
|
-
async function readCurrentQueueEntries(globalPmRoot) {
|
|
1386
|
-
const raw = await readFileIfExists(queuePath(globalPmRoot));
|
|
1387
|
-
if (raw === null || raw.trim().length === 0) {
|
|
1388
|
-
return [];
|
|
1389
|
-
}
|
|
1390
|
-
return parseQueueLines(raw);
|
|
1391
|
-
}
|
|
1392
|
-
async function removeFlushedEntriesFromCurrentQueue(globalPmRoot, flushedIds, retentionDays) {
|
|
1393
|
-
return withQueueMutation(async () => {
|
|
1394
|
-
const currentEntries = await readCurrentQueueEntries(globalPmRoot);
|
|
1395
|
-
const { entries: retainedEntries } = pruneExpiredQueueEntries(currentEntries, retentionDays);
|
|
1396
|
-
const remaining = retainedEntries.filter((entry) => !flushedIds.has(entry.event.event_id));
|
|
1397
|
-
await rewriteQueue(globalPmRoot, remaining);
|
|
1398
|
-
return remaining;
|
|
1399
|
-
});
|
|
1400
|
-
}
|
|
1401
|
-
async function markFailedEntriesInCurrentQueue(globalPmRoot, failedIds, attemptTime, retentionDays) {
|
|
1402
|
-
return withQueueMutation(async () => {
|
|
1403
|
-
const currentEntries = await readCurrentQueueEntries(globalPmRoot);
|
|
1404
|
-
const { entries: retainedEntries } = pruneExpiredQueueEntries(currentEntries, retentionDays);
|
|
1405
|
-
const retried = retainedEntries.map((entry) => {
|
|
1406
|
-
if (!failedIds.has(entry.event.event_id)) {
|
|
1407
|
-
return entry;
|
|
1408
|
-
}
|
|
1409
|
-
const attempts = entry.attempts + 1;
|
|
1410
|
-
return {
|
|
1411
|
-
...entry,
|
|
1412
|
-
attempts,
|
|
1413
|
-
last_attempt_at: attemptTime,
|
|
1414
|
-
next_attempt_after: nextRetryIso(attempts),
|
|
1415
|
-
};
|
|
1416
|
-
});
|
|
1417
|
-
await rewriteQueue(globalPmRoot, retried);
|
|
1418
|
-
return retried;
|
|
1419
|
-
});
|
|
1420
|
-
}
|
|
1421
|
-
async function flushQueue(globalPmRoot, endpoint, retentionDays) {
|
|
1422
|
-
await cleanupTelemetryQueueTempOrphans(globalPmRoot);
|
|
1423
|
-
const normalizedEndpoint = endpoint.trim();
|
|
1424
|
-
if (normalizedEndpoint.length === 0) {
|
|
1425
|
-
return;
|
|
1426
|
-
}
|
|
1427
|
-
const raw = await readFileIfExists(queuePath(globalPmRoot));
|
|
1428
|
-
if (raw === null || raw.trim().length === 0) {
|
|
1429
|
-
await writeRuntimeState(globalPmRoot, {
|
|
1430
|
-
endpoint: normalizedEndpoint,
|
|
1431
|
-
queue_entries: 0,
|
|
1432
|
-
});
|
|
1433
|
-
return;
|
|
1434
|
-
}
|
|
1435
|
-
const queueEntries = parseQueueLines(raw);
|
|
1436
|
-
if (queueEntries.length === 0) {
|
|
1437
|
-
await writeRuntimeState(globalPmRoot, {
|
|
1438
|
-
endpoint: normalizedEndpoint,
|
|
1439
|
-
queue_entries: 0,
|
|
1440
|
-
});
|
|
1441
|
-
return;
|
|
1442
|
-
}
|
|
1443
|
-
const { entries: retainedEntries, prunedCount } = pruneExpiredQueueEntries(queueEntries, retentionDays);
|
|
1444
|
-
if (retainedEntries.length === 0) {
|
|
1445
|
-
await rewriteQueue(globalPmRoot, []);
|
|
1446
|
-
await writeRuntimeState(globalPmRoot, {
|
|
1447
|
-
endpoint: normalizedEndpoint,
|
|
1448
|
-
queue_entries: 0,
|
|
1449
|
-
});
|
|
1450
|
-
return;
|
|
1451
|
-
}
|
|
1452
|
-
const dueEntries = retainedEntries
|
|
1453
|
-
.filter((entry) => isDueForRetry(entry))
|
|
1454
|
-
.slice(0, TELEMETRY_FLUSH_BATCH_SIZE);
|
|
1455
|
-
if (dueEntries.length === 0) {
|
|
1456
|
-
if (prunedCount > 0) {
|
|
1457
|
-
await rewriteQueue(globalPmRoot, retainedEntries);
|
|
1458
|
-
}
|
|
1459
|
-
await writeRuntimeState(globalPmRoot, {
|
|
1460
|
-
endpoint: normalizedEndpoint,
|
|
1461
|
-
queue_entries: retainedEntries.length,
|
|
1462
|
-
});
|
|
1463
|
-
return;
|
|
1464
|
-
}
|
|
1465
|
-
const dueIds = new Set(dueEntries.map((entry) => entry.event.event_id));
|
|
1466
|
-
const attemptTime = nowIso();
|
|
1467
|
-
const requestHeaders = {
|
|
1468
|
-
"content-type": "application/json",
|
|
1469
|
-
};
|
|
1470
|
-
const ingestKey = process.env.PM_TELEMETRY_INGEST_KEY?.trim();
|
|
1471
|
-
if (ingestKey) {
|
|
1472
|
-
requestHeaders["x-pm-telemetry-key"] = ingestKey;
|
|
1473
|
-
}
|
|
1474
|
-
try {
|
|
1475
|
-
const status = await postTelemetryJson(normalizedEndpoint, requestHeaders, JSON.stringify({
|
|
1476
|
-
schema_version: TELEMETRY_SCHEMA_VERSION,
|
|
1477
|
-
events: dueEntries.map((entry) => entry.event),
|
|
1478
|
-
}));
|
|
1479
|
-
if (status < 200 || status >= 300) {
|
|
1480
|
-
throw new Error(`telemetry_flush_http_${status}`);
|
|
1481
|
-
}
|
|
1482
|
-
}
|
|
1483
|
-
catch (error) {
|
|
1484
|
-
const retried = await markFailedEntriesInCurrentQueue(globalPmRoot, dueIds, attemptTime, retentionDays);
|
|
1485
|
-
const errorMessage = (() => {
|
|
1486
|
-
if (error instanceof Error) {
|
|
1487
|
-
return sanitizeString(error.message, "redacted");
|
|
1488
|
-
}
|
|
1489
|
-
return "telemetry_flush_failed";
|
|
1490
|
-
})();
|
|
1491
|
-
await writeRuntimeState(globalPmRoot, {
|
|
1492
|
-
endpoint: normalizedEndpoint,
|
|
1493
|
-
queue_entries: retried.length,
|
|
1494
|
-
last_attempted_flush_at: attemptTime,
|
|
1495
|
-
last_failed_flush_at: attemptTime,
|
|
1496
|
-
last_failed_flush_error: errorMessage,
|
|
1497
|
-
});
|
|
1498
|
-
return;
|
|
1499
|
-
}
|
|
1500
|
-
try {
|
|
1501
|
-
const remaining = await removeFlushedEntriesFromCurrentQueue(globalPmRoot, dueIds, retentionDays);
|
|
1502
|
-
await writeRuntimeState(globalPmRoot, {
|
|
1503
|
-
endpoint: normalizedEndpoint,
|
|
1504
|
-
queue_entries: remaining.length,
|
|
1505
|
-
last_attempted_flush_at: attemptTime,
|
|
1506
|
-
last_successful_flush_at: attemptTime,
|
|
1507
|
-
last_failed_flush_at: undefined,
|
|
1508
|
-
last_failed_flush_error: undefined,
|
|
1509
|
-
});
|
|
1510
|
-
/* c8 ignore start */
|
|
1511
|
-
}
|
|
1512
|
-
catch (error) {
|
|
1513
|
-
const errorMessage = (() => {
|
|
1514
|
-
if (error instanceof Error) {
|
|
1515
|
-
return sanitizeString(error.message, "redacted");
|
|
1516
|
-
}
|
|
1517
|
-
return "telemetry_flush_failed";
|
|
1518
|
-
})();
|
|
1519
|
-
const currentEntries = await readCurrentQueueEntries(globalPmRoot).catch(() => retainedEntries);
|
|
1520
|
-
await writeRuntimeState(globalPmRoot, {
|
|
1521
|
-
endpoint: normalizedEndpoint,
|
|
1522
|
-
queue_entries: currentEntries.length,
|
|
1523
|
-
last_attempted_flush_at: attemptTime,
|
|
1524
|
-
last_failed_flush_at: attemptTime,
|
|
1525
|
-
last_failed_flush_error: errorMessage,
|
|
1526
|
-
});
|
|
1527
|
-
}
|
|
1528
|
-
/* c8 ignore stop */
|
|
1529
|
-
}
|
|
1530
|
-
async function acquireTelemetryFlushLock(globalPmRoot) {
|
|
1531
|
-
const lockPath = flushLockPath(globalPmRoot);
|
|
1532
|
-
await mkdir(path.dirname(lockPath), { recursive: true });
|
|
1533
|
-
try {
|
|
1534
|
-
await mkdir(lockPath);
|
|
1535
|
-
return true;
|
|
1536
|
-
}
|
|
1537
|
-
catch (error) {
|
|
1538
|
-
if (typeof error !== "object" ||
|
|
1539
|
-
error === null ||
|
|
1540
|
-
!("code" in error) ||
|
|
1541
|
-
error.code !== "EEXIST") {
|
|
1542
|
-
throw error;
|
|
1543
|
-
}
|
|
1544
|
-
}
|
|
1545
|
-
try {
|
|
1546
|
-
const lockStats = await stat(lockPath);
|
|
1547
|
-
if (Date.now() - lockStats.mtimeMs < TELEMETRY_FLUSH_LOCK_STALE_MS) {
|
|
1548
|
-
return false;
|
|
1549
|
-
}
|
|
1550
|
-
await rm(lockPath, { recursive: true, force: true });
|
|
1551
|
-
await mkdir(lockPath);
|
|
1552
|
-
return true;
|
|
1553
|
-
}
|
|
1554
|
-
catch {
|
|
1555
|
-
return false;
|
|
1556
|
-
}
|
|
1557
|
-
}
|
|
1558
|
-
function isFreshDirectoryLock(lockPath, staleMs) {
|
|
1559
|
-
try {
|
|
1560
|
-
return Date.now() - statSync(lockPath).mtimeMs < staleMs;
|
|
1561
|
-
}
|
|
1562
|
-
catch {
|
|
1563
|
-
return false;
|
|
1564
|
-
}
|
|
1565
|
-
}
|
|
1566
|
-
function removeDirectoryLockBestEffort(lockPath) {
|
|
1567
|
-
try {
|
|
1568
|
-
rmSync(lockPath, { recursive: true, force: true });
|
|
1569
|
-
}
|
|
1570
|
-
catch {
|
|
1571
|
-
// Flush scheduling is best effort and must never fail user commands.
|
|
1572
|
-
}
|
|
1573
|
-
}
|
|
1574
|
-
function errorCode(error) {
|
|
1575
|
-
if (typeof error !== "object" || error === null || !("code" in error)) {
|
|
1576
|
-
return undefined;
|
|
1577
|
-
}
|
|
1578
|
-
const code = error.code;
|
|
1579
|
-
return typeof code === "string" ? code : undefined;
|
|
1580
|
-
}
|
|
1581
|
-
function createDirectoryLock(lockPath) {
|
|
1582
|
-
try {
|
|
1583
|
-
mkdirSync(lockPath);
|
|
1584
|
-
return true;
|
|
1585
|
-
}
|
|
1586
|
-
catch (error) {
|
|
1587
|
-
const code = errorCode(error);
|
|
1588
|
-
if (code === "EEXIST") {
|
|
1589
|
-
return false;
|
|
1590
|
-
}
|
|
1591
|
-
if (!isFileMissingError(error)) {
|
|
1592
|
-
return false;
|
|
1593
|
-
}
|
|
1594
|
-
}
|
|
1595
|
-
/* c8 ignore start */
|
|
1596
|
-
try {
|
|
1597
|
-
mkdirSync(path.dirname(lockPath), { recursive: true });
|
|
1598
|
-
mkdirSync(lockPath);
|
|
1599
|
-
return true;
|
|
1600
|
-
}
|
|
1601
|
-
catch {
|
|
1602
|
-
return false;
|
|
1603
|
-
}
|
|
1604
|
-
/* c8 ignore stop */
|
|
1605
|
-
}
|
|
1606
|
-
function acquireTelemetryFlushSpawnGate(globalPmRoot) {
|
|
1607
|
-
if (isFreshDirectoryLock(flushLockPath(globalPmRoot), TELEMETRY_FLUSH_LOCK_STALE_MS)) {
|
|
1608
|
-
return false;
|
|
1609
|
-
}
|
|
1610
|
-
const lockPath = flushSpawnLockPath(globalPmRoot);
|
|
1611
|
-
try {
|
|
1612
|
-
if (Date.now() - statSync(lockPath).mtimeMs <
|
|
1613
|
-
TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS) {
|
|
1614
|
-
return false;
|
|
1615
|
-
}
|
|
1616
|
-
removeDirectoryLockBestEffort(lockPath);
|
|
1617
|
-
}
|
|
1618
|
-
catch (error) {
|
|
1619
|
-
if (!isFileMissingError(error)) {
|
|
1620
|
-
return false;
|
|
1621
|
-
}
|
|
1622
|
-
}
|
|
1623
|
-
return createDirectoryLock(lockPath);
|
|
1624
|
-
}
|
|
1625
|
-
function releaseTelemetryFlushSpawnGate(globalPmRoot) {
|
|
1626
|
-
removeDirectoryLockBestEffort(flushSpawnLockPath(globalPmRoot));
|
|
1627
|
-
}
|
|
1628
|
-
/** Public contract for test only, shared by SDK and presentation-layer consumers. */
|
|
1629
|
-
export const _testOnly = {
|
|
1630
|
-
acquireTelemetryFlushSpawnGate,
|
|
1631
|
-
acquireTelemetryFlushLock,
|
|
1632
|
-
buildAuthorContextPayloadFields,
|
|
1633
|
-
buildCommandErrorPayload,
|
|
1634
|
-
buildCommandFinishPayload,
|
|
1635
|
-
buildCommandStartPayload,
|
|
1636
|
-
buildOtelSpanRequest,
|
|
1637
|
-
createDirectoryLock,
|
|
1638
|
-
enqueuePendingOtelSpan,
|
|
1639
|
-
enqueueTelemetryEvent,
|
|
1640
|
-
errorCode,
|
|
1641
|
-
flushPendingOtelSpans,
|
|
1642
|
-
flushQueue,
|
|
1643
|
-
flushQueueWithProcessLock,
|
|
1644
|
-
flushTelemetryArtifacts,
|
|
1645
|
-
hashTelemetryErrorFingerprint,
|
|
1646
|
-
hashTelemetryValue,
|
|
1647
|
-
isEmailDomainCharacter,
|
|
1648
|
-
isEmailLocalCharacter,
|
|
1649
|
-
isExpiredPendingOtelSpan,
|
|
1650
|
-
isExpiredQueueEntry,
|
|
1651
|
-
isFreshDirectoryLock,
|
|
1652
|
-
isDueForRetry,
|
|
1653
|
-
isDueForRetryAt,
|
|
1654
|
-
isRetryableQueueRewriteError,
|
|
1655
|
-
looksLikeEmailToken,
|
|
1656
|
-
otelSpansQueuePath,
|
|
1657
|
-
parseBooleanTrueLike,
|
|
1658
|
-
postTelemetryJson,
|
|
1659
|
-
parsePendingOtelSpanLines,
|
|
1660
|
-
prunePendingOtelSpans,
|
|
1661
|
-
reconcilePendingOtelSpansAfterFlush,
|
|
1662
|
-
retentionCutoffMs,
|
|
1663
|
-
resolveOtelTracesEndpoint,
|
|
1664
|
-
resolveTelemetryHttpTimeoutMs,
|
|
1665
|
-
rewritePendingOtelSpans,
|
|
1666
|
-
normalizeForHash,
|
|
1667
|
-
normalizeCaptureLevel,
|
|
1668
|
-
normalizePmVersion,
|
|
1669
|
-
normalizeTelemetryErrorCategory,
|
|
1670
|
-
normalizeTelemetryErrorCode,
|
|
1671
|
-
normalizeTelemetryExitCode,
|
|
1672
|
-
parseQueueLines,
|
|
1673
|
-
pruneExpiredQueueEntries,
|
|
1674
|
-
readRuntimeState,
|
|
1675
|
-
readCurrentQueueEntries,
|
|
1676
|
-
releaseTelemetryFlushSpawnGate,
|
|
1677
|
-
removeFlushedEntriesFromCurrentQueue,
|
|
1678
|
-
removeDirectoryLockBestEffort,
|
|
1679
|
-
resolveTelemetrySourceContext,
|
|
1680
|
-
rewriteQueue,
|
|
1681
|
-
sanitizeCommandArgs,
|
|
1682
|
-
sanitizeStringMax,
|
|
1683
|
-
sanitizeStringRedacted,
|
|
1684
|
-
sanitizeValue,
|
|
1685
|
-
scheduleTelemetryFlush,
|
|
1686
|
-
shouldFlushInline,
|
|
1687
|
-
sleep,
|
|
1688
|
-
summarizeResult,
|
|
1689
|
-
telemetryFlushRunnerPath,
|
|
1690
|
-
withQueueMutation,
|
|
1691
|
-
flushLockPath,
|
|
1692
|
-
flushSpawnLockPath,
|
|
1693
|
-
runtimeStatePath,
|
|
1694
|
-
writeRuntimeState,
|
|
1695
|
-
};
|
|
1696
|
-
async function flushQueueWithProcessLock(globalPmRoot, endpoint, retentionDays) {
|
|
1697
|
-
const acquired = await acquireTelemetryFlushLock(globalPmRoot);
|
|
1698
|
-
releaseTelemetryFlushSpawnGate(globalPmRoot);
|
|
1699
|
-
if (!acquired) {
|
|
1700
|
-
return;
|
|
1701
|
-
}
|
|
1702
|
-
try {
|
|
1703
|
-
await flushTelemetryArtifacts(globalPmRoot, endpoint, retentionDays);
|
|
1704
|
-
}
|
|
1705
|
-
finally {
|
|
1706
|
-
try {
|
|
1707
|
-
await rm(flushLockPath(globalPmRoot), { recursive: true, force: true });
|
|
1708
|
-
}
|
|
1709
|
-
catch {
|
|
1710
|
-
// Best effort lock cleanup; stale locks are recovered by TTL checks.
|
|
1711
|
-
}
|
|
1712
|
-
}
|
|
1713
|
-
}
|
|
1714
|
-
function scheduleTelemetryFlush(globalPmRoot, endpoint, retentionDays) {
|
|
1715
|
-
if (shouldFlushInline()) {
|
|
1716
|
-
const previousFlush = _lastFlushPromise;
|
|
1717
|
-
const nextFlush = flushTelemetryArtifacts(globalPmRoot, endpoint, retentionDays);
|
|
1718
|
-
_lastFlushPromise = Promise.allSettled([previousFlush, nextFlush]).then(() => { });
|
|
1719
|
-
return;
|
|
1720
|
-
}
|
|
1721
|
-
try {
|
|
1722
|
-
const acquiredSpawnGate = acquireTelemetryFlushSpawnGate(globalPmRoot);
|
|
1723
|
-
if (!acquiredSpawnGate) {
|
|
1724
|
-
return;
|
|
1725
|
-
}
|
|
1726
|
-
const child = spawn(process.execPath, [telemetryFlushRunnerPath()], {
|
|
1727
|
-
detached: true,
|
|
1728
|
-
stdio: "ignore",
|
|
1729
|
-
// Detached workers inherit cwd by default. On Windows that can keep a
|
|
1730
|
-
// disposable project directory locked after the foreground command exits.
|
|
1731
|
-
cwd: os.tmpdir(),
|
|
1732
|
-
env: {
|
|
1733
|
-
...process.env,
|
|
1734
|
-
PM_GLOBAL_PATH: globalPmRoot,
|
|
1735
|
-
[PM_TELEMETRY_FLUSH_CHILD_ENV]: "1",
|
|
1736
|
-
},
|
|
1737
|
-
});
|
|
1738
|
-
// A detached spawn can fail asynchronously — the runtime cannot launch the
|
|
1739
|
-
// executable (locked-down Windows runners, missing flush runner, EACCES).
|
|
1740
|
-
// Node re-throws an 'error' event with no listener as an uncaught exception,
|
|
1741
|
-
// which would crash the foreground CLI and, under the test runner, the
|
|
1742
|
-
// vitest worker during teardown (GH-348). Flush is strictly best effort, so
|
|
1743
|
-
// swallow the failure and release the spawn gate to permit a later retry.
|
|
1744
|
-
child.on("error", () => {
|
|
1745
|
-
releaseTelemetryFlushSpawnGate(globalPmRoot);
|
|
1746
|
-
});
|
|
1747
|
-
child.unref();
|
|
1748
|
-
}
|
|
1749
|
-
catch {
|
|
1750
|
-
releaseTelemetryFlushSpawnGate(globalPmRoot);
|
|
1751
|
-
// Flush scheduling is best effort and must not keep the CLI alive.
|
|
1752
|
-
}
|
|
1753
|
-
}
|
|
1754
|
-
/** Implements flush telemetry queue now for the public runtime surface of this module. */
|
|
1755
|
-
export async function flushTelemetryQueueNow(globalPmRoot = resolveGlobalPmRoot(process.cwd())) {
|
|
1756
|
-
if (telemetryDisabledByEnvironment()) {
|
|
1757
|
-
return;
|
|
1758
|
-
}
|
|
1759
|
-
try {
|
|
1760
|
-
const settings = await readSettings(globalPmRoot);
|
|
1761
|
-
if (!settings.telemetry.enabled) {
|
|
1762
|
-
return;
|
|
1763
|
-
}
|
|
1764
|
-
const { endpoint, retentionDays } = await ensureInstallationId(globalPmRoot);
|
|
1765
|
-
await flushQueueWithProcessLock(globalPmRoot, endpoint, retentionDays);
|
|
1766
|
-
}
|
|
1767
|
-
catch {
|
|
1768
|
-
// Telemetry workers are best effort and must never fail user commands.
|
|
1769
|
-
}
|
|
1770
|
-
}
|
|
1771
|
-
/** Implements start telemetry command for the public runtime surface of this module. */
|
|
1772
|
-
export async function startTelemetryCommand(context) {
|
|
1773
|
-
if (telemetryDisabledByEnvironment()) {
|
|
1774
|
-
return null;
|
|
1775
|
-
}
|
|
1776
|
-
if (context.command === "telemetry" &&
|
|
1777
|
-
context.args.some((token) => token.trim().toLowerCase() === "clear")) {
|
|
1778
|
-
return null;
|
|
1779
|
-
}
|
|
1780
|
-
try {
|
|
1781
|
-
const globalPmRoot = resolveGlobalPmRoot(process.cwd());
|
|
1782
|
-
const settings = await readSettings(globalPmRoot);
|
|
1783
|
-
if (!settings.telemetry.enabled) {
|
|
1784
|
-
return null;
|
|
1785
|
-
}
|
|
1786
|
-
const captureLevel = normalizeCaptureLevel(settings.telemetry.capture_level);
|
|
1787
|
-
const { installationId, endpoint, retentionDays } = await ensureInstallationId(globalPmRoot);
|
|
1788
|
-
const pmVersion = normalizePmVersion(context.pm_version);
|
|
1789
|
-
const sourceContext = resolveTelemetrySourceContext(context.global);
|
|
1790
|
-
const pmRootHash = hashWithInstallationId(installationId, context.pm_root);
|
|
1791
|
-
const cwdHash = hashWithInstallationId(installationId, process.cwd());
|
|
1792
|
-
const otelTracesEndpoint = resolveOtelTracesEndpoint();
|
|
1793
|
-
const occurredAt = nowIso();
|
|
1794
|
-
const event = {
|
|
1795
|
-
schema_version: TELEMETRY_SCHEMA_VERSION,
|
|
1796
|
-
event_id: crypto.randomUUID(),
|
|
1797
|
-
event_type: "command_start",
|
|
1798
|
-
occurred_at: occurredAt,
|
|
1799
|
-
installation_id: installationId,
|
|
1800
|
-
session_id: PROCESS_SESSION_ID,
|
|
1801
|
-
command: context.command,
|
|
1802
|
-
payload: buildCommandStartPayload({
|
|
1803
|
-
captureLevel,
|
|
1804
|
-
context,
|
|
1805
|
-
pmVersion,
|
|
1806
|
-
sourceContext,
|
|
1807
|
-
pmRootHash,
|
|
1808
|
-
cwdHash,
|
|
1809
|
-
installationId,
|
|
1810
|
-
}),
|
|
1811
|
-
};
|
|
1812
|
-
await enqueueTelemetryEvent(globalPmRoot, event);
|
|
1813
|
-
scheduleTelemetryFlush(globalPmRoot, endpoint, retentionDays);
|
|
1814
|
-
const commandTaxonomy = deriveTelemetryCommandTaxonomy(context.command);
|
|
1815
|
-
return {
|
|
1816
|
-
started_at: occurredAt,
|
|
1817
|
-
started_at_ms: Date.now(),
|
|
1818
|
-
command: context.command,
|
|
1819
|
-
command_taxonomy: commandTaxonomy,
|
|
1820
|
-
pm_version: pmVersion,
|
|
1821
|
-
source_context: sourceContext.source_context,
|
|
1822
|
-
source_context_source: sourceContext.source_context_source,
|
|
1823
|
-
installation_id: installationId,
|
|
1824
|
-
pm_root_hash: pmRootHash,
|
|
1825
|
-
cwd_hash: cwdHash,
|
|
1826
|
-
endpoint,
|
|
1827
|
-
retention_days: retentionDays,
|
|
1828
|
-
global_pm_root: globalPmRoot,
|
|
1829
|
-
capture_level: captureLevel,
|
|
1830
|
-
otel_traces_endpoint: otelTracesEndpoint ?? undefined,
|
|
1831
|
-
otel_trace_id: otelTracesEndpoint
|
|
1832
|
-
? crypto.randomBytes(16).toString("hex")
|
|
1833
|
-
: undefined,
|
|
1834
|
-
otel_span_id: otelTracesEndpoint
|
|
1835
|
-
? crypto.randomBytes(8).toString("hex")
|
|
1836
|
-
: undefined,
|
|
1837
|
-
};
|
|
1838
|
-
}
|
|
1839
|
-
catch {
|
|
1840
|
-
// Telemetry must never block command execution.
|
|
1841
|
-
return null;
|
|
1842
|
-
}
|
|
1843
|
-
}
|
|
1844
|
-
/** Implements finish telemetry command for the public runtime surface of this module. */
|
|
1845
|
-
export async function finishTelemetryCommand(activeCommand, outcome) {
|
|
1846
|
-
if (!activeCommand) {
|
|
1847
|
-
return;
|
|
1848
|
-
}
|
|
1849
|
-
try {
|
|
1850
|
-
const finishedAt = nowIso();
|
|
1851
|
-
const durationMs = Math.max(0, Date.now() - activeCommand.started_at_ms);
|
|
1852
|
-
const normalizedErrorCode = normalizeTelemetryErrorCode(inferTelemetryErrorCode({
|
|
1853
|
-
ok: outcome.ok,
|
|
1854
|
-
errorCode: outcome.error_code,
|
|
1855
|
-
errorMessage: outcome.error,
|
|
1856
|
-
exitCode: outcome.exit_code,
|
|
1857
|
-
}));
|
|
1858
|
-
const normalizedErrorCategory = normalizeTelemetryErrorCategory({
|
|
1859
|
-
ok: outcome.ok,
|
|
1860
|
-
errorCode: normalizedErrorCode,
|
|
1861
|
-
errorCategory: outcome.error_category,
|
|
1862
|
-
});
|
|
1863
|
-
const normalizedExitCode = normalizeTelemetryExitCode(outcome.exit_code, outcome.ok);
|
|
1864
|
-
const commandResolution = outcome.command_resolution ??
|
|
1865
|
-
deriveTelemetryCommandResolution({
|
|
1866
|
-
ok: outcome.ok,
|
|
1867
|
-
errorCode: normalizedErrorCode,
|
|
1868
|
-
errorCategory: normalizedErrorCategory,
|
|
1869
|
-
});
|
|
1870
|
-
const resolutionStage = outcome.resolution_stage ?? "execute";
|
|
1871
|
-
const event = {
|
|
1872
|
-
schema_version: TELEMETRY_SCHEMA_VERSION,
|
|
1873
|
-
event_id: crypto.randomUUID(),
|
|
1874
|
-
event_type: "command_finish",
|
|
1875
|
-
occurred_at: finishedAt,
|
|
1876
|
-
installation_id: activeCommand.installation_id,
|
|
1877
|
-
session_id: PROCESS_SESSION_ID,
|
|
1878
|
-
command: activeCommand.command,
|
|
1879
|
-
payload: buildCommandFinishPayload({
|
|
1880
|
-
captureLevel: activeCommand.capture_level,
|
|
1881
|
-
pmVersion: activeCommand.pm_version,
|
|
1882
|
-
sourceContext: {
|
|
1883
|
-
source_context: activeCommand.source_context,
|
|
1884
|
-
source_context_source: activeCommand.source_context_source,
|
|
1885
|
-
},
|
|
1886
|
-
outcome,
|
|
1887
|
-
durationMs,
|
|
1888
|
-
startedAt: activeCommand.started_at,
|
|
1889
|
-
command: activeCommand.command,
|
|
1890
|
-
installationId: activeCommand.installation_id,
|
|
1891
|
-
commandTaxonomy: activeCommand.command_taxonomy,
|
|
1892
|
-
exitCode: normalizedExitCode,
|
|
1893
|
-
errorCode: normalizedErrorCode,
|
|
1894
|
-
errorCategory: normalizedErrorCategory,
|
|
1895
|
-
commandResolution,
|
|
1896
|
-
resolutionStage,
|
|
1897
|
-
}),
|
|
1898
|
-
};
|
|
1899
|
-
await enqueueTelemetryEvent(activeCommand.global_pm_root, event);
|
|
1900
|
-
const otelRequest = buildOtelSpanRequest(activeCommand, {
|
|
1901
|
-
...outcome,
|
|
1902
|
-
exit_code: normalizedExitCode,
|
|
1903
|
-
error_code: normalizedErrorCode,
|
|
1904
|
-
error_category: normalizedErrorCategory,
|
|
1905
|
-
}, finishedAt, durationMs);
|
|
1906
|
-
if (otelRequest) {
|
|
1907
|
-
// Persist the span for the detached worker; never POST inline so the
|
|
1908
|
-
// foreground command exits promptly even if the traces endpoint is
|
|
1909
|
-
// unreachable (GH-209).
|
|
1910
|
-
await enqueuePendingOtelSpan(activeCommand.global_pm_root, otelRequest);
|
|
1911
|
-
}
|
|
1912
|
-
scheduleTelemetryFlush(activeCommand.global_pm_root, activeCommand.endpoint, activeCommand.retention_days);
|
|
1913
|
-
}
|
|
1914
|
-
catch {
|
|
1915
|
-
// Telemetry must never block command execution.
|
|
1916
|
-
}
|
|
1917
|
-
}
|
|
1918
|
-
/** Implements emit telemetry error event for the public runtime surface of this module. */
|
|
1919
|
-
export async function emitTelemetryErrorEvent(context) {
|
|
1920
|
-
if (telemetryDisabledByEnvironment()) {
|
|
1921
|
-
return;
|
|
1922
|
-
}
|
|
1923
|
-
try {
|
|
1924
|
-
const globalPmRoot = resolveGlobalPmRoot(process.cwd());
|
|
1925
|
-
const settings = await readSettings(globalPmRoot);
|
|
1926
|
-
if (!settings.telemetry.enabled) {
|
|
1927
|
-
return;
|
|
1928
|
-
}
|
|
1929
|
-
const captureLevel = normalizeCaptureLevel(settings.telemetry.capture_level);
|
|
1930
|
-
const { installationId, endpoint, retentionDays } = await ensureInstallationId(globalPmRoot);
|
|
1931
|
-
const pmVersion = normalizePmVersion(context.pm_version);
|
|
1932
|
-
const sourceContext = resolveTelemetrySourceContext(context.global);
|
|
1933
|
-
const pmRootHash = hashWithInstallationId(installationId, context.pm_root);
|
|
1934
|
-
const cwdHash = hashWithInstallationId(installationId, process.cwd());
|
|
1935
|
-
const occurredAt = nowIso();
|
|
1936
|
-
const normalizedErrorCode = normalizeTelemetryErrorCode(inferTelemetryErrorCode({
|
|
1937
|
-
ok: false,
|
|
1938
|
-
errorCode: context.error_code,
|
|
1939
|
-
errorMessage: context.error_message,
|
|
1940
|
-
exitCode: context.exit_code,
|
|
1941
|
-
}));
|
|
1942
|
-
const normalizedErrorCategory = context.error_category ??
|
|
1943
|
-
resolveTelemetryErrorCategory(normalizedErrorCode);
|
|
1944
|
-
const normalizedExitCode = normalizeTelemetryExitCode(context.exit_code, false);
|
|
1945
|
-
const normalizedCommand = context.command.trim().length > 0 ? context.command : "<unknown>";
|
|
1946
|
-
const commandTaxonomy = deriveTelemetryCommandTaxonomy(normalizedCommand);
|
|
1947
|
-
const commandResolution = context.command_resolution ??
|
|
1948
|
-
deriveTelemetryCommandResolution({
|
|
1949
|
-
ok: false,
|
|
1950
|
-
errorCode: normalizedErrorCode,
|
|
1951
|
-
errorCategory: normalizedErrorCategory,
|
|
1952
|
-
});
|
|
1953
|
-
const resolutionStage = context.resolution_stage ?? "unknown";
|
|
1954
|
-
const event = {
|
|
1955
|
-
schema_version: TELEMETRY_SCHEMA_VERSION,
|
|
1956
|
-
event_id: crypto.randomUUID(),
|
|
1957
|
-
event_type: "command_error",
|
|
1958
|
-
occurred_at: occurredAt,
|
|
1959
|
-
installation_id: installationId,
|
|
1960
|
-
session_id: PROCESS_SESSION_ID,
|
|
1961
|
-
command: sanitizeString(normalizedCommand, "redacted"),
|
|
1962
|
-
payload: buildCommandErrorPayload({
|
|
1963
|
-
captureLevel,
|
|
1964
|
-
pmVersion,
|
|
1965
|
-
sourceContext,
|
|
1966
|
-
command: normalizedCommand,
|
|
1967
|
-
commandTaxonomy,
|
|
1968
|
-
commandResolution,
|
|
1969
|
-
resolutionStage,
|
|
1970
|
-
args: context.args,
|
|
1971
|
-
options: context.options,
|
|
1972
|
-
pmRootHash,
|
|
1973
|
-
cwdHash,
|
|
1974
|
-
installationId,
|
|
1975
|
-
errorCode: normalizedErrorCode,
|
|
1976
|
-
errorCategory: normalizedErrorCategory,
|
|
1977
|
-
exitCode: normalizedExitCode,
|
|
1978
|
-
errorMessage: context.error_message,
|
|
1979
|
-
}),
|
|
1980
|
-
};
|
|
1981
|
-
await enqueueTelemetryEvent(globalPmRoot, event);
|
|
1982
|
-
scheduleTelemetryFlush(globalPmRoot, endpoint, retentionDays);
|
|
1983
|
-
}
|
|
1984
|
-
catch {
|
|
1985
|
-
// Telemetry must never block command execution.
|
|
1986
|
-
}
|
|
1987
|
-
}
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a80b4f33-b43b-5056-a4eb-ba784c9746a4")}catch(e2){}})();import crypto from"node:crypto";import{spawn}from"node:child_process";import{mkdirSync,rmSync,statSync}from"node:fs";import{mkdir,readdir,rm,stat}from"node:fs/promises";import{request as httpRequest}from"node:http";import{request as httpsRequest}from"node:https";import os from"node:os";import path from"node:path";import{resolvePmPackageRootFromModule}from"../packages/root.js";import{isFileMissingError,appendLineAtomic,readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{resolveTelemetryErrorCategory}from"../shared/constants.js";import{nowIso}from"../shared/time.js";import{detectAgentIdentity,readAuthorEnvironment}from"../shared/author.js";import{resolveGlobalPmRoot}from"../store/paths.js";import{readSettings,writeSettings}from"../store/settings.js";import{deriveTelemetryCommandResolution,deriveTelemetryCommandTaxonomy,inferTelemetryErrorCode}from"./observability.js";const TELEMETRY_QUEUE_RELATIVE_PATH=path.join("runtime","telemetry","events.jsonl");const TELEMETRY_STATE_RELATIVE_PATH=path.join("runtime","telemetry","state.json");const TELEMETRY_OTEL_SPANS_RELATIVE_PATH=path.join("runtime","telemetry","otel-spans.jsonl");const TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE=8;const TELEMETRY_OTEL_SPANS_MAX_PENDING=500;const TELEMETRY_SCHEMA_VERSION=1;const TELEMETRY_CLIENT_SCHEMA_VERSION=1;const TELEMETRY_FLUSH_BATCH_SIZE=100;const TELEMETRY_MAX_RETRY_DELAY_MS=36e5;const TELEMETRY_RETRY_BASE_DELAY_MS=3e4;const TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS=2e4;const TELEMETRY_HTTP_TIMEOUT_MIN_MS=1e3;const TELEMETRY_HTTP_TIMEOUT_MAX_MS=25e3;const MILLISECONDS_PER_DAY=864e5;const TELEMETRY_MAX_EVENT_BYTES=65536;const TELEMETRY_SANITIZE_MAX_DEPTH=6;const TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS=20;const TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS=15;const TELEMETRY_RESULT_PREVIEW_MAX_BYTES=8192;const TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS=[25,50,100,200];const TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS=60*60*1e3;const TELEMETRY_FLUSH_LOCK_STALE_MS=6e4;const TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS=6e4;const OTEL_TRACES_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT";const OTEL_BASE_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_ENDPOINT";const OTEL_SERVICE_NAME_ENV="OTEL_SERVICE_NAME";const PM_TELEMETRY_DISABLED_ENV="PM_TELEMETRY_DISABLED";const PM_NO_TELEMETRY_ENV="PM_NO_TELEMETRY";const PM_TELEMETRY_DISABLED_VALUES=new Set(["1","true","yes","on"]);const PM_TELEMETRY_OTEL_DISABLED_ENV="PM_TELEMETRY_OTEL_DISABLED";const PM_TELEMETRY_OTEL_DISABLED_VALUES=new Set(["1","true","yes","on"]);const PM_TELEMETRY_INLINE_FLUSH_ENV="PM_TELEMETRY_INLINE_FLUSH";const PM_TELEMETRY_FLUSH_CHILD_ENV="PM_TELEMETRY_FLUSH_CHILD";const PM_TELEMETRY_SOURCE_CONTEXT_ENV="PM_TELEMETRY_SOURCE_CONTEXT";const PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV="PM_TELEMETRY_HTTP_TIMEOUT_MS";const NATIVE_FETCH=globalThis.fetch;const PM_TELEMETRY_SOURCE_CONTEXT_VALUES=["user","automation","test","dogfood"];let _lastFlushPromise=Promise.resolve();let _queueMutationPromise=Promise.resolve();async function waitForPendingFlush(){await _lastFlushPromise;await _queueMutationPromise}const PM_TELEMETRY_SOURCE_CONTEXT_SET=new Set(PM_TELEMETRY_SOURCE_CONTEXT_VALUES);const BOOLEAN_TRUE_VALUES=new Set(["1","true","yes","on"]);const PROCESS_SESSION_ID=crypto.randomUUID();const SENSITIVE_KEYWORDS=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"];const REDACTION_INPUT_KEYS=new Set(["literal","literals","regex","regexes","replacement","replacements"]);const SENSITIVE_INLINE_KEY_PATTERN="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)";const INLINE_SENSITIVE_ASSIGNMENT_PATTERN=new RegExp(`\\b(${SENSITIVE_INLINE_KEY_PATTERN})\\s*([:=])\\s*([^\\s,;]+)`,"giu");const INLINE_SENSITIVE_FLAG_PATTERN=new RegExp(`(--${SENSITIVE_INLINE_KEY_PATTERN})(=|\\s+)([^\\s,;]+)`,"giu");const ABSOLUTE_PATH_TOKEN_PATTERN=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g;const BEARER_TOKEN_PATTERN=/bearer\s+[a-z0-9._=-]+/giu;const PRIVATE_IP_PATTERN=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function queuePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_QUEUE_RELATIVE_PATH)}function otelSpansQueuePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_OTEL_SPANS_RELATIVE_PATH)}function telemetryRuntimeDirectory(globalPmRoot){return path.dirname(queuePath(globalPmRoot))}function runtimeStatePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_STATE_RELATIVE_PATH)}function flushLockPath(globalPmRoot){return path.join(globalPmRoot,"runtime","telemetry","flush.lock")}function flushSpawnLockPath(globalPmRoot){return path.join(globalPmRoot,"runtime","telemetry","flush.spawn.lock")}function telemetryFlushRunnerPath(){return path.join(resolvePmPackageRootFromModule(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function shouldFlushInline(){if(parseBooleanTrueLike(process.env[PM_TELEMETRY_INLINE_FLUSH_ENV])){return true}if(parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])){return true}const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();return typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"}async function readRuntimeState(globalPmRoot){const raw=await readFileIfExists(runtimeStatePath(globalPmRoot));if(!raw||raw.trim().length===0){return{}}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){return{}}return parsed}catch{return{}}}async function writeRuntimeState(globalPmRoot,patch){try{const current=await readRuntimeState(globalPmRoot);const next={...current,...patch};const normalized=Object.fromEntries(Object.entries(next).filter(([,value])=>value!==void 0).sort((left,right)=>left[0].localeCompare(right[0])));await writeFileAtomic(runtimeStatePath(globalPmRoot),`${JSON.stringify(normalized,null,2)}
|
|
2
|
+
`)}catch{}}function isSensitiveKey(key){const normalized=key.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_");const tokens=normalized.split("_").filter(token=>token.length>0);return REDACTION_INPUT_KEYS.has(normalized)||SENSITIVE_KEYWORDS.some(keyword=>normalized===keyword||normalized.endsWith(`_${keyword}`)||tokens.includes(keyword))}function redactInlineSensitiveAssignments(input){const withoutAssignments=input.replaceAll(INLINE_SENSITIVE_ASSIGNMENT_PATTERN,(_match,key,delimiter)=>`${key}${delimiter}[redacted]`);return withoutAssignments.replaceAll(INLINE_SENSITIVE_FLAG_PATTERN,(_match,flag,delimiter)=>`${flag}${delimiter}[redacted]`)}function redactAbsolutePathTokens(input){return input.replaceAll(ABSOLUTE_PATH_TOKEN_PATTERN,(_match,prefix)=>`${prefix}[redacted_path]`)}function isAsciiLetterOrDigitCode(code){const isUpper=code>=65&&code<=90;const isLower=code>=97&&code<=122;const isDigit=code>=48&&code<=57;return isUpper||isLower||isDigit}function isEmailLocalCharacter(character){if(!character){return false}const code=character.charCodeAt(0);if(isAsciiLetterOrDigitCode(code)){return true}return character==="."||character==="_"||character==="%"||character==="+"||character==="-"}function isEmailDomainCharacter(character){if(!character){return false}const code=character.charCodeAt(0);if(isAsciiLetterOrDigitCode(code)){return true}return character==="."||character==="-"}function looksLikeEmailToken(token){const atIndex=token.indexOf("@");if(atIndex<=0||atIndex!==token.lastIndexOf("@")||atIndex===token.length-1){return false}const localPart=token.slice(0,atIndex);const domainPart=token.slice(atIndex+1);const lastDot=domainPart.lastIndexOf(".");if(lastDot<=0||lastDot===domainPart.length-1){return false}if(domainPart.length-(lastDot+1)<2){return false}for(const character of localPart){if(!isEmailLocalCharacter(character)){return false}}for(const character of domainPart){if(!isEmailDomainCharacter(character)){return false}}return true}function redactEmailTokens(input){let redacted="";let cursor=0;while(cursor<input.length){const atIndex=input.indexOf("@",cursor);if(atIndex<0){redacted+=input.slice(cursor);break}let start=atIndex-1;while(start>=cursor&&isEmailLocalCharacter(input[start])){start-=1}start+=1;let end=atIndex+1;while(end<input.length&&isEmailDomainCharacter(input[end])){end+=1}const candidate=input.slice(start,end);if(looksLikeEmailToken(candidate)){redacted+=input.slice(cursor,start);redacted+="[redacted_email]";cursor=end;continue}redacted+=input.slice(cursor,atIndex+1);cursor=atIndex+1}return redacted}function sanitizeCommonSensitiveTokens(input){const withoutEmails=redactEmailTokens(input);const withoutBearer=withoutEmails.replaceAll(BEARER_TOKEN_PATTERN,"bearer [redacted_token]");return withoutBearer.replaceAll(PRIVATE_IP_PATTERN,"[redacted_ip]")}function sanitizeStringRedacted(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input);const withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);const withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets);const trimmed=withoutAbsolutePaths.trim();if(trimmed.startsWith("/")&&trimmed.length>1){return"[redacted_path]"}if(withoutAbsolutePaths.length>512){return`${withoutAbsolutePaths.slice(0,509)}...`}return withoutAbsolutePaths}function sanitizeStringMax(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input);const withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);const withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets);const trimmed=withoutAbsolutePaths.trim();if(trimmed.startsWith("/")&&trimmed.length>1){return"[redacted_path]"}if(withoutAbsolutePaths.length>2048){return`${withoutAbsolutePaths.slice(0,2045)}...`}return withoutAbsolutePaths}function sanitizeString(input,captureLevel="redacted"){if(captureLevel==="max"){return sanitizeStringMax(input)}return sanitizeStringRedacted(input)}function sanitizeValue(value,keyHint,captureLevel="redacted",depth=0){if(keyHint&&isSensitiveKey(keyHint)){return"[redacted]"}if(value===null||value===void 0){return value}if(typeof value==="string"){return sanitizeString(value,captureLevel)}if(typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>sanitizeValue(entry,void 0,captureLevel,depth+1))}if(typeof value==="object"){const record=value;const sanitized={};for(const[key,nested]of Object.entries(record)){sanitized[key]=sanitizeValue(nested,key,captureLevel,depth+1)}return sanitized}return String(value)}function sanitizeCommandArgs(args,captureLevel="redacted"){const sanitized=[];let nextIsSensitiveValue=false;for(const rawArg of args){const arg=sanitizeString(rawArg,captureLevel);if(nextIsSensitiveValue){sanitized.push("[redacted]");nextIsSensitiveValue=false;continue}if(arg.startsWith("--")){const withoutPrefix=arg.slice(2);const delimiterIndex=withoutPrefix.indexOf("=");if(delimiterIndex>=0){const key=withoutPrefix.slice(0,delimiterIndex);const value=withoutPrefix.slice(delimiterIndex+1);if(isSensitiveKey(key)){sanitized.push(`--${key}=[redacted]`)}else{sanitized.push(`--${key}=${sanitizeString(value,captureLevel)}`)}continue}if(isSensitiveKey(withoutPrefix)){sanitized.push(`--${withoutPrefix}`);nextIsSensitiveValue=true;continue}}sanitized.push(arg)}return sanitized}function normalizeCaptureLevel(value){const normalized=value?.trim().toLowerCase();if(normalized==="minimal"||normalized==="redacted"||normalized==="max"){return normalized}return"redacted"}function parseBooleanTrueLike(value){return BOOLEAN_TRUE_VALUES.has((value??"").trim().toLowerCase())}function resolveTelemetryHttpTimeoutMs(){const rawConfigured=process.env[PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV]?.trim();if(!rawConfigured){return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}const configured=Number(rawConfigured);if(!Number.isFinite(configured)){return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}return Math.min(TELEMETRY_HTTP_TIMEOUT_MAX_MS,Math.max(TELEMETRY_HTTP_TIMEOUT_MIN_MS,Math.trunc(configured)))}async function postTelemetryJson(endpoint,headers,body){const url=new URL(endpoint);if(globalThis.fetch!==NATIVE_FETCH){const controller=new AbortController;let timeout;const deadline=new Promise((_resolve,reject)=>{timeout=setTimeout(()=>{controller.abort();reject(new Error("telemetry_http_timeout"))},resolveTelemetryHttpTimeoutMs())});try{const response=await Promise.race([globalThis.fetch(endpoint,{method:"POST",headers,body,signal:controller.signal}),deadline]);return response.status}finally{clearTimeout(timeout)}}const request=url.protocol==="https:"?httpsRequest:url.protocol==="http:"?httpRequest:void 0;if(!request){throw new Error(`telemetry_http_protocol_unsupported_${url.protocol}`)}return new Promise((resolve,reject)=>{const timeoutMs=resolveTelemetryHttpTimeoutMs();const requestOptions={method:"POST",headers:{...headers,"content-length":Buffer.byteLength(body)},signal:AbortSignal.timeout(timeoutMs),autoSelectFamilyAttemptTimeout:Math.min(5e3,timeoutMs)};const clientRequest=request(url,requestOptions,response=>{response.once("error",reject);response.once("end",()=>resolve(response.statusCode));response.resume()});clientRequest.once("error",reject);clientRequest.end(body)})}function normalizePmVersion(value){const trimmed=typeof value==="string"?value.trim():"";return trimmed.length>0?trimmed:"0.0.0"}function normalizeTelemetryErrorCode(value){const normalized=value?.trim();return normalized&&normalized.length>0?normalized:void 0}function normalizeTelemetryExitCode(exitCode,ok){if(Number.isFinite(exitCode)){return Math.max(0,Math.trunc(exitCode))}return ok?0:1}function normalizeTelemetryErrorCategory(params){if(params.ok){return void 0}if(typeof params.errorCategory==="string"&¶ms.errorCategory.trim().length>0){return params.errorCategory}if(typeof params.errorCode==="string"&¶ms.errorCode.trim().length>0){return resolveTelemetryErrorCategory(params.errorCode)}return"unknown"}function resolveTelemetrySourceContext(globalOptions){const override=(process.env[PM_TELEMETRY_SOURCE_CONTEXT_ENV]??"").trim().toLowerCase();if(PM_TELEMETRY_SOURCE_CONTEXT_SET.has(override)){return{source_context:override,source_context_source:"env_override"}}const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"){return{source_context:"test",source_context_source:"inferred"}}const nonTty=process.stdin.isTTY!==true||process.stdout.isTTY!==true;const ci=parseBooleanTrueLike(process.env.CI);const scriptLikeMode=globalOptions.json===true||globalOptions.quiet===true;if(nonTty||ci||scriptLikeMode){return{source_context:"automation",source_context_source:"inferred"}}return{source_context:"user",source_context_source:"inferred"}}function hashWithInstallationId(installationId,value){return crypto.createHash("sha256").update(`${installationId}:${value}`).digest("hex")}function buildAuthorContextPayloadFields(captureLevel,installationId){const author=(readAuthorEnvironment()??"").trim();const agent=detectAgentIdentity({env:process.env,argv:process.argv});const hasAgentContext=agent.harness!==void 0||agent.model!==void 0;if(captureLevel==="minimal"){return{has_author_context:author.length>0,has_agent_context:hasAgentContext}}return{...author.length>0?{author_context_hash:hashWithInstallationId(installationId,author)}:{},...agent.harness?{agent_harness_hash:hashWithInstallationId(installationId,agent.harness)}:{},...agent.model?{agent_model_hash:hashWithInstallationId(installationId,agent.model)}:{},...agent.model_source?{agent_model_source:agent.model_source}:{}}}function normalizeForHash(value,depth=0){if(value===null||value===void 0){return value}if(typeof value==="string"||typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>normalizeForHash(entry,depth+1))}if(typeof value==="object"){const record=value;const normalized={};const sortedKeys=Object.keys(record).sort((left,right)=>left.localeCompare(right));for(const key of sortedKeys){normalized[key]=normalizeForHash(record[key],depth+1)}return normalized}return String(value)}function hashTelemetryValue(installationId,value){return hashWithInstallationId(installationId,JSON.stringify(normalizeForHash(value)))}function hashCommandArgs(installationId,args){return{hashes:args.map(arg=>hashWithInstallationId(installationId,arg)),digest:hashWithInstallationId(installationId,args.join("\0"))}}function hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage){const normalizedMessage=sanitizeString(typeof errorMessage==="string"?errorMessage:"","redacted");const normalizedCode=typeof errorCode2==="string"&&errorCode2.length>0?errorCode2:"unknown_error";const fingerprintSource=`${command}\0${normalizedCode}\0${normalizedMessage}`;return hashWithInstallationId(installationId,fingerprintSource)}function telemetryDisabledByEnvironment(){return PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_TELEMETRY_DISABLED_ENV]??"").trim().toLowerCase())||PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_NO_TELEMETRY_ENV]??"").trim().toLowerCase())}function resolveOtelTracesEndpoint(){if(PM_TELEMETRY_OTEL_DISABLED_VALUES.has((process.env[PM_TELEMETRY_OTEL_DISABLED_ENV]??"").trim().toLowerCase())){return null}const directEndpoint=(process.env[OTEL_TRACES_ENDPOINT_ENV]??"").trim();if(directEndpoint.length>0){try{return new URL(directEndpoint).toString()}catch{return null}}const baseEndpoint=(process.env[OTEL_BASE_ENDPOINT_ENV]??"").trim();if(baseEndpoint.length===0){return null}try{const url=new URL(baseEndpoint);const normalizedPath=url.pathname.replace(/\/+$/,"");if(!normalizedPath.endsWith("/v1/traces")){url.pathname=`${normalizedPath.length===0?"":normalizedPath}/v1/traces`}return url.toString()}catch{return null}}function isoToUnixNano(iso){const parsedMs=Date.parse(iso);const epochMs=Number.isNaN(parsedMs)?Date.now():parsedMs;return`${BigInt(epochMs)*1000000n}`}function otlpStringAttribute(key,value){return{key,value:{stringValue:value}}}function otlpBoolAttribute(key,value){return{key,value:{boolValue:value}}}function otlpIntAttribute(key,value){return{key,value:{intValue:String(Math.max(0,Math.trunc(value)))}}}function buildOtelSpanRequest(activeCommand,outcome,finishedAtIso,durationMs){if(typeof activeCommand.otel_traces_endpoint!=="string"||activeCommand.otel_traces_endpoint.trim().length===0||typeof activeCommand.otel_trace_id!=="string"||activeCommand.otel_trace_id.length===0||typeof activeCommand.otel_span_id!=="string"||activeCommand.otel_span_id.length===0){return null}const serviceNameCandidate=sanitizeString((process.env[OTEL_SERVICE_NAME_ENV]??"").trim());const serviceName=serviceNameCandidate.length>0?serviceNameCandidate:"pm-cli";const normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok);const normalizedErrorCode=normalizeTelemetryErrorCode(outcome.error_code);const normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category});const attributes=[otlpStringAttribute("pm.command",sanitizeString(activeCommand.command)),otlpStringAttribute("pm.version",activeCommand.pm_version),otlpStringAttribute("pm.source_context",activeCommand.source_context),otlpStringAttribute("pm.source_context_source",activeCommand.source_context_source),otlpStringAttribute("pm.installation_id",activeCommand.installation_id),otlpStringAttribute("pm.session_id",PROCESS_SESSION_ID),otlpStringAttribute("pm.pm_root_hash",activeCommand.pm_root_hash),otlpStringAttribute("pm.cwd_hash",activeCommand.cwd_hash),otlpBoolAttribute("pm.ok",outcome.ok),otlpIntAttribute("pm.exit_code",normalizedExitCode),otlpIntAttribute("pm.duration_ms",durationMs)];if(typeof normalizedErrorCode==="string"){attributes.push(otlpStringAttribute("pm.error_code",normalizedErrorCode))}if(typeof normalizedErrorCategory==="string"){attributes.push(otlpStringAttribute("pm.error_category",normalizedErrorCategory))}if(typeof outcome.error==="string"&&outcome.error.trim().length>0){attributes.push(otlpStringAttribute("pm.error",sanitizeString(outcome.error)))}const payload={resourceSpans:[{resource:{attributes:[otlpStringAttribute("service.name",serviceName)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:activeCommand.otel_trace_id,spanId:activeCommand.otel_span_id,name:`pm.command.${sanitizeString(activeCommand.command)}`,kind:1,startTimeUnixNano:isoToUnixNano(activeCommand.started_at),endTimeUnixNano:isoToUnixNano(finishedAtIso),attributes,status:{code:outcome.ok?1:2,message:outcome.ok?"":sanitizeString(typeof outcome.error==="string"?outcome.error:"command_failed")}}]}]}]};return{endpoint:activeCommand.otel_traces_endpoint,payload}}function summarizeResult(result,captureLevel="redacted"){if(result===null||result===void 0){return{type:"nullish"}}if(typeof result==="string"){return{type:"string",value:sanitizeString(result,captureLevel)}}if(typeof result==="number"||typeof result==="boolean"){return{type:typeof result,value:result}}if(Array.isArray(result)){return{type:"array",length:result.length,sample:result.slice(0,5).map(entry=>sanitizeValue(entry,void 0,captureLevel))}}if(typeof result==="object"){const record=result;const keys=Object.keys(record).sort((left,right)=>left.localeCompare(right));const sanitized={};let previewBytes=0;for(const key of keys.slice(0,25)){const sanitizedValue=sanitizeValue(record[key],key,captureLevel);const entrySize=JSON.stringify(sanitizedValue).length;if(previewBytes+entrySize>TELEMETRY_RESULT_PREVIEW_MAX_BYTES){sanitized[key]="[preview_truncated]";break}previewBytes+=entrySize;sanitized[key]=sanitizedValue}return{type:"object",key_count:keys.length,keys_preview:keys.slice(0,50),preview:sanitized}}return{type:typeof result,value:String(result)}}function buildCommandStartPayload(params){const{captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId}=params;const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);const hashedArgs=hashCommandArgs(installationId,context.args);const commandInvocationDigest=hashWithInstallationId(installationId,`${context.command}\0${context.args.join("\0")}`);const commandOptionsDigest=hashTelemetryValue(installationId,context.options);const globalOptionsDigest=hashTelemetryValue(installationId,context.global);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options_digest:commandOptionsDigest,global_options_digest:globalOptionsDigest,...authorContextFields}}return{pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,...authorContextFields,command_args:sanitizeCommandArgs(context.args,captureLevel),command_args_hashes:hashedArgs.hashes,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options:sanitizeValue(context.options,void 0,captureLevel),command_options_digest:commandOptionsDigest,global_options:sanitizeValue(context.global,void 0,captureLevel),global_options_digest:globalOptionsDigest,pm_root_hash:pmRootHash,cwd_hash:cwdHash,capture_level:captureLevel,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}function buildCommandFinishPayload(params){const{captureLevel,pmVersion,sourceContext,outcome,durationMs,startedAt,command,installationId,commandTaxonomy,exitCode,errorCode:errorCode2,errorCategory,commandResolution,resolutionStage}=params;const errorFingerprint=outcome.ok===false?hashTelemetryErrorFingerprint(installationId,command,errorCode2,outcome.error):void 0;const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,"redacted"):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,captureLevel):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,started_at:startedAt,result_summary:summarizeResult(outcome.result,captureLevel)}}function buildCommandErrorPayload(params){const{captureLevel,pmVersion,sourceContext,command,commandTaxonomy,commandResolution,resolutionStage,args,options,pmRootHash,cwdHash,installationId,errorCode:errorCode2,errorMessage,errorCategory,exitCode}=params;const attemptedArgHashes=hashCommandArgs(installationId,args);const attemptedCommandDigest=hashWithInstallationId(installationId,command);const attemptedOptionsDigest=hashTelemetryValue(installationId,options);const errorFingerprint=hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,attempted_command_digest:attemptedCommandDigest,attempted_args_digest:attemptedArgHashes.digest,attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,"redacted"),error_fingerprint:errorFingerprint,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,attempted_command:sanitizeString(command,captureLevel),attempted_command_digest:attemptedCommandDigest,attempted_args:sanitizeCommandArgs(args,captureLevel),attempted_args_hashes:attemptedArgHashes.hashes,attempted_args_digest:attemptedArgHashes.digest,attempted_options:sanitizeValue(options,void 0,captureLevel),attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,captureLevel),error_fingerprint:errorFingerprint,pm_root_hash:pmRootHash,cwd_hash:cwdHash,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}async function ensureInstallationId(globalPmRoot){const settings=await readSettings(globalPmRoot);let changed=false;if(settings.telemetry.installation_id.trim().length===0){settings.telemetry.installation_id=crypto.randomUUID();changed=true}if(changed){await writeSettings(globalPmRoot,settings,"telemetry:install_id")}return{installationId:settings.telemetry.installation_id,endpoint:settings.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(settings.telemetry.retention_days))}}async function enqueueTelemetryEvent(globalPmRoot,event){const queued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event,attempts:0};let serialized=JSON.stringify(queued);if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){const trimmed={...event,payload:{...event.payload,result_summary:{truncated:true,reason:"payload_size_exceeded",original_bytes:serialized.length}}};const trimmedQueued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event:trimmed,attempts:0};serialized=JSON.stringify(trimmedQueued)}await withQueueMutation(async()=>{await appendLineAtomic(queuePath(globalPmRoot),serialized)})}function parseQueueLines(raw){const entries=[];for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}try{const parsed=JSON.parse(trimmed);if(parsed&&typeof parsed==="object"&&parsed.event&&typeof parsed.event==="object"&&typeof parsed.attempts==="number"&&(parsed.client_schema_version===void 0||typeof parsed.client_schema_version==="number"&&Number.isFinite(parsed.client_schema_version))){entries.push(parsed)}}catch{}}return entries}function nextRetryIso(attempts){const delay=Math.min(TELEMETRY_RETRY_BASE_DELAY_MS*2**Math.max(attempts-1,0),TELEMETRY_MAX_RETRY_DELAY_MS);return new Date(Date.now()+delay).toISOString()}function isDueForRetryAt(nextAttemptAfter){if(typeof nextAttemptAfter!=="string"||nextAttemptAfter.trim().length===0){return true}const dueAtMs=Date.parse(nextAttemptAfter);if(Number.isNaN(dueAtMs)){return true}return dueAtMs<=Date.now()}function isDueForRetry(entry){return isDueForRetryAt(entry.next_attempt_after)}function retentionCutoffMs(retentionDays){const normalizedDays=Number.isFinite(retentionDays)?Math.max(1,Math.trunc(retentionDays)):1;return Date.now()-normalizedDays*MILLISECONDS_PER_DAY}function isExpiredQueueEntry(entry,cutoffMs){const occurredAt=entry.event?.occurred_at;if(typeof occurredAt!=="string"||occurredAt.trim().length===0){return false}const occurredAtMs=Date.parse(occurredAt);if(Number.isNaN(occurredAtMs)){return false}return occurredAtMs<cutoffMs}function pruneExpiredQueueEntries(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays);const retained=[];let prunedCount=0;for(const entry of entries){const serializedSize=JSON.stringify(entry).length;const oversized=serializedSize>TELEMETRY_MAX_EVENT_BYTES;if(oversized||isExpiredQueueEntry(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}return{entries:retained,prunedCount}}async function rewriteQueue(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join("\n");const contents=serialized.length>0?`${serialized}
|
|
3
|
+
`:"";for(let attempt=0;;attempt+=1){try{await writeFileAtomic(queuePath(globalPmRoot),contents);return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error)){throw error}await sleep(retryDelay)}}}function isRetryableQueueRewriteError(error){if(typeof error!=="object"||error===null||!("code"in error)){return false}const code=error.code;return code==="EACCES"||code==="EBUSY"||code==="EPERM"}function sleep(milliseconds){return new Promise(resolve=>{setTimeout(resolve,milliseconds)})}async function enqueuePendingOtelSpan(globalPmRoot,request){const pending={id:crypto.randomUUID(),endpoint:request.endpoint,payload:request.payload,enqueued_at:nowIso(),attempts:0};const serialized=JSON.stringify(pending);if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){return}await withQueueMutation(async()=>{await appendLineAtomic(otelSpansQueuePath(globalPmRoot),serialized)})}function backfillPendingOtelSpanId(entry){const material=JSON.stringify([entry.endpoint,entry.enqueued_at,entry.payload]);return crypto.createHash("sha256").update(material).digest("hex").slice(0,32)}function parsePendingOtelSpanLines(raw){const entries=[];for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}try{const parsed=JSON.parse(trimmed);if(parsed&&typeof parsed==="object"&&typeof parsed.endpoint==="string"&&parsed.endpoint.trim().length>0&&"payload"in parsed&&typeof parsed.attempts==="number"&&Number.isFinite(parsed.attempts)){if(typeof parsed.id!=="string"||parsed.id.length===0){parsed.id=backfillPendingOtelSpanId(parsed)}entries.push(parsed)}}catch{}}return entries}function isExpiredPendingOtelSpan(entry,cutoffMs){if(typeof entry.enqueued_at!=="string"||entry.enqueued_at.trim().length===0){return false}const enqueuedAtMs=Date.parse(entry.enqueued_at);if(Number.isNaN(enqueuedAtMs)){return false}return enqueuedAtMs<cutoffMs}function prunePendingOtelSpans(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays);const retained=[];let prunedCount=0;for(const entry of entries){const oversized=JSON.stringify(entry).length>TELEMETRY_MAX_EVENT_BYTES;if(oversized||isExpiredPendingOtelSpan(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}if(retained.length>TELEMETRY_OTEL_SPANS_MAX_PENDING){const overflow=retained.length-TELEMETRY_OTEL_SPANS_MAX_PENDING;prunedCount+=overflow;return{entries:retained.slice(overflow),prunedCount}}return{entries:retained,prunedCount}}async function rewritePendingOtelSpans(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join("\n");const contents=serialized.length>0?`${serialized}
|
|
4
|
+
`:"";for(let attempt=0;;attempt+=1){try{await writeFileAtomic(otelSpansQueuePath(globalPmRoot),contents);return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error)){throw error}await sleep(retryDelay)}}}async function reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates){return withQueueMutation(async()=>{const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));const current=raw===null?[]:parsePendingOtelSpanLines(raw);const reconciled=[];for(const entry of current){if(succeededIds.has(entry.id)){continue}const failure=failedUpdates.get(entry.id);reconciled.push(failure?{...entry,attempts:failure.attempts,next_attempt_after:failure.next_attempt_after}:entry)}const{entries:retained}=prunePendingOtelSpans(reconciled,retentionDays);await rewritePendingOtelSpans(globalPmRoot,retained);return retained.length})}async function flushPendingOtelSpans(globalPmRoot,retentionDays){const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));if(raw===null||raw.trim().length===0){await writeRuntimeState(globalPmRoot,{pending_otel_spans:0});return}const entries=parsePendingOtelSpanLines(raw);const{entries:retained,prunedCount}=prunePendingOtelSpans(entries,retentionDays);const due=retained.filter(entry=>isDueForRetryAt(entry.next_attempt_after)).slice(0,TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE);if(due.length===0){const remaining2=prunedCount>0?await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,new Set,new Map):retained.length;await writeRuntimeState(globalPmRoot,{pending_otel_spans:remaining2});return}const attemptTime=nowIso();const succeededIds=new Set;const failedUpdates=new Map;let succeededCount=0;let lastError;await Promise.all(due.map(async span=>{try{const status=await postTelemetryJson(span.endpoint,{"content-type":"application/json"},JSON.stringify(span.payload));if(status<200||status>=300){throw new Error(`local_otel_export_http_${status}`)}succeededIds.add(span.id);succeededCount+=1}catch(error){lastError=error instanceof Error?sanitizeString(error.message,"redacted"):"local_otel_export_failed";const nextAttempts=span.attempts+1;failedUpdates.set(span.id,{attempts:nextAttempts,next_attempt_after:nextRetryIso(nextAttempts)})}}));const remaining=await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates);const statePatch={pending_otel_spans:remaining,last_otel_attempt_at:attemptTime};if(succeededCount>0){statePatch.last_otel_success_at=attemptTime}if(lastError!==void 0){statePatch.last_otel_failure_at=attemptTime;statePatch.last_otel_failure_error=lastError}else if(remaining===0){statePatch.last_otel_failure_at=void 0;statePatch.last_otel_failure_error=void 0}await writeRuntimeState(globalPmRoot,statePatch)}async function flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays){try{await flushQueue(globalPmRoot,endpoint,retentionDays)}catch{}try{await flushPendingOtelSpans(globalPmRoot,retentionDays)}catch{}}async function cleanupTelemetryQueueTempOrphans(globalPmRoot,maxAgeMs=TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS){try{const dirPath=telemetryRuntimeDirectory(globalPmRoot);const entries=await readdir(dirPath,{withFileTypes:true});const cutoffMs=Date.now()-Math.max(0,maxAgeMs);await Promise.all(entries.filter(entry=>entry.isFile()&&/^\.events\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(entry.name)).map(async entry=>{const candidate=path.join(dirPath,entry.name);const candidateStats=await stat(candidate);if(candidateStats.mtimeMs<cutoffMs){await rm(candidate,{force:true})}}))}catch{}}async function withQueueMutation(operation){const run=_queueMutationPromise.catch(()=>{}).then(operation);_queueMutationPromise=run.catch(()=>{});return run}async function readCurrentQueueEntries(globalPmRoot){const raw=await readFileIfExists(queuePath(globalPmRoot));if(raw===null||raw.trim().length===0){return[]}return parseQueueLines(raw)}async function removeFlushedEntriesFromCurrentQueue(globalPmRoot,flushedIds,retentionDays){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot);const{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays);const remaining=retainedEntries.filter(entry=>!flushedIds.has(entry.event.event_id));await rewriteQueue(globalPmRoot,remaining);return remaining})}async function markFailedEntriesInCurrentQueue(globalPmRoot,failedIds,attemptTime,retentionDays){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot);const{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays);const retried=retainedEntries.map(entry=>{if(!failedIds.has(entry.event.event_id)){return entry}const attempts=entry.attempts+1;return{...entry,attempts,last_attempt_at:attemptTime,next_attempt_after:nextRetryIso(attempts)}});await rewriteQueue(globalPmRoot,retried);return retried})}async function flushQueue(globalPmRoot,endpoint,retentionDays){await cleanupTelemetryQueueTempOrphans(globalPmRoot);const normalizedEndpoint=endpoint.trim();if(normalizedEndpoint.length===0){return}const raw=await readFileIfExists(queuePath(globalPmRoot));if(raw===null||raw.trim().length===0){await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const queueEntries=parseQueueLines(raw);if(queueEntries.length===0){await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const{entries:retainedEntries,prunedCount}=pruneExpiredQueueEntries(queueEntries,retentionDays);if(retainedEntries.length===0){await rewriteQueue(globalPmRoot,[]);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const dueEntries=retainedEntries.filter(entry=>isDueForRetry(entry)).slice(0,TELEMETRY_FLUSH_BATCH_SIZE);if(dueEntries.length===0){if(prunedCount>0){await rewriteQueue(globalPmRoot,retainedEntries)}await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:retainedEntries.length});return}const dueIds=new Set(dueEntries.map(entry=>entry.event.event_id));const attemptTime=nowIso();const requestHeaders={"content-type":"application/json"};const ingestKey=process.env.PM_TELEMETRY_INGEST_KEY?.trim();if(ingestKey){requestHeaders["x-pm-telemetry-key"]=ingestKey}try{const status=await postTelemetryJson(normalizedEndpoint,requestHeaders,JSON.stringify({schema_version:TELEMETRY_SCHEMA_VERSION,events:dueEntries.map(entry=>entry.event)}));if(status<200||status>=300){throw new Error(`telemetry_flush_http_${status}`)}}catch(error){const retried=await markFailedEntriesInCurrentQueue(globalPmRoot,dueIds,attemptTime,retentionDays);const errorMessage=(()=>{if(error instanceof Error){return sanitizeString(error.message,"redacted")}return"telemetry_flush_failed"})();await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:retried.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage});return}try{const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,dueIds,retentionDays);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.length,last_attempted_flush_at:attemptTime,last_successful_flush_at:attemptTime,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(error){const errorMessage=(()=>{if(error instanceof Error){return sanitizeString(error.message,"redacted")}return"telemetry_flush_failed"})();const currentEntries=await readCurrentQueueEntries(globalPmRoot).catch(()=>retainedEntries);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:currentEntries.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage})}}async function acquireTelemetryFlushLock(globalPmRoot){const lockPath=flushLockPath(globalPmRoot);await mkdir(path.dirname(lockPath),{recursive:true});try{await mkdir(lockPath);return true}catch(error){if(typeof error!=="object"||error===null||!("code"in error)||error.code!=="EEXIST"){throw error}}try{const lockStats=await stat(lockPath);if(Date.now()-lockStats.mtimeMs<TELEMETRY_FLUSH_LOCK_STALE_MS){return false}await rm(lockPath,{recursive:true,force:true});await mkdir(lockPath);return true}catch{return false}}function isFreshDirectoryLock(lockPath,staleMs){try{return Date.now()-statSync(lockPath).mtimeMs<staleMs}catch{return false}}function removeDirectoryLockBestEffort(lockPath){try{rmSync(lockPath,{recursive:true,force:true})}catch{}}function errorCode(error){if(typeof error!=="object"||error===null||!("code"in error)){return void 0}const code=error.code;return typeof code==="string"?code:void 0}function createDirectoryLock(lockPath){try{mkdirSync(lockPath);return true}catch(error){const code=errorCode(error);if(code==="EEXIST"){return false}if(!isFileMissingError(error)){return false}}try{mkdirSync(path.dirname(lockPath),{recursive:true});mkdirSync(lockPath);return true}catch{return false}}function acquireTelemetryFlushSpawnGate(globalPmRoot){if(isFreshDirectoryLock(flushLockPath(globalPmRoot),TELEMETRY_FLUSH_LOCK_STALE_MS)){return false}const lockPath=flushSpawnLockPath(globalPmRoot);try{if(Date.now()-statSync(lockPath).mtimeMs<TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS){return false}removeDirectoryLockBestEffort(lockPath)}catch(error){if(!isFileMissingError(error)){return false}}return createDirectoryLock(lockPath)}function releaseTelemetryFlushSpawnGate(globalPmRoot){removeDirectoryLockBestEffort(flushSpawnLockPath(globalPmRoot))}const _testOnly={acquireTelemetryFlushSpawnGate,acquireTelemetryFlushLock,buildAuthorContextPayloadFields,buildCommandErrorPayload,buildCommandFinishPayload,buildCommandStartPayload,buildOtelSpanRequest,createDirectoryLock,enqueuePendingOtelSpan,enqueueTelemetryEvent,errorCode,flushPendingOtelSpans,flushQueue,flushQueueWithProcessLock,flushTelemetryArtifacts,hashTelemetryErrorFingerprint,hashTelemetryValue,isEmailDomainCharacter,isEmailLocalCharacter,isExpiredPendingOtelSpan,isExpiredQueueEntry,isFreshDirectoryLock,isDueForRetry,isDueForRetryAt,isRetryableQueueRewriteError,looksLikeEmailToken,otelSpansQueuePath,parseBooleanTrueLike,postTelemetryJson,parsePendingOtelSpanLines,prunePendingOtelSpans,reconcilePendingOtelSpansAfterFlush,retentionCutoffMs,resolveOtelTracesEndpoint,resolveTelemetryHttpTimeoutMs,rewritePendingOtelSpans,normalizeForHash,normalizeCaptureLevel,normalizePmVersion,normalizeTelemetryErrorCategory,normalizeTelemetryErrorCode,normalizeTelemetryExitCode,parseQueueLines,pruneExpiredQueueEntries,readRuntimeState,readCurrentQueueEntries,releaseTelemetryFlushSpawnGate,removeFlushedEntriesFromCurrentQueue,removeDirectoryLockBestEffort,resolveTelemetrySourceContext,rewriteQueue,sanitizeCommandArgs,sanitizeStringMax,sanitizeStringRedacted,sanitizeValue,scheduleTelemetryFlush,shouldFlushInline,sleep,summarizeResult,telemetryFlushRunnerPath,withQueueMutation,flushLockPath,flushSpawnLockPath,runtimeStatePath,writeRuntimeState};async function flushQueueWithProcessLock(globalPmRoot,endpoint,retentionDays){const acquired=await acquireTelemetryFlushLock(globalPmRoot);releaseTelemetryFlushSpawnGate(globalPmRoot);if(!acquired){return}try{await flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays)}finally{try{await rm(flushLockPath(globalPmRoot),{recursive:true,force:true})}catch{}}}function scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays){if(shouldFlushInline()){const previousFlush=_lastFlushPromise;const nextFlush=flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays);_lastFlushPromise=Promise.allSettled([previousFlush,nextFlush]).then(()=>{});return}try{const acquiredSpawnGate=acquireTelemetryFlushSpawnGate(globalPmRoot);if(!acquiredSpawnGate){return}const child=spawn(process.execPath,[telemetryFlushRunnerPath()],{detached:true,stdio:"ignore",cwd:os.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:globalPmRoot,[PM_TELEMETRY_FLUSH_CHILD_ENV]:"1"}});child.on("error",()=>{releaseTelemetryFlushSpawnGate(globalPmRoot)});child.unref()}catch{releaseTelemetryFlushSpawnGate(globalPmRoot)}}async function flushTelemetryQueueNow(globalPmRoot=resolveGlobalPmRoot(process.cwd())){if(telemetryDisabledByEnvironment()){return}try{const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const{endpoint,retentionDays}=await ensureInstallationId(globalPmRoot);await flushQueueWithProcessLock(globalPmRoot,endpoint,retentionDays)}catch{}}async function startTelemetryCommand(context){if(telemetryDisabledByEnvironment()){return null}if(context.command==="telemetry"&&context.args.some(token=>token.trim().toLowerCase()==="clear")){return null}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return null}const captureLevel=normalizeCaptureLevel(settings.telemetry.capture_level);const{installationId,endpoint,retentionDays}=await ensureInstallationId(globalPmRoot);const pmVersion=normalizePmVersion(context.pm_version);const sourceContext=resolveTelemetrySourceContext(context.global);const pmRootHash=hashWithInstallationId(installationId,context.pm_root);const cwdHash=hashWithInstallationId(installationId,process.cwd());const otelTracesEndpoint=resolveOtelTracesEndpoint();const occurredAt=nowIso();const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_start",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:context.command,payload:buildCommandStartPayload({captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId})};await enqueueTelemetryEvent(globalPmRoot,event);scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays);const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);return{started_at:occurredAt,started_at_ms:Date.now(),command:context.command,command_taxonomy:commandTaxonomy,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,installation_id:installationId,pm_root_hash:pmRootHash,cwd_hash:cwdHash,endpoint,retention_days:retentionDays,global_pm_root:globalPmRoot,capture_level:captureLevel,otel_traces_endpoint:otelTracesEndpoint??void 0,otel_trace_id:otelTracesEndpoint?crypto.randomBytes(16).toString("hex"):void 0,otel_span_id:otelTracesEndpoint?crypto.randomBytes(8).toString("hex"):void 0}}catch{return null}}async function finishTelemetryCommand(activeCommand,outcome){if(!activeCommand){return}try{const finishedAt=nowIso();const durationMs=Math.max(0,Date.now()-activeCommand.started_at_ms);const normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:outcome.ok,errorCode:outcome.error_code,errorMessage:outcome.error,exitCode:outcome.exit_code}));const normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category});const normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok);const commandResolution=outcome.command_resolution??deriveTelemetryCommandResolution({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory});const resolutionStage=outcome.resolution_stage??"execute";const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_finish",occurred_at:finishedAt,installation_id:activeCommand.installation_id,session_id:PROCESS_SESSION_ID,command:activeCommand.command,payload:buildCommandFinishPayload({captureLevel:activeCommand.capture_level,pmVersion:activeCommand.pm_version,sourceContext:{source_context:activeCommand.source_context,source_context_source:activeCommand.source_context_source},outcome,durationMs,startedAt:activeCommand.started_at,command:activeCommand.command,installationId:activeCommand.installation_id,commandTaxonomy:activeCommand.command_taxonomy,exitCode:normalizedExitCode,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,commandResolution,resolutionStage})};await enqueueTelemetryEvent(activeCommand.global_pm_root,event);const otelRequest=buildOtelSpanRequest(activeCommand,{...outcome,exit_code:normalizedExitCode,error_code:normalizedErrorCode,error_category:normalizedErrorCategory},finishedAt,durationMs);if(otelRequest){await enqueuePendingOtelSpan(activeCommand.global_pm_root,otelRequest)}scheduleTelemetryFlush(activeCommand.global_pm_root,activeCommand.endpoint,activeCommand.retention_days)}catch{}}async function emitTelemetryErrorEvent(context){if(telemetryDisabledByEnvironment()){return}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const captureLevel=normalizeCaptureLevel(settings.telemetry.capture_level);const{installationId,endpoint,retentionDays}=await ensureInstallationId(globalPmRoot);const pmVersion=normalizePmVersion(context.pm_version);const sourceContext=resolveTelemetrySourceContext(context.global);const pmRootHash=hashWithInstallationId(installationId,context.pm_root);const cwdHash=hashWithInstallationId(installationId,process.cwd());const occurredAt=nowIso();const normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:false,errorCode:context.error_code,errorMessage:context.error_message,exitCode:context.exit_code}));const normalizedErrorCategory=context.error_category??resolveTelemetryErrorCategory(normalizedErrorCode);const normalizedExitCode=normalizeTelemetryExitCode(context.exit_code,false);const normalizedCommand=context.command.trim().length>0?context.command:"<unknown>";const commandTaxonomy=deriveTelemetryCommandTaxonomy(normalizedCommand);const commandResolution=context.command_resolution??deriveTelemetryCommandResolution({ok:false,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory});const resolutionStage=context.resolution_stage??"unknown";const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_error",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:sanitizeString(normalizedCommand,"redacted"),payload:buildCommandErrorPayload({captureLevel,pmVersion,sourceContext,command:normalizedCommand,commandTaxonomy,commandResolution,resolutionStage,args:context.args,options:context.options,pmRootHash,cwdHash,installationId,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,exitCode:normalizedExitCode,errorMessage:context.error_message})};await enqueueTelemetryEvent(globalPmRoot,event);scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays)}catch{}}export{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,TELEMETRY_SCHEMA_VERSION,_testOnly,emitTelemetryErrorEvent,finishTelemetryCommand,flushTelemetryQueueNow,startTelemetryCommand,waitForPendingFlush};
|
|
1988
5
|
//# sourceMappingURL=runtime.js.map
|
|
1989
|
-
//# debugId=26ea62d9-874d-5826-9822-83c5523b673b
|