@unbrained/pm-cli 2026.10.1 → 2026.10.3

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.
Files changed (134) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +23 -0
  3. package/dist/cli/error-guidance.d.ts +5 -0
  4. package/dist/cli/error-guidance.js +1 -1
  5. package/dist/cli/main.js +2 -2
  6. package/dist/cli/register-structured-mutation.d.ts +2 -0
  7. package/dist/cli/register-structured-mutation.js +1 -1
  8. package/dist/cli/runtime/projection-retry.d.ts +9 -0
  9. package/dist/cli/runtime/projection-retry.js +2 -0
  10. package/dist/cli/runtime/selection.d.ts +5 -1
  11. package/dist/cli/runtime/selection.js +1 -1
  12. package/dist/cli-bundle/bundle-manifest.json +156 -156
  13. package/dist/cli-bundle/chunks/chunk-3AF2R3Y6.js +6 -0
  14. package/dist/cli-bundle/chunks/chunk-44UGMMQ6.js +3 -0
  15. package/dist/cli-bundle/chunks/{chunk-VWVFKPLX.js → chunk-5XKF5SQV.js} +38 -38
  16. package/dist/cli-bundle/chunks/{chunk-AYHLUJKD.js → chunk-6ST3SCQ6.js} +2 -2
  17. package/dist/cli-bundle/chunks/chunk-6Z4IV2MC.js +8 -0
  18. package/dist/cli-bundle/chunks/{chunk-A2UPOCSW.js → chunk-FW5LJXQY.js} +31 -31
  19. package/dist/cli-bundle/chunks/{chunk-SCZMJ5DC.js → chunk-H2DZW6I6.js} +2 -2
  20. package/dist/cli-bundle/chunks/chunk-H7CXQBGQ.js +2 -0
  21. package/dist/cli-bundle/chunks/{chunk-DGOIXJZJ.js → chunk-KP7NBQK3.js} +47 -47
  22. package/dist/cli-bundle/chunks/chunk-MKXBCBAN.js +20 -0
  23. package/dist/cli-bundle/chunks/chunk-QPKQKSQU.js +238 -0
  24. package/dist/cli-bundle/chunks/chunk-YCBGZF3T.js +2 -0
  25. package/dist/cli-bundle/chunks/chunk-YDWKGUQU.js +3 -0
  26. package/dist/cli-bundle/chunks/{register-list-query-L6HAHW7V.js → register-list-query-DYCGUQEW.js} +2 -2
  27. package/dist/cli-bundle/chunks/register-mutation-5PT3NW3A.js +20 -0
  28. package/dist/cli-bundle/chunks/{register-operations-3E5U4TOE.js → register-operations-QDDQOAAV.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-setup-VUD37N4A.js → register-setup-BBX67YMA.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-MOUCTR72.js → chunk-3BIYG72P.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-T4PZJQG4.js → chunk-4FFPGNCJ.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-YBQ27KG7.js → chunk-73DA7ISY.js} +47 -47
  33. package/dist/cli-bundle/focused-chunks/{chunk-XUCXRZZZ.js → chunk-DBD4W4QP.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-6275G2AN.js → chunk-E754JDLY.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-4AORVUT4.js → chunk-EJN7DY3B.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-OMBDUJWZ.js → chunk-FKK2HI3S.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-ZJ3CLTV4.js → chunk-GMYUNHST.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/chunk-HIA2ZF64.js +12 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-RIJQQOEZ.js → chunk-UTRSM3ZK.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-EVMH4SKN.js → chunk-VVWYI2X7.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-WAJNX4RN.js +20 -0
  42. package/dist/cli-bundle/focused-chunks/chunk-WCY6HRZO.js +30 -0
  43. package/dist/cli-bundle/focused-chunks/{chunk-XB5Q2P7Z.js → chunk-XRSCIYHR.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-YC32ZSLS.js +165 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-IQBFYQF2.js → chunk-ZIXFMIUL.js} +2 -2
  46. package/dist/cli-bundle/main.js +22 -22
  47. package/dist/cli-bundle/sdk-authoring.js +1 -1
  48. package/dist/cli-bundle/sdk-contracts.js +2 -2
  49. package/dist/cli-bundle/sdk-core.js +31 -31
  50. package/dist/cli-bundle/sdk-governance.js +1 -1
  51. package/dist/cli-bundle/sdk-graph.js +1 -1
  52. package/dist/cli-bundle/sdk-merge.js +48 -48
  53. package/dist/cli-bundle/sdk-query.js +1 -1
  54. package/dist/cli-bundle/sdk-runtime.js +1 -1
  55. package/dist/cli-bundle/sdk-testing.js +1 -1
  56. package/dist/cli-bundle/sdk.js +7 -7
  57. package/dist/core/fs/fs-utils.d.ts +11 -0
  58. package/dist/core/fs/fs-utils.js +2 -2
  59. package/dist/core/shared/errors.d.ts +9 -0
  60. package/dist/core/shared/errors.js +1 -1
  61. package/dist/core/shared/secret-rules.js +1 -1
  62. package/dist/core/store/settings.d.ts +15 -5
  63. package/dist/core/store/settings.js +3 -3
  64. package/dist/core/telemetry/runtime.js +3 -3
  65. package/dist/mcp/server.js +1 -1
  66. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  67. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  68. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  69. package/dist/sdk/item-transaction.d.ts +11 -0
  70. package/dist/sdk/item-transaction.js +1 -1
  71. package/dist/sdk/linked-artifacts.d.ts +1 -1
  72. package/dist/sdk/linked-artifacts.js +1 -1
  73. package/dist/sdk/pagination.js +1 -1
  74. package/dist/sdk/public-surface.json +1 -1
  75. package/dist/sdk/query/context.d.ts +2 -0
  76. package/dist/sdk/query/context.js +1 -1
  77. package/dist/sdk/query/get.js +1 -1
  78. package/dist/sdk/query/list.js +1 -1
  79. package/dist/sdk/query/search-contracts.js +1 -1
  80. package/dist/sdk/query/search-pagination.d.ts +4 -0
  81. package/dist/sdk/query/search-pagination.js +1 -1
  82. package/dist/sdk/query/search.js +1 -1
  83. package/dist/sdk/read-output/options.d.ts +14 -0
  84. package/dist/sdk/read-output/options.js +2 -0
  85. package/dist/sdk/read-output-budget.js +1 -1
  86. package/dist/sdk/read-output-contracts.js +1 -1
  87. package/dist/sdk/read-output-rows.d.ts +4 -0
  88. package/dist/sdk/read-output-rows.js +1 -1
  89. package/dist/sdk/runtime-primitives.d.ts +2 -2
  90. package/dist/sdk/runtime-primitives.js +1 -1
  91. package/dist/sdk/runtime.js +1 -1
  92. package/dist/sdk/test/execution.js +2 -2
  93. package/dist/sdk/test/workspace-snapshot.d.ts +11 -0
  94. package/dist/sdk/test/workspace-snapshot.js +2 -0
  95. package/dist/sdk/workspace-transaction.d.ts +2 -0
  96. package/dist/sdk/workspace-transaction.js +2 -2
  97. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +109 -0
  98. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +27 -0
  99. package/docs/SDK.md +98 -0
  100. package/docs/TESTING.md +32 -5
  101. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +5 -3
  102. package/marketplace.json +2 -2
  103. package/package.json +5 -4
  104. package/packages/pm-beads/package.json +1 -1
  105. package/packages/pm-calendar/package.json +1 -1
  106. package/packages/pm-command-kit/package.json +1 -1
  107. package/packages/pm-digital-twin/package.json +1 -1
  108. package/packages/pm-governance-audit/package.json +1 -1
  109. package/packages/pm-guide-shell/package.json +1 -1
  110. package/packages/pm-kanban/package.json +1 -1
  111. package/packages/pm-lifecycle-hooks/package.json +1 -1
  112. package/packages/pm-linked-test-adapters/package.json +1 -1
  113. package/packages/pm-search-advanced/package.json +1 -1
  114. package/packages/pm-templates/package.json +1 -1
  115. package/packages/pm-todos/package.json +1 -1
  116. package/packages/pm-vcs/package.json +1 -1
  117. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  118. package/plugins/pm-claude/package.json +2 -2
  119. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  120. package/plugins/pm-codex/package.json +2 -2
  121. package/plugins/pm-codex/plugin.json +1 -1
  122. package/dist/cli-bundle/chunks/chunk-7E2EBJLY.js +0 -3
  123. package/dist/cli-bundle/chunks/chunk-BNAT4EYR.js +0 -20
  124. package/dist/cli-bundle/chunks/chunk-HGJLVN56.js +0 -8
  125. package/dist/cli-bundle/chunks/chunk-JAVO3Z42.js +0 -6
  126. package/dist/cli-bundle/chunks/chunk-TV3YDE36.js +0 -2
  127. package/dist/cli-bundle/chunks/chunk-UIAH7UFK.js +0 -238
  128. package/dist/cli-bundle/chunks/chunk-USTAFHIM.js +0 -2
  129. package/dist/cli-bundle/chunks/chunk-YM342ELM.js +0 -3
  130. package/dist/cli-bundle/chunks/register-mutation-6OCZVTW5.js +0 -20
  131. package/dist/cli-bundle/focused-chunks/chunk-3CAZ7Z4R.js +0 -30
  132. package/dist/cli-bundle/focused-chunks/chunk-DJPP2HAK.js +0 -12
  133. package/dist/cli-bundle/focused-chunks/chunk-IDB6E3ZV.js +0 -165
  134. package/dist/cli-bundle/focused-chunks/chunk-UPOMLSW7.js +0 -20
@@ -1,6 +1,6 @@
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]="f0ef8253-1b96-56d2-bf94-6ff5debcab08")}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{acquireLock}from"../lock/lock.js";import{isActiveCommandUnextended,runWithIsolatedExtensionRuntime}from"../extensions/index.js";import{resolveAutomaticReadSampleRate}from"./read-sampling.js";import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,resolveTelemetryEnvironmentPolicy}from"./policy.js";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{clearSettingsReadCache}from"../store/settings-read-cache.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 TELEMETRY_FOREGROUND_LOCK_WAIT_MS=250;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_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;import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES as PM_TELEMETRY_SOURCE_CONTEXT_VALUES2}from"./policy.js";let sourceContextWarningEmitted=false;let _lastFlushPromise=Promise.resolve();let _queueMutationPromise=Promise.resolve();const deferredReadStarts=new WeakMap;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 TELEMETRY_HARNESSES=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]);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{await withQueueMutation(async()=>{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)}
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]="24609690-c2af-5957-872b-772dc57ac0ae")}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{acquireLock}from"../lock/lock.js";import{isActiveCommandUnextended,runWithIsolatedExtensionRuntime}from"../extensions/index.js";import{resolveAutomaticReadSampleRate}from"./read-sampling.js";import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,resolveTelemetryEnvironmentPolicy}from"./policy.js";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{isConfigurationOnlySettingsRead,readSettings,writeSettings}from"../store/settings.js";import{clearSettingsReadCache}from"../store/settings-read-cache.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 TELEMETRY_FOREGROUND_LOCK_WAIT_MS=250;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_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;import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES as PM_TELEMETRY_SOURCE_CONTEXT_VALUES2}from"./policy.js";let sourceContextWarningEmitted=false;let _lastFlushPromise=Promise.resolve();let _queueMutationPromise=Promise.resolve();const deferredReadStarts=new WeakMap;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 TELEMETRY_HARNESSES=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]);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{await withQueueMutation(async()=>{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
2
  `)},globalPmRoot)}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"&&params.errorCategory.trim().length>0){return params.errorCategory}if(typeof params.errorCode==="string"&&params.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 source=override.length>0?"env_override_rejected":"inferred";if(source==="env_override_rejected"&&!sourceContextWarningEmitted&&!globalOptions.quiet){sourceContextWarningEmitted=true;process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${PM_TELEMETRY_SOURCE_CONTEXT_VALUES.join("|")}; ignoring override.
3
- `)}return{source_context:inferTelemetrySourceContext(globalOptions),source_context_source:source}}function inferTelemetrySourceContext(globalOptions){const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"){return"test"}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"automation"}return"user"}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{agent_harness:agent.harness?TELEMETRY_HARNESSES.has(agent.harness)?agent.harness:"other":"none",ci:parseBooleanTrueLike(process.env.CI),...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 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,sampleRate=1){const endpoint=activeCommand.otel_traces_endpoint;if(typeof endpoint!=="string"||endpoint.trim().length===0||[activeCommand.otel_trace_id,activeCommand.otel_span_id].some(id=>typeof id!=="string"||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),otlpStringAttribute("pm.sample_rate",String(sampleRate))];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,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);if(sanitizedValue===void 0)continue;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);if(!settings.telemetry.enabled||resolveTelemetryEnvironmentPolicy().telemetry_disabled)return null;if(settings.telemetry.installation_id.trim().length===0){settings.telemetry.installation_id=crypto.randomUUID();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)),captureLevel:normalizeCaptureLevel(settings.telemetry.capture_level)}}async function appendTelemetryEvent(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 appendLineAtomic(queuePath(globalPmRoot),serialized)}async function enqueueTelemetryEvent(globalPmRoot,event){await withQueueMutation(()=>appendTelemetryEvent(globalPmRoot,event),globalPmRoot)}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
+ `)}return{source_context:inferTelemetrySourceContext(globalOptions),source_context_source:source}}function inferTelemetrySourceContext(globalOptions){const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"){return"test"}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"automation"}return"user"}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{agent_harness:agent.harness?TELEMETRY_HARNESSES.has(agent.harness)?agent.harness:"other":"none",ci:parseBooleanTrueLike(process.env.CI),...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 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,sampleRate=1){const endpoint=activeCommand.otel_traces_endpoint;if(typeof endpoint!=="string"||endpoint.trim().length===0||[activeCommand.otel_trace_id,activeCommand.otel_span_id].some(id=>typeof id!=="string"||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),otlpStringAttribute("pm.sample_rate",String(sampleRate))];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,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);if(sanitizedValue===void 0)continue;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);if(!settings.telemetry.enabled||resolveTelemetryEnvironmentPolicy().telemetry_disabled)return null;if(settings.telemetry.installation_id.trim().length===0){if(isConfigurationOnlySettingsRead(globalPmRoot))return null;settings.telemetry.installation_id=crypto.randomUUID();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)),captureLevel:normalizeCaptureLevel(settings.telemetry.capture_level)}}async function appendTelemetryEvent(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 appendLineAtomic(queuePath(globalPmRoot),serialized)}async function enqueueTelemetryEvent(globalPmRoot,event){await withQueueMutation(()=>appendTelemetryEvent(globalPmRoot,event),globalPmRoot)}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}
4
4
  `:"";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 appendPendingOtelSpan(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 appendLineAtomic(otelSpansQueuePath(globalPmRoot),serialized)}async function enqueuePendingOtelSpan(globalPmRoot,request){await withQueueMutation(()=>appendPendingOtelSpan(globalPmRoot,request),globalPmRoot)}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}
5
- `:"";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},globalPmRoot)}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,globalPmRoot=resolveGlobalPmRoot(process.cwd()),waitMs=5e3){const run=_queueMutationPromise.catch(()=>{}).then(()=>runWithIsolatedExtensionRuntime(async()=>{const release=await acquireLock(globalPmRoot,"telemetry-queue",60,"telemetry",false,false,waitMs);try{clearSettingsReadCache(globalPmRoot);return await operation()}finally{await release()}}));_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},globalPmRoot)}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},globalPmRoot)}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){const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,new Set,retentionDays);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.length});return}const dueEntries=retainedEntries.filter(entry=>isDueForRetry(entry)).slice(0,TELEMETRY_FLUSH_BATCH_SIZE);if(dueEntries.length===0){const remaining=prunedCount>0?await removeFlushedEntriesFromCurrentQueue(globalPmRoot,new Set,retentionDays):retainedEntries;await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.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(resolveTelemetryEnvironmentPolicy().telemetry_disabled){return}try{const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const installation=await withQueueMutation(()=>ensureInstallationId(globalPmRoot),globalPmRoot);if(!installation)return;await flushQueueWithProcessLock(globalPmRoot,installation.endpoint,installation.retentionDays)}catch{}}async function startTelemetryCommand(context){if(resolveTelemetryEnvironmentPolicy().telemetry_disabled){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 coreReadOwned=context.global.noExtensions===true||isActiveCommandUnextended(context.command);const activeCommand=await withQueueMutation(async()=>{const installation=await ensureInstallationId(globalPmRoot);if(!installation)return null;const{installationId,endpoint,retentionDays,captureLevel}=installation;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})};const sampleRate=await resolveAutomaticReadSampleRate(globalPmRoot,context.command,coreReadOwned);if(sampleRate===1){await appendTelemetryEvent(globalPmRoot,event)}const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);const active={...sampleRate<1?{sample_rate:sampleRate}:{},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};if(sampleRate<1)deferredReadStarts.set(active,event);return active},globalPmRoot,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);if(activeCommand&&activeCommand.sample_rate===void 0){scheduleTelemetryFlush(globalPmRoot,activeCommand.endpoint,activeCommand.retention_days)}return activeCommand}catch{return null}}async function finishTelemetryCommand(activeCommand,outcome){if(!activeCommand||resolveTelemetryEnvironmentPolicy().telemetry_disabled){return}try{const captured=await withQueueMutation(async()=>{const settings=await readSettings(activeCommand.global_pm_root);if(resolveTelemetryEnvironmentPolicy().telemetry_disabled||!settings.telemetry.enabled||settings.telemetry.installation_id!==activeCommand.installation_id){deferredReadStarts.delete(activeCommand);return false}const deferredStart=deferredReadStarts.get(activeCommand);const sampleRate=outcome.ok?activeCommand.sample_rate??1:1;if(deferredStart){deferredReadStarts.delete(activeCommand);if(crypto.randomBytes(6).readUIntBE(0,6)/2**48>=sampleRate)return false;deferredStart.payload.sample_rate=sampleRate;await appendTelemetryEvent(activeCommand.global_pm_root,deferredStart)}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:{...deferredStart?{sample_rate:sampleRate}:{},...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 appendTelemetryEvent(activeCommand.global_pm_root,event);const otelRequest=buildOtelSpanRequest(activeCommand,{...outcome,exit_code:normalizedExitCode,error_code:normalizedErrorCode,error_category:normalizedErrorCategory},finishedAt,durationMs,sampleRate);if(otelRequest){await appendPendingOtelSpan(activeCommand.global_pm_root,otelRequest)}return true},activeCommand.global_pm_root,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);if(!captured)return;scheduleTelemetryFlush(activeCommand.global_pm_root,activeCommand.endpoint,activeCommand.retention_days)}catch{}}async function emitTelemetryErrorEvent(context){if(resolveTelemetryEnvironmentPolicy().telemetry_disabled){return}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const captured=await withQueueMutation(async()=>{const installation=await ensureInstallationId(globalPmRoot);if(!installation)return null;const{installationId,captureLevel}=installation;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 appendTelemetryEvent(globalPmRoot,event);return installation},globalPmRoot,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);if(captured)scheduleTelemetryFlush(globalPmRoot,captured.endpoint,captured.retentionDays)}catch{}}export{PM_TELEMETRY_SOURCE_CONTEXT_VALUES2 as PM_TELEMETRY_SOURCE_CONTEXT_VALUES,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,TELEMETRY_SCHEMA_VERSION,_testOnly,emitTelemetryErrorEvent,finishTelemetryCommand,flushTelemetryQueueNow,startTelemetryCommand,waitForPendingFlush,withQueueMutation as withTelemetryQueueMutation};
5
+ `:"";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},globalPmRoot)}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,globalPmRoot=resolveGlobalPmRoot(process.cwd()),waitMs=5e3){const run=_queueMutationPromise.catch(()=>{}).then(()=>runWithIsolatedExtensionRuntime(async()=>{const release=await acquireLock(globalPmRoot,"telemetry-queue",60,"telemetry",false,false,waitMs);try{clearSettingsReadCache(globalPmRoot);return await operation()}finally{await release()}}));_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},globalPmRoot)}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},globalPmRoot)}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){const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,new Set,retentionDays);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.length});return}const dueEntries=retainedEntries.filter(entry=>isDueForRetry(entry)).slice(0,TELEMETRY_FLUSH_BATCH_SIZE);if(dueEntries.length===0){const remaining=prunedCount>0?await removeFlushedEntriesFromCurrentQueue(globalPmRoot,new Set,retentionDays):retainedEntries;await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.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(isConfigurationOnlySettingsRead(globalPmRoot))return;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(resolveTelemetryEnvironmentPolicy().telemetry_disabled){return}try{const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const installation=await withQueueMutation(()=>ensureInstallationId(globalPmRoot),globalPmRoot);if(!installation)return;await flushQueueWithProcessLock(globalPmRoot,installation.endpoint,installation.retentionDays)}catch{}}async function startTelemetryCommand(context){if(resolveTelemetryEnvironmentPolicy().telemetry_disabled){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 coreReadOwned=context.global.noExtensions===true||isActiveCommandUnextended(context.command);const activeCommand=await withQueueMutation(async()=>{const installation=await ensureInstallationId(globalPmRoot);if(!installation)return null;const{installationId,endpoint,retentionDays,captureLevel}=installation;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})};const sampleRate=await resolveAutomaticReadSampleRate(globalPmRoot,context.command,coreReadOwned);if(sampleRate===1){await appendTelemetryEvent(globalPmRoot,event)}const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);const active={...sampleRate<1?{sample_rate:sampleRate}:{},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};if(sampleRate<1)deferredReadStarts.set(active,event);return active},globalPmRoot,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);if(activeCommand&&activeCommand.sample_rate===void 0){scheduleTelemetryFlush(globalPmRoot,activeCommand.endpoint,activeCommand.retention_days)}return activeCommand}catch{return null}}async function finishTelemetryCommand(activeCommand,outcome){if(!activeCommand||resolveTelemetryEnvironmentPolicy().telemetry_disabled){return}try{const captured=await withQueueMutation(async()=>{const settings=await readSettings(activeCommand.global_pm_root);if(resolveTelemetryEnvironmentPolicy().telemetry_disabled||!settings.telemetry.enabled||settings.telemetry.installation_id!==activeCommand.installation_id){deferredReadStarts.delete(activeCommand);return false}const deferredStart=deferredReadStarts.get(activeCommand);const sampleRate=outcome.ok?activeCommand.sample_rate??1:1;if(deferredStart){deferredReadStarts.delete(activeCommand);if(crypto.randomBytes(6).readUIntBE(0,6)/2**48>=sampleRate)return false;deferredStart.payload.sample_rate=sampleRate;await appendTelemetryEvent(activeCommand.global_pm_root,deferredStart)}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:{...deferredStart?{sample_rate:sampleRate}:{},...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 appendTelemetryEvent(activeCommand.global_pm_root,event);const otelRequest=buildOtelSpanRequest(activeCommand,{...outcome,exit_code:normalizedExitCode,error_code:normalizedErrorCode,error_category:normalizedErrorCategory},finishedAt,durationMs,sampleRate);if(otelRequest){await appendPendingOtelSpan(activeCommand.global_pm_root,otelRequest)}return true},activeCommand.global_pm_root,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);if(!captured)return;scheduleTelemetryFlush(activeCommand.global_pm_root,activeCommand.endpoint,activeCommand.retention_days)}catch{}}async function emitTelemetryErrorEvent(context){if(resolveTelemetryEnvironmentPolicy().telemetry_disabled){return}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const captured=await withQueueMutation(async()=>{const installation=await ensureInstallationId(globalPmRoot);if(!installation)return null;const{installationId,captureLevel}=installation;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 appendTelemetryEvent(globalPmRoot,event);return installation},globalPmRoot,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);if(captured)scheduleTelemetryFlush(globalPmRoot,captured.endpoint,captured.retentionDays)}catch{}}export{PM_TELEMETRY_SOURCE_CONTEXT_VALUES2 as PM_TELEMETRY_SOURCE_CONTEXT_VALUES,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,TELEMETRY_SCHEMA_VERSION,_testOnly,emitTelemetryErrorEvent,finishTelemetryCommand,flushTelemetryQueueNow,startTelemetryCommand,waitForPendingFlush,withQueueMutation as withTelemetryQueueMutation};
6
6
  //# sourceMappingURL=runtime.js.map
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- !(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]="455fa9a8-92bb-558a-a3ac-901c21ab7506")}catch(e2){}})();import{realpathSync}from"node:fs";import{readFile}from"node:fs/promises";import path from"node:path";import readline from"node:readline";import{fileURLToPath}from"node:url";import{resolvePmCliVersion,PmCliError,decodeHtmlEntitiesInOptions,levenshteinDistanceWithinLimit,asRecordClone,createSerialQueue,evaluateMutationGuard,getSettingsPath,isMutationAction,pathExists,readSettings,runWithHarnessDetectionSignals,runWithWorkspaceHarnessSignalDescriptors,boundAgentEpisodeIdentity}from"../sdk/runtime-primitives.js";import{pmToolActionNestedOptionKeys}from"../sdk/cli-contracts/tool-schema.js";import{readRequiredString,runAction,runWithActiveExtensions}from"../sdk/runtime.js";import{NARROW_TOOL_ACTIONS,TOOLS}from"./tool-definitions.js";import{normalizeWorkspaceToolArguments,resolveMcpToolAccess,resolveMcpToolSurface}from"./runtime-capabilities.js";import{PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS}from"../sdk/agent-capability-contracts.js";import{PM_MCP_ENTRY_TOOL_NAMES,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION,PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY,discoverPmTools,parsePmToolDiscoveryOptions}from"../sdk/mcp/discovery.js";import{commitItemMutations}from"../sdk/item-transaction.js";import{isRuntimeRecord,markMcpMutationTransportInput}from"../sdk/runtime-input.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{createReproducibleProcessRunner,runWithReproducibleProcessEnvironment}from"../sdk/reproducibility/process.js";import{parseAtomicMutationControls,resolveItemMutationDocument}from"../sdk/structured-mutations.js";import{resolveAuthor,resolvePmRoot,resolveWorkspaceRoot}from"../sdk/runtime-primitives.js";import{PM_MCP_ERROR_CODES,PM_MCP_META_KEYS,PM_MCP_PROTOCOL_VERSION,PmMcpProtocolError,attachMcpServerInfo,buildMcpCompleteResult,buildMcpDiscoverResult,hasMcpClientExtension,isMcpRecord,resolveMcpRequestContext}from"../sdk/mcp/protocol.js";import{PmMcpInputRequiredError,buildMcpInputRequiredResult,parseMcpInputResponses,validateMcpJsonSchema,withMcpCachePolicy}from"../sdk/mcp/interactions.js";import{PM_MCP_TASKS_EXTENSION,createMcpTaskStore}from"../sdk/mcp/tasks.js";import{PmMcpSubscriptionRegistry}from"../sdk/mcp/subscriptions.js";import{extractMcpTraceContext,runWithMcpTraceContext}from"../sdk/mcp/authorization.js";import{LegacyMcpAdapter}from"./legacy-adapter.js";import{PM_MCP_APP_CONTRACTS,PM_MCP_APP_MIME_TYPE,PM_MCP_APPS_EXTENSION,PM_MCP_APPS_SERVER_CAPABILITY,decoratePmMcpToolsWithApps,findPmMcpAppByUri,hasPmMcpAppsCapability,renderPmMcpAppHtml}from"../sdk/mcp/apps.js";import{PM_MCP_SKILLS_EXTENSION,PM_MCP_SKILLS_SERVER_CAPABILITY,PmMcpSkillRegistry,assertPmMcpSkillsCapability}from"../sdk/mcp/skills.js";function runMcpAction(args){return runAction(markMcpMutationTransportInput(args))}const PM_PACKAGE_ROOT_ENV="PM_CLI_PACKAGE_ROOT";function resolvePmPackageRoot(){return fileURLToPath(new URL("../..",import.meta.url))}if(typeof process.env[PM_PACKAGE_ROOT_ENV]!=="string"||process.env[PM_PACKAGE_ROOT_ENV]?.trim().length===0){process.env[PM_PACKAGE_ROOT_ENV]=resolvePmPackageRoot()}const PM_MCP_SERVER_VERSION=resolvePmCliVersion(import.meta.url,["../.."])??"0.0.0";const PM_MCP_SERVER_INFO={name:"pm-mcp",version:PM_MCP_SERVER_VERSION,description:"Stateless project-context management through pm SDK contracts.",websiteUrl:"https://github.com/unbraind/pm-cli"};const PM_MCP_SERVER_CAPABILITIES={prompts:{listChanged:true},resources:{listChanged:true,subscribe:true},tools:{listChanged:true},extensions:{[PM_MCP_TASKS_EXTENSION]:{},[PM_MCP_APPS_EXTENSION]:PM_MCP_APPS_SERVER_CAPABILITY,[PM_MCP_SKILLS_EXTENSION]:PM_MCP_SKILLS_SERVER_CAPABILITY,[PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION]:PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY}};const PM_MCP_SUBSCRIPTIONS=new Map;function createMcpSubscriptionRegistry(){return new PmMcpSubscriptionRegistry({capabilities:PM_MCP_SERVER_CAPABILITIES,serverInfo:PM_MCP_SERVER_INFO})}function pruneClosedMcpSubscriptionRegistries(){for(const[key,subscription]of PM_MCP_SUBSCRIPTIONS){if(subscription.registry.size===0)PM_MCP_SUBSCRIPTIONS.delete(key)}}const PM_MCP_CACHE_POLICIES={prompts:{ttlMs:6e4,cacheScope:"public"},resource:{ttlMs:0,cacheScope:"private"},resources:{ttlMs:6e4,cacheScope:"public"},tools:{ttlMs:3e4,cacheScope:"private"}};const PM_MCP_DIRECT_TASK_TOOLS=new Set(["pm_graph","pm_health","pm_validate"]);const PM_MCP_RUN_TASK_ACTIONS=new Set(["graph","health","import","reindex","test-all","validate"]);const PM_MCP_SKILL_METHODS=new Set(["skills/list","skills/get","resources/directory/read"]);const PM_MCP_INSTRUCTIONS="You have access to native pm CLI tools for git-based project management. When progressive discovery is negotiated, use pm_discover to expand the small entry catalog by intent and request schemas only when needed. Use pm_next to pick the next actionable item, or pm_context or pm_search before creating new work. Prefer narrow tools (pm_next, pm_context, pm_list, pm_get, pm_search, pm_events, pm_create, pm_mutate, pm_copy, pm_focus, pm_update, pm_append, pm_claim, pm_release, pm_close, pm_comments, pm_files, pm_docs, pm_notes, pm_learnings, pm_deps, pm_graph, pm_test, pm_validate, pm_health, pm_contracts, pm_schema, pm_profile, pm_config, pm_plan) over pm_run when they cover the operation. Use pm_plan for agent harness Plan workflows: it provides Codex/Claude/Cursor-style planning with durable steps, dependencies, decisions, discoveries, validation, and materialization. Use pm_schema and pm_config for workspace configuration: pm_schema manages custom item types/statuses and pm_config reads or writes settings keys. Use pm_run with an explicit action for active package-owned operations, plus activity, aggregate, history, stats, test-all, and gc. Use history-redact for audited history-stream redaction workflows, history-repair to re-anchor a drifted history chain, and history-compact to checkpoint/prune long history streams while preserving replay integrity. Agent harness and model provenance are detected automatically; pass author only for an intentional identity override. Do not pass path during real repository tracking \u2014 only pass path for sandbox or test runs.";function declaredToolKeys(tools=TOOLS){return new Map(tools.map(tool=>{const schema=tool.inputSchema;const properties=schema.properties??{};return[tool.name,Object.keys(properties)]}))}function nearestDeclaredKey(unexpected,declared){const limit=Math.max(1,Math.min(3,Math.floor(unexpected.length/4)+1));let best;for(const candidate of declared){const distance=levenshteinDistanceWithinLimit(unexpected,candidate,limit);if(distance===null){continue}if(best===void 0||distance<best.distance){best={key:candidate,distance}}}return best?.key}const UNEXPECTED_KEY_WARNING_EXEMPT_TOOLS=new Set(["pm_run"]);const MCP_RETRY_ARGUMENT_KEYS=new Set(["inputResponses","requestState"]);function resolveMcpDiscoveryCursorIntegrityKey(){const configuredKey=process.env.PM_MCP_DISCOVERY_CURSOR_KEY;if(configuredKey===void 0)return void 0;const key=Buffer.from(configuredKey,"utf8");if(key.byteLength<32){throw new PmCliError("PM_MCP_DISCOVERY_CURSOR_KEY must contain at least 32 UTF-8 bytes.",64)}return key}function detectUnexpectedTopLevelKeys(toolName,args,toolDeclaredKeys=declaredToolKeys()){if(typeof args!=="object"||args===null||Array.isArray(args)){return[]}if(UNEXPECTED_KEY_WARNING_EXEMPT_TOOLS.has(toolName)){return[]}const declared=toolDeclaredKeys.get(toolName);if(declared===void 0){return[]}const declaredSet=new Set([...declared,...MCP_RETRY_ARGUMENT_KEYS]);const warnings=[];for(const key of Object.keys(args)){if(declaredSet.has(key)){continue}const suggestion=nearestDeclaredKey(key,declared);warnings.push(suggestion!==void 0?`Unexpected top-level argument "${key}" for ${toolName} (did you mean "${suggestion}"?). It is not declared and may be ignored; declared arguments are: ${declared.join(", ")}.`:`Unexpected top-level argument "${key}" for ${toolName}. It is not declared and may be ignored; declared arguments are: ${declared.join(", ")}.`)}return warnings}const HANDLERS={pm_run:args=>runMcpAction(args),pm_discover:async args=>{const surface=await resolveMcpToolSurface(TOOLS,args);const cursorIntegrityKey=resolveMcpDiscoveryCursorIntegrityKey();const discoveryOptions=parsePmToolDiscoveryOptions(args);return discoverPmTools(surface.tools.map(tool=>({name:tool.name,description:tool.description,inputSchema:tool.inputSchema,authorized:true,signals:{freshness:1,usage:PM_MCP_ENTRY_TOOL_NAMES.includes(tool.name)?1:0}})),{...discoveryOptions,profile:surface.profile,...cursorIntegrityKey===void 0?{}:{cursorIntegrityKey}})},pm_mutate:async args=>{const transactionId=readRequiredString(args,"transactionId");const controls=parseAtomicMutationControls(args);const cwd=typeof args.cwd==="string"?args.cwd:process.cwd();const pmRoot=resolvePmRoot(cwd,typeof args.path==="string"?args.path:void 0);const resolved=resolveItemMutationDocument(JSON.stringify({schema_version:1,mutations:args.mutations}),{transactionId,idPrefix:(await readSettings(pmRoot)).id_prefix});const{mutations,references}=resolved;if(args.dryRun===true){return{transaction_id:transactionId,dry_run:true,mutation_count:mutations.length,mutations,references}}const result=await runWithActiveExtensions({cwd:typeof args.cwd==="string"?args.cwd:void 0,path:typeof args.path==="string"?args.path:void 0,noExtensions:args.noExtensions===true},()=>commitItemMutations({pmRoot,transactionId,author:resolveAuthor(typeof args.author==="string"?args.author:void 0,"unknown"),mutations,...controls}));const{transactionId:committedTransactionId,...commitResult}=result;return{...commitResult,transaction_id:committedTransactionId,mutation_count:mutations.length,references}},...Object.fromEntries(Object.entries(NARROW_TOOL_ACTIONS).map(([tool,action])=>[tool,args=>runMcpAction({...args,action})]))};function resolveInvokedAction(toolName,args){if(toolName==="pm_run"){return typeof args.action==="string"?args.action:void 0}return NARROW_TOOL_ACTIONS[toolName]}async function collectMutationGuardWarnings(toolName,action,args){if(toolName!=="pm_mutate"&&!isMutationAction(action??"")){return[]}const cwd=typeof args.cwd==="string"?args.cwd:process.cwd();const pmRoot=resolvePmRoot(cwd,typeof args.path==="string"?args.path:void 0);if(!await pathExists(getSettingsPath(pmRoot))){return[]}const settings=await readSettings(pmRoot);const nestedOptions=typeof args.options==="object"&&args.options!==null&&!Array.isArray(args.options)?args.options:{};const result=evaluateMutationGuard({author:resolveAuthor(typeof args.author==="string"?args.author:typeof nestedOptions.author==="string"?nestedOptions.author:void 0,settings.author_default),payload:Object.fromEntries(Object.entries(args).filter(([key])=>key!=="cwd"&&key!=="path")),settings:settings.mutation_guard,force:args.force===true||nestedOptions.force===true});return result.warnings}function detectUnexpectedOptionKeys(toolName,action,args){const options=args.options;if(action===void 0||typeof options!=="object"||options===null||Array.isArray(options)){return[]}const declared=pmToolActionNestedOptionKeys(action);if(declared===void 0){return[]}const declaredSet=new Set(declared);const warnings=[];for(const key of Object.keys(options)){if(declaredSet.has(key)){continue}const suggestion=nearestDeclaredKey(key,declared);warnings.push(suggestion!==void 0?`Unknown option "${key}" for ${toolName} action "${action}" (did you mean "${suggestion}"?). The ${action} contract does not read it, so it has no effect; declared keys are: ${declared.join(", ")}.`:`Unknown option "${key}" for ${toolName} action "${action}". The ${action} contract does not read it, so it has no effect; declared keys are: ${declared.join(", ")}.`)}return warnings}function resultContent(result,warnings,tokenAccounting=false,canonicalStructuredResult=false){const effectiveResult=tokenAccounting?attachOutputTokenAccounting(result,value=>JSON.stringify(value,null,2)):result;const structuredContent=warnings!==void 0&&warnings.length>0?{result:effectiveResult,warnings}:{result:effectiveResult};return{content:[{type:"text",text:canonicalStructuredResult?"Canonical result: structuredContent.result":JSON.stringify(effectiveResult,null,2)}],structuredContent}}function errorContent(error,canonicalStructuredResult=false){const code=error instanceof PmCliError?error.exitCode:1;const message=error instanceof Error?error.message:String(error);const details=error instanceof PmCliError?error.context:void 0;return{isError:true,content:[{type:"text",text:canonicalStructuredResult?"Canonical error: structuredContent":JSON.stringify({error:message,code,details},null,2)}],structuredContent:{result:null,error:message,code,details}}}function boundMcpClientProvenance(value){const provenance=isRuntimeRecord(value)?value:{};const bounded={};let acceptedCount=0;for(const key in provenance){if(acceptedCount>=32)break;if(!Object.prototype.hasOwnProperty.call(provenance,key))continue;const entry=provenance[key];if(/^[a-z][a-z0-9_-]{0,63}$/u.test(key)&&typeof entry==="string"&&entry.trim().length>0){bounded[key]=entry.trim().slice(0,256);acceptedCount+=1}}return bounded}function readMcpClientInfo(value){const clientInfo=isRuntimeRecord(value)?value:{};const clientName=typeof clientInfo.name==="string"?clientInfo.name.trim():"";if(clientName.length===0)return void 0;const optionalValues=[["version",clientInfo.version,128],["model",clientInfo.model,256],["session",clientInfo.session,256]];const result={name:clientName.slice(0,128)};for(const[key,value2,limit]of optionalValues){if(typeof value2==="string"&&value2.trim().length>0){result[key]=value2.trim().slice(0,limit)}}const boundedProvenance=boundMcpClientProvenance(clientInfo.provenance);if(Object.keys(boundedProvenance).length>0){result.provenance=boundedProvenance}const episode=boundAgentEpisodeIdentity(clientInfo.episode,false);if(episode!==void 0)result.episode=episode;return result}async function emitMcpChangeNotifications(action){if(isMutationAction(action??"")){await Promise.all([...PM_MCP_SUBSCRIPTIONS.values()].flatMap(({registry})=>PM_MCP_RESOURCE_CONTRACTS.map(resource=>registry.emitResourceUpdated(resource.uri))))}if(["extension","install","package","uninstall"].includes(action??"")){await Promise.all([...PM_MCP_SUBSCRIPTIONS.values()].map(({registry})=>registry.emitListChanged("tools")))}pruneClosedMcpSubscriptionRegistries()}async function handleToolCall(paramsInput,clientInfo,progressiveDiscoveryNegotiated=false){const clientSignals=clientInfo?{client_info:clientInfo}:{};return runWithHarnessDetectionSignals({env:process.env,argv:process.argv,...clientSignals},async()=>{const params=asRecordClone(paramsInput);const name=readRequiredString(params,"name");const handler=Object.prototype.hasOwnProperty.call(HANDLERS,name)?HANDLERS[name]:void 0;if(!handler){throw new PmCliError(`Unknown pm MCP tool: ${name}`,64)}const inputResponses=params.inputResponses===void 0?void 0:parseMcpInputResponses(params.inputResponses);validateMcpToolArguments(params.arguments);const requestedArgs={...decodeHtmlEntitiesInOptions(asRecordClone(params.arguments)),...inputResponses?{inputResponses}:{},...typeof params.requestState==="string"?{requestState:params.requestState}:{}};const access=await resolveMcpToolAccess(TOOLS,name,requestedArgs);const requiredCustomDiscoveryEntry=progressiveDiscoveryNegotiated&&access.profile==="custom"&&name==="pm_discover";if(!access.available&&!requiredCustomDiscoveryEntry){throw new PmCliError(`pm MCP tool "${name}" is unavailable in the ${access.profile} profile.`,64)}const args=await normalizeWorkspaceToolArguments(name,requestedArgs);const cwd=typeof args.cwd==="string"?args.cwd:process.cwd();const pmRoot=resolvePmRoot(cwd,typeof args.path==="string"?args.path:void 0);const workspaceIdentity=await pathExists(getSettingsPath(pmRoot))?(await readSettings(pmRoot)).agent_identity:void 0;return runWithHarnessDetectionSignals({env:{...process.env,PM_PATH:pmRoot},argv:process.argv,cwd,...clientSignals},()=>runWithWorkspaceHarnessSignalDescriptors(workspaceIdentity?.harness_signals??[],async()=>{const action=resolveInvokedAction(name,args);const warnings=[...detectUnexpectedTopLevelKeys(name,args,declaredToolKeys()),...detectUnexpectedOptionKeys(name,action,args),...await collectMutationGuardWarnings(name,action,args)];for(const warning of warnings){console.error(`[pm-mcp] ${warning}`)}const result=await handler(args);void emitMcpChangeNotifications(action);return resultContent(result,warnings,args.tokenAccounting===true,progressiveDiscoveryNegotiated)},{probesEnabled:workspaceIdentity?.probes_enabled}))})}async function openMcpSubscription(input){if(typeof input.request.id!=="string"&&typeof input.request.id!=="number"||input.request.method!=="subscriptions/listen"){throw new PmMcpProtocolError("Invalid MCP subscriptions/listen request",PM_MCP_ERROR_CODES.invalidParams,{required:["id","method","params.notifications"]})}resolveMcpRequestContext(input.request.params);const key=input.key??input.request.id;if(PM_MCP_SUBSCRIPTIONS.has(key)){throw new PmMcpProtocolError("MCP subscription id is already active",PM_MCP_ERROR_CODES.invalidParams,{subscriptionId:input.request.id})}const registry=createMcpSubscriptionRegistry();await registry.open({id:input.request.id,notifications:input.request.params?.notifications,sink:input.sink});PM_MCP_SUBSCRIPTIONS.set(key,{id:input.request.id,registry})}function closeMcpSubscription(id,key=id){const subscription=PM_MCP_SUBSCRIPTIONS.get(key);if(!subscription||subscription.id!==id)return void 0;PM_MCP_SUBSCRIPTIONS.delete(key);return subscription.registry.close(id)}function closeStdioMcpSubscriptions(){const closed=[];for(const[key,subscription]of PM_MCP_SUBSCRIPTIONS){if(key!==subscription.id)continue;const result=closeMcpSubscription(subscription.id,key);if(result)closed.push({id:subscription.id,result})}return closed}async function resolveMcpToolSchemaForRequest(request){if(request.method!=="tools/call")return void 0;const name=request.params?.name;if(typeof name!=="string")return void 0;const surface=await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(request.params));return surface.tools.find(tool=>tool.name===name)?.inputSchema}function buildMcpToolCallErrorResult(request,error){if(request.method!=="tools/call"||error instanceof PmMcpProtocolError){return void 0}const content=errorContent(error,hasMcpProtocolVersionMetadata(request)&&hasMcpClientExtension(resolveMcpRequestContext(request.params),PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION));return hasMcpProtocolVersionMetadata(request)?buildMcpCompleteResult(content,PM_MCP_SERVER_INFO):content}function requestWorkspaceArgs(params){const paramsRecord=asRecordClone(params);return asRecordClone(paramsRecord.arguments??paramsRecord)}async function readWorkspaceResource(uri,params){const args=requestWorkspaceArgs(params);const cwd=typeof args.cwd==="string"?args.cwd:process.cwd();const contract=PM_MCP_RESOURCE_CONTRACTS.find(resource=>resource.uri===uri);if(!contract){throw new PmCliError(`Unknown pm MCP resource: ${uri}`,64)}let value;if(uri==="pm://workspace/context"){value=await runMcpAction({...args,action:"context",limit:10})}else if(uri==="pm://workspace/claims"){value=await runMcpAction({...args,action:"list",status:"in_progress",limit:20})}else if(uri==="pm://workspace/focus"){value=await runMcpAction({...args,action:"focus",subcommand:"show"})}else{const guidePath=path.join(cwd,"AGENTS.md");value=await pathExists(guidePath)?(await readFile(guidePath,"utf8")).slice(0,32e3):"No repository-local AGENTS.md was found."}return{contents:[{uri,mimeType:contract.mimeType,text:typeof value==="string"?value:JSON.stringify(value,null,2)}]}}async function loadRequestSkillRegistry(params){const args=requestWorkspaceArgs(params);const cwd=typeof args.cwd==="string"?args.cwd:process.cwd();const workspaceRoot=resolveWorkspaceRoot(resolvePmRoot(cwd,typeof args.path==="string"?args.path:void 0));return PmMcpSkillRegistry.load({packageRoot:resolvePmPackageRoot(),workspaceRoot,packageVersion:PM_MCP_SERVER_VERSION})}function renderWorkflowPrompt(params){const paramsRecord=asRecordClone(params);const name=readRequiredString(paramsRecord,"name");const prompt=PM_MCP_PROMPT_CONTRACTS.find(candidate=>candidate.name===name);if(!prompt){throw new PmCliError(`Unknown pm MCP prompt: ${name}`,64)}const argumentsRecord=asRecordClone(paramsRecord.arguments);let text=prompt.template;for(const argument of prompt.arguments){const value=argumentsRecord[argument.name];if(argument.required&&(typeof value!=="string"||value.trim().length===0)){throw new PmCliError(`Missing required prompt argument: ${argument.name}`,64)}text=text.replaceAll(`{{${argument.name}}}`,typeof value==="string"?value:"")}return{description:prompt.description,messages:[{role:"user",content:{type:"text",text}}]}}const LEGACY_MCP_ADAPTER=new LegacyMcpAdapter({serverInfo:PM_MCP_SERVER_INFO,capabilities:PM_MCP_SERVER_CAPABILITIES,instructions:PM_MCP_INSTRUCTIONS,parseClientInfo:readMcpClientInfo,listTools:async params=>({tools:(await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(params))).tools}),callTool:handleToolCall,listResources:()=>({resources:PM_MCP_RESOURCE_CONTRACTS}),readResource:params=>readWorkspaceResource(readRequiredString(asRecordClone(params),"uri"),params),listPrompts:()=>({prompts:PM_MCP_PROMPT_CONTRACTS.map(prompt=>({name:prompt.name,description:prompt.description,arguments:prompt.arguments}))}),getPrompt:renderWorkflowPrompt});function deterministicMcpTools(tools){return tools.map(tool=>({...tool,inputSchema:validateMcpJsonSchema(tool.inputSchema)})).sort((left,right)=>left.name.localeCompare(right.name))}function mcpTaskPrincipal(requestContext){return requestContext.clientInfo?`${requestContext.clientInfo.name}@${requestContext.clientInfo.version}`:"anonymous-stdio"}function mcpTaskStore(){return createMcpTaskStore({pmRoot:resolvePmRoot(process.cwd()),owner:"pm-mcp-task-provider"})}function validateMcpToolArguments(value){if(value!==void 0&&!isMcpRecord(value)){throw new PmCliError("pm MCP tool arguments must be an object.",64)}}function shouldCreateMcpTask(params,requestContext){if(!hasMcpClientExtension(requestContext,PM_MCP_TASKS_EXTENSION)){return false}const requestParams=asRecordClone(params);const name=requestParams.name;const args=asRecordClone(requestParams.arguments);if(PM_MCP_DIRECT_TASK_TOOLS.has(name))return true;if(name==="pm_test"&&(args.subcommand==="run"||isMcpRecord(args.options)&&args.options.subcommand==="run")){return true}if(name!=="pm_run")return false;return typeof args.action==="string"&&PM_MCP_RUN_TASK_ACTIONS.has(args.action)}const PENDING_MCP_TASKS=new Map;async function executeMcpTask(execution,inputResponses){const params={...execution.params,...inputResponses?{inputResponses}:{},...execution.requestState?{requestState:execution.requestState}:{}};try{const result=await handleToolCall(params,execution.context.clientInfo,hasMcpClientExtension(execution.context,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION));await execution.store.complete(execution.taskId,execution.principal,buildMcpCompleteResult(result,PM_MCP_SERVER_INFO));PENDING_MCP_TASKS.delete(execution.taskId)}catch(error){if(error instanceof PmMcpInputRequiredError){execution.requestState=error.requestState;await execution.store.requireInput({taskId:execution.taskId,principal:execution.principal,requestContext:execution.context,inputRequests:error.inputRequests,statusMessage:"Task requires additional client input."});return}if(error instanceof PmMcpProtocolError){await execution.store.fail(execution.taskId,execution.principal,{code:error.code,message:error.message,data:error.data})}else{await execution.store.complete(execution.taskId,execution.principal,buildMcpCompleteResult(errorContent(error,hasMcpClientExtension(execution.context,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)),PM_MCP_SERVER_INFO))}PENDING_MCP_TASKS.delete(execution.taskId)}}async function settleMcpTaskExecution(taskId,execution){try{await execution}catch{PENDING_MCP_TASKS.delete(taskId)}}function scheduleMcpTaskExecution(execution,inputResponses){void settleMcpTaskExecution(execution.taskId,executeMcpTask(execution,inputResponses))}async function createMcpTaskForToolCall(params,requestContext){const store=mcpTaskStore();const principal=mcpTaskPrincipal(requestContext);const task=await store.create({principal,statusMessage:"pm operation accepted for asynchronous execution."});const execution={context:requestContext,params:asRecordClone(params),principal,store,taskId:task.taskId};PENDING_MCP_TASKS.set(task.taskId,execution);scheduleMcpTaskExecution(execution);return attachMcpServerInfo(task,PM_MCP_SERVER_INFO)}async function dispatchMcpTaskMethod(request,requestContext){if(!hasMcpClientExtension(requestContext,PM_MCP_TASKS_EXTENSION)){throw new PmMcpProtocolError("Missing required client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[PM_MCP_TASKS_EXTENSION]:{}}}})}const params=asRecordClone(request.params);const taskId=readRequiredString(params,"taskId");const principal=mcpTaskPrincipal(requestContext);const store=mcpTaskStore();if(request.method==="tasks/get"){return buildMcpCompleteResult(await store.get(taskId,principal),PM_MCP_SERVER_INFO)}if(request.method==="tasks/update"){const update=await store.update(taskId,principal,params.inputResponses);const execution=PENDING_MCP_TASKS.get(taskId);if(execution&&update.acceptedKeys.length>0&&update.remainingKeys.length===0){scheduleMcpTaskExecution(execution,await store.takeInputResponses(taskId,principal))}return buildMcpCompleteResult({},PM_MCP_SERVER_INFO)}await store.cancel(taskId,principal);PENDING_MCP_TASKS.delete(taskId);return buildMcpCompleteResult({},PM_MCP_SERVER_INFO)}async function dispatchModernToolMethod(request,requestContext,clientInfo){if(request.method==="tools/list"){const surface=await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(request.params));const progressiveDiscovery=hasMcpClientExtension(requestContext,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION);const listedTools=progressiveDiscovery?[...surface.tools.filter(tool=>PM_MCP_ENTRY_TOOL_NAMES.includes(tool.name)),...surface.profile==="custom"&&!surface.tools.some(tool=>tool.name==="pm_discover")?TOOLS.filter(tool=>tool.name==="pm_discover"):[]]:surface.tools;return buildMcpCompleteResult(withMcpCachePolicy({tools:hasCompatiblePmMcpAppsCapability(requestContext)?decoratePmMcpToolsWithApps(deterministicMcpTools(listedTools)):deterministicMcpTools(listedTools)},PM_MCP_CACHE_POLICIES.tools),PM_MCP_SERVER_INFO)}validateMcpToolArguments(request.params?.arguments);if(shouldCreateMcpTask(request.params,requestContext)){return createMcpTaskForToolCall(request.params,requestContext)}try{return buildMcpCompleteResult(await handleToolCall(request.params,clientInfo,hasMcpClientExtension(requestContext,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)),PM_MCP_SERVER_INFO)}catch(error){if(!(error instanceof PmMcpInputRequiredError))throw error;return buildMcpInputRequiredResult({requestContext,serverInfo:PM_MCP_SERVER_INFO,inputRequests:error.inputRequests,requestState:error.requestState})}}async function dispatchModernResourceMethod(request,requestContext){if(request.method==="resources/list"){const resources=[...PM_MCP_RESOURCE_CONTRACTS,...hasCompatiblePmMcpAppsCapability(requestContext)?PM_MCP_APP_CONTRACTS.map(contract=>({uri:contract.uri,name:contract.name,description:contract.description,mimeType:PM_MCP_APP_MIME_TYPE,_meta:{ui:contract.resourceMeta}})):[]].sort((left,right)=>left.uri.localeCompare(right.uri));return buildMcpCompleteResult(withMcpCachePolicy({resources},PM_MCP_CACHE_POLICIES.resources),PM_MCP_SERVER_INFO)}if(request.method==="resources/templates/list"){return buildMcpCompleteResult(withMcpCachePolicy({resourceTemplates:[]},PM_MCP_CACHE_POLICIES.resources),PM_MCP_SERVER_INFO)}try{const uri=readRequiredString(asRecordClone(request.params),"uri");const app=findPmMcpAppByUri(uri);let resource;if(app){if(!hasPmMcpAppsCapability(requestContext)){throw new PmMcpProtocolError("MCP App resource requires negotiated client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[PM_MCP_APPS_EXTENSION]:PM_MCP_APPS_SERVER_CAPABILITY}}})}resource={contents:[{uri,mimeType:PM_MCP_APP_MIME_TYPE,text:renderPmMcpAppHtml(app),_meta:{ui:app.resourceMeta}}]}}else if(uri.startsWith("skill://")){assertPmMcpSkillsCapability(requestContext);resource={...(await loadRequestSkillRegistry(request.params)).read(uri)}}else{resource=await readWorkspaceResource(uri,request.params)}return buildMcpCompleteResult(withMcpCachePolicy(resource,PM_MCP_CACHE_POLICIES.resource),PM_MCP_SERVER_INFO)}catch(error){if(!(error instanceof PmCliError)||!error.message.startsWith("Unknown pm MCP resource:")){throw error}throw new PmMcpProtocolError(error.message,PM_MCP_ERROR_CODES.invalidParams,{field:"uri"})}}function hasCompatiblePmMcpAppsCapability(requestContext){try{return hasPmMcpAppsCapability(requestContext)}catch(error){if(error instanceof PmMcpProtocolError)return false;throw error}}function readSkillPageOptions(params){if(params.cursor!==void 0&&typeof params.cursor!=="string"){throw new PmMcpProtocolError("Skills cursor must be a string",PM_MCP_ERROR_CODES.invalidParams,{field:"cursor"})}if(params.limit!==void 0&&typeof params.limit!=="number"){throw new PmMcpProtocolError("Skills limit must be a number",PM_MCP_ERROR_CODES.invalidParams,{field:"limit"})}return{...typeof params.cursor==="string"?{cursor:params.cursor}:{},...typeof params.limit==="number"?{limit:params.limit}:{}}}async function dispatchModernSkillMethod(request,requestContext){const directoryRead=request.method==="resources/directory/read";assertPmMcpSkillsCapability(requestContext,directoryRead);const params=asRecordClone(request.params);const registry=await loadRequestSkillRegistry(request.params);let result;if(request.method==="skills/list"){result={...registry.list(readSkillPageOptions(params))}}else if(request.method==="skills/get"){result={skill:registry.get(readRequiredString(params,"uri"))}}else{result={...registry.readDirectory(readRequiredString(params,"uri"),readSkillPageOptions(params))}}return buildMcpCompleteResult(withMcpCachePolicy(result,PM_MCP_CACHE_POLICIES.resource),PM_MCP_SERVER_INFO)}function dispatchModernPromptMethod(request){const result=request.method==="prompts/list"?withMcpCachePolicy({prompts:PM_MCP_PROMPT_CONTRACTS.map(prompt=>({name:prompt.name,description:prompt.description,arguments:prompt.arguments})).sort((left,right)=>left.name.localeCompare(right.name))},PM_MCP_CACHE_POLICIES.prompts):renderWorkflowPrompt(request.params);return buildMcpCompleteResult(result,PM_MCP_SERVER_INFO)}async function dispatchModernMcpRequest(request,meta){const requestContext=resolveMcpRequestContext(request.params);const clientInfo=readMcpClientInfo(meta[PM_MCP_META_KEYS.clientInfo]);if(request.method==="server/discover"){return buildMcpDiscoverResult({serverInfo:PM_MCP_SERVER_INFO,capabilities:PM_MCP_SERVER_CAPABILITIES,instructions:PM_MCP_INSTRUCTIONS})}if(request.method==="ping"){throw new PmMcpProtocolError("MCP method not found: ping",-32601,{removedIn:PM_MCP_PROTOCOL_VERSION})}if(PM_MCP_SKILL_METHODS.has(request.method??"")){return dispatchModernSkillMethod(request,requestContext)}if(request.method==="tasks/get"||request.method==="tasks/update"||request.method==="tasks/cancel"){return dispatchMcpTaskMethod(request,requestContext)}if(request.method==="tools/list"||request.method==="tools/call"){return dispatchModernToolMethod(request,requestContext,clientInfo)}if(request.method==="resources/list"||request.method==="resources/templates/list"||request.method==="resources/read"){return dispatchModernResourceMethod(request,requestContext)}if(request.method==="prompts/list"||request.method==="prompts/get"){return dispatchModernPromptMethod(request)}throw new PmMcpProtocolError(`MCP method not found: ${request.method??"(missing)"}`,-32601)}async function handleRequestInReproducibleContext(request){if(!request.id&&request.method?.startsWith("notifications/")){return void 0}if(hasMcpProtocolVersionMetadata(request)){const allowlist=(process.env.PM_MCP_BAGGAGE_ALLOWLIST??"").split(",").map(entry=>entry.trim()).filter(Boolean);return runWithMcpTraceContext(extractMcpTraceContext(request.params,{baggageAllowlist:allowlist}),()=>dispatchModernMcpRequest(request,request.params._meta))}if(request.method==="initialize"){return LEGACY_MCP_ADAPTER.initialize(request.params)}return LEGACY_MCP_ADAPTER.dispatch(request)}function hasMcpProtocolVersionMetadata(request){const meta=isMcpRecord(request.params)?request.params._meta:void 0;return isMcpRecord(meta)&&Object.prototype.hasOwnProperty.call(meta,PM_MCP_META_KEYS.protocolVersion)}async function handleRequest(request){return runWithReproducibleProcessEnvironment(process.env,()=>handleRequestInReproducibleContext(request))}function writeResponse(id,payload){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id,result:payload})}
2
+ !(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]="dd6e2455-d5f5-565f-bcbb-6d754b6be2e2")}catch(e2){}})();import{realpathSync}from"node:fs";import{readFile}from"node:fs/promises";import path from"node:path";import readline from"node:readline";import{fileURLToPath}from"node:url";import{resolvePmCliVersion,PmCliError,decodeHtmlEntitiesInOptions,levenshteinDistanceWithinLimit,asRecordClone,createSerialQueue,evaluateMutationGuard,getSettingsPath,isMutationAction,pathExists,readSettings,runWithHarnessDetectionSignals,runWithWorkspaceHarnessSignalDescriptors,boundAgentEpisodeIdentity}from"../sdk/runtime-primitives.js";import{pmToolActionNestedOptionKeys}from"../sdk/cli-contracts/tool-schema.js";import{readRequiredString,runAction,runWithActiveExtensions}from"../sdk/runtime.js";import{NARROW_TOOL_ACTIONS,TOOLS}from"./tool-definitions.js";import{normalizeWorkspaceToolArguments,resolveMcpToolAccess,resolveMcpToolSurface}from"./runtime-capabilities.js";import{PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS}from"../sdk/agent-capability-contracts.js";import{PM_MCP_ENTRY_TOOL_NAMES,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION,PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY,discoverPmTools,parsePmToolDiscoveryOptions}from"../sdk/mcp/discovery.js";import{commitItemMutations,previewItemMutations}from"../sdk/item-transaction.js";import{isRuntimeRecord,markMcpMutationTransportInput}from"../sdk/runtime-input.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{createReproducibleProcessRunner,runWithReproducibleProcessEnvironment}from"../sdk/reproducibility/process.js";import{parseAtomicMutationControls,resolveItemMutationDocument}from"../sdk/structured-mutations.js";import{resolveAuthor,resolvePmRoot,resolveWorkspaceRoot}from"../sdk/runtime-primitives.js";import{PM_MCP_ERROR_CODES,PM_MCP_META_KEYS,PM_MCP_PROTOCOL_VERSION,PmMcpProtocolError,attachMcpServerInfo,buildMcpCompleteResult,buildMcpDiscoverResult,hasMcpClientExtension,isMcpRecord,resolveMcpRequestContext}from"../sdk/mcp/protocol.js";import{PmMcpInputRequiredError,buildMcpInputRequiredResult,parseMcpInputResponses,validateMcpJsonSchema,withMcpCachePolicy}from"../sdk/mcp/interactions.js";import{PM_MCP_TASKS_EXTENSION,createMcpTaskStore}from"../sdk/mcp/tasks.js";import{PmMcpSubscriptionRegistry}from"../sdk/mcp/subscriptions.js";import{extractMcpTraceContext,runWithMcpTraceContext}from"../sdk/mcp/authorization.js";import{LegacyMcpAdapter}from"./legacy-adapter.js";import{PM_MCP_APP_CONTRACTS,PM_MCP_APP_MIME_TYPE,PM_MCP_APPS_EXTENSION,PM_MCP_APPS_SERVER_CAPABILITY,decoratePmMcpToolsWithApps,findPmMcpAppByUri,hasPmMcpAppsCapability,renderPmMcpAppHtml}from"../sdk/mcp/apps.js";import{PM_MCP_SKILLS_EXTENSION,PM_MCP_SKILLS_SERVER_CAPABILITY,PmMcpSkillRegistry,assertPmMcpSkillsCapability}from"../sdk/mcp/skills.js";function runMcpAction(args){return runAction(markMcpMutationTransportInput(args))}const PM_PACKAGE_ROOT_ENV="PM_CLI_PACKAGE_ROOT";function resolvePmPackageRoot(){return fileURLToPath(new URL("../..",import.meta.url))}if(typeof process.env[PM_PACKAGE_ROOT_ENV]!=="string"||process.env[PM_PACKAGE_ROOT_ENV]?.trim().length===0){process.env[PM_PACKAGE_ROOT_ENV]=resolvePmPackageRoot()}const PM_MCP_SERVER_VERSION=resolvePmCliVersion(import.meta.url,["../.."])??"0.0.0";const PM_MCP_SERVER_INFO={name:"pm-mcp",version:PM_MCP_SERVER_VERSION,description:"Stateless project-context management through pm SDK contracts.",websiteUrl:"https://github.com/unbraind/pm-cli"};const PM_MCP_SERVER_CAPABILITIES={prompts:{listChanged:true},resources:{listChanged:true,subscribe:true},tools:{listChanged:true},extensions:{[PM_MCP_TASKS_EXTENSION]:{},[PM_MCP_APPS_EXTENSION]:PM_MCP_APPS_SERVER_CAPABILITY,[PM_MCP_SKILLS_EXTENSION]:PM_MCP_SKILLS_SERVER_CAPABILITY,[PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION]:PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY}};const PM_MCP_SUBSCRIPTIONS=new Map;function createMcpSubscriptionRegistry(){return new PmMcpSubscriptionRegistry({capabilities:PM_MCP_SERVER_CAPABILITIES,serverInfo:PM_MCP_SERVER_INFO})}function pruneClosedMcpSubscriptionRegistries(){for(const[key,subscription]of PM_MCP_SUBSCRIPTIONS){if(subscription.registry.size===0)PM_MCP_SUBSCRIPTIONS.delete(key)}}const PM_MCP_CACHE_POLICIES={prompts:{ttlMs:6e4,cacheScope:"public"},resource:{ttlMs:0,cacheScope:"private"},resources:{ttlMs:6e4,cacheScope:"public"},tools:{ttlMs:3e4,cacheScope:"private"}};const PM_MCP_DIRECT_TASK_TOOLS=new Set(["pm_graph","pm_health","pm_validate"]);const PM_MCP_RUN_TASK_ACTIONS=new Set(["graph","health","import","reindex","test-all","validate"]);const PM_MCP_SKILL_METHODS=new Set(["skills/list","skills/get","resources/directory/read"]);const PM_MCP_INSTRUCTIONS="You have access to native pm CLI tools for git-based project management. When progressive discovery is negotiated, use pm_discover to expand the small entry catalog by intent and request schemas only when needed. Use pm_next to pick the next actionable item, or pm_context or pm_search before creating new work. Prefer narrow tools (pm_next, pm_context, pm_list, pm_get, pm_search, pm_events, pm_create, pm_mutate, pm_copy, pm_focus, pm_update, pm_append, pm_claim, pm_release, pm_close, pm_comments, pm_files, pm_docs, pm_notes, pm_learnings, pm_deps, pm_graph, pm_test, pm_validate, pm_health, pm_contracts, pm_schema, pm_profile, pm_config, pm_plan) over pm_run when they cover the operation. Use pm_plan for agent harness Plan workflows: it provides Codex/Claude/Cursor-style planning with durable steps, dependencies, decisions, discoveries, validation, and materialization. Use pm_schema and pm_config for workspace configuration: pm_schema manages custom item types/statuses and pm_config reads or writes settings keys. Use pm_run with an explicit action for active package-owned operations, plus activity, aggregate, history, stats, test-all, and gc. Use history-redact for audited history-stream redaction workflows, history-repair to re-anchor a drifted history chain, and history-compact to checkpoint/prune long history streams while preserving replay integrity. Agent harness and model provenance are detected automatically; pass author only for an intentional identity override. Do not pass path during real repository tracking \u2014 only pass path for sandbox or test runs.";function declaredToolKeys(tools=TOOLS){return new Map(tools.map(tool=>{const schema=tool.inputSchema;const properties=schema.properties??{};return[tool.name,Object.keys(properties)]}))}function nearestDeclaredKey(unexpected,declared){const limit=Math.max(1,Math.min(3,Math.floor(unexpected.length/4)+1));let best;for(const candidate of declared){const distance=levenshteinDistanceWithinLimit(unexpected,candidate,limit);if(distance===null){continue}if(best===void 0||distance<best.distance){best={key:candidate,distance}}}return best?.key}const UNEXPECTED_KEY_WARNING_EXEMPT_TOOLS=new Set(["pm_run"]);const MCP_RETRY_ARGUMENT_KEYS=new Set(["inputResponses","requestState"]);function resolveMcpDiscoveryCursorIntegrityKey(){const configuredKey=process.env.PM_MCP_DISCOVERY_CURSOR_KEY;if(configuredKey===void 0)return void 0;const key=Buffer.from(configuredKey,"utf8");if(key.byteLength<32){throw new PmCliError("PM_MCP_DISCOVERY_CURSOR_KEY must contain at least 32 UTF-8 bytes.",64)}return key}function detectUnexpectedTopLevelKeys(toolName,args,toolDeclaredKeys=declaredToolKeys()){if(typeof args!=="object"||args===null||Array.isArray(args)){return[]}if(UNEXPECTED_KEY_WARNING_EXEMPT_TOOLS.has(toolName)){return[]}const declared=toolDeclaredKeys.get(toolName);if(declared===void 0){return[]}const declaredSet=new Set([...declared,...MCP_RETRY_ARGUMENT_KEYS]);const warnings=[];for(const key of Object.keys(args)){if(declaredSet.has(key)){continue}const suggestion=nearestDeclaredKey(key,declared);warnings.push(suggestion!==void 0?`Unexpected top-level argument "${key}" for ${toolName} (did you mean "${suggestion}"?). It is not declared and may be ignored; declared arguments are: ${declared.join(", ")}.`:`Unexpected top-level argument "${key}" for ${toolName}. It is not declared and may be ignored; declared arguments are: ${declared.join(", ")}.`)}return warnings}const HANDLERS={pm_run:args=>runMcpAction(args),pm_discover:async args=>{const surface=await resolveMcpToolSurface(TOOLS,args);const cursorIntegrityKey=resolveMcpDiscoveryCursorIntegrityKey();const discoveryOptions=parsePmToolDiscoveryOptions(args);return discoverPmTools(surface.tools.map(tool=>({name:tool.name,description:tool.description,inputSchema:tool.inputSchema,authorized:true,signals:{freshness:1,usage:PM_MCP_ENTRY_TOOL_NAMES.includes(tool.name)?1:0}})),{...discoveryOptions,profile:surface.profile,...cursorIntegrityKey===void 0?{}:{cursorIntegrityKey}})},pm_mutate:async args=>{const transactionId=readRequiredString(args,"transactionId");const controls=parseAtomicMutationControls(args);const cwd=typeof args.cwd==="string"?args.cwd:process.cwd();const pmRoot=resolvePmRoot(cwd,typeof args.path==="string"?args.path:void 0);const resolved=resolveItemMutationDocument(JSON.stringify({schema_version:1,mutations:args.mutations}),{transactionId,idPrefix:(await readSettings(pmRoot)).id_prefix});const{mutations,references}=resolved;if(args.dryRun===true){const validation=await runWithActiveExtensions({cwd:typeof args.cwd==="string"?args.cwd:void 0,path:pmRoot,noExtensions:args.noExtensions===true},()=>previewItemMutations({pmRoot,transactionId,author:resolveAuthor(typeof args.author==="string"?args.author:void 0,"unknown"),mutations}));return{transaction_id:transactionId,dry_run:true,validation,mutation_count:mutations.length,mutations,references}}const result=await runWithActiveExtensions({cwd:typeof args.cwd==="string"?args.cwd:void 0,path:typeof args.path==="string"?args.path:void 0,noExtensions:args.noExtensions===true},()=>commitItemMutations({pmRoot,transactionId,author:resolveAuthor(typeof args.author==="string"?args.author:void 0,"unknown"),mutations,...controls}));const{transactionId:committedTransactionId,...commitResult}=result;return{...commitResult,transaction_id:committedTransactionId,mutation_count:mutations.length,references}},...Object.fromEntries(Object.entries(NARROW_TOOL_ACTIONS).map(([tool,action])=>[tool,args=>runMcpAction({...args,action})]))};function resolveInvokedAction(toolName,args){if(toolName==="pm_run"){return typeof args.action==="string"?args.action:void 0}return NARROW_TOOL_ACTIONS[toolName]}async function collectMutationGuardWarnings(toolName,action,args){if(toolName!=="pm_mutate"&&!isMutationAction(action??"")){return[]}const cwd=typeof args.cwd==="string"?args.cwd:process.cwd();const pmRoot=resolvePmRoot(cwd,typeof args.path==="string"?args.path:void 0);if(!await pathExists(getSettingsPath(pmRoot))){return[]}const settings=await readSettings(pmRoot);const nestedOptions=typeof args.options==="object"&&args.options!==null&&!Array.isArray(args.options)?args.options:{};const result=evaluateMutationGuard({author:resolveAuthor(typeof args.author==="string"?args.author:typeof nestedOptions.author==="string"?nestedOptions.author:void 0,settings.author_default),payload:Object.fromEntries(Object.entries(args).filter(([key])=>key!=="cwd"&&key!=="path")),settings:settings.mutation_guard,force:args.force===true||nestedOptions.force===true});return result.warnings}function detectUnexpectedOptionKeys(toolName,action,args){const options=args.options;if(action===void 0||typeof options!=="object"||options===null||Array.isArray(options)){return[]}const declared=pmToolActionNestedOptionKeys(action);if(declared===void 0){return[]}const declaredSet=new Set(declared);const warnings=[];for(const key of Object.keys(options)){if(declaredSet.has(key)){continue}const suggestion=nearestDeclaredKey(key,declared);warnings.push(suggestion!==void 0?`Unknown option "${key}" for ${toolName} action "${action}" (did you mean "${suggestion}"?). The ${action} contract does not read it, so it has no effect; declared keys are: ${declared.join(", ")}.`:`Unknown option "${key}" for ${toolName} action "${action}". The ${action} contract does not read it, so it has no effect; declared keys are: ${declared.join(", ")}.`)}return warnings}function resultContent(result,warnings,tokenAccounting=false,canonicalStructuredResult=false){const effectiveResult=tokenAccounting?attachOutputTokenAccounting(result,value=>JSON.stringify(value,null,2)):result;const structuredContent=warnings!==void 0&&warnings.length>0?{result:effectiveResult,warnings}:{result:effectiveResult};return{content:[{type:"text",text:canonicalStructuredResult?"Canonical result: structuredContent.result":JSON.stringify(effectiveResult,null,2)}],structuredContent}}function errorContent(error,canonicalStructuredResult=false){const code=error instanceof PmCliError?error.exitCode:1;const message=error instanceof Error?error.message:String(error);const details=error instanceof PmCliError?error.context:void 0;return{isError:true,content:[{type:"text",text:canonicalStructuredResult?"Canonical error: structuredContent":JSON.stringify({error:message,code,details},null,2)}],structuredContent:{result:null,error:message,code,details}}}function boundMcpClientProvenance(value){const provenance=isRuntimeRecord(value)?value:{};const bounded={};let acceptedCount=0;for(const key in provenance){if(acceptedCount>=32)break;if(!Object.prototype.hasOwnProperty.call(provenance,key))continue;const entry=provenance[key];if(/^[a-z][a-z0-9_-]{0,63}$/u.test(key)&&typeof entry==="string"&&entry.trim().length>0){bounded[key]=entry.trim().slice(0,256);acceptedCount+=1}}return bounded}function readMcpClientInfo(value){const clientInfo=isRuntimeRecord(value)?value:{};const clientName=typeof clientInfo.name==="string"?clientInfo.name.trim():"";if(clientName.length===0)return void 0;const optionalValues=[["version",clientInfo.version,128],["model",clientInfo.model,256],["session",clientInfo.session,256]];const result={name:clientName.slice(0,128)};for(const[key,value2,limit]of optionalValues){if(typeof value2==="string"&&value2.trim().length>0){result[key]=value2.trim().slice(0,limit)}}const boundedProvenance=boundMcpClientProvenance(clientInfo.provenance);if(Object.keys(boundedProvenance).length>0){result.provenance=boundedProvenance}const episode=boundAgentEpisodeIdentity(clientInfo.episode,false);if(episode!==void 0)result.episode=episode;return result}async function emitMcpChangeNotifications(action){if(isMutationAction(action??"")){await Promise.all([...PM_MCP_SUBSCRIPTIONS.values()].flatMap(({registry})=>PM_MCP_RESOURCE_CONTRACTS.map(resource=>registry.emitResourceUpdated(resource.uri))))}if(["extension","install","package","uninstall"].includes(action??"")){await Promise.all([...PM_MCP_SUBSCRIPTIONS.values()].map(({registry})=>registry.emitListChanged("tools")))}pruneClosedMcpSubscriptionRegistries()}async function handleToolCall(paramsInput,clientInfo,progressiveDiscoveryNegotiated=false){const clientSignals=clientInfo?{client_info:clientInfo}:{};return runWithHarnessDetectionSignals({env:process.env,argv:process.argv,...clientSignals},async()=>{const params=asRecordClone(paramsInput);const name=readRequiredString(params,"name");const handler=Object.prototype.hasOwnProperty.call(HANDLERS,name)?HANDLERS[name]:void 0;if(!handler){throw new PmCliError(`Unknown pm MCP tool: ${name}`,64)}const inputResponses=params.inputResponses===void 0?void 0:parseMcpInputResponses(params.inputResponses);validateMcpToolArguments(params.arguments);const requestedArgs={...decodeHtmlEntitiesInOptions(asRecordClone(params.arguments)),...inputResponses?{inputResponses}:{},...typeof params.requestState==="string"?{requestState:params.requestState}:{}};const access=await resolveMcpToolAccess(TOOLS,name,requestedArgs);const requiredCustomDiscoveryEntry=progressiveDiscoveryNegotiated&&access.profile==="custom"&&name==="pm_discover";if(!access.available&&!requiredCustomDiscoveryEntry){throw new PmCliError(`pm MCP tool "${name}" is unavailable in the ${access.profile} profile.`,64)}const args=await normalizeWorkspaceToolArguments(name,requestedArgs);const cwd=typeof args.cwd==="string"?args.cwd:process.cwd();const pmRoot=resolvePmRoot(cwd,typeof args.path==="string"?args.path:void 0);const workspaceIdentity=await pathExists(getSettingsPath(pmRoot))?(await readSettings(pmRoot)).agent_identity:void 0;return runWithHarnessDetectionSignals({env:{...process.env,PM_PATH:pmRoot},argv:process.argv,cwd,...clientSignals},()=>runWithWorkspaceHarnessSignalDescriptors(workspaceIdentity?.harness_signals??[],async()=>{const action=resolveInvokedAction(name,args);const warnings=[...detectUnexpectedTopLevelKeys(name,args,declaredToolKeys()),...detectUnexpectedOptionKeys(name,action,args),...await collectMutationGuardWarnings(name,action,args)];for(const warning of warnings){console.error(`[pm-mcp] ${warning}`)}const result=await handler(args);void emitMcpChangeNotifications(action);return resultContent(result,warnings,args.tokenAccounting===true,progressiveDiscoveryNegotiated)},{probesEnabled:workspaceIdentity?.probes_enabled}))})}async function openMcpSubscription(input){if(typeof input.request.id!=="string"&&typeof input.request.id!=="number"||input.request.method!=="subscriptions/listen"){throw new PmMcpProtocolError("Invalid MCP subscriptions/listen request",PM_MCP_ERROR_CODES.invalidParams,{required:["id","method","params.notifications"]})}resolveMcpRequestContext(input.request.params);const key=input.key??input.request.id;if(PM_MCP_SUBSCRIPTIONS.has(key)){throw new PmMcpProtocolError("MCP subscription id is already active",PM_MCP_ERROR_CODES.invalidParams,{subscriptionId:input.request.id})}const registry=createMcpSubscriptionRegistry();await registry.open({id:input.request.id,notifications:input.request.params?.notifications,sink:input.sink});PM_MCP_SUBSCRIPTIONS.set(key,{id:input.request.id,registry})}function closeMcpSubscription(id,key=id){const subscription=PM_MCP_SUBSCRIPTIONS.get(key);if(!subscription||subscription.id!==id)return void 0;PM_MCP_SUBSCRIPTIONS.delete(key);return subscription.registry.close(id)}function closeStdioMcpSubscriptions(){const closed=[];for(const[key,subscription]of PM_MCP_SUBSCRIPTIONS){if(key!==subscription.id)continue;const result=closeMcpSubscription(subscription.id,key);if(result)closed.push({id:subscription.id,result})}return closed}async function resolveMcpToolSchemaForRequest(request){if(request.method!=="tools/call")return void 0;const name=request.params?.name;if(typeof name!=="string")return void 0;const surface=await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(request.params));return surface.tools.find(tool=>tool.name===name)?.inputSchema}function buildMcpToolCallErrorResult(request,error){if(request.method!=="tools/call"||error instanceof PmMcpProtocolError){return void 0}const content=errorContent(error,hasMcpProtocolVersionMetadata(request)&&hasMcpClientExtension(resolveMcpRequestContext(request.params),PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION));return hasMcpProtocolVersionMetadata(request)?buildMcpCompleteResult(content,PM_MCP_SERVER_INFO):content}function requestWorkspaceArgs(params){const paramsRecord=asRecordClone(params);return asRecordClone(paramsRecord.arguments??paramsRecord)}async function readWorkspaceResource(uri,params){const args=requestWorkspaceArgs(params);const cwd=typeof args.cwd==="string"?args.cwd:process.cwd();const contract=PM_MCP_RESOURCE_CONTRACTS.find(resource=>resource.uri===uri);if(!contract){throw new PmCliError(`Unknown pm MCP resource: ${uri}`,64)}let value;if(uri==="pm://workspace/context"){value=await runMcpAction({...args,action:"context",limit:10})}else if(uri==="pm://workspace/claims"){value=await runMcpAction({...args,action:"list",status:"in_progress",limit:20})}else if(uri==="pm://workspace/focus"){value=await runMcpAction({...args,action:"focus",subcommand:"show"})}else{const guidePath=path.join(cwd,"AGENTS.md");value=await pathExists(guidePath)?(await readFile(guidePath,"utf8")).slice(0,32e3):"No repository-local AGENTS.md was found."}return{contents:[{uri,mimeType:contract.mimeType,text:typeof value==="string"?value:JSON.stringify(value,null,2)}]}}async function loadRequestSkillRegistry(params){const args=requestWorkspaceArgs(params);const cwd=typeof args.cwd==="string"?args.cwd:process.cwd();const workspaceRoot=resolveWorkspaceRoot(resolvePmRoot(cwd,typeof args.path==="string"?args.path:void 0));return PmMcpSkillRegistry.load({packageRoot:resolvePmPackageRoot(),workspaceRoot,packageVersion:PM_MCP_SERVER_VERSION})}function renderWorkflowPrompt(params){const paramsRecord=asRecordClone(params);const name=readRequiredString(paramsRecord,"name");const prompt=PM_MCP_PROMPT_CONTRACTS.find(candidate=>candidate.name===name);if(!prompt){throw new PmCliError(`Unknown pm MCP prompt: ${name}`,64)}const argumentsRecord=asRecordClone(paramsRecord.arguments);let text=prompt.template;for(const argument of prompt.arguments){const value=argumentsRecord[argument.name];if(argument.required&&(typeof value!=="string"||value.trim().length===0)){throw new PmCliError(`Missing required prompt argument: ${argument.name}`,64)}text=text.replaceAll(`{{${argument.name}}}`,typeof value==="string"?value:"")}return{description:prompt.description,messages:[{role:"user",content:{type:"text",text}}]}}const LEGACY_MCP_ADAPTER=new LegacyMcpAdapter({serverInfo:PM_MCP_SERVER_INFO,capabilities:PM_MCP_SERVER_CAPABILITIES,instructions:PM_MCP_INSTRUCTIONS,parseClientInfo:readMcpClientInfo,listTools:async params=>({tools:(await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(params))).tools}),callTool:handleToolCall,listResources:()=>({resources:PM_MCP_RESOURCE_CONTRACTS}),readResource:params=>readWorkspaceResource(readRequiredString(asRecordClone(params),"uri"),params),listPrompts:()=>({prompts:PM_MCP_PROMPT_CONTRACTS.map(prompt=>({name:prompt.name,description:prompt.description,arguments:prompt.arguments}))}),getPrompt:renderWorkflowPrompt});function deterministicMcpTools(tools){return tools.map(tool=>({...tool,inputSchema:validateMcpJsonSchema(tool.inputSchema)})).sort((left,right)=>left.name.localeCompare(right.name))}function mcpTaskPrincipal(requestContext){return requestContext.clientInfo?`${requestContext.clientInfo.name}@${requestContext.clientInfo.version}`:"anonymous-stdio"}function mcpTaskStore(){return createMcpTaskStore({pmRoot:resolvePmRoot(process.cwd()),owner:"pm-mcp-task-provider"})}function validateMcpToolArguments(value){if(value!==void 0&&!isMcpRecord(value)){throw new PmCliError("pm MCP tool arguments must be an object.",64)}}function shouldCreateMcpTask(params,requestContext){if(!hasMcpClientExtension(requestContext,PM_MCP_TASKS_EXTENSION)){return false}const requestParams=asRecordClone(params);const name=requestParams.name;const args=asRecordClone(requestParams.arguments);if(PM_MCP_DIRECT_TASK_TOOLS.has(name))return true;if(name==="pm_test"&&(args.subcommand==="run"||isMcpRecord(args.options)&&args.options.subcommand==="run")){return true}if(name!=="pm_run")return false;return typeof args.action==="string"&&PM_MCP_RUN_TASK_ACTIONS.has(args.action)}const PENDING_MCP_TASKS=new Map;async function executeMcpTask(execution,inputResponses){const params={...execution.params,...inputResponses?{inputResponses}:{},...execution.requestState?{requestState:execution.requestState}:{}};try{const result=await handleToolCall(params,execution.context.clientInfo,hasMcpClientExtension(execution.context,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION));await execution.store.complete(execution.taskId,execution.principal,buildMcpCompleteResult(result,PM_MCP_SERVER_INFO));PENDING_MCP_TASKS.delete(execution.taskId)}catch(error){if(error instanceof PmMcpInputRequiredError){execution.requestState=error.requestState;await execution.store.requireInput({taskId:execution.taskId,principal:execution.principal,requestContext:execution.context,inputRequests:error.inputRequests,statusMessage:"Task requires additional client input."});return}if(error instanceof PmMcpProtocolError){await execution.store.fail(execution.taskId,execution.principal,{code:error.code,message:error.message,data:error.data})}else{await execution.store.complete(execution.taskId,execution.principal,buildMcpCompleteResult(errorContent(error,hasMcpClientExtension(execution.context,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)),PM_MCP_SERVER_INFO))}PENDING_MCP_TASKS.delete(execution.taskId)}}async function settleMcpTaskExecution(taskId,execution){try{await execution}catch{PENDING_MCP_TASKS.delete(taskId)}}function scheduleMcpTaskExecution(execution,inputResponses){void settleMcpTaskExecution(execution.taskId,executeMcpTask(execution,inputResponses))}async function createMcpTaskForToolCall(params,requestContext){const store=mcpTaskStore();const principal=mcpTaskPrincipal(requestContext);const task=await store.create({principal,statusMessage:"pm operation accepted for asynchronous execution."});const execution={context:requestContext,params:asRecordClone(params),principal,store,taskId:task.taskId};PENDING_MCP_TASKS.set(task.taskId,execution);scheduleMcpTaskExecution(execution);return attachMcpServerInfo(task,PM_MCP_SERVER_INFO)}async function dispatchMcpTaskMethod(request,requestContext){if(!hasMcpClientExtension(requestContext,PM_MCP_TASKS_EXTENSION)){throw new PmMcpProtocolError("Missing required client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[PM_MCP_TASKS_EXTENSION]:{}}}})}const params=asRecordClone(request.params);const taskId=readRequiredString(params,"taskId");const principal=mcpTaskPrincipal(requestContext);const store=mcpTaskStore();if(request.method==="tasks/get"){return buildMcpCompleteResult(await store.get(taskId,principal),PM_MCP_SERVER_INFO)}if(request.method==="tasks/update"){const update=await store.update(taskId,principal,params.inputResponses);const execution=PENDING_MCP_TASKS.get(taskId);if(execution&&update.acceptedKeys.length>0&&update.remainingKeys.length===0){scheduleMcpTaskExecution(execution,await store.takeInputResponses(taskId,principal))}return buildMcpCompleteResult({},PM_MCP_SERVER_INFO)}await store.cancel(taskId,principal);PENDING_MCP_TASKS.delete(taskId);return buildMcpCompleteResult({},PM_MCP_SERVER_INFO)}async function dispatchModernToolMethod(request,requestContext,clientInfo){if(request.method==="tools/list"){const surface=await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(request.params));const progressiveDiscovery=hasMcpClientExtension(requestContext,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION);const listedTools=progressiveDiscovery?[...surface.tools.filter(tool=>PM_MCP_ENTRY_TOOL_NAMES.includes(tool.name)),...surface.profile==="custom"&&!surface.tools.some(tool=>tool.name==="pm_discover")?TOOLS.filter(tool=>tool.name==="pm_discover"):[]]:surface.tools;return buildMcpCompleteResult(withMcpCachePolicy({tools:hasCompatiblePmMcpAppsCapability(requestContext)?decoratePmMcpToolsWithApps(deterministicMcpTools(listedTools)):deterministicMcpTools(listedTools)},PM_MCP_CACHE_POLICIES.tools),PM_MCP_SERVER_INFO)}validateMcpToolArguments(request.params?.arguments);if(shouldCreateMcpTask(request.params,requestContext)){return createMcpTaskForToolCall(request.params,requestContext)}try{return buildMcpCompleteResult(await handleToolCall(request.params,clientInfo,hasMcpClientExtension(requestContext,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)),PM_MCP_SERVER_INFO)}catch(error){if(!(error instanceof PmMcpInputRequiredError))throw error;return buildMcpInputRequiredResult({requestContext,serverInfo:PM_MCP_SERVER_INFO,inputRequests:error.inputRequests,requestState:error.requestState})}}async function dispatchModernResourceMethod(request,requestContext){if(request.method==="resources/list"){const resources=[...PM_MCP_RESOURCE_CONTRACTS,...hasCompatiblePmMcpAppsCapability(requestContext)?PM_MCP_APP_CONTRACTS.map(contract=>({uri:contract.uri,name:contract.name,description:contract.description,mimeType:PM_MCP_APP_MIME_TYPE,_meta:{ui:contract.resourceMeta}})):[]].sort((left,right)=>left.uri.localeCompare(right.uri));return buildMcpCompleteResult(withMcpCachePolicy({resources},PM_MCP_CACHE_POLICIES.resources),PM_MCP_SERVER_INFO)}if(request.method==="resources/templates/list"){return buildMcpCompleteResult(withMcpCachePolicy({resourceTemplates:[]},PM_MCP_CACHE_POLICIES.resources),PM_MCP_SERVER_INFO)}try{const uri=readRequiredString(asRecordClone(request.params),"uri");const app=findPmMcpAppByUri(uri);let resource;if(app){if(!hasPmMcpAppsCapability(requestContext)){throw new PmMcpProtocolError("MCP App resource requires negotiated client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[PM_MCP_APPS_EXTENSION]:PM_MCP_APPS_SERVER_CAPABILITY}}})}resource={contents:[{uri,mimeType:PM_MCP_APP_MIME_TYPE,text:renderPmMcpAppHtml(app),_meta:{ui:app.resourceMeta}}]}}else if(uri.startsWith("skill://")){assertPmMcpSkillsCapability(requestContext);resource={...(await loadRequestSkillRegistry(request.params)).read(uri)}}else{resource=await readWorkspaceResource(uri,request.params)}return buildMcpCompleteResult(withMcpCachePolicy(resource,PM_MCP_CACHE_POLICIES.resource),PM_MCP_SERVER_INFO)}catch(error){if(!(error instanceof PmCliError)||!error.message.startsWith("Unknown pm MCP resource:")){throw error}throw new PmMcpProtocolError(error.message,PM_MCP_ERROR_CODES.invalidParams,{field:"uri"})}}function hasCompatiblePmMcpAppsCapability(requestContext){try{return hasPmMcpAppsCapability(requestContext)}catch(error){if(error instanceof PmMcpProtocolError)return false;throw error}}function readSkillPageOptions(params){if(params.cursor!==void 0&&typeof params.cursor!=="string"){throw new PmMcpProtocolError("Skills cursor must be a string",PM_MCP_ERROR_CODES.invalidParams,{field:"cursor"})}if(params.limit!==void 0&&typeof params.limit!=="number"){throw new PmMcpProtocolError("Skills limit must be a number",PM_MCP_ERROR_CODES.invalidParams,{field:"limit"})}return{...typeof params.cursor==="string"?{cursor:params.cursor}:{},...typeof params.limit==="number"?{limit:params.limit}:{}}}async function dispatchModernSkillMethod(request,requestContext){const directoryRead=request.method==="resources/directory/read";assertPmMcpSkillsCapability(requestContext,directoryRead);const params=asRecordClone(request.params);const registry=await loadRequestSkillRegistry(request.params);let result;if(request.method==="skills/list"){result={...registry.list(readSkillPageOptions(params))}}else if(request.method==="skills/get"){result={skill:registry.get(readRequiredString(params,"uri"))}}else{result={...registry.readDirectory(readRequiredString(params,"uri"),readSkillPageOptions(params))}}return buildMcpCompleteResult(withMcpCachePolicy(result,PM_MCP_CACHE_POLICIES.resource),PM_MCP_SERVER_INFO)}function dispatchModernPromptMethod(request){const result=request.method==="prompts/list"?withMcpCachePolicy({prompts:PM_MCP_PROMPT_CONTRACTS.map(prompt=>({name:prompt.name,description:prompt.description,arguments:prompt.arguments})).sort((left,right)=>left.name.localeCompare(right.name))},PM_MCP_CACHE_POLICIES.prompts):renderWorkflowPrompt(request.params);return buildMcpCompleteResult(result,PM_MCP_SERVER_INFO)}async function dispatchModernMcpRequest(request,meta){const requestContext=resolveMcpRequestContext(request.params);const clientInfo=readMcpClientInfo(meta[PM_MCP_META_KEYS.clientInfo]);if(request.method==="server/discover"){return buildMcpDiscoverResult({serverInfo:PM_MCP_SERVER_INFO,capabilities:PM_MCP_SERVER_CAPABILITIES,instructions:PM_MCP_INSTRUCTIONS})}if(request.method==="ping"){throw new PmMcpProtocolError("MCP method not found: ping",-32601,{removedIn:PM_MCP_PROTOCOL_VERSION})}if(PM_MCP_SKILL_METHODS.has(request.method??"")){return dispatchModernSkillMethod(request,requestContext)}if(request.method==="tasks/get"||request.method==="tasks/update"||request.method==="tasks/cancel"){return dispatchMcpTaskMethod(request,requestContext)}if(request.method==="tools/list"||request.method==="tools/call"){return dispatchModernToolMethod(request,requestContext,clientInfo)}if(request.method==="resources/list"||request.method==="resources/templates/list"||request.method==="resources/read"){return dispatchModernResourceMethod(request,requestContext)}if(request.method==="prompts/list"||request.method==="prompts/get"){return dispatchModernPromptMethod(request)}throw new PmMcpProtocolError(`MCP method not found: ${request.method??"(missing)"}`,-32601)}async function handleRequestInReproducibleContext(request){if(!request.id&&request.method?.startsWith("notifications/")){return void 0}if(hasMcpProtocolVersionMetadata(request)){const allowlist=(process.env.PM_MCP_BAGGAGE_ALLOWLIST??"").split(",").map(entry=>entry.trim()).filter(Boolean);return runWithMcpTraceContext(extractMcpTraceContext(request.params,{baggageAllowlist:allowlist}),()=>dispatchModernMcpRequest(request,request.params._meta))}if(request.method==="initialize"){return LEGACY_MCP_ADAPTER.initialize(request.params)}return LEGACY_MCP_ADAPTER.dispatch(request)}function hasMcpProtocolVersionMetadata(request){const meta=isMcpRecord(request.params)?request.params._meta:void 0;return isMcpRecord(meta)&&Object.prototype.hasOwnProperty.call(meta,PM_MCP_META_KEYS.protocolVersion)}async function handleRequest(request){return runWithReproducibleProcessEnvironment(process.env,()=>handleRequestInReproducibleContext(request))}function writeResponse(id,payload){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id,result:payload})}
3
3
  `)}function writeError(id,error){const code=error instanceof PmMcpProtocolError?error.code:error instanceof PmCliError?error.exitCode:-32603;const message=error instanceof Error?error.message:String(error);const data=error instanceof PmMcpProtocolError?error.data:error instanceof PmCliError?error.context:void 0;process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id,error:{code,message,data}})}
4
4
  `)}function writeToolCallErrorResponse(request,error){if(request.method!=="tools/call"||error instanceof PmMcpProtocolError){return false}writeResponse(request.id,buildMcpToolCallErrorResult(request,error));return true}async function handleStdioTransportControl(request){if(request.method==="subscriptions/listen"){await openMcpSubscription({request,sink:notification=>{process.stdout.write(`${JSON.stringify(notification)}
5
5
  `)}});return true}if(request.method!=="notifications/cancelled")return false;const requestId=request.params?.requestId;if(typeof requestId==="string"||typeof requestId==="number"){const result=closeMcpSubscription(requestId);if(result)writeResponse(requestId,result)}return true}async function processRpcLineWithHandler(line,requestHandler){if(line.trim().length===0){return}let request;try{request=JSON.parse(line)}catch(error){const message=error instanceof Error?error.message:String(error);writeError(null,new PmCliError(`Parse error: ${message}`,-32700));return}if(typeof request!=="object"||request===null||Array.isArray(request)){writeError(null,new PmCliError("Invalid JSON-RPC request: expected an object",-32600));return}const shouldRespond=Object.prototype.hasOwnProperty.call(request,"id");try{if(await handleStdioTransportControl(request))return;const result=await requestHandler(request);if(shouldRespond&&result!==void 0){writeResponse(request.id,result)}}catch(error){if(!shouldRespond){return}if(!writeToolCallErrorResponse(request,error)){writeError(request.id,error)}}}async function processRpcLine(line){await processRpcLineWithHandler(line,handleRequest)}function startMcpServer(){const rl=readline.createInterface({input:process.stdin,crlfDelay:Infinity});const queue=createSerialQueue();let processLine;try{const runInProcessContext=createReproducibleProcessRunner(process.env);processLine=line=>runInProcessContext(()=>processRpcLineWithHandler(line,handleRequestInReproducibleContext))}catch{processLine=processRpcLine}rl.on("line",line=>{void queue.enqueue(()=>processLine(line))});rl.on("close",()=>{void queue.enqueue(()=>{for(const closed of closeStdioMcpSubscriptions()){writeResponse(closed.id,closed.result)}})})}function isInvokedAsMcpMainModule(argvPath,moduleUrl){if(!argvPath){return false}const selfPath=fileURLToPath(moduleUrl);if(argvPath===selfPath){return true}try{return realpathSync(argvPath)===realpathSync(selfPath)}catch{return false}}function readRuntimeTestHook(key){const runtimeTestHooks=globalThis.__pmCliActionRunnerTestHooks;if(runtimeTestHooks===void 0){throw new PmCliError(`MCP runtime test hook "${String(key)}" is only available in test environments.`,64)}return runtimeTestHooks[key]}const _testOnly={boundMcpClientProvenance,createMcpInputRequiredError:input=>new PmMcpInputRequiredError(input),createMcpProtocolError:(...input)=>new PmMcpProtocolError(...input),get closeManyOptionsFromFlat(){return readRuntimeTestHook("closeManyOptionsFromFlat")},detectUnexpectedOptionKeys,detectUnexpectedTopLevelKeys,collectMutationGuardWarnings,closeStdioMcpSubscriptions,errorContent,emitMcpChangeNotifications,expireMcpSubscriptionRecord:(id,key=id)=>PM_MCP_SUBSCRIPTIONS.get(key).registry.close(id),getMcpClientInfo:()=>LEGACY_MCP_ADAPTER.getClientInfo(),get extensionOptionsFromArgs(){return readRuntimeTestHook("extensionOptionsFromArgs")},get globalOptions(){return readRuntimeTestHook("globalOptions")},get mutationListOptions(){return readRuntimeTestHook("mutationListOptions")},nearestDeclaredKey,mcpTaskPrincipal,resultContent,resolveMcpRequestContext,shouldCreateMcpTask,settleMcpTaskExecution,subscriptionCount:()=>PM_MCP_SUBSCRIPTIONS.size,get normalizeActionName(){return readRuntimeTestHook("normalizeActionName")},get normalizeCommandPath(){return readRuntimeTestHook("normalizeCommandPath")},get normalizeMcpOptionsArrays(){return readRuntimeTestHook("normalizeMcpOptionsArrays")},get normalizeMcpUpdateOptions(){return readRuntimeTestHook("normalizeMcpUpdateOptions")},get optionsWithAuthor(){return readRuntimeTestHook("optionsWithAuthor")},get readRequiredString(){return readRuntimeTestHook("readRequiredString")},get readScalarString(){return readRuntimeTestHook("readScalarString")},get readScalarStringAllowBlank(){return readRuntimeTestHook("readScalarStringAllowBlank")},get readStringArray(){return readRuntimeTestHook("readStringArray")},runAction:runMcpAction,get updateManyOptionsFromFlat(){return readRuntimeTestHook("updateManyOptionsFromFlat")},get withAddNoteOption(){return readRuntimeTestHook("withAddNoteOption")},get withFilesDiscoveryOptions(){return readRuntimeTestHook("withFilesDiscoveryOptions")},get withMutationCompaction(){return readRuntimeTestHook("withMutationCompaction")},writeError};if(isInvokedAsMcpMainModule(process.argv[1],import.meta.url)){startMcpServer()}export{_testOnly,buildMcpToolCallErrorResult,closeMcpSubscription,handleRequest,isInvokedAsMcpMainModule,openMcpSubscription,processRpcLine,resolveMcpToolSchemaForRequest,startMcpServer};
@@ -1,2 +1,2 @@
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]="4b0b0999-9172-51f5-9645-bab74d30cb3d")}catch(e2){}})();import{PM_CONTEXT_INTENT_CONTRACTS}from"../context-intent-contracts.js";import{LIST_COMMAND_DEFAULT_PROJECTIONS,listGetProjectionFields,listListProjectionFields,listSearchProjectionFields}from"../query/projection-contracts.js";const REJECTED_INTENT="not-a-declared-intent";const REJECTED_FIELD="not-a-declared-field";function listCoreClosedDomainContracts(){const positionalArguments={get:["pm-domain"],search:["Domain query"]};const intentContracts=[...new Set(PM_CONTEXT_INTENT_CONTRACTS.map(({command})=>command))].map(command=>{const commandContracts=PM_CONTEXT_INTENT_CONTRACTS.filter(candidate=>candidate.command===command);const contract=commandContracts[0];const positionals=positionalArguments[contract.command]??[];return{probe_id:`${contract.command}-invalid-intent`,command:contract.command,flag:"--for",rejected_value:REJECTED_INTENT,refusal_args:[contract.command,...positionals,"--for",REJECTED_INTENT],allowed_values:commandContracts.map(({intent})=>intent).sort(),suggested_retry_args:[contract.command,...positionals,"--for",contract.intent],error_code:"unknown_context_intent"}});const listFields=listListProjectionFields();const listFieldContracts=Object.keys(LIST_COMMAND_DEFAULT_PROJECTIONS).map(command=>({probe_id:`${command}-invalid-field`,command,flag:"--fields",rejected_value:REJECTED_FIELD,refusal_args:[command,"--fields",REJECTED_FIELD],allowed_values:listFields,suggested_retry_args:[command,"--fields","id,title,status","--limit","10"],error_code:"unknown_field_projection"}));const contracts=[...intentContracts,...listFieldContracts,{probe_id:"get-invalid-field",command:"get",flag:"--fields",rejected_value:REJECTED_FIELD,refusal_args:["get","pm-domain","--fields",REJECTED_FIELD],allowed_values:listGetProjectionFields(),suggested_retry_args:["get","pm-domain","--fields","id,title,status"],error_code:"unknown_field_projection"},{probe_id:"list-mutually-exclusive-projection",command:"list",flag:"--projection",rejected_value:"--brief+--full",refusal_args:["list","--brief","--full"],allowed_values:[],suggested_retry_args:["list","--brief"],error_code:"projection_options_mutually_exclusive",allowed_values_required:false},{probe_id:"get-mutually-exclusive-projection",command:"get",flag:"--projection",rejected_value:"--full+--fields",refusal_args:["get","pm-domain","--full","--fields","id"],allowed_values:[],suggested_retry_args:["get","pm-domain","--full"],error_code:"projection_options_mutually_exclusive",allowed_values_required:false},{probe_id:"search-mutually-exclusive-projection",command:"search",flag:"--projection",rejected_value:"--full+--fields",refusal_args:["search","Domain query","--full","--fields","id"],allowed_values:[],suggested_retry_args:["search","Domain query","--full"],error_code:"projection_options_mutually_exclusive",allowed_values_required:false},{probe_id:"package-upgrade-mutually-exclusive-modes",command:"package upgrade",flag:"--cli-only/--packages-only",rejected_value:"--cli-only+--packages-only",refusal_args:["package","upgrade","--cli-only","--packages-only","--dry-run"],allowed_values:[],suggested_retry_args:["package","upgrade","--packages-only","--dry-run"],error_code:"package_upgrade_modes_mutually_exclusive",allowed_values_required:false},{probe_id:"search-invalid-field",command:"search",flag:"--fields",rejected_value:REJECTED_FIELD,refusal_args:["search","Domain query","--fields",REJECTED_FIELD],allowed_values:listSearchProjectionFields(),suggested_retry_args:["search","Domain query","--fields","id,title,status,score"],error_code:"unknown_field_projection"}];return contracts.sort((left,right)=>left.probe_id.localeCompare(right.probe_id))}function renderPmClosedDomainHelp(command,flag){const contract=listCoreClosedDomainContracts().find(candidate=>candidate.command===command&&candidate.flag===flag);if(!contract)return"No stable core values are declared.";const canonicalValues=contract.allowed_values.filter(value=>!value.startsWith("item."));const runtimeSuffix=flag==="--fields"?" item.<field> aliases and configured runtime metadata fields are also accepted.":" Configured package and workspace intents may extend this domain.";return`Allowed core values: ${canonicalValues.join("|")}.${runtimeSuffix}`}export{listCoreClosedDomainContracts,renderPmClosedDomainHelp};
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]="d3714178-d64c-564c-a1bc-e5393fc57758")}catch(e2){}})();import{PM_CONTEXT_INTENT_CONTRACTS}from"../context-intent-contracts.js";import{LIST_COMMAND_DEFAULT_PROJECTIONS,listGetProjectionFields,listListProjectionFields,listSearchProjectionFields}from"../query/projection-contracts.js";const REJECTED_INTENT="not-a-declared-intent";const REJECTED_FIELD="not-a-declared-field";function listCoreClosedDomainContracts(){const positionalArguments={get:["pm-domain"],search:["Domain query"]};const intentContracts=[...new Set(PM_CONTEXT_INTENT_CONTRACTS.map(({command})=>command))].map(command=>{const commandContracts=PM_CONTEXT_INTENT_CONTRACTS.filter(candidate=>candidate.command===command);const contract=commandContracts[0];const positionals=positionalArguments[contract.command]??[];return{probe_id:`${contract.command}-invalid-intent`,command:contract.command,flag:"--for",rejected_value:REJECTED_INTENT,refusal_args:[contract.command,...positionals,"--for",REJECTED_INTENT],allowed_values:commandContracts.map(({intent})=>intent).sort(),suggested_retry_args:[contract.command,...positionals,"--for",contract.intent],error_code:"unknown_context_intent"}});const listFields=listListProjectionFields();const listFieldContracts=Object.keys(LIST_COMMAND_DEFAULT_PROJECTIONS).map(command=>({probe_id:`${command}-invalid-field`,command,flag:"--fields",rejected_value:REJECTED_FIELD,refusal_args:[command,"--fields",REJECTED_FIELD],allowed_values:listFields,suggested_retry_args:[command,"--fields","id,title,status"],error_code:"unknown_field_projection"}));const contracts=[...intentContracts,...listFieldContracts,{probe_id:"get-invalid-field",command:"get",flag:"--fields",rejected_value:REJECTED_FIELD,refusal_args:["get","pm-domain","--fields",REJECTED_FIELD],allowed_values:listGetProjectionFields(),suggested_retry_args:["get","pm-domain","--fields","id,title,status"],error_code:"unknown_field_projection"},{probe_id:"list-mutually-exclusive-projection",command:"list",flag:"--projection",rejected_value:"--brief+--full",refusal_args:["list","--brief","--full"],allowed_values:[],suggested_retry_args:["list","--brief"],error_code:"projection_options_mutually_exclusive",allowed_values_required:false},{probe_id:"get-mutually-exclusive-projection",command:"get",flag:"--projection",rejected_value:"--full+--fields",refusal_args:["get","pm-domain","--full","--fields","id"],allowed_values:[],suggested_retry_args:["get","pm-domain","--full"],error_code:"projection_options_mutually_exclusive",allowed_values_required:false},{probe_id:"search-mutually-exclusive-projection",command:"search",flag:"--projection",rejected_value:"--full+--fields",refusal_args:["search","Domain query","--full","--fields","id"],allowed_values:[],suggested_retry_args:["search","Domain query","--full"],error_code:"projection_options_mutually_exclusive",allowed_values_required:false},{probe_id:"package-upgrade-mutually-exclusive-modes",command:"package upgrade",flag:"--cli-only/--packages-only",rejected_value:"--cli-only+--packages-only",refusal_args:["package","upgrade","--cli-only","--packages-only","--dry-run"],allowed_values:[],suggested_retry_args:["package","upgrade","--packages-only","--dry-run"],error_code:"package_upgrade_modes_mutually_exclusive",allowed_values_required:false},{probe_id:"search-invalid-field",command:"search",flag:"--fields",rejected_value:REJECTED_FIELD,refusal_args:["search","Domain query","--fields",REJECTED_FIELD],allowed_values:listSearchProjectionFields(),suggested_retry_args:["search","Domain query","--fields","id,title,status,score"],error_code:"unknown_field_projection"}];return contracts.sort((left,right)=>left.probe_id.localeCompare(right.probe_id))}function renderPmClosedDomainHelp(command,flag){const contract=listCoreClosedDomainContracts().find(candidate=>candidate.command===command&&candidate.flag===flag);if(!contract)return"No stable core values are declared.";const canonicalValues=contract.allowed_values.filter(value=>!value.startsWith("item."));const runtimeSuffix=flag==="--fields"?" item.<field> aliases and configured runtime metadata fields are also accepted.":" Configured package and workspace intents may extend this domain.";return`Allowed core values: ${canonicalValues.join("|")}.${runtimeSuffix}`}export{listCoreClosedDomainContracts,renderPmClosedDomainHelp};
2
2
  //# sourceMappingURL=closed-domain-contracts.js.map