@unbrained/pm-cli 2026.10.28 → 2026.10.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +50 -0
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/commands/lifecycle/append.d.ts +4 -0
- package/dist/cli/commands/lifecycle/append.js +1 -1
- package/dist/cli/commands/lifecycle/create.d.ts +4 -0
- package/dist/cli/commands/lifecycle/create.js +1 -1
- package/dist/cli/commands/lifecycle/plan.d.ts +3 -0
- package/dist/cli/commands/lifecycle/plan.js +1 -1
- package/dist/cli/commands/lifecycle/update-many.d.ts +4 -0
- package/dist/cli/commands/lifecycle/update-many.js +1 -1
- package/dist/cli/commands/lifecycle/update.d.ts +4 -0
- package/dist/cli/commands/lifecycle/update.js +1 -1
- package/dist/cli/error-guidance.d.ts +45 -5
- package/dist/cli/error-guidance.js +5 -3
- package/dist/cli/extension-command-help.d.ts +1 -0
- package/dist/cli/extension-command-help.js +2 -2
- package/dist/cli/help-content.js +2 -2
- package/dist/cli/main.d.ts +1 -5
- package/dist/cli/main.js +5 -5
- package/dist/cli/migration-gates.d.ts +1 -1
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/preflight-warnings.d.ts +11 -0
- package/dist/cli/preflight-warnings.js +4 -0
- package/dist/cli/register-list-query.js +3 -3
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-24J6TNYE.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-YYD5MNAV.js → chunk-2AHSPMKJ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-35Q2B2GJ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-43R7UTWV.js +2 -0
- package/dist/cli-bundle/chunks/chunk-6PSDQ7T7.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-YUBUNECD.js → chunk-BS2KXT24.js} +84 -84
- package/dist/cli-bundle/chunks/{chunk-D3AIQZXF.js → chunk-GMBDZID5.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-HSBTITO4.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-LWW4F4G2.js → chunk-MRUA2Z43.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-P3LNMWL2.js +2 -0
- package/dist/cli-bundle/chunks/chunk-PT7TS6E7.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-TH5KPAN4.js → chunk-SBVX5CMV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D6P6IBPN.js → chunk-TL3O5GZA.js} +45 -45
- package/dist/cli-bundle/chunks/chunk-U7JXZMU5.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-DM3PICGU.js → chunk-V6EWBTNH.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VC7TA67O.js +20 -0
- package/dist/cli-bundle/chunks/chunk-WNF6FOL7.js +31 -0
- package/dist/cli-bundle/chunks/chunk-WRXQAW7Q.js +114 -0
- package/dist/cli-bundle/chunks/{chunk-RZQNFHXO.js → chunk-WX25MU4N.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-XDDPSWIW.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YT5D5HNG.js +2 -0
- package/dist/cli-bundle/chunks/chunk-ZTJVOBDU.js +128 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-LHLE7PSG.js → indexed-receipt-blobs-KGMJVFH2.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-UWV6UNSV.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-GKDKHRTZ.js → mutation-admission-I4RHIT3Q.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-MHJJUM6M.js → register-list-query-MVDL5EXG.js} +6 -6
- package/dist/cli-bundle/chunks/register-mutation-GAF7LXRB.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-JLFRL36Q.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-WUZ2ZSMY.js → register-setup-MZN6ONB3.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-MN3Y7LVX.js → settlement-hook-YWSWFOZY.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-2FYJGGG3.js → stage-2ZORTOF6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4GN2ZPT5.js → chunk-2J7T2UCH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YLVHHWHN.js → chunk-4PW5XWVI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4QPGJO2G.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IQKLJFJE.js → chunk-57HPXGOQ.js} +18 -18
- package/dist/cli-bundle/focused-chunks/chunk-5MCGYBOQ.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-6F6APBCX.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-AFVN2KCP.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ON5WFDCG.js → chunk-DFUTCKUF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-EA65HVBO.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-GP2WU43K.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-C2GLO7HU.js → chunk-HPWT3RBG.js} +54 -54
- package/dist/cli-bundle/focused-chunks/chunk-HSAEEWSI.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7SZPZOIC.js → chunk-JLXGRDTG.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-JNKRUCVZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JTCGDODH.js → chunk-KH5QJXY7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KKRIFBSL.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-TUN4M757.js → chunk-MW77Q3AQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-NOKG4RFN.js +22 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DRN4W3YJ.js → chunk-NRBUMDLF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ML5JIUM6.js → chunk-PC3R5CJV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-PFBQOZPK.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-R3EA3SDW.js → chunk-QFMJGQGO.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-I4X6AKOO.js → chunk-SFQKCA5K.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-WHIE2C6Q.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y6UYRMVG.js +6 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-5H6RMRTK.js → indexed-receipt-blobs-KHWT44EK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-LU75EG7D.js +2 -0
- package/dist/cli-bundle/focused-chunks/{mutation-admission-TM3SVU2O.js → mutation-admission-KDJ7SCPA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-LBVWWSCF.js → settlement-hook-SJV52ZTV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-7ZBRX2Q2.js → stage-R4KEBO37.js} +2 -2
- package/dist/cli-bundle/main.js +26 -22
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +4 -4
- package/dist/cli-bundle/sdk-core.js +1 -43
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +61 -61
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-types.d.ts +4 -0
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/history/operation-contract.d.ts +2 -2
- package/dist/core/history/operation-contract.js +1 -1
- package/dist/core/item/literal-mutation-input.d.ts +12 -0
- package/dist/core/item/literal-mutation-input.js +2 -0
- package/dist/core/item/parse.d.ts +2 -0
- package/dist/core/item/parse.js +2 -2
- package/dist/core/lock/lock.js +4 -4
- package/dist/core/output/output.js +3 -3
- package/dist/core/schema/fields-file.js +1 -1
- package/dist/core/sentry/helpers.d.ts +6 -0
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.d.ts +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/errors.d.ts +6 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/output-unicode.d.ts +10 -0
- package/dist/core/shared/output-unicode.js +2 -0
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/settings-validator.d.ts +1 -0
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.js +1 -1
- package/dist/core/telemetry/policy.d.ts +8 -0
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/runtime.js +3 -3
- package/dist/sdk/agent/command-recovery.d.ts +15 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +28 -0
- package/dist/sdk/cli-contracts/agent-output-contracts.js +2 -2
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/completion/fish.js +4 -4
- package/dist/sdk/completion/zsh.js +3 -3
- package/dist/sdk/config.d.ts +1 -0
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/core.d.ts +1 -0
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/error-runtime.d.ts +9 -0
- package/dist/sdk/error-runtime.js +1 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/index.d.ts +2 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/item-transaction.d.ts +33 -2
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/append.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/cli-input.d.ts +4 -0
- package/dist/sdk/lifecycle/cli-input.js +2 -0
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
- package/dist/sdk/lifecycle/plan.d.ts +2 -3
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/reopen.js +1 -1
- package/dist/sdk/lifecycle/repeated-terminal-state.d.ts +45 -0
- package/dist/sdk/lifecycle/repeated-terminal-state.js +2 -0
- package/dist/sdk/lifecycle/shared-unset-fields.d.ts +9 -0
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/update-many.d.ts +0 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.d.ts +29 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/output/table-rows.d.ts +15 -1
- package/dist/sdk/output/table-rows.js +1 -1
- package/dist/sdk/output.d.ts +1 -0
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/ownership-source.d.ts +18 -0
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/get.d.ts +1 -1
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/history.d.ts +2 -0
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/query/next-ranking-policy.d.ts +35 -0
- package/dist/sdk/query/next-ranking-policy.js +2 -0
- package/dist/sdk/query/next.d.ts +12 -2
- package/dist/sdk/query/next.js +2 -2
- package/dist/sdk/query/projection-contracts.d.ts +4 -0
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/read-output/surfaces.d.ts +27 -0
- package/dist/sdk/read-output/surfaces.js +2 -0
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/runtime/mutation-value-validation.d.ts +16 -0
- package/dist/sdk/runtime/mutation-value-validation.js +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +2 -0
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +14 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/test/execution-receipts.d.ts +25 -0
- package/dist/sdk/test/execution-receipts.js +2 -2
- package/dist/sdk/test/execution.d.ts +5 -0
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.d.ts +54 -0
- package/dist/sdk/workspace-transaction.js +2 -2
- package/dist/types.d.ts +2 -0
- package/dist/types.js +1 -1
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AGENT_OUTPUT_ENCODINGS.md +12 -0
- package/docs/AGENT_UX_CONTRACTS.md +2 -1
- package/docs/COMMANDS.md +73 -15
- package/docs/CONFIGURATION.md +48 -1
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +26 -0
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +24 -2
- package/docs/PACKED_FIRST_RUN.md +2 -1
- package/docs/READ_OUTPUT_CONTRACTS.md +24 -6
- package/docs/SDK.md +207 -11
- package/docs/TESTING.md +46 -2
- package/docs/agent-task-token-baseline.json +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -1
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/extensions/calendar/index.ts +1 -0
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2J7I54MQ.js +0 -2
- package/dist/cli-bundle/chunks/chunk-3KMYHYJV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-4D25HF3V.js +0 -2
- package/dist/cli-bundle/chunks/chunk-7V37RC2L.js +0 -114
- package/dist/cli-bundle/chunks/chunk-AHVN4GHF.js +0 -31
- package/dist/cli-bundle/chunks/chunk-CS7QDSUX.js +0 -128
- package/dist/cli-bundle/chunks/chunk-CXUQEZDX.js +0 -8
- package/dist/cli-bundle/chunks/chunk-DKLEDWVW.js +0 -3
- package/dist/cli-bundle/chunks/chunk-E5QBZ4HI.js +0 -8
- package/dist/cli-bundle/chunks/chunk-JESLOJD7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-PQLRKFPZ.js +0 -20
- package/dist/cli-bundle/chunks/chunk-SGFQQXFD.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XHONSCLJ.js +0 -6
- package/dist/cli-bundle/chunks/chunk-ZX3XMTZG.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-SN425O3R.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-EYUIUGPW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3EHVI673.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-46WLWK73.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-6L4KKRK7.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-6VDRAJYX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-B4ZQJEMT.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-BZSACRVX.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-F6UQJJYB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-L5GX2FGZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LPWZERVD.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-OASYSUOH.js +0 -22
- package/dist/cli-bundle/focused-chunks/chunk-QUPGBO2L.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-Z26ZPQH6.js +0 -3
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
-
`,{createParentDirectories:!parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])})},globalPmRoot)}catch{}}function isSensitiveKey(key){const normalized=key.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),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){return input.replaceAll(INLINE_SENSITIVE_ASSIGNMENT_PATTERN,(_match,key,delimiter)=>`${key}${delimiter}[redacted]`).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,isLower=code>=97&&code<=122,isDigit=code>=48&&code<=57;return isUpper||isLower||isDigit}function isEmailLocalCharacter(character){if(!character)return!1;const code=character.charCodeAt(0);return isAsciiLetterOrDigitCode(code)?!0:character==="."||character==="_"||character==="%"||character==="+"||character==="-"}function isEmailDomainCharacter(character){if(!character)return!1;const code=character.charCodeAt(0);return isAsciiLetterOrDigitCode(code)?!0:character==="."||character==="-"}function looksLikeEmailToken(token){const atIndex=token.indexOf("@");if(atIndex<=0||atIndex!==token.lastIndexOf("@")||atIndex===token.length-1)return!1;const localPart=token.slice(0,atIndex),domainPart=token.slice(atIndex+1),lastDot=domainPart.lastIndexOf(".");if(lastDot<=0||lastDot===domainPart.length-1||domainPart.length-(lastDot+1)<2)return!1;for(const character of localPart)if(!isEmailLocalCharacter(character))return!1;for(const character of domainPart)if(!isEmailDomainCharacter(character))return!1;return!0}function redactEmailTokens(input){let redacted="",cursor=0;for(;cursor<input.length;){const atIndex=input.indexOf("@",cursor);if(atIndex<0){redacted+=input.slice(cursor);break}let start=atIndex-1;for(;start>=cursor&&isEmailLocalCharacter(input[start]);)start-=1;start+=1;let end=atIndex+1;for(;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){return redactEmailTokens(input).replaceAll(BEARER_TOKEN_PATTERN,"bearer [redacted_token]").replaceAll(PRIVATE_IP_PATTERN,"[redacted_ip]")}function sanitizeStringRedacted(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input),withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens),withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets),trimmed=withoutAbsolutePaths.trim();return trimmed.startsWith("/")&&trimmed.length>1?"[redacted_path]":withoutAbsolutePaths.length>512?`${withoutAbsolutePaths.slice(0,509)}...`:withoutAbsolutePaths}function sanitizeStringMax(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input),withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens),withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets),trimmed=withoutAbsolutePaths.trim();return trimmed.startsWith("/")&&trimmed.length>1?"[redacted_path]":withoutAbsolutePaths.length>2048?`${withoutAbsolutePaths.slice(0,2045)}...`:withoutAbsolutePaths}function sanitizeString(input,captureLevel="redacted"){return captureLevel==="max"?sanitizeStringMax(input):sanitizeStringRedacted(input)}function sanitizeValue(value,keyHint,captureLevel="redacted",depth=0){if(keyHint&&isSensitiveKey(keyHint))return"[redacted]";if(value==null)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,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=!1;for(const rawArg of args){const arg=sanitizeString(rawArg,captureLevel);if(nextIsSensitiveValue){sanitized.push("[redacted]"),nextIsSensitiveValue=!1;continue}if(arg.startsWith("--")){const withoutPrefix=arg.slice(2),delimiterIndex=withoutPrefix.indexOf("=");if(delimiterIndex>=0){const key=withoutPrefix.slice(0,delimiterIndex),value=withoutPrefix.slice(delimiterIndex+1);isSensitiveKey(key)?sanitized.push(`--${key}=[redacted]`):sanitized.push(`--${key}=${sanitizeString(value,captureLevel)}`);continue}if(isSensitiveKey(withoutPrefix)){sanitized.push(`--${withoutPrefix}`),nextIsSensitiveValue=!0;continue}}sanitized.push(arg)}return sanitized}function normalizeCaptureLevel(value){const normalized=value?.trim().toLowerCase();return normalized==="minimal"||normalized==="redacted"||normalized==="max"?normalized:"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);return Number.isFinite(configured)?Math.min(TELEMETRY_HTTP_TIMEOUT_MAX_MS,Math.max(TELEMETRY_HTTP_TIMEOUT_MIN_MS,Math.trunc(configured))):TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}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{return(await Promise.race([globalThis.fetch(endpoint,{method:"POST",headers,body,signal:controller.signal}),deadline])).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(),requestOptions={method:"POST",headers:{...headers,"content-length":Buffer.byteLength(body)},signal:AbortSignal.timeout(timeoutMs),autoSelectFamilyAttemptTimeout:Math.min(5e3,timeoutMs)},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){return Number.isFinite(exitCode)?Math.max(0,Math.trunc(exitCode)):ok?0:1}function normalizeTelemetryErrorCategory(params){if(!params.ok)return typeof params.errorCategory=="string"&¶ms.errorCategory.trim().length>0?params.errorCategory:typeof params.errorCode=="string"&¶ms.errorCode.trim().length>0?resolveTelemetryErrorCategory(params.errorCode):"unknown"}function resolveTelemetrySourceContext(globalOptions){const
|
|
3
|
-
`)),{source_context:inferTelemetrySourceContext(globalOptions),source_context_source:source}}function inferTelemetrySourceContext(globalOptions){if(isTelemetryTestEnvironment())return"test";const nonTty=process.stdin.isTTY!==!0||process.stdout.isTTY!==!0,ci=parseBooleanTrueLike(process.env.CI),scriptLikeMode=globalOptions.json===!0||globalOptions.quiet===!0;return nonTty||ci||scriptLikeMode?"automation":"user"}function hashWithInstallationId(installationId,value){return crypto.createHash("sha256").update(`${installationId}:${value}`).digest("hex")}function buildAuthorContextPayloadFields(captureLevel,installationId){const author=(readAuthorEnvironment()??"").trim(),agent=detectAgentIdentity({env:process.env,argv:process.argv}),hasAgentContext=agent.harness!==void 0||agent.model!==void 0;return captureLevel==="minimal"?{has_author_context:author.length>0,has_agent_context:hasAgentContext}:{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||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,normalized={},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"),normalizedCode=typeof errorCode2=="string"&&errorCode2.length>0?errorCode2:"unknown_error",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),normalizedPath=url.pathname.replace(/\/+$/,"");return normalizedPath.endsWith("/v1/traces")||(url.pathname=`${normalizedPath.length===0?"":normalizedPath}/v1/traces`),url.toString()}catch{return null}}function isoToUnixNano(iso){const parsedMs=Date.parse(iso),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()),serviceName=serviceNameCandidate.length>0?serviceNameCandidate:"pm-cli",normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok),normalizedErrorCode=normalizeTelemetryErrorCode(outcome.error_code),normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category}),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))];typeof normalizedErrorCode=="string"&&attributes.push(otlpStringAttribute("pm.error_code",normalizedErrorCode)),typeof normalizedErrorCategory=="string"&&attributes.push(otlpStringAttribute("pm.error_category",normalizedErrorCategory)),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)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,keys=Object.keys(record).filter(key=>key!=="tests").sort((left,right)=>left.localeCompare(right)),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,commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command),hashedArgs=hashCommandArgs(installationId,context.args),commandInvocationDigest=hashWithInstallationId(installationId,`${context.command}\0${context.args.join("\0")}`),commandOptionsDigest=hashTelemetryValue(installationId,context.options),globalOptionsDigest=hashTelemetryValue(installationId,context.global),authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);return captureLevel==="minimal"?{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}:{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===!0,stdout_tty:process.stdout.isTTY===!0}}}function buildCommandFinishPayload(params){const{captureLevel,pmVersion,sourceContext,outcome,durationMs,startedAt,command,installationId,commandTaxonomy,exitCode,errorCode:errorCode2,errorCategory,commandResolution,resolutionStage}=params,errorFingerprint=outcome.ok===!1?hashTelemetryErrorFingerprint(installationId,command,errorCode2,outcome.error):void 0,authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);return captureLevel==="minimal"?{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}:{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,attemptedArgHashes=hashCommandArgs(installationId,args),attemptedCommandDigest=hashWithInstallationId(installationId,command),attemptedOptionsDigest=hashTelemetryValue(installationId,options),errorFingerprint=hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage),authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);return captureLevel==="minimal"?{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}:{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===!0,stdout_tty:process.stdout.isTTY===!0}}}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){let serialized=JSON.stringify({client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event,attempts:0});if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){const trimmed={...event,payload:{...event.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:serialized.length}}};serialized=JSON.stringify({client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event:trimmed,attempts:0})}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(`
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4b15f41e-4b2a-511a-b2a1-c1c3e3d909c5")}catch{}})();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,isTelemetryTestEnvironment,resolveTelemetryEnvironmentPolicy,resolveTelemetrySourceAttribution}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,runWithConfigurationOnlySettings,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"),TELEMETRY_STATE_RELATIVE_PATH=path.join("runtime","telemetry","state.json"),TELEMETRY_OTEL_SPANS_RELATIVE_PATH=path.join("runtime","telemetry","otel-spans.jsonl"),TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE=8,TELEMETRY_OTEL_SPANS_MAX_PENDING=500,TELEMETRY_SCHEMA_VERSION=1,TELEMETRY_CLIENT_SCHEMA_VERSION=1,TELEMETRY_FLUSH_BATCH_SIZE=100,TELEMETRY_MAX_RETRY_DELAY_MS=36e5,TELEMETRY_RETRY_BASE_DELAY_MS=3e4,TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS=2e4,TELEMETRY_HTTP_TIMEOUT_MIN_MS=1e3,TELEMETRY_HTTP_TIMEOUT_MAX_MS=25e3,TELEMETRY_FOREGROUND_LOCK_WAIT_MS=250,MILLISECONDS_PER_DAY=864e5,TELEMETRY_MAX_EVENT_BYTES=65536,TELEMETRY_SANITIZE_MAX_DEPTH=6,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS=20,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS=15,TELEMETRY_RESULT_PREVIEW_MAX_BYTES=8192,TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS=[25,50,100,200],TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS=3600*1e3,TELEMETRY_FLUSH_LOCK_STALE_MS=6e4,TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS=6e4,OTEL_TRACES_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",OTEL_BASE_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_ENDPOINT",OTEL_SERVICE_NAME_ENV="OTEL_SERVICE_NAME",PM_TELEMETRY_OTEL_DISABLED_ENV="PM_TELEMETRY_OTEL_DISABLED",PM_TELEMETRY_OTEL_DISABLED_VALUES=new Set(["1","true","yes","on"]),PM_TELEMETRY_INLINE_FLUSH_ENV="PM_TELEMETRY_INLINE_FLUSH",PM_TELEMETRY_FLUSH_CHILD_ENV="PM_TELEMETRY_FLUSH_CHILD",PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV="PM_TELEMETRY_HTTP_TIMEOUT_MS",NATIVE_FETCH=globalThis.fetch;import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES as PM_TELEMETRY_SOURCE_CONTEXT_VALUES2}from"./policy.js";let sourceContextWarningEmitted=!1,_lastFlushPromise=Promise.resolve(),_queueMutationPromise=Promise.resolve();const deferredReadStarts=new WeakMap;async function waitForPendingFlush(){await _lastFlushPromise,await _queueMutationPromise}const BOOLEAN_TRUE_VALUES=new Set(["1","true","yes","on"]),TELEMETRY_HARNESSES=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]),PROCESS_SESSION_ID=crypto.randomUUID(),SENSITIVE_KEYWORDS=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],REDACTION_INPUT_KEYS=new Set(["literal","literals","regex","regexes","replacement","replacements","setjson","set_json","update"]),SENSITIVE_INLINE_KEY_PATTERN="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",INLINE_SENSITIVE_ASSIGNMENT_PATTERN=new RegExp(`\\b(${SENSITIVE_INLINE_KEY_PATTERN})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),INLINE_SENSITIVE_FLAG_PATTERN=new RegExp(`(--${SENSITIVE_INLINE_KEY_PATTERN})(=|\\s+)([^\\s,;]+)`,"giu"),ABSOLUTE_PATH_TOKEN_PATTERN=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,BEARER_TOKEN_PATTERN=/bearer\s+[a-z0-9._=-]+/giu,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(){return parseBooleanTrueLike(process.env[PM_TELEMETRY_INLINE_FLUSH_ENV])||parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])?!0:isTelemetryTestEnvironment()}async function readRuntimeState(globalPmRoot){const raw=await readFileIfExists(runtimeStatePath(globalPmRoot));if(!raw||raw.trim().length===0)return{};try{const parsed=JSON.parse(raw);return typeof parsed!="object"||parsed===null||Array.isArray(parsed)?{}:parsed}catch{return{}}}async function writeRuntimeState(globalPmRoot,patch){try{await withQueueMutation(async()=>{const next={...await readRuntimeState(globalPmRoot),...patch},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
|
+
`,{createParentDirectories:!parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])})},globalPmRoot)}catch{}}function isSensitiveKey(key){const normalized=key.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),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){return input.replaceAll(INLINE_SENSITIVE_ASSIGNMENT_PATTERN,(_match,key,delimiter)=>`${key}${delimiter}[redacted]`).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,isLower=code>=97&&code<=122,isDigit=code>=48&&code<=57;return isUpper||isLower||isDigit}function isEmailLocalCharacter(character){if(!character)return!1;const code=character.charCodeAt(0);return isAsciiLetterOrDigitCode(code)?!0:character==="."||character==="_"||character==="%"||character==="+"||character==="-"}function isEmailDomainCharacter(character){if(!character)return!1;const code=character.charCodeAt(0);return isAsciiLetterOrDigitCode(code)?!0:character==="."||character==="-"}function looksLikeEmailToken(token){const atIndex=token.indexOf("@");if(atIndex<=0||atIndex!==token.lastIndexOf("@")||atIndex===token.length-1)return!1;const localPart=token.slice(0,atIndex),domainPart=token.slice(atIndex+1),lastDot=domainPart.lastIndexOf(".");if(lastDot<=0||lastDot===domainPart.length-1||domainPart.length-(lastDot+1)<2)return!1;for(const character of localPart)if(!isEmailLocalCharacter(character))return!1;for(const character of domainPart)if(!isEmailDomainCharacter(character))return!1;return!0}function redactEmailTokens(input){let redacted="",cursor=0;for(;cursor<input.length;){const atIndex=input.indexOf("@",cursor);if(atIndex<0){redacted+=input.slice(cursor);break}let start=atIndex-1;for(;start>=cursor&&isEmailLocalCharacter(input[start]);)start-=1;start+=1;let end=atIndex+1;for(;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){return redactEmailTokens(input).replaceAll(BEARER_TOKEN_PATTERN,"bearer [redacted_token]").replaceAll(PRIVATE_IP_PATTERN,"[redacted_ip]")}function sanitizeStringRedacted(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input),withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens),withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets),trimmed=withoutAbsolutePaths.trim();return trimmed.startsWith("/")&&trimmed.length>1?"[redacted_path]":withoutAbsolutePaths.length>512?`${withoutAbsolutePaths.slice(0,509)}...`:withoutAbsolutePaths}function sanitizeStringMax(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input),withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens),withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets),trimmed=withoutAbsolutePaths.trim();return trimmed.startsWith("/")&&trimmed.length>1?"[redacted_path]":withoutAbsolutePaths.length>2048?`${withoutAbsolutePaths.slice(0,2045)}...`:withoutAbsolutePaths}function sanitizeString(input,captureLevel="redacted"){return captureLevel==="max"?sanitizeStringMax(input):sanitizeStringRedacted(input)}function sanitizeValue(value,keyHint,captureLevel="redacted",depth=0){if(keyHint&&isSensitiveKey(keyHint))return"[redacted]";if(value==null)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,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=!1;for(const rawArg of args){const arg=sanitizeString(rawArg,captureLevel);if(nextIsSensitiveValue){sanitized.push("[redacted]"),nextIsSensitiveValue=!1;continue}if(arg.startsWith("--")){const withoutPrefix=arg.slice(2),delimiterIndex=withoutPrefix.indexOf("=");if(delimiterIndex>=0){const key=withoutPrefix.slice(0,delimiterIndex),value=withoutPrefix.slice(delimiterIndex+1);isSensitiveKey(key)?sanitized.push(`--${key}=[redacted]`):sanitized.push(`--${key}=${sanitizeString(value,captureLevel)}`);continue}if(isSensitiveKey(withoutPrefix)){sanitized.push(`--${withoutPrefix}`),nextIsSensitiveValue=!0;continue}}sanitized.push(arg)}return sanitized}function normalizeCaptureLevel(value){const normalized=value?.trim().toLowerCase();return normalized==="minimal"||normalized==="redacted"||normalized==="max"?normalized:"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);return Number.isFinite(configured)?Math.min(TELEMETRY_HTTP_TIMEOUT_MAX_MS,Math.max(TELEMETRY_HTTP_TIMEOUT_MIN_MS,Math.trunc(configured))):TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}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{return(await Promise.race([globalThis.fetch(endpoint,{method:"POST",headers,body,signal:controller.signal}),deadline])).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(),requestOptions={method:"POST",headers:{...headers,"content-length":Buffer.byteLength(body)},signal:AbortSignal.timeout(timeoutMs),autoSelectFamilyAttemptTimeout:Math.min(5e3,timeoutMs)},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){return Number.isFinite(exitCode)?Math.max(0,Math.trunc(exitCode)):ok?0:1}function normalizeTelemetryErrorCategory(params){if(!params.ok)return typeof params.errorCategory=="string"&¶ms.errorCategory.trim().length>0?params.errorCategory:typeof params.errorCode=="string"&¶ms.errorCode.trim().length>0?resolveTelemetryErrorCategory(params.errorCode):"unknown"}function resolveTelemetrySourceContext(globalOptions){const resolved=resolveTelemetrySourceAttribution(globalOptions);return resolved.source_context_source==="env_override_rejected"&&!sourceContextWarningEmitted&&!globalOptions.quiet&&(sourceContextWarningEmitted=!0,process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${PM_TELEMETRY_SOURCE_CONTEXT_VALUES.join("|")}; ignoring override.
|
|
3
|
+
`)),resolved}function hashWithInstallationId(installationId,value){return crypto.createHash("sha256").update(`${installationId}:${value}`).digest("hex")}function buildAuthorContextPayloadFields(captureLevel,installationId){const author=(readAuthorEnvironment()??"").trim(),agent=detectAgentIdentity({env:process.env,argv:process.argv}),hasAgentContext=agent.harness!==void 0||agent.model!==void 0;return captureLevel==="minimal"?{has_author_context:author.length>0,has_agent_context:hasAgentContext}:{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||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,normalized={},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"),normalizedCode=typeof errorCode2=="string"&&errorCode2.length>0?errorCode2:"unknown_error",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),normalizedPath=url.pathname.replace(/\/+$/,"");return normalizedPath.endsWith("/v1/traces")||(url.pathname=`${normalizedPath.length===0?"":normalizedPath}/v1/traces`),url.toString()}catch{return null}}function isoToUnixNano(iso){const parsedMs=Date.parse(iso),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()),serviceName=serviceNameCandidate.length>0?serviceNameCandidate:"pm-cli",normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok),normalizedErrorCode=normalizeTelemetryErrorCode(outcome.error_code),normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category}),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))];typeof normalizedErrorCode=="string"&&attributes.push(otlpStringAttribute("pm.error_code",normalizedErrorCode)),typeof normalizedErrorCategory=="string"&&attributes.push(otlpStringAttribute("pm.error_category",normalizedErrorCategory)),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)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,keys=Object.keys(record).filter(key=>key!=="tests").sort((left,right)=>left.localeCompare(right)),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,commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command),hashedArgs=hashCommandArgs(installationId,context.args),commandInvocationDigest=hashWithInstallationId(installationId,`${context.command}\0${context.args.join("\0")}`),commandOptionsDigest=hashTelemetryValue(installationId,context.options),globalOptionsDigest=hashTelemetryValue(installationId,context.global),authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);return captureLevel==="minimal"?{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}:{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===!0,stdout_tty:process.stdout.isTTY===!0}}}function buildCommandFinishPayload(params){const{captureLevel,pmVersion,sourceContext,outcome,durationMs,startedAt,command,installationId,commandTaxonomy,exitCode,errorCode:errorCode2,errorCategory,commandResolution,resolutionStage}=params,errorFingerprint=outcome.ok===!1?hashTelemetryErrorFingerprint(installationId,command,errorCode2,outcome.error):void 0,authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);return captureLevel==="minimal"?{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}:{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,attemptedArgHashes=hashCommandArgs(installationId,args),attemptedCommandDigest=hashWithInstallationId(installationId,command),attemptedOptionsDigest=hashTelemetryValue(installationId,options),errorFingerprint=hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage),authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);return captureLevel==="minimal"?{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}:{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===!0,stdout_tty:process.stdout.isTTY===!0}}}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){let serialized=JSON.stringify({client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event,attempts:0});if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){const trimmed={...event,payload:{...event.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:serialized.length}}};serialized=JSON.stringify({client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event:trimmed,attempts:0})}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(`
|
|
4
4
|
`)){const trimmed=line.trim();if(trimmed.length!==0)try{const parsed=JSON.parse(trimmed);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!0;const dueAtMs=Date.parse(nextAttemptAfter);return Number.isNaN(dueAtMs)?!0: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!1;const occurredAtMs=Date.parse(occurredAt);return Number.isNaN(occurredAtMs)?!1:occurredAtMs<cutoffMs}function pruneExpiredQueueEntries(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays),retained=[];let prunedCount=0;for(const entry of entries){if(JSON.stringify(entry).length>TELEMETRY_MAX_EVENT_BYTES||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(`
|
|
5
5
|
`),contents=serialized.length>0?`${serialized}
|
|
6
6
|
`:"";for(let attempt=0;;attempt+=1)try{await writeFileAtomic(queuePath(globalPmRoot),contents,{createParentDirectories:!parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])});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!1;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},serialized=JSON.stringify(pending);serialized.length>TELEMETRY_MAX_EVENT_BYTES||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(`
|
|
@@ -4,6 +4,21 @@ export declare function resolveLifecycleVerbRecovery(verb:string,availablePaths:
|
|
|
4
4
|
examples:string[][];
|
|
5
5
|
nextSteps:string[];
|
|
6
6
|
} | undefined;
|
|
7
|
+
/** Completeness controls one read command declares, derived from its read-output surface and flag contracts. */
|
|
8
|
+
export interface ReadCompletenessControls {
|
|
9
|
+
/** Canonical read-output surface. */
|
|
10
|
+
command:string;
|
|
11
|
+
/** Projection modes the command spells as boolean `--<mode>` flags. */
|
|
12
|
+
modes:string[];
|
|
13
|
+
/** Closed `--depth` value domain, empty when the command declares no detail depth. */
|
|
14
|
+
depth_values:string[];
|
|
15
|
+
/** Every declared flag spelling, used to refuse corrections for options the command already accepts. */
|
|
16
|
+
declared_flags:string[];
|
|
17
|
+
}
|
|
18
|
+
/** Resolve the completeness spellings a read command accepts, so recovery never guesses from another command's vocabulary. */
|
|
19
|
+
export declare function resolveReadCompletenessControls(commandName:string):ReadCompletenessControls | undefined;
|
|
20
|
+
/** Render one command's completeness controls as the flags an agent can type on that same command. */
|
|
21
|
+
export declare function describeReadCompletenessControls(controls:ReadCompletenessControls):string;
|
|
7
22
|
/** Derive a same-command read retry for known completeness and encoding mistakes without discarding intent. */
|
|
8
23
|
export declare function resolveReadOptionRetryArgs(commandName:string,invocationArgv:readonly string[],unknownOption:string):string[] | undefined;
|
|
9
24
|
/** Identify presentation intent that must not be silently dropped from an unknown-option retry. */
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="682c27fa-94d8-529b-92fc-ac8a2eb7e138")}catch{}})();import{renderPmCommand}from"../command-line.js";import{resolveLinkedResourcePositionalRecovery}from"./linked-resource-recovery.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";import{findBootstrapCommandTokenIndex,parseBootstrapCommandName}from"../cli-contracts/bootstrap-command-scanner.js";import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS}from"../read-output/options.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";import{readOutputIncludeModeOptionsForSurface,resolveNativeReadOutputSurface}from"../read-output/surfaces.js";const READ_PROJECTION_FLAGS=new Set([...Object.values(READ_OUTPUT_DIMENSION_FLAGS),...READ_OUTPUT_COMPOSITION_FLAGS,"--full","--brief","--compact","--summary","--fields","--section","--token-budget"]),MUTATION_RECEIPT_FLAGS=new Set(["--full-changed-fields","--no-changed-fields","--id-only"]);function resolveLifecycleVerbRecovery(verb,availablePaths){if(!["block","unblock"].includes(verb)||availablePaths.includes(verb)||!availablePaths.includes("update"))return;const flags=new Set(resolveSubcommandFlagContractsForCommand("update").map(entry=>entry.flag));if((verb==="block"?["--blocked-by","--blocked-reason"]:["--unset","--unblock-note"]).every(flag=>flags.has(flag)))return verb==="block"?{examples:[["update","<item-id>","--blocked-by","<blocker-id>","--blocked-reason","<reason>"]],nextSteps:["Choose the actual item and blocker identifiers before running update. --blocked-by records the blocker field and its blocked_by relationship."]}:{examples:[["update","<item-id>","--unset","blocked-by","--unset","blocked-reason","--unblock-note","<note>"]],nextSteps:["Inspect the item's blockers before running update. --unset blocked-by removes the blocker field and all blocked_by relationships; --unset blocked-reason clears the stale reason. --unblock-note alone records a note and does not unblock the item.","If your project also uses a blocked lifecycle status, choose its appropriate next status separately with update --status."]}}function activitySinceCorrection(token,next){const inline=token.includes("="),value=inline?token.slice(token.indexOf("=")+1):next;if(!(!value||value.startsWith("--")))return{consumed:inline?1:2,replacement:["--from",value],conflicts:["--from"]}}const COMPLETENESS_CONFLICT_FLAGS=["--depth","--output-include","--fields","--section","--for"];function resolveReadCompletenessControls(commandName){const surface=resolveNativeReadOutputSurface(resolvePmCommandOperation(commandName.trim().toLowerCase()));if(surface===void 0)return;const flags=resolveSubcommandFlagContractsForCommand(surface),declared=flags.flatMap(entry=>[entry.flag,...entry.aliases??[]]),modes=[...readOutputIncludeModeOptionsForSurface(surface).keys()].filter(mode=>declared.includes(`--${mode}`)),depthValues=[...flags.find(entry=>entry.flag==="--depth")?.values??[]];if(!(modes.length===0&&depthValues.length===0))return{command:surface,modes,depth_values:depthValues,declared_flags:declared}}function describeReadCompletenessControls(controls){return[...controls.depth_values.length>0?[`--depth ${controls.depth_values.join("|")}`]:[],...controls.modes.map(mode=>`--${mode}`)].join(", ")}function completenessCorrection(command,flag,token,next){const controls=resolveReadCompletenessControls(command);if(controls===void 0||controls.declared_flags.includes(flag))return;const conflicts=[...COMPLETENESS_CONFLICT_FLAGS,...controls.modes.map(mode=>`--${mode}`)].filter(entry=>entry!==flag);if(flag==="--depth"){const inline=token.includes("="),value=(inline?token.slice(token.indexOf("=")+1):next)?.trim().toLowerCase();if(!value)return;const consumed=inline?1:2;return controls.modes.includes(value)?{consumed,replacement:[`--${value}`],conflicts}:value==="standard"?{consumed,replacement:[],conflicts}:void 0}const level=flag.slice(2);return token===flag&&controls.depth_values.includes(level)?{consumed:1,replacement:["--depth",level],conflicts}:void 0}function readOptionCorrection(command,flag,token,next){return flag==="--since"&&command==="activity"?activitySinceCorrection(token,next):flag==="--toon"&&token===flag?{consumed:1,replacement:["--output-format","toon"],conflicts:["--json","--format","--output-format","--stream"]}:completenessCorrection(command,flag,token,next)}function resolveInvokedCommand(argv){const index=findBootstrapCommandTokenIndex(argv);if(index===void 0)return;const root=argv[index].trim().toLowerCase(),path=`${root} ${argv[index+1]?.trim().toLowerCase()??""}`,namespaced=resolvePmCommandOperation(path);return namespaced!==path.trim()?namespaced:root==="ctx"?"context":resolvePmCommandOperation(root)}function resolveReadOptionRetryArgs(commandName,invocationArgv,unknownOption){const command=commandName==="ctx"?"context":resolvePmCommandOperation(commandName);if(resolveNativeReadOutputSurface(command)===void 0||invocationArgv.includes("--")||resolveInvokedCommand(invocationArgv)!==command)return;const flag=unknownOption.split("=",1)[0],indices=invocationArgv.flatMap((token,index2)=>token===flag||token.startsWith(`${flag}=`)?[index2]:[]);if(indices.length!==1)return;const index=indices[0],correction=readOptionCorrection(command,flag,invocationArgv[index],invocationArgv[index+1]);if(!correction)return;const{replacement,consumed,conflicts}=correction;if(!invocationArgv.some(argument=>conflicts.includes(argument.split("=",1)[0])))return[...invocationArgv.slice(0,index),...replacement,...invocationArgv.slice(index+consumed)]}function isReadProjectionRecoveryFlag(flag){const normalized=flag.split("=",1)[0].replaceAll("_","-");return READ_PROJECTION_FLAGS.has(normalized)||normalized.length>=5&&[...READ_PROJECTION_FLAGS].some(candidate=>candidate.startsWith(normalized))}function isCompatibleRecoveryFlag(requested,candidate){const unknownFlag=requested.split("=",1)[0].replaceAll("_","-");return isReadProjectionRecoveryFlag(unknownFlag)?!MUTATION_RECEIPT_FLAGS.has(candidate):MUTATION_RECEIPT_FLAGS.has(unknownFlag)?!isReadProjectionRecoveryFlag(candidate):!0}function normalizeMissingFlag(label){return label.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function resolveRecoveryCommandName(invocationArgv){if(!(!Array.isArray(invocationArgv)||invocationArgv.length===0))return parseBootstrapCommandName(invocationArgv)}function resolveMissingOptionPlaceholder(commandName,missingLabel){const flag=normalizeMissingFlag(missingLabel);if(!flag)return;const contract=resolveSubcommandFlagContractsForCommand(commandName).find(entry=>entry.flag===flag||entry.aliases?.includes(flag));return contract?contract.value_type==="boolean"?null:`<${contract.value_name??"value"}>`:"<value>"}function renderMissingOptionRetry(invocationArgv,commandName,missingLabels){const retry=[...invocationArgv],terminatorIndex=retry.indexOf("--");let insertionIndex=terminatorIndex<0?retry.length:terminatorIndex;for(const label of missingLabels){const flag=normalizeMissingFlag(label);if(!flag||retry.slice(0,insertionIndex).some(token=>token===flag||token.startsWith(`${flag}=`)))continue;const placeholder=resolveMissingOptionPlaceholder(commandName,flag),recoveredOption=placeholder?[flag,placeholder]:[flag];retry.splice(insertionIndex,0,...recoveredOption),insertionIndex+=recoveredOption.length}return retry.length===invocationArgv.length?void 0:renderPmCommand(retry)}export{describeReadCompletenessControls,isCompatibleRecoveryFlag,isReadProjectionRecoveryFlag,renderMissingOptionRetry,resolveLifecycleVerbRecovery,resolveLinkedResourcePositionalRecovery,resolveMissingOptionPlaceholder,resolveReadCompletenessControls,resolveReadOptionRetryArgs,resolveRecoveryCommandName};
|
|
2
2
|
//# sourceMappingURL=command-recovery.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f05cec18-5e48-5151-8ada-577c9df5885d")}catch{}})();import{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias}from"./cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand}from"./cli-contracts/flag-contracts.js";import{levenshteinDistanceWithinLimit}from"../core/shared/levenshtein.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{findPmNamespacedCommand,resolvePmCommandOperation}from"./cli-contracts/command-aliases.js";import{normalizeItemAddressInvocation}from"./agent/item-addressing.js";import{BOOTSTRAP_BOOLEAN_FLAGS,GLOBAL_VALUE_CONSUMING_FLAGS,consumesBootstrapValue,findBootstrapCommandTokenIndex as findContractBootstrapCommandTokenIndex,isInlineGlobalValueToken,parseBootstrapCommandName as parseContractBootstrapCommandName}from"./cli-contracts/bootstrap-command-scanner.js";const OUTPUT_VALUE_FLAGS=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]),BOOTSTRAP_OUTPUT_ENCODINGS=new Set(["toon","json"]);function consumeBootstrapGlobalToken(argv,index,state){const token=argv[index];if(BOOTSTRAP_BOOLEAN_FLAGS.has(token))return state.booleanFlags.add(token),1;const equalsIndex=token.indexOf("="),canonicalFlag=equalsIndex>0?token.slice(0,equalsIndex):token;if(!GLOBAL_VALUE_CONSUMING_FLAGS.has(canonicalFlag))return 1;const inlineValue=equalsIndex>0?token.slice(equalsIndex+1):void 0,consumesValue=inlineValue===void 0&&consumesBootstrapValue(canonicalFlag,argv[index+1]),value=inlineValue??(consumesValue?argv[index+1]:void 0);return canonicalFlag==="--author"?state.author=value??"":typeof value=="string"&&value.length>0&&(OUTPUT_VALUE_FLAGS.has(canonicalFlag)?state.outputValues:state.pathValues).set(canonicalFlag,value),consumesValue?2:1}function parseBootstrapGlobalOptions(argv){const state={booleanFlags:new Set,outputValues:new Map,pathValues:new Map};let index=0;for(;index<argv.length&&argv[index]!=="--";)index+=consumeBootstrapGlobalToken(argv,index,state);return{path:state.pathValues.get("--pm-path")??state.pathValues.get("--path"),noExtensions:state.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(parseBootstrapCommandPathName(argv)??""),noPager:state.booleanFlags.has("--no-pager"),json:state.booleanFlags.has("--json")?state.outputValues.get("--output-format")!=="toon":state.outputValues.get("--output-format")==="json",quiet:state.booleanFlags.has("--quiet"),lean:state.booleanFlags.has("--lean"),tokenAccounting:state.booleanFlags.has("--token-accounting"),...state.booleanFlags.has("--output-row-contract")?{outputRowContract:!0}:{},...state.outputValues.get("--output-include")===void 0?{}:{outputInclude:state.outputValues.get("--output-include")},...state.outputValues.get("--output-limit")===void 0?{}:{outputLimit:state.outputValues.get("--output-limit")},...state.outputValues.get("--output-budget")===void 0?{}:{outputBudget:state.outputValues.get("--output-budget")},...BOOTSTRAP_OUTPUT_ENCODINGS.has(state.outputValues.get("--output-format"))?{outputFormat:state.outputValues.get("--output-format")}:{},...state.outputValues.get("--output-session")===void 0?{}:{outputSession:state.outputValues.get("--output-session")},...state.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:state.outputValues.get("--output-cursor")},...state.author===""?{authorMissingValue:!0}:state.author!==void 0?{author:state.author}:{}}}function stripGlobalBootstrapTokens(argv){const remaining=[];let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--")break;if(BOOTSTRAP_BOOLEAN_FLAGS.has(token)||token==="--profile"||token==="--id-only"||token==="--full-changed-fields"||token==="--explain"){index+=1;continue}if(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)){index+=consumesBootstrapValue(token,argv[index+1])?2:1;continue}if(isInlineGlobalValueToken(token)){index+=1;continue}remaining.push(token),index+=1}return remaining}function parseBootstrapHelpRequest(argv){const stripped=stripGlobalBootstrapTokens(argv);if(stripped[0]?.trim().toLowerCase()==="help"){const commandPathTokens2=[];for(let index=1;index<stripped.length;index+=1){const token=stripped[index];if(token.startsWith("-"))break;commandPathTokens2.push(token.trim().toLowerCase())}return{requested:!0,commandPathTokens:commandPathTokens2}}if(stripped.findIndex(token=>token==="--help"||token==="-h")<0)return{requested:!1,commandPathTokens:[]};const commandPathTokens=[];for(const token of stripped){if(token.startsWith("-"))break;commandPathTokens.push(token.trim().toLowerCase())}return{requested:!0,commandPathTokens}}function findBootstrapCommandTokenIndex(argv){return findContractBootstrapCommandTokenIndex(argv)}function parseBootstrapCommandName(argv){return parseContractBootstrapCommandName(argv)}function shouldDisablePagerForInvocation(argv,bootstrapGlobal){return bootstrapGlobal.noPager?!0:process.stdout.isTTY===!0?!1:parseBootstrapHelpRequest(argv).requested}function applyBootstrapPagerPolicy(argv){const pagerEnvironmentKeys=["PAGER","MANPAGER","GIT_PAGER","LESS"],previousValues=pagerEnvironmentKeys.map(key=>process.env[key]),restore=()=>{for(const[index,key]of pagerEnvironmentKeys.entries()){const value=previousValues[index];value===void 0?delete process.env[key]:process.env[key]=value}},bootstrapGlobal=parseBootstrapGlobalOptions(argv);return shouldDisablePagerForInvocation(argv,bootstrapGlobal)&&(process.env.PAGER="cat",process.env.MANPAGER="cat",process.env.GIT_PAGER="cat",(typeof process.env.LESS!="string"||process.env.LESS.trim().length===0)&&(process.env.LESS="FRX")),restore}const EXTENSION_ACTION_SYNTAX_TOKENS=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function normalizeLegacyExtensionActionSyntax(argv){const extensionIndex=findBootstrapCommandTokenIndex(argv);if(extensionIndex===void 0||argv[extensionIndex]!=="extension")return[...argv];const actionToken=argv[extensionIndex+1];if(!actionToken||actionToken.startsWith("-"))return[...argv];if(!EXTENSION_ACTION_SYNTAX_TOKENS.has(actionToken))return[...argv];if(argv.includes("--help")||argv.includes("-h"))return[...argv];const forcedActionFlag=`--${actionToken}`;return argv.includes(forcedActionFlag)?[...argv]:[...argv.slice(0,extensionIndex+1),forcedActionFlag,...argv.slice(extensionIndex+2)]}const CLI_EXECUTABLE_ALIASES=new Set(["pm","pm-cli"]);function stripLeadingExecutableAlias(argv,trace){const index=findBootstrapCommandTokenIndex(argv);if(index===void 0)return argv;const token=argv[index];return CLI_EXECUTABLE_ALIASES.has(token.trim().toLowerCase())?(trace.push({from:token,to:[],reason:"executable_alias",confidence:"high"}),[...argv.slice(0,index),...argv.slice(index+1)]):argv}function rewriteCommandAlias(argv,trace){let index=findBootstrapCommandTokenIndex(argv);if(index!==void 0&&argv[index]==="help"){const offset=findBootstrapCommandTokenIndex(argv.slice(index+1));index=offset===void 0?void 0:index+1+offset}if(index===void 0)return argv;const token=argv[index],canonical=EXECUTABLE_COMMAND_ALIASES[token.trim().toLowerCase()];if(!canonical)return argv;const canonicalTokens=canonical.split(" "),rewritten=[...argv.slice(0,index),...canonicalTokens,...argv.slice(index+1)];return trace.push({from:token,to:canonicalTokens,reason:"command_alias",confidence:"high"}),rewritten}function normalizeFlagKeyToken(raw){return raw.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function toComparableFlagKey(raw){return normalizeFlagKeyToken(raw).replace(/-/g,"")}function markUnambiguousFlag(map,key,canonicalFlag){const existing=map.get(key);if(existing===void 0){map.set(key,canonicalFlag);return}existing!==canonicalFlag&&map.set(key,null)}function collectLongFlagCandidates(contract){const candidates=[],pushLongFlag=value=>{typeof value=="string"&&value.startsWith("--")&&candidates.push(value)};pushLongFlag(contract.flag);for(const alias of contract.aliases??[])pushLongFlag(alias);return candidates}function buildFlagLookup(commandName,contractsOverride){const contracts=contractsOverride??resolveSubcommandFlagContractsForCommand(commandName),canonicalByNormalized=new Map,canonicalByCompact=new Map,canonicalComparablesMap=new Map,listCanonicalFlags=new Set;for(const contract of contracts){const longCandidates=collectLongFlagCandidates(contract);if(longCandidates.length===0)continue;const canonicalFlag=`--${normalizeFlagKeyToken(longCandidates[0])}`;for(const candidate of longCandidates)markUnambiguousFlag(canonicalByNormalized,normalizeFlagKeyToken(candidate),canonicalFlag),markUnambiguousFlag(canonicalByCompact,toComparableFlagKey(candidate),canonicalFlag);const comparable=toComparableFlagKey(canonicalFlag);canonicalComparablesMap.has(canonicalFlag)||canonicalComparablesMap.set(canonicalFlag,comparable),contract.list===!0&&listCanonicalFlags.add(canonicalFlag)}return{canonicalByNormalized,canonicalByCompact,canonicalComparables:[...canonicalComparablesMap.entries()].map(([canonicalFlag,comparable])=>({canonicalFlag,comparable})),listCanonicalFlags}}function resolveCanonicalFlag(rawKey,lookup){const normalizedKey=normalizeFlagKeyToken(rawKey),direct=lookup.canonicalByNormalized.get(normalizedKey);if(typeof direct=="string")return{flag:direct,reason:"flag_alias",confidence:"high"};const comparableKey=normalizedKey.replace(/-/g,""),compactMatch=lookup.canonicalByCompact.get(comparableKey);if(typeof compactMatch=="string")return{flag:compactMatch,reason:"flag_alias",confidence:"high"};const maxDistance=comparableKey.length>=8?2:1;let bestDistance=Number.POSITIVE_INFINITY,bestFlag,tied=!1;for(const candidate of lookup.canonicalComparables){const distance=levenshteinDistanceWithinLimit(comparableKey,candidate.comparable,maxDistance);if(distance!==null){if(distance<bestDistance){bestDistance=distance,bestFlag=candidate.canonicalFlag,tied=!1;continue}distance===bestDistance&&bestFlag!==candidate.canonicalFlag&&(tied=!0)}}return!bestFlag||tied||!Number.isFinite(bestDistance)||bestDistance<=0?null:{flag:bestFlag,reason:"flag_typo",confidence:bestDistance>=2?"medium":"high"}}function listAliasPluralKeys(normalizedKey){const candidates=[`${normalizedKey}s`];return normalizedKey.endsWith("y")&&normalizedKey.length>1&&candidates.push(`${normalizedKey.slice(0,-1)}ies`),candidates}function parseBareKeyValueToken(token,preserve=!1){if(preserve||token.includes("://"))return null;const match=token.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!match)return null;const key=match[1],value=match[3];return value.length===0?null:{key,value}}function normalizeLongOptionToken(token,lookup,preserve=!1){if(preserve||!token.startsWith("--"))return{tokens:[token]};const equalsIndex=token.indexOf("="),key=equalsIndex>=0?token.slice(0,equalsIndex):token,inlineValue=equalsIndex>=0?token.slice(equalsIndex+1):void 0,resolution=resolveCanonicalFlag(key,lookup);if(!resolution)return{tokens:[token]};const normalizedToken=inlineValue===void 0?resolution.flag:`${resolution.flag}=${inlineValue}`;return normalizedToken===token?{tokens:[token]}:{tokens:[normalizedToken],event:{from:token,to:[normalizedToken],reason:resolution.reason,confidence:resolution.confidence}}}function collectBootstrapPathValueIndices(argv){const indices=new Set;let expectsValue=!1;for(let index=0;index<argv.length;index+=1){if(expectsValue){indices.add(index),expectsValue=!1;continue}const token=argv[index];expectsValue=token==="--path"||token==="--pm-path"}return indices}function splitCanonicalListToken(token){if(!token.startsWith("--"))return null;const equalsIndex=token.indexOf("=");return equalsIndex<0?{flag:token}:{flag:token.slice(0,equalsIndex),inlineValue:token.slice(equalsIndex+1)}}function copyValueConsumingFlag(argv,index,result){result.push(argv[index]);const next=argv[index+1];return typeof next=="string"&&next!=="--"?(result.push(next),index+2):index+1}function readListFlagOccurrence(argv,index,parsed,multiValueListFlags){if(parsed.inlineValue!==void 0)return{originalTokens:[argv[index]],value:parsed.inlineValue,consumed:1};const values=[];let valueIndex=index+1;for(;valueIndex<argv.length&&argv[valueIndex]!=="--"&&!argv[valueIndex].startsWith("-")&&(values.length===0||multiValueListFlags.has(parsed.flag));)values.push(argv[valueIndex]),valueIndex+=1;const consumed=values.length===0?1:1+values.length;return{originalTokens:argv.slice(index,index+consumed),value:values.length===0?void 0:values.join(","),consumed}}function recordListFlagOccurrence(slots,result,flag,occurrence){const existing=slots.get(flag);if(existing){existing.values.push(occurrence.value),existing.occurrences+=1;return}slots.set(flag,{outputIndex:result.length,originalTokens:occurrence.originalTokens,values:[occurrence.value],occurrences:1}),result.push(null)}function buildListFlagCoalescingSplices(slots,multiValueListFlags){const events=[],splices=[];for(const[flag,slot]of slots){if(!(slot.occurrences>=2||multiValueListFlags.has(flag)&&slot.originalTokens.length>2)){splices.push({outputIndex:slot.outputIndex,tokens:slot.originalTokens});continue}const mergedToken=`${flag}=${slot.values.join(",")}`;splices.push({outputIndex:slot.outputIndex,tokens:[mergedToken]}),events.push({from:`${flag} (x${slot.occurrences})`,to:[mergedToken],reason:"list_merge",confidence:"high"})}return{events,splices}}function applyListFlagSplices(result,splices){splices.sort((a,b)=>b.outputIndex-a.outputIndex);for(const splice of splices)result.splice(splice.outputIndex,1,...splice.tokens)}function coalesceRepeatedListFlags(argv,listFlags,valueConsumingFlags=new Set,multiValueListFlags=new Set){if(listFlags.size===0)return{argv:[...argv],events:[]};const result=[],slots=new Map;let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--"){result.push(...argv.slice(index));break}if(valueConsumingFlags.has(token)){index=copyValueConsumingFlag(argv,index,result);continue}const parsed=splitCanonicalListToken(token);if(!parsed||!listFlags.has(parsed.flag)){result.push(token),index+=1;continue}const occurrence=readListFlagOccurrence(argv,index,parsed,multiValueListFlags);if(occurrence.value===void 0){result.push(token),index+=occurrence.consumed;continue}recordListFlagOccurrence(slots,result,parsed.flag,{originalTokens:occurrence.originalTokens,value:occurrence.value}),index+=occurrence.consumed}const{events,splices}=buildListFlagCoalescingSplices(slots,multiValueListFlags);return applyListFlagSplices(result,splices),{argv:result,events}}const LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function isLinkedTestTwoTokenValuePosition(commandName,emittedTokens){if(commandName!=="test"||emittedTokens.length<2)return!1;const key=emittedTokens[emittedTokens.length-1],flag=emittedTokens[emittedTokens.length-2],keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(flag);return keys!==void 0&&keys.has(key)}function mergeLinkedTestTwoTokenEntries(argv,commandName,trace){if(commandName!=="test")return argv;const result=[];let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--")return result.push(...argv.slice(index)),result;const keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(token),key=keys?argv[index+1]:void 0;if(!keys||typeof key!="string"||!keys.has(key)){result.push(token),index+=1;continue}let runEnd=index+2;for(;runEnd<argv.length&&!argv[runEnd].startsWith("-");)runEnd+=1;if(runEnd-(index+2)!==1){result.push(token),index+=1;continue}const value=argv[index+2],mergedValue=`${key}=${value}`;result.push(token,mergedValue),trace.push({from:`${token} ${key} ${value}`,to:[token,mergedValue],reason:"bare_key_value",confidence:"high"}),index+=3}return result}function normalizeBootstrapTokens(argv,lookup,commandName,trace){const normalizedArgv=[],pathValueIndices=collectBootstrapPathValueIndices(argv);for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--"){normalizedArgv.push(...argv.slice(index));break}const preserveCurrentToken=pathValueIndices.has(index),previous=normalizedArgv[normalizedArgv.length-1];if(token.startsWith("--")){const normalizedToken=normalizeLongOptionToken(token,lookup,preserveCurrentToken);normalizedArgv.push(...normalizedToken.tokens),normalizedToken.event&&trace.push(normalizedToken.event);continue}const bareKeyValue=parseBareKeyValueToken(token,preserveCurrentToken);if(!bareKeyValue||typeof previous=="string"&&previous.startsWith("-")&&!previous.includes("=")||["search","comments","notes","learnings"].includes(commandName)||isLinkedTestTwoTokenValuePosition(commandName,normalizedArgv)){normalizedArgv.push(token);continue}const resolution=resolveCanonicalFlag(bareKeyValue.key,lookup);if(!resolution){normalizedArgv.push(token);continue}const replacement=bareKeyValue.value.startsWith("-")?[`${resolution.flag}=${bareKeyValue.value}`]:[resolution.flag,bareKeyValue.value];normalizedArgv.push(...replacement),trace.push({from:token,to:replacement,reason:"bare_key_value",confidence:resolution.confidence})}return normalizedArgv}function bindAttestationVerification(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--verify"){const value=argv[index+1];if(value===void 0||value==="--")throw new PmCliError("history attest --verify requires a bundle file.",EXIT_CODE.USAGE);argv.splice(index,2,`--verify=${value}`)}else(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)||token==="--output"||token==="--hash-algorithm")&&(index+=1)}}function protectBootstrapHelpDiscovery(argv,command){if(!argv.some(token=>token==="--help"||token==="-h"))return;const declaredFlags=new Set(resolveSubcommandFlagContractsForCommand(command).flatMap(contract=>[contract.flag,...contract.aliases??[],...contract.short===void 0?[]:[contract.short]]));for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;token!=="--help"&&token!=="-h"||declaredFlags.has(argv[index-1])&&!BOOTSTRAP_BOOLEAN_FLAGS.has(argv[index-1])&&(argv[index-1]=token)}}function normalizeBootstrapInvocation(argv){const trace=[],executableNormalized=stripLeadingExecutableAlias(argv,trace),legacyNormalized=normalizeLegacyExtensionActionSyntax(executableNormalized);(legacyNormalized.length!==executableNormalized.length||legacyNormalized.some((token,index)=>token!==executableNormalized[index]))&&trace.push({from:executableNormalized.join(" "),to:[...legacyNormalized],reason:"legacy_extension_action",confidence:"high"});const aliasNormalized=rewriteCommandAlias(legacyNormalized,trace),itemAddress=normalizeItemAddressInvocation(aliasNormalized);if(itemAddress.conflict)throw new PmCliError("Provide the item id either positionally or with --id, not both.",EXIT_CODE.USAGE);itemAddress.changed&&trace.push({from:`--id ${itemAddress.itemId}`,to:[itemAddress.itemId],reason:"item_id_alias",confidence:"high"});const commandName=parseBootstrapCommandName(itemAddress.argv),commandPathName=parseBootstrapCommandPathName(itemAddress.argv),operationName=resolvePmCommandOperation(commandPathName??commandName??""),lookup=buildFlagLookup(commandPathName??commandName),normalizedArgv=normalizeBootstrapTokens(itemAddress.argv,lookup,operationName,trace),linkedTestNormalized=mergeLinkedTestTwoTokenEntries(normalizedArgv,operationName,trace),coalesced=coalesceRepeatedListFlags(linkedTestNormalized,lookup.listCanonicalFlags,GLOBAL_VALUE_CONSUMING_FLAGS,commandName==="create"?new Set(["--tags"]):new Set);for(const event of coalesced.events)trace.push(event);return protectBootstrapHelpDiscovery(coalesced.argv,commandPathName??commandName),commandPathName==="history attest"&&bindAttestationVerification(coalesced.argv),{argv:coalesced.argv,commandName,trace}}function parseBootstrapCommandPathName(argv){const stripped=stripGlobalBootstrapTokens(argv),first=stripped[0]?.trim().toLowerCase(),second=stripped[1]?.trim().toLowerCase(),namespaced=findPmNamespacedCommand(stripped);return namespaced?namespaced.canonical:(first==="extension"||first==="package"||first==="packages")&&typeof second=="string"&&second.length>0&&!second.startsWith("-")?`${first} ${second}`:first}function parseBootstrapTypeValue(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--type"){const candidate=argv[index+1];if(typeof candidate=="string"&&candidate.trim().length>0)return candidate.trim();continue}if(token.startsWith("--type=")){const candidate=token.slice(7).trim();if(candidate.length>0)return candidate}}}const _testOnly={buildFlagLookup,collectBootstrapPathValueIndices,collectLongFlagCandidates,markUnambiguousFlag,normalizeLongOptionToken,resolveCanonicalFlag};export{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,_testOnly,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,findBootstrapCommandTokenIndex,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,stripGlobalBootstrapTokens};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7b271a35-800c-52bf-9368-0410e76b8d4e")}catch{}})();import{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias}from"./cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand}from"./cli-contracts/flag-contracts.js";import{levenshteinDistanceWithinLimit}from"../core/shared/levenshtein.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{findPmNamespacedCommand,resolvePmCommandOperation}from"./cli-contracts/command-aliases.js";import{normalizeItemAddressInvocation}from"./agent/item-addressing.js";import{BOOTSTRAP_BOOLEAN_FLAGS,GLOBAL_VALUE_CONSUMING_FLAGS,consumesBootstrapValue,findBootstrapCommandTokenIndex as findContractBootstrapCommandTokenIndex,isInlineGlobalValueToken,parseBootstrapCommandName as parseContractBootstrapCommandName}from"./cli-contracts/bootstrap-command-scanner.js";const OUTPUT_VALUE_FLAGS=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]),BOOTSTRAP_OUTPUT_ENCODINGS=new Set(["toon","json"]);function consumeBootstrapGlobalToken(argv,index,state){const token=argv[index];if(BOOTSTRAP_BOOLEAN_FLAGS.has(token))return state.booleanFlags.add(token),1;const equalsIndex=token.indexOf("="),canonicalFlag=equalsIndex>0?token.slice(0,equalsIndex):token;if(!GLOBAL_VALUE_CONSUMING_FLAGS.has(canonicalFlag))return 1;const inlineValue=equalsIndex>0?token.slice(equalsIndex+1):void 0,consumesValue=inlineValue===void 0&&consumesBootstrapValue(canonicalFlag,argv[index+1]),value=inlineValue??(consumesValue?argv[index+1]:void 0);return canonicalFlag==="--author"?state.author=value??"":typeof value=="string"&&value.length>0&&(OUTPUT_VALUE_FLAGS.has(canonicalFlag)?state.outputValues:state.pathValues).set(canonicalFlag,value),consumesValue?2:1}function isBootstrapJsonOutput(state){return state.outputValues.get("--output-format")!=="toon"&&(state.booleanFlags.has("--json")||state.outputValues.get("--output-format")==="json"||state.pathValues.get("--format")?.trim().toLowerCase()==="json")}function parseBootstrapGlobalOptions(argv){const state={booleanFlags:new Set,outputValues:new Map,pathValues:new Map};let index=0;for(;index<argv.length&&argv[index]!=="--";)index+=consumeBootstrapGlobalToken(argv,index,state);return{path:state.pathValues.get("--pm-path")??state.pathValues.get("--path"),noExtensions:state.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(parseBootstrapCommandPathName(argv)??""),noPager:state.booleanFlags.has("--no-pager"),json:isBootstrapJsonOutput(state),quiet:state.booleanFlags.has("--quiet"),lean:state.booleanFlags.has("--lean"),tokenAccounting:state.booleanFlags.has("--token-accounting"),...state.booleanFlags.has("--output-row-contract")?{outputRowContract:!0}:{},...state.outputValues.get("--output-include")===void 0?{}:{outputInclude:state.outputValues.get("--output-include")},...state.outputValues.get("--output-limit")===void 0?{}:{outputLimit:state.outputValues.get("--output-limit")},...state.outputValues.get("--output-budget")===void 0?{}:{outputBudget:state.outputValues.get("--output-budget")},...BOOTSTRAP_OUTPUT_ENCODINGS.has(state.outputValues.get("--output-format"))?{outputFormat:state.outputValues.get("--output-format")}:{},...state.outputValues.get("--output-session")===void 0?{}:{outputSession:state.outputValues.get("--output-session")},...state.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:state.outputValues.get("--output-cursor")},...state.author===""?{authorMissingValue:!0}:state.author!==void 0?{author:state.author}:{}}}function stripGlobalBootstrapTokens(argv){const remaining=[];let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--")break;if(BOOTSTRAP_BOOLEAN_FLAGS.has(token)||token==="--profile"||token==="--id-only"||token==="--full-changed-fields"||token==="--explain"){index+=1;continue}if(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)){index+=consumesBootstrapValue(token,argv[index+1])?2:1;continue}if(isInlineGlobalValueToken(token)){index+=1;continue}remaining.push(token),index+=1}return remaining}function parseBootstrapHelpRequest(argv){const stripped=stripGlobalBootstrapTokens(argv);if(stripped[0]?.trim().toLowerCase()==="help"){const commandPathTokens2=[];for(let index=1;index<stripped.length;index+=1){const token=stripped[index];if(token.startsWith("-"))break;commandPathTokens2.push(token.trim().toLowerCase())}return{requested:!0,commandPathTokens:commandPathTokens2}}if(stripped.findIndex(token=>token==="--help"||token==="-h")<0)return{requested:!1,commandPathTokens:[]};const commandPathTokens=[];for(const token of stripped){if(token.startsWith("-"))break;commandPathTokens.push(token.trim().toLowerCase())}return{requested:!0,commandPathTokens}}function findBootstrapCommandTokenIndex(argv){return findContractBootstrapCommandTokenIndex(argv)}function parseBootstrapCommandName(argv){return parseContractBootstrapCommandName(argv)}function shouldDisablePagerForInvocation(argv,bootstrapGlobal){return bootstrapGlobal.noPager?!0:process.stdout.isTTY===!0?!1:parseBootstrapHelpRequest(argv).requested}function applyBootstrapPagerPolicy(argv){const pagerEnvironmentKeys=["PAGER","MANPAGER","GIT_PAGER","LESS"],previousValues=pagerEnvironmentKeys.map(key=>process.env[key]),restore=()=>{for(const[index,key]of pagerEnvironmentKeys.entries()){const value=previousValues[index];value===void 0?delete process.env[key]:process.env[key]=value}},bootstrapGlobal=parseBootstrapGlobalOptions(argv);return shouldDisablePagerForInvocation(argv,bootstrapGlobal)&&(process.env.PAGER="cat",process.env.MANPAGER="cat",process.env.GIT_PAGER="cat",(typeof process.env.LESS!="string"||process.env.LESS.trim().length===0)&&(process.env.LESS="FRX")),restore}const EXTENSION_ACTION_SYNTAX_TOKENS=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function normalizeLegacyExtensionActionSyntax(argv){const extensionIndex=findBootstrapCommandTokenIndex(argv);if(extensionIndex===void 0||argv[extensionIndex]!=="extension")return[...argv];const actionToken=argv[extensionIndex+1];if(!actionToken||actionToken.startsWith("-"))return[...argv];if(!EXTENSION_ACTION_SYNTAX_TOKENS.has(actionToken))return[...argv];if(argv.includes("--help")||argv.includes("-h"))return[...argv];const forcedActionFlag=`--${actionToken}`;return argv.includes(forcedActionFlag)?[...argv]:[...argv.slice(0,extensionIndex+1),forcedActionFlag,...argv.slice(extensionIndex+2)]}const CLI_EXECUTABLE_ALIASES=new Set(["pm","pm-cli"]);function stripLeadingExecutableAlias(argv,trace){const index=findBootstrapCommandTokenIndex(argv);if(index===void 0)return argv;const token=argv[index];return CLI_EXECUTABLE_ALIASES.has(token.trim().toLowerCase())?(trace.push({from:token,to:[],reason:"executable_alias",confidence:"high"}),[...argv.slice(0,index),...argv.slice(index+1)]):argv}function rewriteCommandAlias(argv,trace){let index=findBootstrapCommandTokenIndex(argv);if(index!==void 0&&argv[index]==="help"){const offset=findBootstrapCommandTokenIndex(argv.slice(index+1));index=offset===void 0?void 0:index+1+offset}if(index===void 0)return argv;const token=argv[index],canonical=EXECUTABLE_COMMAND_ALIASES[token.trim().toLowerCase()];if(!canonical)return argv;const canonicalTokens=canonical.split(" "),rewritten=[...argv.slice(0,index),...canonicalTokens,...argv.slice(index+1)];return trace.push({from:token,to:canonicalTokens,reason:"command_alias",confidence:"high"}),rewritten}function normalizeFlagKeyToken(raw){return raw.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function toComparableFlagKey(raw){return normalizeFlagKeyToken(raw).replace(/-/g,"")}function markUnambiguousFlag(map,key,canonicalFlag){const existing=map.get(key);if(existing===void 0){map.set(key,canonicalFlag);return}existing!==canonicalFlag&&map.set(key,null)}function collectLongFlagCandidates(contract){const candidates=[],pushLongFlag=value=>{typeof value=="string"&&value.startsWith("--")&&candidates.push(value)};pushLongFlag(contract.flag);for(const alias of contract.aliases??[])pushLongFlag(alias);return candidates}function buildFlagLookup(commandName,contractsOverride){const contracts=contractsOverride??resolveSubcommandFlagContractsForCommand(commandName),canonicalByNormalized=new Map,canonicalByCompact=new Map,canonicalComparablesMap=new Map,listCanonicalFlags=new Set;for(const contract of contracts){const longCandidates=collectLongFlagCandidates(contract);if(longCandidates.length===0)continue;const canonicalFlag=`--${normalizeFlagKeyToken(longCandidates[0])}`;for(const candidate of longCandidates)markUnambiguousFlag(canonicalByNormalized,normalizeFlagKeyToken(candidate),canonicalFlag),markUnambiguousFlag(canonicalByCompact,toComparableFlagKey(candidate),canonicalFlag);const comparable=toComparableFlagKey(canonicalFlag);canonicalComparablesMap.has(canonicalFlag)||canonicalComparablesMap.set(canonicalFlag,comparable),contract.list===!0&&listCanonicalFlags.add(canonicalFlag)}return{canonicalByNormalized,canonicalByCompact,canonicalComparables:[...canonicalComparablesMap.entries()].map(([canonicalFlag,comparable])=>({canonicalFlag,comparable})),listCanonicalFlags}}function resolveCanonicalFlag(rawKey,lookup){const normalizedKey=normalizeFlagKeyToken(rawKey),direct=lookup.canonicalByNormalized.get(normalizedKey);if(typeof direct=="string")return{flag:direct,reason:"flag_alias",confidence:"high"};const comparableKey=normalizedKey.replace(/-/g,""),compactMatch=lookup.canonicalByCompact.get(comparableKey);if(typeof compactMatch=="string")return{flag:compactMatch,reason:"flag_alias",confidence:"high"};const maxDistance=comparableKey.length>=8?2:1;let bestDistance=Number.POSITIVE_INFINITY,bestFlag,tied=!1;for(const candidate of lookup.canonicalComparables){const distance=levenshteinDistanceWithinLimit(comparableKey,candidate.comparable,maxDistance);if(distance!==null){if(distance<bestDistance){bestDistance=distance,bestFlag=candidate.canonicalFlag,tied=!1;continue}distance===bestDistance&&bestFlag!==candidate.canonicalFlag&&(tied=!0)}}return!bestFlag||tied||!Number.isFinite(bestDistance)||bestDistance<=0?null:{flag:bestFlag,reason:"flag_typo",confidence:bestDistance>=2?"medium":"high"}}function listAliasPluralKeys(normalizedKey){const candidates=[`${normalizedKey}s`];return normalizedKey.endsWith("y")&&normalizedKey.length>1&&candidates.push(`${normalizedKey.slice(0,-1)}ies`),candidates}function parseBareKeyValueToken(token,preserve=!1){if(preserve||token.includes("://"))return null;const match=token.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!match)return null;const key=match[1],value=match[3];return value.length===0?null:{key,value}}function normalizeLongOptionToken(token,lookup,preserve=!1){if(preserve||!token.startsWith("--"))return{tokens:[token]};const equalsIndex=token.indexOf("="),key=equalsIndex>=0?token.slice(0,equalsIndex):token,inlineValue=equalsIndex>=0?token.slice(equalsIndex+1):void 0,resolution=resolveCanonicalFlag(key,lookup);if(!resolution)return{tokens:[token]};const normalizedToken=inlineValue===void 0?resolution.flag:`${resolution.flag}=${inlineValue}`;return normalizedToken===token?{tokens:[token]}:{tokens:[normalizedToken],event:{from:token,to:[normalizedToken],reason:resolution.reason,confidence:resolution.confidence}}}function collectBootstrapPathValueIndices(argv){const indices=new Set;let expectsValue=!1;for(let index=0;index<argv.length;index+=1){if(expectsValue){indices.add(index),expectsValue=!1;continue}const token=argv[index];expectsValue=token==="--path"||token==="--pm-path"}return indices}function splitCanonicalListToken(token){if(!token.startsWith("--"))return null;const equalsIndex=token.indexOf("=");return equalsIndex<0?{flag:token}:{flag:token.slice(0,equalsIndex),inlineValue:token.slice(equalsIndex+1)}}function copyValueConsumingFlag(argv,index,result){result.push(argv[index]);const next=argv[index+1];return typeof next=="string"&&next!=="--"?(result.push(next),index+2):index+1}function readListFlagOccurrence(argv,index,parsed,multiValueListFlags){if(parsed.inlineValue!==void 0)return{originalTokens:[argv[index]],value:parsed.inlineValue,consumed:1};const values=[];let valueIndex=index+1;for(;valueIndex<argv.length&&argv[valueIndex]!=="--"&&!argv[valueIndex].startsWith("-")&&(values.length===0||multiValueListFlags.has(parsed.flag));)values.push(argv[valueIndex]),valueIndex+=1;const consumed=values.length===0?1:1+values.length;return{originalTokens:argv.slice(index,index+consumed),value:values.length===0?void 0:values.join(","),consumed}}function recordListFlagOccurrence(slots,result,flag,occurrence){const existing=slots.get(flag);if(existing){existing.values.push(occurrence.value),existing.occurrences+=1;return}slots.set(flag,{outputIndex:result.length,originalTokens:occurrence.originalTokens,values:[occurrence.value],occurrences:1}),result.push(null)}function buildListFlagCoalescingSplices(slots,multiValueListFlags){const events=[],splices=[];for(const[flag,slot]of slots){if(!(slot.occurrences>=2||multiValueListFlags.has(flag)&&slot.originalTokens.length>2)){splices.push({outputIndex:slot.outputIndex,tokens:slot.originalTokens});continue}const mergedToken=`${flag}=${slot.values.join(",")}`;splices.push({outputIndex:slot.outputIndex,tokens:[mergedToken]}),events.push({from:`${flag} (x${slot.occurrences})`,to:[mergedToken],reason:"list_merge",confidence:"high"})}return{events,splices}}function applyListFlagSplices(result,splices){splices.sort((a,b)=>b.outputIndex-a.outputIndex);for(const splice of splices)result.splice(splice.outputIndex,1,...splice.tokens)}function coalesceRepeatedListFlags(argv,listFlags,valueConsumingFlags=new Set,multiValueListFlags=new Set){if(listFlags.size===0)return{argv:[...argv],events:[]};const result=[],slots=new Map;let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--"){result.push(...argv.slice(index));break}if(valueConsumingFlags.has(token)){index=copyValueConsumingFlag(argv,index,result);continue}const parsed=splitCanonicalListToken(token);if(!parsed||!listFlags.has(parsed.flag)){result.push(token),index+=1;continue}const occurrence=readListFlagOccurrence(argv,index,parsed,multiValueListFlags);if(occurrence.value===void 0){result.push(token),index+=occurrence.consumed;continue}recordListFlagOccurrence(slots,result,parsed.flag,{originalTokens:occurrence.originalTokens,value:occurrence.value}),index+=occurrence.consumed}const{events,splices}=buildListFlagCoalescingSplices(slots,multiValueListFlags);return applyListFlagSplices(result,splices),{argv:result,events}}const LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function isLinkedTestTwoTokenValuePosition(commandName,emittedTokens){if(commandName!=="test"||emittedTokens.length<2)return!1;const key=emittedTokens[emittedTokens.length-1],flag=emittedTokens[emittedTokens.length-2],keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(flag);return keys!==void 0&&keys.has(key)}function mergeLinkedTestTwoTokenEntries(argv,commandName,trace){if(commandName!=="test")return argv;const result=[];let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--")return result.push(...argv.slice(index)),result;const keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(token),key=keys?argv[index+1]:void 0;if(!keys||typeof key!="string"||!keys.has(key)){result.push(token),index+=1;continue}let runEnd=index+2;for(;runEnd<argv.length&&!argv[runEnd].startsWith("-");)runEnd+=1;if(runEnd-(index+2)!==1){result.push(token),index+=1;continue}const value=argv[index+2],mergedValue=`${key}=${value}`;result.push(token,mergedValue),trace.push({from:`${token} ${key} ${value}`,to:[token,mergedValue],reason:"bare_key_value",confidence:"high"}),index+=3}return result}function normalizeBootstrapTokens(argv,lookup,commandName,trace){const normalizedArgv=[],pathValueIndices=collectBootstrapPathValueIndices(argv);for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--"){normalizedArgv.push(...argv.slice(index));break}const preserveCurrentToken=pathValueIndices.has(index),previous=normalizedArgv[normalizedArgv.length-1];if(token.startsWith("--")){const normalizedToken=normalizeLongOptionToken(token,lookup,preserveCurrentToken);normalizedArgv.push(...normalizedToken.tokens),normalizedToken.event&&trace.push(normalizedToken.event);continue}const bareKeyValue=parseBareKeyValueToken(token,preserveCurrentToken);if(!bareKeyValue||typeof previous=="string"&&previous.startsWith("-")&&!previous.includes("=")||["search","comments","notes","learnings"].includes(commandName)||isLinkedTestTwoTokenValuePosition(commandName,normalizedArgv)){normalizedArgv.push(token);continue}const resolution=resolveCanonicalFlag(bareKeyValue.key,lookup);if(!resolution){normalizedArgv.push(token);continue}const replacement=bareKeyValue.value.startsWith("-")?[`${resolution.flag}=${bareKeyValue.value}`]:[resolution.flag,bareKeyValue.value];normalizedArgv.push(...replacement),trace.push({from:token,to:replacement,reason:"bare_key_value",confidence:resolution.confidence})}return normalizedArgv}function bindAttestationVerification(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--verify"){const value=argv[index+1];if(value===void 0||value==="--")throw new PmCliError("history attest --verify requires a bundle file.",EXIT_CODE.USAGE);argv.splice(index,2,`--verify=${value}`)}else(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)||token==="--output"||token==="--hash-algorithm")&&(index+=1)}}function protectBootstrapHelpDiscovery(argv,command){if(!argv.some(token=>token==="--help"||token==="-h"))return;const declaredFlags=new Set(resolveSubcommandFlagContractsForCommand(command).flatMap(contract=>[contract.flag,...contract.aliases??[],...contract.short===void 0?[]:[contract.short]]));for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;token!=="--help"&&token!=="-h"||declaredFlags.has(argv[index-1])&&!BOOTSTRAP_BOOLEAN_FLAGS.has(argv[index-1])&&(argv[index-1]=token)}}function normalizeBootstrapInvocation(argv){const trace=[],executableNormalized=stripLeadingExecutableAlias(argv,trace),legacyNormalized=normalizeLegacyExtensionActionSyntax(executableNormalized);(legacyNormalized.length!==executableNormalized.length||legacyNormalized.some((token,index)=>token!==executableNormalized[index]))&&trace.push({from:executableNormalized.join(" "),to:[...legacyNormalized],reason:"legacy_extension_action",confidence:"high"});const aliasNormalized=rewriteCommandAlias(legacyNormalized,trace),itemAddress=normalizeItemAddressInvocation(aliasNormalized);if(itemAddress.conflict)throw new PmCliError("Provide the item id either positionally or with --id, not both.",EXIT_CODE.USAGE);itemAddress.changed&&trace.push({from:`--id ${itemAddress.itemId}`,to:[itemAddress.itemId],reason:"item_id_alias",confidence:"high"});const commandName=parseBootstrapCommandName(itemAddress.argv),commandPathName=parseBootstrapCommandPathName(itemAddress.argv),operationName=resolvePmCommandOperation(commandPathName??commandName??""),lookup=buildFlagLookup(commandPathName??commandName),normalizedArgv=normalizeBootstrapTokens(itemAddress.argv,lookup,operationName,trace),linkedTestNormalized=mergeLinkedTestTwoTokenEntries(normalizedArgv,operationName,trace),coalesced=coalesceRepeatedListFlags(linkedTestNormalized,lookup.listCanonicalFlags,GLOBAL_VALUE_CONSUMING_FLAGS,commandName==="create"?new Set(["--tags"]):new Set);for(const event of coalesced.events)trace.push(event);return protectBootstrapHelpDiscovery(coalesced.argv,commandPathName??commandName),commandPathName==="history attest"&&bindAttestationVerification(coalesced.argv),{argv:coalesced.argv,commandName,trace}}function parseBootstrapCommandPathName(argv){const stripped=stripGlobalBootstrapTokens(argv),first=stripped[0]?.trim().toLowerCase(),second=stripped[1]?.trim().toLowerCase(),namespaced=findPmNamespacedCommand(stripped);return namespaced?namespaced.canonical:(first==="extension"||first==="package"||first==="packages")&&typeof second=="string"&&second.length>0&&!second.startsWith("-")?`${first} ${second}`:first}function parseBootstrapTypeValue(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--type"){const candidate=argv[index+1];if(typeof candidate=="string"&&candidate.trim().length>0)return candidate.trim();continue}if(token.startsWith("--type=")){const candidate=token.slice(7).trim();if(candidate.length>0)return candidate}}}const _testOnly={buildFlagLookup,collectBootstrapPathValueIndices,collectLongFlagCandidates,markUnambiguousFlag,normalizeLongOptionToken,resolveCanonicalFlag};export{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,_testOnly,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,findBootstrapCommandTokenIndex,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,stripGlobalBootstrapTokens};
|
|
2
2
|
//# sourceMappingURL=cli-bootstrap.js.map
|
|
@@ -125,3 +125,31 @@ export declare function projectPmDiagnosticText(output:string,correctiveAction:s
|
|
|
125
125
|
diagnosticClass?:PmDiagnosticOutputClass;
|
|
126
126
|
maxEstimatedTokens?:number;
|
|
127
127
|
}):PmProjectedTextDiagnostic;
|
|
128
|
+
/**
|
|
129
|
+
* Guidance that every refusal can carry regardless of its code. Lean output
|
|
130
|
+
* omits it because it never changes the caller's next action; default output
|
|
131
|
+
* keeps it for human readers (GH-1610). Declared once here so the text and
|
|
132
|
+
* JSON lean projections agree on what counts as boilerplate.
|
|
133
|
+
*/
|
|
134
|
+
export declare const PM_GENERIC_REFUSAL_GUIDANCE:Readonly<{
|
|
135
|
+
required:"Adjust command input or tracker state and retry.";
|
|
136
|
+
why:readonly string[];
|
|
137
|
+
examples:readonly string[];
|
|
138
|
+
}>;
|
|
139
|
+
/** True when the `What is required` text is the generic constant. */
|
|
140
|
+
export declare function isGenericRefusalRequired(value:string | undefined):boolean;
|
|
141
|
+
/** True when the `Why` text carries no code-specific rationale. */
|
|
142
|
+
export declare function isGenericRefusalWhy(value:string | undefined):boolean;
|
|
143
|
+
/**
|
|
144
|
+
* Drop each generic help pointer from an example list so a mixed list keeps
|
|
145
|
+
* only its code-specific entries; an all-generic list becomes empty.
|
|
146
|
+
*/
|
|
147
|
+
export declare function withoutGenericRefusalExamples(values:readonly string[] | undefined):string[];
|
|
148
|
+
/** Recovery fields that only echo the caller's own invocation. */
|
|
149
|
+
export declare const PM_RECOVERY_ECHO_FIELDS:readonly ["attempted_command","normalized_args","provided_fields"];
|
|
150
|
+
/**
|
|
151
|
+
* Drop the invocation echo from a recovery payload. Specific recovery such as
|
|
152
|
+
* `suggested_retry`, `missing`, `allowed_values` and `next_best_command`
|
|
153
|
+
* survives; an empty remainder is omitted entirely.
|
|
154
|
+
*/
|
|
155
|
+
export declare function projectLeanRecoveryPayload<Recovery extends Partial<Record<(typeof PM_RECOVERY_ECHO_FIELDS)[number],unknown>>>(recovery:Recovery | undefined):Omit<Recovery,(typeof PM_RECOVERY_ECHO_FIELDS)[number]> | undefined;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1a14ce9e-1074-5434-9646-dd5e25e34814")}catch{}})();import{stripVTControlCharacters}from"node:util";import{unicodeSafePrefix}from"../../core/shared/text-normalization.js";import{resolvePmHistoryOperation}from"./command-aliases.js";import{PM_CORE_COMMAND_NAMES}from"./enum-contracts.js";const PM_OUTPUT_DEGRADATION_STEPS=["full","compact","brief","summary","counts"],PM_OUTPUT_BUDGET_CLASSES=["mutation","read","discovery","governance"],PM_DIAGNOSTIC_OUTPUT_CLASSES=["error","warning","validation_summary","recovery_bundle"],PM_DIAGNOSTIC_DEGRADATION_STEPS=["full","omit_explanation","limit_collections","compact_recovery","action_only"],MUTATION_COMMANDS=new Set(["append","claim","close","close-many","close-task","comments","config","copy","create","delete","docs","event","files","focus","history-author-acknowledge","history-compact","history-redact","history-repair","init","item","learnings","meet","notes","pause-task","release","remind","restore","schema","start-task","update","update-many"]),DISCOVERY_COMMANDS=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),GOVERNANCE_COMMANDS=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),DEFAULT_MAX_ESTIMATED_TOKENS={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},JSON_BUDGET_NUMERATOR=3,JSON_BUDGET_DENOMINATOR=2,MINIMUM_DIAGNOSTIC_BUDGET=192,DIAGNOSTIC_DEFAULT_BUDGETS={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS=PM_DIAGNOSTIC_OUTPUT_CLASSES.map(diagnosticClass=>({diagnostic_class:diagnosticClass,default_max_estimated_tokens_by_format:DIAGNOSTIC_DEFAULT_BUDGETS[diagnosticClass],minimum_max_estimated_tokens:MINIMUM_DIAGNOSTIC_BUDGET,degradation_ladder:PM_DIAGNOSTIC_DEGRADATION_STEPS,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),DIAGNOSTIC_BUDGET_BY_CLASS=new Map(PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS.map(contract=>[contract.diagnostic_class,contract]));function inferPmOutputBudgetClass(command){const[rootCommand=""]=resolvePmHistoryOperation(command).split(/\s+/u);return MUTATION_COMMANDS.has(rootCommand)?"mutation":DISCOVERY_COMMANDS.has(rootCommand)?"discovery":GOVERNANCE_COMMANDS.has(rootCommand)?"governance":"read"}function createPmCommandOutputBudget(command,budgetClass=inferPmOutputBudgetClass(command)){const normalizedCommand=command.trim().replace(/\s+/gu," ");if(normalizedCommand.length===0)throw new TypeError("command must be a non-empty command path");const toonBudget=DEFAULT_MAX_ESTIMATED_TOKENS[budgetClass];return definePmCommandOutputBudget({command:normalizedCommand,budget_class:budgetClass,default_max_estimated_tokens:toonBudget,default_max_estimated_tokens_by_format:{toon:toonBudget,json:Math.ceil(toonBudget*JSON_BUDGET_NUMERATOR/JSON_BUDGET_DENOMINATOR)},degradation_ladder:PM_OUTPUT_DEGRADATION_STEPS,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function definePmCommandOutputBudget(contract){if(!Number.isSafeInteger(contract.default_max_estimated_tokens)||contract.default_max_estimated_tokens<=0)throw new RangeError("default_max_estimated_tokens must be a positive safe integer");for(const[format,ceiling]of Object.entries(contract.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(ceiling)||ceiling<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${format} must be a positive safe integer`);return contract}const PM_COMMAND_OUTPUT_BUDGET_CONTRACTS=PM_CORE_COMMAND_NAMES.map(command=>createPmCommandOutputBudget(command)),OUTPUT_BUDGET_BY_COMMAND=new Map(PM_COMMAND_OUTPUT_BUDGET_CONTRACTS.map(contract=>[contract.command,contract]));function resolvePmCommandOutputBudget(command,options={}){const normalizedCommand=command.trim().replace(/\s+/gu," "),[rootCommand]=resolvePmHistoryOperation(normalizedCommand).split(" "),declared=OUTPUT_BUDGET_BY_COMMAND.get(rootCommand);return declared?{...declared,command:normalizedCommand}:options.generateFallback?createPmCommandOutputBudget(normalizedCommand):null}function estimatePmOutputTokens(utf8Bytes){return Math.ceil(Math.max(0,utf8Bytes)/4)}function resolvePmDiagnosticOutputBudget(diagnosticClass){const contract=DIAGNOSTIC_BUDGET_BY_CLASS.get(diagnosticClass);if(contract===void 0)throw new TypeError(`diagnosticClass must be one of: ${PM_DIAGNOSTIC_OUTPUT_CLASSES.join(", ")}`);return contract}function estimateJsonDiagnosticTokens(value){return estimatePmOutputTokens(Buffer.byteLength(JSON.stringify(value,null,2),"utf8"))}function isDiagnosticRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function compactDiagnosticRecovery(value){if(!isDiagnosticRecord(value))return;const compact={};for(const key of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms","waited_ms","owner_handoffs"]){const candidate=value[key];Array.isArray(candidate)?compact[key]=key==="suggested_retry_args"?candidate:candidate.slice(0,3):candidate!==void 0&&(compact[key]=candidate)}return Object.keys(compact).length>0?compact:void 0}function truncateDiagnosticString(value,maximum){return typeof value!="string"||value.length<=maximum?value:`${unicodeSafePrefix(value,Math.max(1,maximum-3))}...`}function truncateDiagnosticUtf8Text(value,maximumBytes){if(Buffer.byteLength(value,"utf8")<=maximumBytes)return value;const suffix="...",codePoints=Array.from(value);let lower=0,upper=codePoints.length;for(;lower<upper;){const middle=Math.ceil((lower+upper)/2),candidate=`${codePoints.slice(0,middle).join("")}${suffix}`;Buffer.byteLength(candidate,"utf8")<=maximumBytes?lower=middle:upper=middle-1}return`${codePoints.slice(0,lower).join("")}${suffix}`}function prioritizeDiagnosticFields(diagnostic){const prioritized={};for(const key of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(diagnostic,key)&&diagnostic[key]!==void 0&&(prioritized[key]=diagnostic[key]);for(const[key,value]of Object.entries(diagnostic))key!=="__proto__"&&!Object.hasOwn(prioritized,key)&&(prioritized[key]=value);return prioritized}const DIAGNOSTIC_COLLECTION_LIMIT_STAGES=new Set(["limit_collections","compact_recovery","action_only"]),DIAGNOSTIC_RECOVERY_COMPACTION_STAGES=new Set(["compact_recovery","action_only"]);function actionOnlyDiagnostic(candidate){const actionOnly={code:typeof candidate.code=="string"?candidate.code:"diagnostic",required:truncateDiagnosticString(candidate.required,160)??"Inspect the diagnostic code and retry with corrected input."},recovery=compactDiagnosticRecovery(candidate.recovery);return recovery!==void 0?actionOnly.recovery=recovery:Array.isArray(candidate.next_steps)&&(actionOnly.next_steps=candidate.next_steps.slice(0,1)),candidate.exit_code!==void 0&&(actionOnly.exit_code=candidate.exit_code),candidate.type!==void 0&&(actionOnly.type=candidate.type),actionOnly}function diagnosticCandidate(diagnostic,stage){const candidate=structuredClone(diagnostic);if(stage!=="full"&&(delete candidate.why,delete candidate.examples),DIAGNOSTIC_COLLECTION_LIMIT_STAGES.has(stage))for(const[key,value]of Object.entries(candidate))Array.isArray(value)&&(candidate[key]=value.slice(0,3));if(DIAGNOSTIC_RECOVERY_COMPACTION_STAGES.has(stage)){const recovery=compactDiagnosticRecovery(candidate.recovery);recovery?candidate.recovery=recovery:delete candidate.recovery}return stage!=="action_only"?prioritizeDiagnosticFields(candidate):actionOnlyDiagnostic(candidate)}function attachDiagnosticReceipt(candidate,receipt){const projected={...candidate,diagnostic_output:{...receipt,estimated_tokens:0}};for(let attempt=0;attempt<4;attempt+=1){const estimatedTokens=estimateJsonDiagnosticTokens(projected),outputReceipt=projected.diagnostic_output;if(outputReceipt.estimated_tokens===estimatedTokens)break;outputReceipt.estimated_tokens=estimatedTokens}return projected}function shrinkMinimalDiagnosticCandidate(candidate,receipt,budget){let fallback=attachDiagnosticReceipt(candidate,receipt);for(const optionalField of["recovery","exit_code"])estimateJsonDiagnosticTokens(fallback)<=budget||candidate[optionalField]===void 0||(delete candidate[optionalField],fallback=attachDiagnosticReceipt(candidate,receipt));let maximumActionBytes=40;for(;estimateJsonDiagnosticTokens(fallback)>budget&&maximumActionBytes>4;)maximumActionBytes-=4,candidate.code=truncateDiagnosticUtf8Text(String(candidate.code),maximumActionBytes),candidate.required=truncateDiagnosticUtf8Text(String(candidate.required),maximumActionBytes),fallback=attachDiagnosticReceipt(candidate,receipt);return fallback}function createMinimalDiagnosticFallback(projected,budget){const receipt=projected.diagnostic_output,{estimated_tokens:_estimatedTokens,...receiptWithoutEstimate}=receipt,boundedOmittedFields=receiptWithoutEstimate.omitted_fields.slice(0,8).map(field=>truncateDiagnosticUtf8Text(field,32)),boundedReceipt={...receiptWithoutEstimate,omitted_fields:boundedOmittedFields,...receiptWithoutEstimate.omitted_fields.length>boundedOmittedFields.length?{omitted_fields_overflow_count:receiptWithoutEstimate.omitted_fields.length-boundedOmittedFields.length}:{}},recoveryCandidate=compactDiagnosticRecovery(projected.recovery),recovery=recoveryCandidate&&estimateJsonDiagnosticTokens(recoveryCandidate)<=48?recoveryCandidate:void 0,candidate={code:truncateDiagnosticUtf8Text(String(projected.code),320),required:truncateDiagnosticUtf8Text(String(projected.required),320),...recovery?{recovery}:{},...projected.exit_code!==void 0?{exit_code:projected.exit_code}:{}};let fallback=attachDiagnosticReceipt(candidate,boundedReceipt);for(;estimateJsonDiagnosticTokens(fallback)>budget&&boundedReceipt.omitted_fields.length>0;)boundedReceipt.omitted_fields.pop(),boundedReceipt.omitted_fields_overflow_count=receiptWithoutEstimate.omitted_fields.length-boundedReceipt.omitted_fields.length,fallback=attachDiagnosticReceipt(candidate,boundedReceipt);return fallback=shrinkMinimalDiagnosticCandidate(candidate,boundedReceipt,budget),fallback}function projectPmDiagnosticOutput(diagnostic,options={}){const diagnosticRecord=diagnostic,diagnosticClass=options.diagnosticClass??"error",contract=resolvePmDiagnosticOutputBudget(diagnosticClass),explicitBudget=options.maxEstimatedTokens;if(explicitBudget!==void 0&&(!Number.isSafeInteger(explicitBudget)||explicitBudget<contract.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${contract.minimum_max_estimated_tokens}`);const budget=explicitBudget??contract.default_max_estimated_tokens_by_format.json,originalEstimatedTokens=estimateJsonDiagnosticTokens(diagnosticRecord),originalFields=Object.keys(diagnosticRecord);if(originalEstimatedTokens<=budget)return prioritizeDiagnosticFields(structuredClone(diagnosticRecord));let projected;for(const[index,stage]of contract.degradation_ladder.entries()){const candidate=diagnosticCandidate(diagnosticRecord,stage),omittedFields=originalFields.filter(field=>!Object.hasOwn(candidate,field)),withReceipt=attachDiagnosticReceipt(candidate,{diagnostic_class:diagnosticClass,format:"json",budget,budget_source:explicitBudget===void 0?"default":"explicit",original_estimated_tokens:originalEstimatedTokens,truncated:index>0,degradation_steps:contract.degradation_ladder.slice(0,index+1),omitted_fields:omittedFields});if(projected=withReceipt,estimateJsonDiagnosticTokens(withReceipt)<=budget)break}return estimateJsonDiagnosticTokens(projected)>budget&&(projected=createMinimalDiagnosticFallback(projected,budget)),projected}function sanitizeDiagnosticText(text){return stripVTControlCharacters(text).replace(/\r\n/gu,`
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="493a0675-0114-5b93-b3b4-5bd895ac691f")}catch{}})();import{stripVTControlCharacters}from"node:util";import{unicodeSafePrefix}from"../../core/shared/text-normalization.js";import{resolvePmHistoryOperation}from"./command-aliases.js";import{PM_CORE_COMMAND_NAMES}from"./enum-contracts.js";const PM_OUTPUT_DEGRADATION_STEPS=["full","compact","brief","summary","counts"],PM_OUTPUT_BUDGET_CLASSES=["mutation","read","discovery","governance"],PM_DIAGNOSTIC_OUTPUT_CLASSES=["error","warning","validation_summary","recovery_bundle"],PM_DIAGNOSTIC_DEGRADATION_STEPS=["full","omit_explanation","limit_collections","compact_recovery","action_only"],MUTATION_COMMANDS=new Set(["append","claim","close","close-many","close-task","comments","config","copy","create","delete","docs","event","files","focus","history-author-acknowledge","history-compact","history-redact","history-repair","init","item","learnings","meet","notes","pause-task","release","remind","restore","schema","start-task","update","update-many"]),DISCOVERY_COMMANDS=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),GOVERNANCE_COMMANDS=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),DEFAULT_MAX_ESTIMATED_TOKENS={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},JSON_BUDGET_NUMERATOR=3,JSON_BUDGET_DENOMINATOR=2,MINIMUM_DIAGNOSTIC_BUDGET=192,DIAGNOSTIC_DEFAULT_BUDGETS={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS=PM_DIAGNOSTIC_OUTPUT_CLASSES.map(diagnosticClass=>({diagnostic_class:diagnosticClass,default_max_estimated_tokens_by_format:DIAGNOSTIC_DEFAULT_BUDGETS[diagnosticClass],minimum_max_estimated_tokens:MINIMUM_DIAGNOSTIC_BUDGET,degradation_ladder:PM_DIAGNOSTIC_DEGRADATION_STEPS,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),DIAGNOSTIC_BUDGET_BY_CLASS=new Map(PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS.map(contract=>[contract.diagnostic_class,contract]));function inferPmOutputBudgetClass(command){const[rootCommand=""]=resolvePmHistoryOperation(command).split(/\s+/u);return MUTATION_COMMANDS.has(rootCommand)?"mutation":DISCOVERY_COMMANDS.has(rootCommand)?"discovery":GOVERNANCE_COMMANDS.has(rootCommand)?"governance":"read"}function createPmCommandOutputBudget(command,budgetClass=inferPmOutputBudgetClass(command)){const normalizedCommand=command.trim().replace(/\s+/gu," ");if(normalizedCommand.length===0)throw new TypeError("command must be a non-empty command path");const toonBudget=DEFAULT_MAX_ESTIMATED_TOKENS[budgetClass];return definePmCommandOutputBudget({command:normalizedCommand,budget_class:budgetClass,default_max_estimated_tokens:toonBudget,default_max_estimated_tokens_by_format:{toon:toonBudget,json:Math.ceil(toonBudget*JSON_BUDGET_NUMERATOR/JSON_BUDGET_DENOMINATOR)},degradation_ladder:PM_OUTPUT_DEGRADATION_STEPS,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function definePmCommandOutputBudget(contract){if(!Number.isSafeInteger(contract.default_max_estimated_tokens)||contract.default_max_estimated_tokens<=0)throw new RangeError("default_max_estimated_tokens must be a positive safe integer");for(const[format,ceiling]of Object.entries(contract.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(ceiling)||ceiling<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${format} must be a positive safe integer`);return contract}const PM_COMMAND_OUTPUT_BUDGET_CONTRACTS=PM_CORE_COMMAND_NAMES.map(command=>createPmCommandOutputBudget(command)),OUTPUT_BUDGET_BY_COMMAND=new Map(PM_COMMAND_OUTPUT_BUDGET_CONTRACTS.map(contract=>[contract.command,contract]));function resolvePmCommandOutputBudget(command,options={}){const normalizedCommand=command.trim().replace(/\s+/gu," "),[rootCommand]=resolvePmHistoryOperation(normalizedCommand).split(" "),declared=OUTPUT_BUDGET_BY_COMMAND.get(rootCommand);return declared?{...declared,command:normalizedCommand}:options.generateFallback?createPmCommandOutputBudget(normalizedCommand):null}function estimatePmOutputTokens(utf8Bytes){return Math.ceil(Math.max(0,utf8Bytes)/4)}function resolvePmDiagnosticOutputBudget(diagnosticClass){const contract=DIAGNOSTIC_BUDGET_BY_CLASS.get(diagnosticClass);if(contract===void 0)throw new TypeError(`diagnosticClass must be one of: ${PM_DIAGNOSTIC_OUTPUT_CLASSES.join(", ")}`);return contract}function estimateJsonDiagnosticTokens(value){return estimatePmOutputTokens(Buffer.byteLength(JSON.stringify(value,null,2),"utf8"))}function isDiagnosticRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function compactDiagnosticRecovery(value){if(!isDiagnosticRecord(value))return;const compact={};for(const key of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms","waited_ms","owner_handoffs"]){const candidate=value[key];Array.isArray(candidate)?compact[key]=key==="suggested_retry_args"?candidate:candidate.slice(0,3):candidate!==void 0&&(compact[key]=candidate)}return Object.keys(compact).length>0?compact:void 0}function truncateDiagnosticString(value,maximum){return typeof value!="string"||value.length<=maximum?value:`${unicodeSafePrefix(value,Math.max(1,maximum-3))}...`}function truncateDiagnosticUtf8Text(value,maximumBytes){if(Buffer.byteLength(value,"utf8")<=maximumBytes)return value;const suffix="...",codePoints=Array.from(value);let lower=0,upper=codePoints.length;for(;lower<upper;){const middle=Math.ceil((lower+upper)/2),candidate=`${codePoints.slice(0,middle).join("")}${suffix}`;Buffer.byteLength(candidate,"utf8")<=maximumBytes?lower=middle:upper=middle-1}return`${codePoints.slice(0,lower).join("")}${suffix}`}function prioritizeDiagnosticFields(diagnostic){const prioritized={};for(const key of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(diagnostic,key)&&diagnostic[key]!==void 0&&(prioritized[key]=diagnostic[key]);for(const[key,value]of Object.entries(diagnostic))key!=="__proto__"&&!Object.hasOwn(prioritized,key)&&(prioritized[key]=value);return prioritized}const DIAGNOSTIC_COLLECTION_LIMIT_STAGES=new Set(["limit_collections","compact_recovery","action_only"]),DIAGNOSTIC_RECOVERY_COMPACTION_STAGES=new Set(["compact_recovery","action_only"]);function actionOnlyDiagnostic(candidate){const actionOnly={code:typeof candidate.code=="string"?candidate.code:"diagnostic",required:truncateDiagnosticString(candidate.required,160)??"Inspect the diagnostic code and retry with corrected input."},recovery=compactDiagnosticRecovery(candidate.recovery);return recovery!==void 0?actionOnly.recovery=recovery:Array.isArray(candidate.next_steps)&&(actionOnly.next_steps=candidate.next_steps.slice(0,1)),candidate.exit_code!==void 0&&(actionOnly.exit_code=candidate.exit_code),candidate.type!==void 0&&(actionOnly.type=candidate.type),actionOnly}function diagnosticCandidate(diagnostic,stage){const candidate=structuredClone(diagnostic);if(stage!=="full"&&(delete candidate.why,delete candidate.examples),DIAGNOSTIC_COLLECTION_LIMIT_STAGES.has(stage))for(const[key,value]of Object.entries(candidate))Array.isArray(value)&&(candidate[key]=value.slice(0,3));if(DIAGNOSTIC_RECOVERY_COMPACTION_STAGES.has(stage)){const recovery=compactDiagnosticRecovery(candidate.recovery);recovery?candidate.recovery=recovery:delete candidate.recovery}return stage!=="action_only"?prioritizeDiagnosticFields(candidate):actionOnlyDiagnostic(candidate)}function attachDiagnosticReceipt(candidate,receipt){const projected={...candidate,diagnostic_output:{...receipt,estimated_tokens:0}};for(let attempt=0;attempt<4;attempt+=1){const estimatedTokens=estimateJsonDiagnosticTokens(projected),outputReceipt=projected.diagnostic_output;if(outputReceipt.estimated_tokens===estimatedTokens)break;outputReceipt.estimated_tokens=estimatedTokens}return projected}function shrinkMinimalDiagnosticCandidate(candidate,receipt,budget){let fallback=attachDiagnosticReceipt(candidate,receipt);for(const optionalField of["recovery","exit_code"])estimateJsonDiagnosticTokens(fallback)<=budget||candidate[optionalField]===void 0||(delete candidate[optionalField],fallback=attachDiagnosticReceipt(candidate,receipt));let maximumActionBytes=40;for(;estimateJsonDiagnosticTokens(fallback)>budget&&maximumActionBytes>4;)maximumActionBytes-=4,candidate.code=truncateDiagnosticUtf8Text(String(candidate.code),maximumActionBytes),candidate.required=truncateDiagnosticUtf8Text(String(candidate.required),maximumActionBytes),fallback=attachDiagnosticReceipt(candidate,receipt);return fallback}function createMinimalDiagnosticFallback(projected,budget){const receipt=projected.diagnostic_output,{estimated_tokens:_estimatedTokens,...receiptWithoutEstimate}=receipt,boundedOmittedFields=receiptWithoutEstimate.omitted_fields.slice(0,8).map(field=>truncateDiagnosticUtf8Text(field,32)),boundedReceipt={...receiptWithoutEstimate,omitted_fields:boundedOmittedFields,...receiptWithoutEstimate.omitted_fields.length>boundedOmittedFields.length?{omitted_fields_overflow_count:receiptWithoutEstimate.omitted_fields.length-boundedOmittedFields.length}:{}},recoveryCandidate=compactDiagnosticRecovery(projected.recovery),recovery=recoveryCandidate&&estimateJsonDiagnosticTokens(recoveryCandidate)<=48?recoveryCandidate:void 0,candidate={code:truncateDiagnosticUtf8Text(String(projected.code),320),required:truncateDiagnosticUtf8Text(String(projected.required),320),...recovery?{recovery}:{},...projected.exit_code!==void 0?{exit_code:projected.exit_code}:{}};let fallback=attachDiagnosticReceipt(candidate,boundedReceipt);for(;estimateJsonDiagnosticTokens(fallback)>budget&&boundedReceipt.omitted_fields.length>0;)boundedReceipt.omitted_fields.pop(),boundedReceipt.omitted_fields_overflow_count=receiptWithoutEstimate.omitted_fields.length-boundedReceipt.omitted_fields.length,fallback=attachDiagnosticReceipt(candidate,boundedReceipt);return fallback=shrinkMinimalDiagnosticCandidate(candidate,boundedReceipt,budget),fallback}function projectPmDiagnosticOutput(diagnostic,options={}){const diagnosticRecord=diagnostic,diagnosticClass=options.diagnosticClass??"error",contract=resolvePmDiagnosticOutputBudget(diagnosticClass),explicitBudget=options.maxEstimatedTokens;if(explicitBudget!==void 0&&(!Number.isSafeInteger(explicitBudget)||explicitBudget<contract.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${contract.minimum_max_estimated_tokens}`);const budget=explicitBudget??contract.default_max_estimated_tokens_by_format.json,originalEstimatedTokens=estimateJsonDiagnosticTokens(diagnosticRecord),originalFields=Object.keys(diagnosticRecord);if(originalEstimatedTokens<=budget)return prioritizeDiagnosticFields(structuredClone(diagnosticRecord));let projected;for(const[index,stage]of contract.degradation_ladder.entries()){const candidate=diagnosticCandidate(diagnosticRecord,stage),omittedFields=originalFields.filter(field=>!Object.hasOwn(candidate,field)),withReceipt=attachDiagnosticReceipt(candidate,{diagnostic_class:diagnosticClass,format:"json",budget,budget_source:explicitBudget===void 0?"default":"explicit",original_estimated_tokens:originalEstimatedTokens,truncated:index>0,degradation_steps:contract.degradation_ladder.slice(0,index+1),omitted_fields:omittedFields});if(projected=withReceipt,estimateJsonDiagnosticTokens(withReceipt)<=budget)break}return estimateJsonDiagnosticTokens(projected)>budget&&(projected=createMinimalDiagnosticFallback(projected,budget)),projected}function sanitizeDiagnosticText(text){return stripVTControlCharacters(text).replace(/\r\n/gu,`
|
|
2
2
|
`).replace(/[^\P{Cc}\n]/gu," ")}function projectPmDiagnosticText(output,correctiveAction,options={}){const diagnosticClass=options.diagnosticClass??"error",contract=resolvePmDiagnosticOutputBudget(diagnosticClass),explicitBudget=options.maxEstimatedTokens;if(explicitBudget!==void 0&&(!Number.isSafeInteger(explicitBudget)||explicitBudget<contract.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${contract.minimum_max_estimated_tokens}`);const budget=explicitBudget??contract.default_max_estimated_tokens_by_format.text,sanitizedOutput=sanitizeDiagnosticText(output),originalEstimatedTokens=estimatePmOutputTokens(Buffer.byteLength(sanitizedOutput,"utf8")),truncated=originalEstimatedTokens>budget,actionPrefix=`What is required:
|
|
3
3
|
`,actionSuffix=`
|
|
4
4
|
|
|
5
5
|
${truncateDiagnosticUtf8Text(sanitizedOutput.trimStart().split(/\r?\n/u,1)[0].trim(),320)}
|
|
6
6
|
|
|
7
|
-
Diagnostic output exceeded its declared ${budget}-token ceiling; rerun with structured JSON for the bounded recovery envelope.`,correctiveActionText=sanitizeDiagnosticText(correctiveAction).trim()||"Inspect the diagnostic code and retry with corrected input.",availableActionBytes=Math.max(1,budget*4-Buffer.byteLength(`${actionPrefix}${actionSuffix}`,"utf8")),projectedOutput=truncated?`${actionPrefix}${truncateDiagnosticUtf8Text(correctiveActionText,availableActionBytes)}${actionSuffix}`:sanitizedOutput;return{output:projectedOutput,diagnostic_output:{diagnostic_class:diagnosticClass,format:"text",budget,budget_source:explicitBudget===void 0?"default":"explicit",original_estimated_tokens:originalEstimatedTokens,estimated_tokens:estimatePmOutputTokens(Buffer.byteLength(projectedOutput,"utf8")),truncated,degradation_steps:truncated?[...contract.degradation_ladder]:["full"],omitted_fields:truncated?["explanation","collections"]:[]}}}export{PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,createPmCommandOutputBudget,definePmCommandOutputBudget,estimatePmOutputTokens,inferPmOutputBudgetClass,projectPmDiagnosticOutput,projectPmDiagnosticText,resolvePmCommandOutputBudget,resolvePmDiagnosticOutputBudget};
|
|
7
|
+
Diagnostic output exceeded its declared ${budget}-token ceiling; rerun with structured JSON for the bounded recovery envelope.`,correctiveActionText=sanitizeDiagnosticText(correctiveAction).trim()||"Inspect the diagnostic code and retry with corrected input.",availableActionBytes=Math.max(1,budget*4-Buffer.byteLength(`${actionPrefix}${actionSuffix}`,"utf8")),projectedOutput=truncated?`${actionPrefix}${truncateDiagnosticUtf8Text(correctiveActionText,availableActionBytes)}${actionSuffix}`:sanitizedOutput;return{output:projectedOutput,diagnostic_output:{diagnostic_class:diagnosticClass,format:"text",budget,budget_source:explicitBudget===void 0?"default":"explicit",original_estimated_tokens:originalEstimatedTokens,estimated_tokens:estimatePmOutputTokens(Buffer.byteLength(projectedOutput,"utf8")),truncated,degradation_steps:truncated?[...contract.degradation_ladder]:["full"],omitted_fields:truncated?["explanation","collections"]:[]}}}const PM_GENERIC_REFUSAL_GUIDANCE=Object.freeze({required:"Adjust command input or tracker state and retry.",why:Object.freeze(["pm enforces explicit, deterministic contracts for data and command semantics.","Commander validates CLI contracts before execution.","Unexpected runtime failures can occur from environment or extension-level issues.","Validation protects data consistency and deterministic behavior across commands.","Required options define command intent and enforce deterministic write contracts."]),examples:Object.freeze(["pm --help","pm <command> --help"])});function isGenericRefusalRequired(value){return value?.trim()===PM_GENERIC_REFUSAL_GUIDANCE.required}function isGenericRefusalWhy(value){const trimmed=value?.trim();return trimmed!==void 0&&PM_GENERIC_REFUSAL_GUIDANCE.why.includes(trimmed)}function withoutGenericRefusalExamples(values){return(values??[]).filter(value=>!PM_GENERIC_REFUSAL_GUIDANCE.examples.includes(value.trim()))}const PM_RECOVERY_ECHO_FIELDS=Object.freeze(["attempted_command","normalized_args","provided_fields"]);function projectLeanRecoveryPayload(recovery){if(!recovery)return;const{attempted_command:_attempted,normalized_args:_args,provided_fields:_fields,...specific}=recovery;return Object.values(specific).some(value=>value!==void 0)?specific:void 0}export{PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_GENERIC_REFUSAL_GUIDANCE,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PM_RECOVERY_ECHO_FIELDS,createPmCommandOutputBudget,definePmCommandOutputBudget,estimatePmOutputTokens,inferPmOutputBudgetClass,isGenericRefusalRequired,isGenericRefusalWhy,projectLeanRecoveryPayload,projectPmDiagnosticOutput,projectPmDiagnosticText,resolvePmCommandOutputBudget,resolvePmDiagnosticOutputBudget,withoutGenericRefusalExamples};
|
|
8
8
|
//# sourceMappingURL=agent-output-contracts.js.map
|