@unbrained/pm-cli 2026.11.22 → 2026.11.24
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/dist/cli/after-command-context-usage.js +1 -1
- package/dist/cli/argv-utils.js +1 -1
- package/dist/cli/bootstrap-args.js +1 -1
- package/dist/cli/bundle-integrity.js +2 -2
- package/dist/cli/command-namespaces.js +1 -1
- package/dist/cli/commander-usage.js +11 -11
- package/dist/cli/commands/annotations/comments.js +1 -1
- package/dist/cli/commands/annotations/docs.js +1 -1
- package/dist/cli/commands/annotations/files.js +1 -1
- package/dist/cli/commands/annotations/learnings.js +1 -1
- package/dist/cli/commands/annotations/notes.js +1 -1
- package/dist/cli/commands/extension/describe.js +1 -1
- package/dist/cli/commands/extension/extension.js +1 -1
- package/dist/cli/commands/extension/scaffold.js +1 -1
- package/dist/cli/commands/extension/shared.js +1 -1
- package/dist/cli/commands/governance/gc.js +1 -1
- package/dist/cli/commands/governance/health.js +1 -1
- package/dist/cli/commands/governance/telemetry.js +1 -1
- package/dist/cli/commands/governance/validate.js +1 -1
- package/dist/cli/commands/history/activity.js +1 -1
- package/dist/cli/commands/history/history-compact.js +1 -1
- package/dist/cli/commands/history/history-redact.js +1 -1
- package/dist/cli/commands/history/history-repair.js +1 -1
- package/dist/cli/commands/history/history.js +1 -1
- package/dist/cli/commands/history/restore.js +1 -1
- package/dist/cli/commands/lifecycle/append.js +1 -1
- package/dist/cli/commands/lifecycle/claim.js +1 -1
- package/dist/cli/commands/lifecycle/close-many.js +1 -1
- package/dist/cli/commands/lifecycle/close.js +1 -1
- package/dist/cli/commands/lifecycle/copy.js +1 -1
- package/dist/cli/commands/lifecycle/create.js +1 -1
- package/dist/cli/commands/lifecycle/delete.js +1 -1
- package/dist/cli/commands/lifecycle/focus.js +1 -1
- package/dist/cli/commands/lifecycle/plan.js +1 -1
- package/dist/cli/commands/lifecycle/update-many.js +1 -1
- package/dist/cli/commands/lifecycle/update.js +1 -1
- package/dist/cli/commands/query/aggregate.js +1 -1
- package/dist/cli/commands/query/context.js +1 -1
- package/dist/cli/commands/query/deps.js +1 -1
- package/dist/cli/commands/query/duplicates.js +1 -1
- package/dist/cli/commands/query/eval.js +1 -1
- package/dist/cli/commands/query/get.js +1 -1
- package/dist/cli/commands/query/graph.js +1 -1
- package/dist/cli/commands/query/list.js +1 -1
- package/dist/cli/commands/query/next.js +1 -1
- package/dist/cli/commands/query/search.js +1 -1
- package/dist/cli/commands/query/stats.js +1 -1
- package/dist/cli/commands/test/test-all.js +1 -1
- package/dist/cli/commands/test/test-runs.js +1 -1
- package/dist/cli/commands/test/test.js +1 -1
- package/dist/cli/commands/workspace/config.js +1 -1
- package/dist/cli/commands/workspace/contracts.js +1 -1
- package/dist/cli/commands/workspace/init.js +1 -1
- package/dist/cli/commands/workspace/merge.js +1 -1
- package/dist/cli/commands/workspace/profile.js +1 -1
- package/dist/cli/commands/workspace/schema.js +1 -1
- package/dist/cli/commands/workspace/upgrade.js +1 -1
- package/dist/cli/context-intent-invocation.js +1 -1
- package/dist/cli/description-stdin.js +1 -1
- package/dist/cli/error-guidance.js +5 -5
- package/dist/cli/expected-revisions.js +1 -1
- package/dist/cli/extension-command-help.js +6 -6
- package/dist/cli/extension-recovery.js +1 -1
- package/dist/cli/help-content.js +5 -5
- package/dist/cli/help-json-payload.js +7 -7
- package/dist/cli/invocation-profile.js +2 -2
- package/dist/cli/main.js +5 -5
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/option-values.js +1 -1
- package/dist/cli/preflight-warnings.js +3 -3
- package/dist/cli/public.js +1 -1
- package/dist/cli/register-annotations.js +1 -1
- package/dist/cli/register-assurance.js +1 -1
- package/dist/cli/register-files-lookup.js +1 -1
- package/dist/cli/register-history-activity.js +1 -1
- package/dist/cli/register-history-author.js +1 -1
- package/dist/cli/register-history-maintenance.js +2 -2
- package/dist/cli/register-list-query.js +10 -10
- package/dist/cli/register-mutation-options.js +0 -1
- package/dist/cli/register-mutation.js +6 -6
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli/registration-helpers.js +1 -1
- package/dist/cli/runtime/activation.js +1 -1
- package/dist/cli/runtime/annotation-option-retry.js +1 -1
- package/dist/cli/runtime/close-fields-retry.js +1 -1
- package/dist/cli/runtime/field-route-retry.js +1 -1
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli/runtime/invocation-rewrites.js +1 -1
- package/dist/cli/runtime/projection-retry.js +1 -1
- package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
- package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
- package/dist/cli/runtime/selection.js +1 -1
- package/dist/cli/runtime/telemetry-outcome.js +1 -1
- package/dist/cli/runtime-compatibility-boundary.js +4 -4
- package/dist/cli/schema/registration.js +15 -15
- package/dist/cli/schema-registration-helpers.js +1 -1
- package/dist/cli/search-refresh.js +1 -1
- package/dist/cli/stats-analytics-json.js +1 -1
- package/dist/cli/telemetry-flush.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-23K6DQQY.js +9 -0
- package/dist/cli-bundle/chunks/chunk-37UDIJ2K.js +3 -0
- package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
- package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
- package/dist/cli-bundle/chunks/chunk-7IROAPWI.js +3 -0
- package/dist/cli-bundle/chunks/chunk-7VRFEURZ.js +33 -0
- package/dist/cli-bundle/chunks/chunk-7X253M6Z.js +3 -0
- package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
- package/dist/cli-bundle/chunks/chunk-AWB5KBJS.js +2 -0
- package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
- package/dist/cli-bundle/chunks/chunk-DQDRA3SW.js +2 -0
- package/dist/cli-bundle/chunks/chunk-FXJYZBWV.js +113 -0
- package/dist/cli-bundle/chunks/chunk-HNKK2UG6.js +8 -0
- package/dist/cli-bundle/chunks/chunk-HZZLSBIJ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-I2OJ5B4A.js +2 -0
- package/dist/cli-bundle/chunks/chunk-I3BFCKZR.js +2 -0
- package/dist/cli-bundle/chunks/chunk-MXUSC5RS.js +31 -0
- package/dist/cli-bundle/chunks/chunk-PLIUU37C.js +3 -0
- package/dist/cli-bundle/chunks/chunk-PQUBVRV5.js +2 -0
- package/dist/cli-bundle/chunks/chunk-PW7U7WCE.js +3 -0
- package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
- package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
- package/dist/cli-bundle/chunks/chunk-SSALO4DB.js +2 -0
- package/dist/cli-bundle/chunks/chunk-STOOTHZZ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-TKRY22SO.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-B76TFRO2.js → chunk-TVIJ2VCU.js} +93 -93
- package/dist/cli-bundle/chunks/chunk-VJSGUXGU.js +3 -0
- package/dist/cli-bundle/chunks/chunk-WWTPNIC2.js +6 -0
- package/dist/cli-bundle/chunks/chunk-XFADNMGD.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YOPTAIBD.js +125 -0
- package/dist/cli-bundle/chunks/chunk-YW2HBHRO.js +70 -0
- package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
- package/dist/cli-bundle/chunks/chunk-Z7MFVRDV.js +2 -0
- package/dist/cli-bundle/chunks/chunk-ZOX4SWRL.js +8 -0
- package/dist/cli-bundle/chunks/chunk-ZYCOM4MS.js +9 -0
- package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
- package/dist/cli-bundle/chunks/field-option-collisions-W66HSWMK.js +2 -0
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
- package/dist/cli-bundle/{focused-chunks/item-revision-2O6MLPEX.js → chunks/item-revision-D3LSBNIR.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-M6NTBYH3.js +2 -0
- package/dist/cli-bundle/chunks/mutation-actor-OKL3CQVX.js +2 -0
- package/dist/cli-bundle/chunks/mutation-admission-EKPEOZMF.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-RR5KACJ3.js → register-list-query-3LBV6CS2.js} +11 -11
- package/dist/cli-bundle/chunks/register-mutation-72AGTMNE.js +21 -0
- package/dist/cli-bundle/chunks/register-operations-XERFG2SH.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-W22L34Z4.js +2 -0
- package/dist/cli-bundle/chunks/runtime-schema-JP2KBHBY.js +2 -0
- package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
- package/dist/cli-bundle/chunks/stage-T2LKWN7C.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-24VRBNKE.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-3ELVASVA.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-3GT4A3ZN.js +44 -0
- package/dist/cli-bundle/focused-chunks/chunk-3OCDKITJ.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-3Z7MCUJM.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-46MP7IZN.js +5 -0
- package/dist/cli-bundle/focused-chunks/chunk-5LDBS6MS.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-B6BNHKUW.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
- package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-C7WHWI7K.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-EUQGZPGO.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-FDZPRJXJ.js +27 -0
- package/dist/cli-bundle/focused-chunks/chunk-GXP7Q4XM.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-HL47UQZJ.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-LMFIAQ2V.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-LMU7DDOA.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-OZOCEB2Q.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-Q2HY44LV.js +13 -0
- package/dist/cli-bundle/focused-chunks/chunk-REFMQY47.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
- package/dist/cli-bundle/focused-chunks/chunk-RIQUIHYU.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-RLO2HCZT.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-SMMOZ3H3.js +100 -0
- package/dist/cli-bundle/focused-chunks/chunk-UVTUX54T.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-XDBHD4CY.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-YD66IRSL.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Z7W2RQIB.js +2 -0
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
- package/dist/cli-bundle/focused-chunks/field-option-collisions-UODPSV6W.js +2 -0
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
- package/dist/cli-bundle/focused-chunks/item-revision-QH7RNBX4.js +2 -0
- package/dist/cli-bundle/focused-chunks/item-transaction-ZO72OINF.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-actor-PHVLKG4I.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-ZSG5OECH.js +2 -0
- package/dist/cli-bundle/focused-chunks/runtime-schema-6RQMIDTN.js +2 -0
- package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
- package/dist/cli-bundle/focused-chunks/stage-AQMKRVX4.js +2 -0
- package/dist/cli-bundle/main.js +27 -27
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +5 -5
- package/dist/cli-bundle/sdk-core.js +1 -1
- 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 +66 -66
- 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 +13 -13
- package/dist/cli.js +1 -1
- package/dist/core/checkpoint/checkpoint-gc.js +1 -1
- package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
- package/dist/core/checkpoint/mutation-context.js +1 -1
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/config/positional-value.js +1 -1
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/extensions/activation-summary-markdown.js +2 -2
- package/dist/core/extensions/activation-summary.js +1 -1
- package/dist/core/extensions/activation-transaction.js +1 -1
- package/dist/core/extensions/capability-usage.js +1 -1
- package/dist/core/extensions/command-hook-context.js +1 -1
- package/dist/core/extensions/command-metadata-contract.js +1 -1
- package/dist/core/extensions/command-visibility-tier.js +1 -1
- package/dist/core/extensions/contribution-inventory.js +1 -1
- package/dist/core/extensions/exporter-output-contract.js +1 -1
- package/dist/core/extensions/extension-candidate.js +1 -1
- package/dist/core/extensions/extension-capability-aliases.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-policy.js +1 -1
- package/dist/core/extensions/extension-registries.js +1 -1
- package/dist/core/extensions/extension-runtime-helpers.js +1 -1
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/flag-definition-validation.js +1 -1
- package/dist/core/extensions/flag-value-types.js +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/item-field-types.js +1 -1
- package/dist/core/extensions/item-fields.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/manifest-parser.js +1 -1
- package/dist/core/extensions/manifest-schema.js +1 -1
- package/dist/core/extensions/module-graph-snapshot.js +1 -1
- package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
- package/dist/core/extensions/mutation-actor.js +1 -1
- package/dist/core/extensions/preflight-ownership.js +1 -1
- package/dist/core/extensions/read-output-contract.js +1 -1
- package/dist/core/extensions/registration-contracts.js +1 -1
- package/dist/core/extensions/registration-validation.js +1 -1
- package/dist/core/extensions/registration-values.js +1 -1
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/extensions/runtime-registrations.js +1 -1
- package/dist/core/extensions/service-ownership.js +1 -1
- package/dist/core/extensions/version-compat.js +1 -1
- package/dist/core/extensions/version-diagnostics.js +1 -1
- package/dist/core/fs/atomic-create.js +1 -1
- package/dist/core/fs/file-glob.js +1 -1
- package/dist/core/fs/fs-utils.js +2 -2
- package/dist/core/fs/host-environment-errors.js +1 -1
- package/dist/core/fs/index.js +1 -1
- package/dist/core/fs/path-utils.js +1 -1
- package/dist/core/governance/content-fields.js +1 -1
- package/dist/core/governance/issue-codes.js +1 -1
- package/dist/core/governance/metadata-coverage.js +1 -1
- package/dist/core/history/bridge.js +1 -1
- package/dist/core/history/digest.js +1 -1
- package/dist/core/history/drift-cache.js +3 -3
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/event-classification.js +1 -1
- package/dist/core/history/event-index.js +11 -11
- package/dist/core/history/history-compact-bulk.js +1 -1
- package/dist/core/history/history-diff.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/history/history-storage-stats.js +1 -1
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/history.js +2 -2
- package/dist/core/history/identity.js +1 -1
- package/dist/core/history/index.js +1 -1
- package/dist/core/history/operation-contract.js +1 -1
- package/dist/core/history/projection.js +1 -1
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/replay.js +2 -2
- package/dist/core/history/stream-summary.js +2 -2
- package/dist/core/history/tombstone.js +1 -1
- package/dist/core/history/version-address.js +1 -1
- package/dist/core/history/workspace-history.js +2 -2
- package/dist/core/io/body-file.js +1 -1
- package/dist/core/io/bulk-ids-input.js +2 -2
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/item/deferred-fields.js +1 -1
- package/dist/core/item/dependency-reference.js +1 -1
- package/dist/core/item/id.js +1 -1
- package/dist/core/item/index.js +1 -1
- package/dist/core/item/item-format-version.js +1 -1
- package/dist/core/item/item-format.js +7 -7
- package/dist/core/item/item-record.js +1 -1
- package/dist/core/item/item-type-definition.js +1 -1
- package/dist/core/item/literal-mutation-input.js +1 -1
- package/dist/core/item/parent-reference-policy.js +1 -1
- package/dist/core/item/parse.js +8 -8
- package/dist/core/item/plan-lifecycle.js +1 -1
- package/dist/core/item/priority.js +1 -1
- package/dist/core/item/sprint-release-format.js +1 -1
- package/dist/core/item/status-filter.js +1 -1
- package/dist/core/item/status.js +1 -1
- package/dist/core/item/toon-decode.js +1 -1
- package/dist/core/item/type-registry.js +1 -1
- package/dist/core/item/type-synonyms.js +1 -1
- package/dist/core/lock/index.js +1 -1
- package/dist/core/lock/lock-confinement.js +1 -1
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock-owner.js +1 -1
- package/dist/core/lock/lock.js +4 -4
- package/dist/core/output/linked-test-projection.js +5 -5
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/output/output-control.js +1 -1
- package/dist/core/output/output.js +19 -19
- package/dist/core/output/query-summary.js +1 -1
- package/dist/core/output/tabular.js +3 -3
- package/dist/core/packages/manifest.js +1 -1
- package/dist/core/packages/root.js +1 -1
- package/dist/core/policy/workflow-policy-schema.js +1 -1
- package/dist/core/policy/workflow-policy-store.js +1 -1
- package/dist/core/policy/workflow-policy.js +1 -1
- package/dist/core/profile/profile-describe.js +1 -1
- package/dist/core/profile/profile-lint.d.ts +1 -1
- package/dist/core/profile/profile-lint.js +1 -1
- package/dist/core/profile/profile-plan.js +1 -1
- package/dist/core/profile/profile-presets.js +4 -4
- package/dist/core/reproducibility/context.js +1 -1
- package/dist/core/schema/fields-file.js +2 -2
- package/dist/core/schema/item-types-file.js +2 -2
- package/dist/core/schema/runtime-field-filters.js +1 -1
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/schema/runtime-schema.d.ts +2 -0
- package/dist/core/schema/runtime-schema.js +2 -2
- package/dist/core/schema/status-defs-file.js +2 -2
- package/dist/core/schema/status-token.js +1 -1
- package/dist/core/schema/type-inference.js +1 -1
- package/dist/core/schema/type-presets.js +1 -1
- package/dist/core/schema/type-workflows.js +1 -1
- package/dist/core/search/background-refresh.js +2 -2
- package/dist/core/search/bm25.js +1 -1
- package/dist/core/search/cache.js +2 -2
- package/dist/core/search/corpus.js +1 -1
- package/dist/core/search/embedding-batches.js +1 -1
- package/dist/core/search/eval-thresholds.js +1 -1
- package/dist/core/search/eval.js +1 -1
- package/dist/core/search/http-client.js +1 -1
- package/dist/core/search/providers.js +1 -1
- package/dist/core/search/relevance.js +1 -1
- package/dist/core/search/semantic-defaults.js +1 -1
- package/dist/core/search/staleness.js +1 -1
- package/dist/core/search/vector-stores.js +2 -2
- package/dist/core/search/vectorization-metadata.js +1 -1
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/sentry/sensitive-assignments.js +1 -1
- package/dist/core/session/session-state.js +1 -1
- package/dist/core/shared/agent-session-context.js +1 -1
- package/dist/core/shared/author.js +5 -5
- package/dist/core/shared/command-line.js +1 -1
- package/dist/core/shared/command-types.js +0 -1
- package/dist/core/shared/conflict-markers.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/error-details.js +1 -1
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/html-entity-decode.js +1 -1
- package/dist/core/shared/index.js +1 -1
- package/dist/core/shared/item-metadata-contract.js +1 -1
- package/dist/core/shared/lazy-module.js +1 -1
- package/dist/core/shared/levenshtein.js +1 -1
- package/dist/core/shared/memo.js +1 -1
- package/dist/core/shared/numeric-parsers.js +1 -1
- package/dist/core/shared/option-alias-visibility.js +1 -1
- package/dist/core/shared/output-unicode.js +1 -1
- package/dist/core/shared/primitives.js +1 -1
- package/dist/core/shared/process-tree.js +2 -2
- package/dist/core/shared/secret-rules.js +5 -5
- package/dist/core/shared/serial-queue.js +1 -1
- package/dist/core/shared/serialization.js +1 -1
- package/dist/core/shared/split-comma-list.js +1 -1
- package/dist/core/shared/text-normalization.js +1 -1
- package/dist/core/shared/time.js +2 -2
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/core/store/index.js +1 -1
- package/dist/core/store/item-format-migration.js +1 -1
- package/dist/core/store/item-metadata-cache.js +1 -1
- package/dist/core/store/item-metadata-query-index.js +11 -11
- package/dist/core/store/item-metadata-read-work.js +1 -1
- package/dist/core/store/item-mutation-precondition.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/paths.js +1 -1
- package/dist/core/store/settings-concurrency.js +1 -1
- package/dist/core/store/settings-read-cache.js +1 -1
- package/dist/core/store/settings-sections.js +2 -2
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.d.ts +3 -1
- package/dist/core/store/settings.js +6 -6
- package/dist/core/store/sqlite-runtime.js +1 -1
- package/dist/core/store/tracker-preflight.js +1 -1
- package/dist/core/store/transaction-coordinator-scope.js +1 -1
- package/dist/core/telemetry/consent.js +3 -3
- package/dist/core/telemetry/observability.js +1 -1
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/read-sampling.js +2 -2
- package/dist/core/telemetry/runtime.js +9 -9
- package/dist/core/test/background-runs.js +4 -4
- package/dist/core/test/item-test-run-tracking.js +1 -1
- package/dist/core/test/run-selectors.js +1 -1
- package/dist/core/validate/estimate-defaults.js +1 -1
- package/dist/core/validate/fix-planning.js +1 -1
- package/dist/core/validate/linked-artifact-reference.js +1 -1
- package/dist/core/validate/missing-by-type.js +1 -1
- package/dist/core/validate/missing-link-owners.js +1 -1
- package/dist/core/validate/stale-file-classification.js +1 -1
- package/dist/mcp/http-server.js +5 -5
- package/dist/mcp/legacy-adapter.js +1 -1
- package/dist/mcp/runtime-capabilities.js +1 -1
- package/dist/mcp/server.js +4 -4
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/actionability.js +1 -1
- package/dist/sdk/agent/closed-domain-contracts.js +1 -1
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/agent/command-suggestions.js +1 -1
- package/dist/sdk/agent/create-option-policy.js +1 -1
- package/dist/sdk/agent/identity-config.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent/linked-resource-recovery.js +1 -1
- package/dist/sdk/agent/refusal-closure-census.js +2 -2
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
- package/dist/sdk/agent/subcommand-recovery.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +3 -3
- package/dist/sdk/agent-session-context.js +1 -1
- package/dist/sdk/annotations.js +1 -1
- package/dist/sdk/author-attribution.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/commander-types.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
- package/dist/sdk/cli-contracts/string-lists.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.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/typed-action-inputs.js +0 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/cli-program.js +1 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/comments.js +1 -1
- package/dist/sdk/compile-cache.js +1 -1
- package/dist/sdk/completion/bash.js +2 -2
- package/dist/sdk/completion/fish.js +72 -72
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/completion/zsh.js +75 -75
- package/dist/sdk/completion.js +1 -1
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/context/recency.js +1 -1
- package/dist/sdk/context/semantic-session-attribution.js +1 -1
- package/dist/sdk/context/usage-egress.js +1 -1
- package/dist/sdk/context/usage-ledger.js +6 -6
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/context-intent-runtime.js +1 -1
- package/dist/sdk/context-packing.js +1 -1
- package/dist/sdk/context-relevance.js +1 -1
- package/dist/sdk/context-signal-store.js +2 -2
- package/dist/sdk/context-usage.js +1 -1
- package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/dependency-flag-validation.js +1 -1
- package/dist/sdk/dependency-provenance.js +1 -1
- package/dist/sdk/docs.js +1 -1
- package/dist/sdk/duplicates.js +1 -1
- package/dist/sdk/environment/host-environment-errors.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
- package/dist/sdk/environment/source-context.js +1 -1
- package/dist/sdk/environment/tracker-preflight.js +1 -1
- package/dist/sdk/error-code-catalog.js +1 -1
- package/dist/sdk/error-runtime.js +1 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/eval.js +1 -1
- package/dist/sdk/extension/author-manifest.js +1 -1
- package/dist/sdk/extension/bundled-catalog.js +1 -1
- package/dist/sdk/extension/command-options.d.ts +26 -1
- package/dist/sdk/extension/command-options.js +1 -1
- package/dist/sdk/extension/concurrency.js +1 -1
- package/dist/sdk/extension/copy-scope.js +1 -1
- package/dist/sdk/extension/custom-field-collisions.js +1 -1
- package/dist/sdk/extension/describe.js +3 -3
- package/dist/sdk/extension/doctor.js +1 -1
- package/dist/sdk/extension/install-plan.js +1 -1
- package/dist/sdk/extension/install-receipts.js +1 -1
- package/dist/sdk/extension/install-runtime.js +3 -3
- package/dist/sdk/extension/install-snapshot.js +1 -1
- package/dist/sdk/extension/install-sources.js +5 -5
- package/dist/sdk/extension/managed-state.js +2 -2
- package/dist/sdk/extension/managed-update-status.js +1 -1
- package/dist/sdk/extension/migrations.js +2 -2
- package/dist/sdk/extension/native-command-options.js +1 -1
- package/dist/sdk/extension/output-ownership.js +1 -1
- package/dist/sdk/extension/runtime-summary.js +1 -1
- package/dist/sdk/extension/scaffold.js +11 -11
- package/dist/sdk/extension/shared.js +1 -1
- package/dist/sdk/extension/source-resolution.js +1 -1
- package/dist/sdk/extension/static-inventory.js +1 -1
- package/dist/sdk/extension/update-check.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/extension-contracts.js +1 -1
- package/dist/sdk/extension.js +1 -1
- package/dist/sdk/files.js +1 -1
- package/dist/sdk/flag-invocation-contracts.js +1 -1
- package/dist/sdk/generated/error-code-catalog-rows.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/generated-error-code-catalog.js +1 -1
- package/dist/sdk/governance/assurance-action-contracts.js +0 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance-limits.js +1 -1
- package/dist/sdk/governance/assurance-mutation-error.js +1 -1
- package/dist/sdk/governance/assurance-presets.js +1 -1
- package/dist/sdk/governance/assurance-runtime.js +1 -1
- package/dist/sdk/governance/assurance.js +4 -4
- package/dist/sdk/governance/boundary-fixtures.js +1 -1
- package/dist/sdk/governance/closure-timestamps.js +1 -1
- package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
- package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
- package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
- package/dist/sdk/governance/defect-recurrence.js +2 -2
- package/dist/sdk/governance/extension-host-version.js +1 -1
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health/history-drift-remedies.js +1 -1
- package/dist/sdk/governance/health/projection.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/governance/hierarchy-validation.js +1 -1
- package/dist/sdk/governance/in-progress-work-health.js +1 -1
- package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
- package/dist/sdk/governance/linked-file-report.js +1 -1
- package/dist/sdk/governance/merge-receipt-history.js +1 -1
- package/dist/sdk/governance/provenance-health.js +4 -4
- package/dist/sdk/governance/reindex.js +5 -5
- package/dist/sdk/governance/stale-work.js +1 -1
- package/dist/sdk/governance/status-role-diagnostics.js +1 -1
- package/dist/sdk/governance/storage-integrity.js +1 -1
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
- package/dist/sdk/governance/upgrade.js +2 -2
- package/dist/sdk/governance/validate-deferred-fields.js +1 -1
- package/dist/sdk/governance/validate-history-drift.js +1 -1
- package/dist/sdk/governance/validate-item-reader.js +1 -1
- package/dist/sdk/governance/validate-normalization.js +1 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workflow-completeness.js +1 -1
- package/dist/sdk/governance/workflow-policy.js +3 -3
- package/dist/sdk/governance/workspace-position.js +2 -2
- package/dist/sdk/graph/analytics.js +1 -1
- package/dist/sdk/graph/assembly.js +1 -1
- package/dist/sdk/graph/cache.js +1 -1
- package/dist/sdk/graph/cardinality-integrity.js +1 -1
- package/dist/sdk/graph/centrality.js +1 -1
- package/dist/sdk/graph/deadline-scheduling.js +1 -1
- package/dist/sdk/graph/durable-cache.js +1 -1
- package/dist/sdk/graph/governance-contracts.js +1 -1
- package/dist/sdk/graph/governance.js +1 -1
- package/dist/sdk/graph/hierarchy-integrity.js +1 -1
- package/dist/sdk/graph/lifecycle-coverage.js +1 -1
- package/dist/sdk/graph/mutation-advisory.js +1 -1
- package/dist/sdk/graph/query-contracts.js +1 -1
- package/dist/sdk/graph/remediation.js +1 -1
- package/dist/sdk/graph/run.js +1 -1
- package/dist/sdk/graph/scheduling.js +1 -1
- package/dist/sdk/graph/traversal.js +1 -1
- package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
- package/dist/sdk/guide-topics.js +1 -1
- package/dist/sdk/guide.js +7 -7
- package/dist/sdk/history/append-only-repair.js +4 -4
- package/dist/sdk/history/attestation-command.js +2 -2
- package/dist/sdk/history/attestation-contract.js +1 -1
- package/dist/sdk/history/attestation-scan.js +1 -1
- package/dist/sdk/history/attestation.js +1 -1
- package/dist/sdk/history/maintenance.js +1 -1
- package/dist/sdk/history/reanchor-refusal.js +1 -1
- package/dist/sdk/history/reseed.js +1 -1
- package/dist/sdk/history/salvage.js +5 -5
- package/dist/sdk/history/subject.js +1 -1
- package/dist/sdk/history-analytics.js +1 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-mcp.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/history-read.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/improvement-ledger-validation.js +1 -1
- package/dist/sdk/improvement-ledger.js +2 -2
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/init-agent-guidance.js +10 -10
- package/dist/sdk/init.js +14 -14
- package/dist/sdk/invocation-author.js +1 -1
- package/dist/sdk/item-children.js +1 -1
- package/dist/sdk/item-metadata-index.js +1 -1
- package/dist/sdk/item-schedule.js +1 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/learnings.js +1 -1
- package/dist/sdk/lifecycle/append.js +3 -3
- package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/cli-input.js +1 -1
- package/dist/sdk/lifecycle/close-many.js +1 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/copy.js +1 -1
- package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
- package/dist/sdk/lifecycle/core-item-fields.js +1 -1
- package/dist/sdk/lifecycle/create-deferrals.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/delete.js +1 -1
- package/dist/sdk/lifecycle/dependency-removal.js +1 -1
- package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
- package/dist/sdk/lifecycle/focus.js +1 -1
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
- package/dist/sdk/lifecycle/item-revision.js +1 -1
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
- package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
- package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
- package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
- package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
- package/dist/sdk/lifecycle/release-handoff.js +1 -1
- package/dist/sdk/lifecycle/reopen.js +1 -1
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
- package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/start-blockers.js +1 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/lifecycle/workflow-transition.js +1 -1
- package/dist/sdk/lifecycle-completion.js +1 -1
- package/dist/sdk/lifecycle-policy.js +1 -1
- package/dist/sdk/linked-artifacts.js +2 -2
- package/dist/sdk/mcp/apps.js +5 -5
- package/dist/sdk/mcp/authorization.js +1 -1
- package/dist/sdk/mcp/discovery.js +1 -1
- package/dist/sdk/mcp/executable.js +4 -4
- package/dist/sdk/mcp/interactions.js +1 -1
- package/dist/sdk/mcp/protocol.js +1 -1
- package/dist/sdk/mcp/skills.js +3 -3
- package/dist/sdk/mcp/subscriptions.js +1 -1
- package/dist/sdk/mcp/tasks.js +2 -2
- package/dist/sdk/mcp/transport.js +1 -1
- package/dist/sdk/merge/abandoned-receipts.js +1 -1
- package/dist/sdk/merge/driver.js +7 -7
- package/dist/sdk/merge/history-scalar-rebase.js +1 -1
- package/dist/sdk/merge/ignored-artifacts.js +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
- package/dist/sdk/merge/install.js +6 -6
- package/dist/sdk/merge/receipt-file-boundary.js +1 -1
- package/dist/sdk/merge/receipt-operation.js +1 -1
- package/dist/sdk/merge/receipt-schema.js +1 -1
- package/dist/sdk/merge/receipts.js +4 -4
- package/dist/sdk/merge/reconcile.js +1 -1
- package/dist/sdk/merge/settlement-hook.js +4 -4
- package/dist/sdk/merge/stage.js +1 -1
- package/dist/sdk/merge/three-way.js +9 -9
- package/dist/sdk/merge/worktree-config.js +2 -2
- package/dist/sdk/merge.js +1 -1
- package/dist/sdk/mutation-events.js +1 -1
- package/dist/sdk/mutation-guard.js +1 -1
- package/dist/sdk/notes.js +1 -1
- package/dist/sdk/output/fit-envelope.js +1 -1
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/output/table-rows.js +1 -1
- package/dist/sdk/output-contracts.js +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/output-token-accounting.js +1 -1
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/package-import-adapters.js +1 -1
- package/dist/sdk/package-migrations.js +1 -1
- package/dist/sdk/package-runtime-options.js +1 -1
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/profile.js +5 -5
- package/dist/sdk/provenance.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.js +1 -1
- package/dist/sdk/query/aggregate.js +1 -1
- package/dist/sdk/query/calendar.js +4 -4
- package/dist/sdk/query/complete-list.js +1 -1
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/declared-blockers.js +1 -1
- package/dist/sdk/query/duplicate-candidates.js +1 -1
- package/dist/sdk/query/get-facet-roots.js +1 -1
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/query/item-filter-options.js +0 -1
- package/dist/sdk/query/light-metadata.js +1 -1
- package/dist/sdk/query/list-filter-shared.js +1 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/multi-value-filters.js +1 -1
- package/dist/sdk/query/next-ranking-policy.js +1 -1
- package/dist/sdk/query/next-ready-budget.js +1 -1
- package/dist/sdk/query/next.js +2 -2
- package/dist/sdk/query/parsers.js +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/query/search/corpus.js +2 -2
- package/dist/sdk/query/search/filters.js +1 -1
- package/dist/sdk/query/search/input.js +1 -1
- package/dist/sdk/query/search/lexical.js +1 -1
- package/dist/sdk/query/search/response.js +1 -1
- package/dist/sdk/query/search/semantic.js +3 -3
- package/dist/sdk/query/search/types.js +0 -1
- package/dist/sdk/query/search-contracts.js +1 -1
- package/dist/sdk/query/search-pagination.js +1 -1
- package/dist/sdk/query/search-rendering.js +1 -1
- package/dist/sdk/query/search.js +1 -1
- package/dist/sdk/query/window-pagination.js +1 -1
- package/dist/sdk/query/workspace-contracts.js +1 -1
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output/extension.js +1 -1
- package/dist/sdk/read-output/options.js +1 -1
- package/dist/sdk/read-output/positional-rows.js +1 -1
- package/dist/sdk/read-output/provenance.js +1 -1
- package/dist/sdk/read-output/session-result.js +0 -1
- package/dist/sdk/read-output/surfaces.js +1 -1
- package/dist/sdk/read-output/tail-retention.js +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.d.ts +11 -0
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-rows.js +1 -1
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/relationship-analytics.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/relationship-history.js +6 -6
- package/dist/sdk/relationship-kinds/contract.js +1 -1
- package/dist/sdk/relationships.js +1 -1
- package/dist/sdk/reproducibility/process.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime/context.js +1 -1
- package/dist/sdk/runtime/mutation-admission.js +1 -1
- package/dist/sdk/runtime/mutation-value-validation.js +1 -1
- package/dist/sdk/runtime/schema-preview.js +1 -1
- package/dist/sdk/runtime/schema.js +1 -1
- package/dist/sdk/runtime-action-aliases.js +1 -1
- package/dist/sdk/runtime-extended-actions.js +1 -1
- package/dist/sdk/runtime-input.d.ts +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime-public-contracts.js +0 -1
- package/dist/sdk/runtime-stats-options.js +1 -1
- package/dist/sdk/runtime.d.ts +5 -3
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/scheduling-shortcuts.js +1 -1
- package/dist/sdk/schema/field-flag-spelling.d.ts +22 -0
- package/dist/sdk/schema/field-flag-spelling.js +2 -0
- package/dist/sdk/schema/field-option-collisions.js +2 -0
- package/dist/sdk/schema-migration.js +4 -4
- package/dist/sdk/schema.js +7 -7
- package/dist/sdk/search-refresh-worker.js +1 -1
- package/dist/sdk/similarity-scoring.js +1 -1
- package/dist/sdk/similarity.js +1 -1
- package/dist/sdk/start-task-status.js +1 -1
- package/dist/sdk/stats.js +1 -1
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/telemetry-flush.js +1 -1
- package/dist/sdk/telemetry.js +4 -4
- package/dist/sdk/templates.js +3 -3
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/command-args.js +1 -1
- package/dist/sdk/test/command-resolution.js +2 -2
- package/dist/sdk/test/entry.js +2 -2
- package/dist/sdk/test/execution-receipts.js +2 -2
- package/dist/sdk/test/execution.js +5 -5
- package/dist/sdk/test/json-path.js +1 -1
- package/dist/sdk/test/linked-command-detection.js +1 -1
- package/dist/sdk/test/measurements.js +1 -1
- package/dist/sdk/test/parsers.js +1 -1
- package/dist/sdk/test/prerequisites.js +1 -1
- package/dist/sdk/test/receipt-index-snapshot.js +1 -1
- package/dist/sdk/test/run-phases.js +1 -1
- package/dist/sdk/test/runs.js +1 -1
- package/dist/sdk/test/trust.js +2 -2
- package/dist/sdk/test/update.js +1 -1
- package/dist/sdk/test/workspace-snapshot.js +1 -1
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
- package/dist/sdk/traceability/source-traceability.js +2 -2
- package/dist/sdk/tracker-root-discovery.js +1 -1
- package/dist/sdk/transactions/item-finalization.js +1 -1
- package/dist/sdk/workspace-contracts-cache.js +1 -1
- package/dist/sdk/workspace-contracts.js +1 -1
- package/dist/sdk/workspace-memory.js +2 -2
- package/dist/sdk/workspace-snapshot.js +5 -5
- package/dist/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.js +2 -2
- package/dist/sdk/workspace.js +6 -6
- package/dist/types/index.js +1 -1
- package/dist/types.js +1 -1
- package/docs/COMMANDS.md +1 -1
- package/docs/EXTENSIONS.md +2 -2
- package/docs/READ_OUTPUT_CONTRACTS.md +2 -0
- package/docs/SDK.md +94 -5
- package/docs/SDK_AUDITED_MUTATIONS.md +11 -0
- package/marketplace.json +1 -1
- package/package.json +2 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-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/scripts/finalize-build.mjs +63 -24
- package/scripts/prepare-build-cache.mjs +28 -1
- package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +0 -9
- package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +0 -125
- package/dist/cli-bundle/chunks/chunk-5ZMVLWE3.js +0 -2
- package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +0 -33
- package/dist/cli-bundle/chunks/chunk-AR4NP5HI.js +0 -3
- package/dist/cli-bundle/chunks/chunk-B4PPFOPY.js +0 -3
- package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +0 -8
- package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-EIGUKEV6.js +0 -2
- package/dist/cli-bundle/chunks/chunk-GTPCAJMZ.js +0 -8
- package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +0 -2
- package/dist/cli-bundle/chunks/chunk-HC2OPETM.js +0 -2
- package/dist/cli-bundle/chunks/chunk-HKUV74K3.js +0 -2
- package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +0 -115
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-J2LABXBL.js +0 -2
- package/dist/cli-bundle/chunks/chunk-J52BEBSS.js +0 -2
- package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
- package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
- package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +0 -31
- package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-TC6XLIYO.js +0 -2
- package/dist/cli-bundle/chunks/chunk-U7EL3AYA.js +0 -3
- package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +0 -6
- package/dist/cli-bundle/chunks/chunk-X6MIWTTT.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XFHPKXAE.js +0 -71
- package/dist/cli-bundle/chunks/chunk-YHVLVSEZ.js +0 -9
- package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
- package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
- package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
- package/dist/cli-bundle/chunks/item-revision-4QBMZXKX.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +0 -2
- package/dist/cli-bundle/chunks/mutation-actor-FWLYWJ37.js +0 -2
- package/dist/cli-bundle/chunks/mutation-admission-7ZDCK3G2.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-57AJQWFV.js +0 -21
- package/dist/cli-bundle/chunks/register-operations-RKWST7CU.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-CMI23PC5.js +0 -2
- package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
- package/dist/cli-bundle/chunks/stage-4KDVXC5Z.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2ZD7275J.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-324AHXJO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
- package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-4JZITIJB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-BRZV7BFV.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HDEKFSOK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IWOXAUDU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-ML3JHCC6.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-OPGOOP25.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-RE7ZWT7D.js +0 -27
- package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-URGHTTT3.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +0 -13
- package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-WZWXGDYY.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-YKSLZPLT.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +0 -2
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
- package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-actor-TCYDPUGG.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-LY73EJWM.js +0 -2
- package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
- package/dist/cli-bundle/focused-chunks/stage-DQ7RQQ52.js +0 -2
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(raw))return!0;const firstCommaIndex=raw.indexOf(","),leadingSegment=raw.slice(0,firstCommaIndex>=0?firstCommaIndex:raw.length),equalsIndex=leadingSegment.indexOf("=");return equalsIndex>=0&&!/\s/u.test(raw)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(raw)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(raw)||[raw.indexOf("/"),raw.indexOf("\\")].some(separatorIndex=>separatorIndex>=0&&separatorIndex<equalsIndex))?!1:leadingSegment.includes("=")||looksLikeGenericKeyValueEntry(raw)}function hasBalancedParentheses(value){let depth=0;for(const character of value)if(character==="("&&(depth+=1),character===")"&&(depth-=1),depth<0)return!1;return depth===0}function parseDocumentationReference(trimmed){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(trimmed)&&!looksLikeStructuredPathEntry(trimmed))return{path:trimmed,scope:"project",note:void 0};const labelEnd=trimmed.indexOf("](");if(trimmed.startsWith("[")&&labelEnd>0&&trimmed.endsWith(")")){const destination2=trimmed.slice(labelEnd+2,-1).trim();if(destination2.length>0&&hasBalancedParentheses(destination2))return{path:destination2,scope:"project",note:trimmed.slice(1,labelEnd).trim()||void 0}}const delimiterIndex=trimmed.indexOf(",");if(delimiterIndex<0)return;const label=trimmed.slice(0,delimiterIndex).trim(),destination=trimmed.slice(delimiterIndex+1).trim();if(!(label.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(destination)))return{path:destination,scope:"project",note:label}}function parseAddEntries(raw,bareNoun){return raw?raw.flatMap(entry=>{const trimmed=entry.trim();if(bareNoun==="doc"){const reference=parseDocumentationReference(trimmed);if(reference!==void 0)return[reference]}assertNoAmbiguousBareCommaEntry(trimmed,"--add",`${bareNoun} path`,looksLikeStructuredPathEntry(trimmed));const kv=looksLikeStructuredPathEntry(trimmed)?parseCsvKv(entry,"--add"):{path:trimmed};if(assertNoUnknownCsvKeys(kv,"--add",LINKED_ARTIFACT_ADD_KEYS),!kv.path)throw new PmCliError(`--add requires path=<value> or a bare ${bareNoun} path`,EXIT_CODE.USAGE);return[{path:kv.path,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}]}):[]}function parseAddGlobEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--add-glob requires a glob pattern value",EXIT_CODE.USAGE);if(trimmed.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--add-glob");assertNoUnknownCsvKeys(kv,"--add-glob",LINKED_ARTIFACT_ADD_GLOB_KEYS);const pattern=kv.pattern?.trim()||kv.glob?.trim()||kv.path?.trim();if(!pattern)throw new PmCliError("--add-glob key/value form requires pattern=<glob>",EXIT_CODE.USAGE);return{pattern,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}}return{pattern:trimmed,scope:"project"}}):[]}function parseRemoveEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--remove requires a path value",EXIT_CODE.USAGE);if(trimmed.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--remove"),unsupportedRemoveKeys=Object.keys(kv).filter(key=>LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS.has(key.toLowerCase()));if(unsupportedRemoveKeys.length>0)throw new PmCliError(`--remove identifies a linked artifact by path only and does not accept ${unsupportedRemoveKeys.map(key=>`"${key}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,EXIT_CODE.USAGE);if(assertNoUnknownCsvKeys(kv,"--remove",LINKED_ARTIFACT_REMOVE_KEYS),!kv.path)throw new PmCliError("--remove key/value form requires path=<value>",EXIT_CODE.USAGE);return kv.path}return trimmed}):[]}function parseMigrateEntries(raw){return raw?raw.map(entry=>{const kv=parseCsvKv(entry,"--migrate");assertNoUnknownCsvKeys(kv,"--migrate",LINKED_ARTIFACT_MIGRATE_KEYS);const from=kv.from?.trim(),to=kv.to?.trim();if(!from||!to)throw new PmCliError("--migrate requires from=<value> and to=<value>",EXIT_CODE.USAGE);return{from,to}}):[]}function applyPathMigrations(artifactPath,migrations){let next=artifactPath;for(const migration of migrations)next.startsWith(migration.from)&&(next=`${migration.to}${next.slice(migration.from.length)}`);return next}function assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations=[]){if(adds.length===0||removes.length===0)return;const addedPaths=new Set(adds.map(entry=>storedLinkedPath(applyPathMigrations(entry.path,migrations)))),conflicts=[...new Set(removes.map(entry=>storedLinkedPath(applyPathMigrations(entry,migrations))).filter(entry=>addedPaths.has(entry)))].sort((left,right)=>left.localeCompare(right));if(conflicts.length!==0)throw new PmCliError(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${conflicts.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,EXIT_CODE.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function normalizeLinkedPath(value){return value.split(path.sep).join("/")}function anchorLinkedPath(value,workspaceRoot,invocationRoot=process.cwd()){const trimmed=value.trim();if(isRemoteLinkedArtifactReference(trimmed))return trimmed;if(path.isAbsolute(trimmed)||/^[A-Za-z]:[\\/]/.test(trimmed))return normalizeLinkedPath(trimmed.replaceAll("\\",path.sep));const invocationRelativeToWorkspace=path.relative(workspaceRoot,invocationRoot);return invocationRelativeToWorkspace.startsWith(`..${path.sep}`)||invocationRelativeToWorkspace===".."||path.isAbsolute(invocationRelativeToWorkspace)?normalizeLinkedPath(path.normalize(trimmed)):normalizeLinkedPath(path.relative(workspaceRoot,path.resolve(invocationRoot,trimmed)))}async function expandAddGlobEntries(entries,workspaceRoot=process.cwd(),invocationRoot=process.cwd()){const expanded=[];for(const entry of entries){if(path.resolve(invocationRoot,entry.pattern)===path.resolve(invocationRoot))continue;const matches=await expandFileGlob(entry.pattern,invocationRoot),sortedMatches=[...new Set(matches.map(match=>anchorLinkedPath(match,workspaceRoot,invocationRoot)))].sort((left,right)=>left.localeCompare(right));for(const matchedPath of sortedMatches)expanded.push({path:matchedPath,scope:entry.scope,note:entry.note})}return expanded}function applyStandaloneNote(adds,note,hasAddFlags){if(note===void 0)return adds;if(!hasAddFlags)throw new PmCliError("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",EXIT_CODE.USAGE);const trimmed=note.trim();return trimmed.length===0?adds:adds.map(entry=>entry.note===void 0?{...entry,note:trimmed}:entry)}function artifactKey(value){return`${value.path}::${value.scope}`}function sortLinkedArtifacts(artifacts){return[...artifacts].sort((left,right)=>{const byPath=left.path.localeCompare(right.path);return byPath!==0?byPath:left.scope.localeCompare(right.scope)})}function dedupeLinkedArtifacts(artifacts){return[...new Map(artifacts.map(entry=>[artifactKey(entry),entry])).values()].map(entry=>({...entry,note:entry.note?.trim()||void 0}))}async function validateLinkedPaths(paths,workspaceRoot=process.cwd()){const uniquePaths=[...new Set(paths)].sort((left,right)=>left.localeCompare(right)),existingFiles=[],missingPaths=[],nonFilePaths=[],remoteReferences=[];for(const relativePath of uniquePaths){if(isRemoteLinkedArtifactReference(relativePath)){remoteReferences.push(relativePath.trim());continue}const resolvedPath=path.isAbsolute(relativePath)?relativePath:path.resolve(workspaceRoot,relativePath);try{(await fs.stat(resolvedPath)).isFile()?existingFiles.push(relativePath):nonFilePaths.push(relativePath)}catch(error){if(typeof error=="object"&&error!==null&&"code"in error&&isFileAbsentError(error)){missingPaths.push(relativePath);continue}nonFilePaths.push(relativePath)}}return{checked:uniquePaths.length,existing_files:existingFiles,missing_paths:missingPaths,non_file_paths:nonFilePaths,remote_references:remoteReferences}}function applyLinkedArtifactMigrations(current,adds,removes,migrations){let count=0;for(let index=0;index<current.length;index+=1){const migratedPath=applyPathMigrations(current[index].path,migrations);migratedPath!==current[index].path&&(count+=1);const storedPath=storedLinkedPath(migratedPath);storedPath!==current[index].path&&(current[index]={...current[index],path:storedPath})}return{adds:adds.map(entry=>{const migratedPath=applyPathMigrations(entry.path,migrations);return migratedPath!==entry.path&&(count+=1),{...entry,path:storedLinkedPath(migratedPath)}}),removes:removes.map(entry=>storedLinkedPath(applyPathMigrations(entry,migrations))),count}}function storedLinkedPath(value){return value.replaceAll("\\","/")}function storedLinkKey(entry){return`${entry.scope}\0${storedLinkedPath(entry.path)}`}function linkedArtifactOutcomes(baseline,merged,adds){const before=new Map(baseline.map(entry=>[storedLinkKey(entry),entry.note])),after=new Map(merged.map(entry=>[storedLinkKey(entry),entry.note])),outcomes=new Map;for(const add of adds){const key=storedLinkKey(add);outcomes.has(key)||outcomes.set(key,{path:storedLinkedPath(add.path),scope:add.scope,outcome:classifyLinkOutcome(before.has(key),before.get(key),after.get(key))})}return[...outcomes.values()]}function classifyLinkOutcome(existed,prior,final){return existed?final===prior?"unchanged":prior===void 0?"note_added":final?.startsWith(`${prior}${LINKED_ARTIFACT_NOTE_JOINER}`)?"note_appended":"note_replaced":"added"}function applyLinkedArtifactAdd(state,add,noteConflict){const index=state.merged.findIndex(entry=>entry.path===add.path&&entry.scope===add.scope),stored=state.merged[index];if(stored===void 0){state.merged.push(add),add.note!==void 0&&state.notedHere.add(add);return}const revision=reviseLinkedNote(stored.note,add.note,noteConflict);if(revision.conflict)state.conflicts.push({path:add.path,scope:add.scope,existing_note:stored.note,requested_note:add.note,source:state.notedHere.has(stored)?"this_write":"stored"});else if(revision.note!==stored.note){const revised={...stored,note:revision.note};state.merged[index]=revised,state.notedHere.add(revised)}}function mergeLinkedArtifactChanges(current,adds,removes,appendStable,noteConflict){const baseline=dedupeLinkedArtifacts(current),state={merged:[...baseline],notedHere:new Set,conflicts:[]};for(const add of adds)applyLinkedArtifactAdd(state,add,noteConflict);const{merged}=state,outcomes=linkedArtifactOutcomes(baseline,merged,adds);if(removes.length>0)for(let index=merged.length-1;index>=0;index-=1)removes.includes(merged[index].path)&&merged.splice(index,1);return{entries:appendStable?merged:sortLinkedArtifacts(merged),outcomes,conflicts:state.conflicts}}async function buildLinkedArtifactResult(params){const returned=params.mutation?.entries??params.artifacts,validated=params.options.validatePaths?params.artifacts:returned,{counts,receipts}=linkedCollectionMutationFields(params.mutation);return{id:params.id,artifacts:returned,changed:params.changed,count:returned.length,...counts,migrations_applied:params.migrationsApplied&¶ms.migrationsApplied>0?params.migrationsApplied:void 0,validation:params.options.validatePaths||params.changed&&validated.length>0?await validateLinkedPaths(validated.map(entry=>entry.path),params.workspaceRoot):void 0,...receipts}}function countRemovedLinkedArtifacts(before,after,migrations){const remaining=new Map;for(const entry of after){const key=artifactKey(entry);remaining.set(key,(remaining.get(key)??0)+1)}let removed=0;for(const entry of before){const key=artifactKey({...entry,path:storedLinkedPath(applyPathMigrations(entry.path,migrations))}),left=remaining.get(key)??0;left>0?remaining.set(key,left-1):removed+=1}return removed}function findMisreadNoteSegment(entry,bareNoun){const segments=/[\n\r]|^\s*[-*+`]/u.test(entry)?[]:splitStructuredEntrySegments(entry),noteIndex=segments.findIndex(segment=>segment.key?.toLowerCase()==="note");if(noteIndex<0)return;const fields=segments.slice(0,noteIndex).map(segment=>segment.raw.trim()),keys=new Set(segments.slice(0,noteIndex).map(segment=>segment.key?.toLowerCase())),prose=[segments[noteIndex].value];let misread;for(const segment of segments.slice(noteIndex+1)){const key=segment.key?.toLowerCase();if((key==="path"||key==="scope")&&!keys.has(key)){fields.push(segment.raw.trim()),keys.add(key);continue}misread??=segment.key===void 0?void 0:{segment:segment.text.trim(),key:segment.key},prose.push(segment.text)}if(misread===void 0)return;const note=prose.join(",").trim(),rewritten=[...fields,`note=${JSON.stringify(note)}`].join(",");try{parseAddEntries([rewritten],bareNoun)}catch{return}return{entry:rewritten,note,...misread}}function firstRefusedAddEntry(entries,bareNoun){return entries.findIndex(entry=>{try{return parseAddEntries([entry],bareNoun),!1}catch{return!0}})+1}function repeatFlag(flag,values,literalKey){return(values??[]).flatMap(value=>[flag,literalKey!==void 0&&value.trim()==="-"?`${literalKey}=-`:value])}function noteRecoveryRetryArgs(params){const{options}=params,noteConflict=params.noteConflict??options.noteConflict;return[...resolvePmCommandScopeArgs(params.global),...params.guards.map(guard=>`--expect-hash=${guard}`),params.config.metadataKey,params.id,...repeatFlag("--add",params.entries.map((entry,index)=>index===params.position-1?params.rewritten:entry),"path"),...repeatFlag("--add-glob",params.resolved.addGlob,"pattern"),...repeatFlag("--remove",params.resolved.remove,"path"),...repeatFlag("--migrate",params.resolved.migrate),...options.note===void 0?[]:["--note",options.note],...noteConflict===void 0?[]:["--note-conflict",noteConflict],...params.config.supportsAppendStable&&options.appendStable===!0?["--append-stable"]:[],...options.validatePaths===!0?["--validate-paths"]:[],...options.fullHistory===!0?["--full-history"]:[],...options.author?["--author",options.author]:[],...options.message?["--message",options.message]:[],...options.force===!0?["--force"]:[]]}function misreadKeyHint(key){return LINKED_ARTIFACT_ADD_KEYS.some(allowed=>allowed===key.toLowerCase())?`If "${key}" was meant as a key, give it once per entry.`:`If "${key}" was meant as a key, it is not one of: ${LINKED_ARTIFACT_ADD_KEYS.join(", ")}.`}function parseAddEntriesWithNoteRecovery(params){try{return parseAddEntries(params.entries,params.config.bareNoun)}catch(error){const entries=params.entries,cause=error,position=firstRefusedAddEntry(entries,params.config.bareNoun),misread=findMisreadNoteSegment(entries[position-1],params.config.bareNoun);if(misread===void 0)throw error;const guards=activeItemRevisionExpectations(params.pmRoot),retryArgs=guards===void 0?void 0:noteRecoveryRetryArgs({...params,entries,position,rewritten:misread.entry,guards});throw new PmCliError(`--add read the note segment "${misread.segment}" as a new key "${misread.key}", so the ${params.config.bareNoun} link was refused (${cause.message})`,EXIT_CODE.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:entries[position-1],required:`Retry with the note quoted so its commas stay prose (${retryArgs===void 0?`as ${misread.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${misreadKeyHint(misread.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...retryArgs===void 0?{}:{nextSteps:[renderPmCommand(retryArgs)]},details:{entry_index:position,misread_segment:misread.segment,misread_key:misread.key,note:misread.note,rewritten_entry:misread.entry,cause:cause.context.code??"invalid_argument_value"},...retryArgs===void 0?{}:{recovery:{suggested_retry:renderPmCommand(retryArgs),suggested_retry_args:retryArgs}}})}}function linkedCollectionMutationFields(mutation){return mutation===void 0?{counts:{},receipts:{}}:{counts:{total_count:mutation.total_count,returned_count:mutation.returned_count,has_more:mutation.has_more},receipts:{mutation_receipt:mutation.mutation_receipt,omission_receipt:mutation.omission_receipt}}}async function readLinkedArtifacts(params){const{settings,config}=params,located=await locateItem(params.pmRoot,params.id,settings.id_prefix,settings.item_format,params.typeToFolder);if(!located)throw new PmCliError(`Item ${params.id} not found`,EXIT_CODE.NOT_FOUND);const artifacts=(await readLocatedItem(located,{schema:settings.schema})).document.metadata[config.metadataKey]??[],mutation=params.writeRequested?projectLinkedCollectionMutation({collectionKey:config.metadataKey,stored:artifacts,written:[],removedCount:0,fullHistory:params.options.fullHistory===!0}):void 0;return buildLinkedArtifactResult({id:located.id,artifacts,changed:!1,options:params.options,workspaceRoot:params.workspaceRoot,mutation})}async function runLinkedArtifacts(id,options,global2,config){const{metadataKey}=config,stdinResolver=createStdinTokenResolver(),pmRoot=resolvePmRoot(process.cwd(),global2.path),workspaceRoot=resolveWorkspaceRoot(pmRoot),invocationRoot=process.cwd();await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),resolvedAdds=await stdinResolver.resolveList(options.add,"--add"),resolvedAddGlobs=await stdinResolver.resolveList(options.addGlob,"--add-glob"),resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove"),resolvedMigrations=await stdinResolver.resolveList(options.migrate,"--migrate"),parsedAdds=parseAddEntriesWithNoteRecovery({id,pmRoot,entries:resolvedAdds,resolved:{addGlob:resolvedAddGlobs,remove:resolvedRemoves,migrate:resolvedMigrations},options,global:global2,config}).map(entry=>({...entry,path:anchorLinkedPath(entry.path,workspaceRoot,invocationRoot)})),addGlobs=parseAddGlobEntries(resolvedAddGlobs),expandedGlobAdds=await expandAddGlobEntries(addGlobs,workspaceRoot,invocationRoot),hasAddFlags=parsedAdds.length>0||addGlobs.length>0,adds=applyStandaloneNote([...parsedAdds,...expandedGlobAdds],options.note,hasAddFlags),noteConflict=parseNoteConflictMode(options.noteConflict,hasAddFlags),removes=parseRemoveEntries(resolvedRemoves).map(entry=>anchorLinkedPath(entry,workspaceRoot,invocationRoot)),migrations=parseMigrateEntries(resolvedMigrations);if(assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations),!(adds.length>0||removes.length>0||migrations.length>0))return readLinkedArtifacts({id,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,options,workspaceRoot,config,writeRequested:addGlobs.length>0});const author=resolveAuthor(options.author,settings.author_default);let before=[],removedCount=0,linkOutcomes=[];const result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,skipNoop:!0,mutate(document){const metadata=document.metadata,current=metadata[metadataKey]??[],next=[...current],migrated=applyLinkedArtifactMigrations(next,adds,removes,migrations),merge=mergeLinkedArtifactChanges(next,migrated.adds,migrated.removes,config.supportsAppendStable&&options.appendStable===!0,noteConflict);if(merge.conflicts.length>0){const guards=activeItemRevisionExpectations(pmRoot);throw buildNoteConflictError({itemId:document.metadata.id,noun:config.bareNoun,conflicts:merge.conflicts,retryArgs:mode=>guards===void 0?void 0:noteRecoveryRetryArgs({id:document.metadata.id,entries:resolvedAdds??[],position:0,rewritten:"",resolved:{addGlob:resolvedAddGlobs,remove:resolvedRemoves,migrate:resolvedMigrations},options,global:global2,config,guards,noteConflict:mode}),render:renderPmCommand})}const normalized=merge.entries;linkOutcomes=merge.outcomes,normalized.length>0?metadata[metadataKey]=normalized:delete metadata[metadataKey];const changed=!stableValueEquals(current,normalized);return before=current,removedCount=countRemovedLinkedArtifacts(current,normalized,migrations),{changedFields:changed?[metadataKey]:[],warnings:changed&&migrated.count>0?[`path_migrations_applied:${migrated.count}`]:[]}}}),artifacts=result.item[metadataKey]??[],migrationWarning=result.warnings.find(warning=>warning.startsWith("path_migrations_applied:")),migrationCount=migrationWarning?Number(migrationWarning.slice(24)):0;return buildLinkedArtifactResult({id:result.item.id,artifacts,changed:result.changedFields.includes(metadataKey),migrationsApplied:migrationCount,options,workspaceRoot,mutation:projectLinkedCollectionMutation({collectionKey:metadataKey,stored:artifacts,written:writtenLinkedEntries(before,artifacts),removedCount,fullHistory:options.fullHistory===!0,linkOutcomes})})}function renameArtifactsResultKey(result,key){const out={};for(const[field,value]of Object.entries(result))out[field==="artifacts"?key:field]=value;return out}export{LINKED_ARTIFACT_ADD_GLOB_KEYS,LINKED_ARTIFACT_ADD_KEYS,LINKED_ARTIFACT_MIGRATE_KEYS,LINKED_ARTIFACT_NOTE_CONFLICT_MODES,LINKED_ARTIFACT_NOTE_JOINER,LINKED_ARTIFACT_REMOVE_KEYS,anchorLinkedPath,applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,buildNoteConflictError,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,findMisreadNoteSegment,linkedCollectionMutationFields,looksLikeStructuredPathEntry,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseNoteConflictMode,parseRemoveEntries,projectLinkedCollectionMutation,renameArtifactsResultKey,reviseLinkedNote,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths,writtenLinkedEntries};
|
|
1
|
+
import{assertInitializedTracker as he}from"./environment/tracker-preflight.js";import me from"node:fs/promises";import p from"node:path";import{expandFileGlob as ge}from"../core/fs/file-glob.js";import{isFileAbsentError as _e}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations as ye}from"../core/extensions/index.js";import{assertNoAmbiguousBareCommaEntry as ve,assertNoUnknownCsvKeys as b,createStdinTokenResolver as we,looksLikeGenericKeyValueEntry as Ae,parseCsvKv as E,splitStructuredEntrySegments as ke}from"../core/item/parse.js";import{resolveItemTypeRegistry as xe}from"../core/item/type-registry.js";import{isRemoteLinkedArtifactReference as ee}from"../core/validate/linked-artifact-reference.js";import{EXIT_CODE as u}from"../core/shared/constants.js";import{PmCliError as l}from"../core/shared/errors.js";import{stableValueEquals as te}from"../core/shared/serialization.js";import{locateItem as be,mutateItem as Ee,readLocatedItem as $e}from"../core/store/item-store.js";import{resolvePmRoot as Se,resolveWorkspaceRoot as Ce}from"../core/store/paths.js";import{readSettings as Le}from"../core/store/settings.js";import{SCOPE_VALUES as ne}from"../types/index.js";import{resolveAuthor as Re}from"../core/shared/author.js";import{renderPmCommand as T,resolvePmCommandScopeArgs as Ie}from"./command-line.js";import{activeItemRevisionExpectations as oe}from"../core/store/item-mutation-precondition.js";const G=["refuse","replace","append"],K="; ";function Ne(e,t){if(e===void 0)return"refuse";const n=e.trim().toLowerCase();if(!G.some(o=>o===n))throw new l(`--note-conflict must be one of ${G.join(", ")}; got "${e}"`,u.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:e,required:`Pass --note-conflict ${G.join("|")}.`});if(!t)throw new l("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",u.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return n}function Oe(e,t,n){if(t===void 0||t===e)return{note:e,outcome:"unchanged",conflict:!1};if(e===void 0)return{note:t,outcome:"note_added",conflict:!1};if(n==="replace")return{note:t,outcome:"note_replaced",conflict:!1};if(n==="append"){const o=K;return`${o}${e}${o}`.includes(`${o}${t}${o}`)?{note:e,outcome:"unchanged",conflict:!1}:{note:`${e}${K}${t}`,outcome:"note_appended",conflict:!1}}return{note:e,outcome:"unchanged",conflict:!0}}function Pe(e){const t=e.conflicts[0],n=e.conflicts.length>1?` and ${e.conflicts.length-1} more`:"",o=e.retryArgs("append"),r=e.retryArgs("replace"),i=t.source==="stored"?`${e.itemId} already links ${e.noun} ${t.path} with the note "${t.existing_note}"${n}; the add was refused so that note is kept`:`The add names ${e.noun} ${t.path} on ${e.itemId} with two notes, "${t.existing_note}" and then "${t.requested_note}"${n}; the add was refused because they disagree`;return new l(i,u.CONFLICT,{code:"linked_artifact_note_conflict",item_id:e.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...o===void 0||r===void 0?{}:{nextSteps:[e.render(o),e.render(r)],recovery:{suggested_retry:e.render(o),suggested_retry_args:o}},details:{conflicts:e.conflicts.map(s=>({...s}))}})}const F=["path","scope","note"],Te=["pattern","glob","path","scope","note"],Ge=["path"],Ke=["from","to"],Fe=new Set(["note","scope"]);function re(e){return JSON.parse(JSON.stringify(e))}function Me(e,t){const n=e.map(re);return t.filter(o=>{const r=re(o),i=n.findIndex(s=>te(s,r));return i>=0&&n.splice(i,1),i<0})}function ie(e){const t=e.fullHistory?[...e.stored]:[...e.written],n=t.length<e.stored.length;return{entries:t,total_count:e.stored.length,returned_count:t.length,has_more:n,mutation_receipt:{changed_count:e.written.length,removed_count:e.removedCount,full_history_included:!n,...e.linkOutcomes&&e.linkOutcomes.length>0?{link_outcomes:[...e.linkOutcomes]}:{}},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function se(e){const t=e??"project";if(!ne.includes(t))throw new l(`Invalid scope "${e}". Valid scopes: ${ne.join(", ")} (default: project).`,u.USAGE);return t}function M(e){if(e.startsWith("```")||e.includes(`
|
|
2
|
+
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;const t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),o=n.indexOf("=");return o>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(r=>r>=0&&r<o))?!1:n.includes("=")||Ae(e)}function je(e){let t=0;for(const n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function Ue(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!M(e))return{path:e,scope:"project",note:void 0};const t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){const i=e.slice(t+2,-1).trim();if(i.length>0&&je(i))return{path:i,scope:"project",note:e.slice(1,t).trim()||void 0}}const n=e.indexOf(",");if(n<0)return;const o=e.slice(0,n).trim(),r=e.slice(n+1).trim();if(!(o.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(r)))return{path:r,scope:"project",note:o}}function j(e,t){return e?e.flatMap(n=>{const o=n.trim();if(t==="doc"){const i=Ue(o);if(i!==void 0)return[i]}ve(o,"--add",`${t} path`,M(o));const r=M(o)?E(n,"--add"):{path:o};if(b(r,"--add",F),!r.path)throw new l(`--add requires path=<value> or a bare ${t} path`,u.USAGE);return[{path:r.path,scope:se(r.scope),note:r.note?.trim()||void 0}]}):[]}function qe(e){return e?e.map(t=>{const n=t.trim();if(!n)throw new l("--add-glob requires a glob pattern value",u.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){const o=E(n,"--add-glob");b(o,"--add-glob",Te);const r=o.pattern?.trim()||o.glob?.trim()||o.path?.trim();if(!r)throw new l("--add-glob key/value form requires pattern=<glob>",u.USAGE);return{pattern:r,scope:se(o.scope),note:o.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function De(e){return e?e.map(t=>{const n=t.trim();if(!n)throw new l("--remove requires a path value",u.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){const o=E(n,"--remove"),r=Object.keys(o).filter(i=>Fe.has(i.toLowerCase()));if(r.length>0)throw new l(`--remove identifies a linked artifact by path only and does not accept ${r.map(i=>`"${i}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,u.USAGE);if(b(o,"--remove",Ge),!o.path)throw new l("--remove key/value form requires path=<value>",u.USAGE);return o.path}return n}):[]}function ze(e){return e?e.map(t=>{const n=E(t,"--migrate");b(n,"--migrate",Ke);const o=n.from?.trim(),r=n.to?.trim();if(!o||!r)throw new l("--migrate requires from=<value> and to=<value>",u.USAGE);return{from:o,to:r}}):[]}function _(e,t){let n=e;for(const o of t)n.startsWith(o.from)&&(n=`${o.to}${n.slice(o.from.length)}`);return n}function He(e,t,n=[]){if(e.length===0||t.length===0)return;const o=new Set(e.map(i=>m(_(i.path,n)))),r=[...new Set(t.map(i=>m(_(i,n))).filter(i=>o.has(i)))].sort((i,s)=>i.localeCompare(s));if(r.length!==0)throw new l(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${r.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,u.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function U(e){return e.split(p.sep).join("/")}function q(e,t,n=process.cwd()){const o=e.trim();if(ee(o))return o;if(p.isAbsolute(o)||/^[A-Za-z]:[\\/]/.test(o))return U(o.replaceAll("\\",p.sep));const r=p.relative(t,n);return r.startsWith(`..${p.sep}`)||r===".."||p.isAbsolute(r)?U(p.normalize(o)):U(p.relative(t,p.resolve(n,o)))}async function We(e,t=process.cwd(),n=process.cwd()){const o=[];for(const r of e){if(p.resolve(n,r.pattern)===p.resolve(n))continue;const i=await ge(r.pattern,n),s=[...new Set(i.map(c=>q(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(const c of s)o.push({path:c,scope:r.scope,note:r.note})}return o}function Ze(e,t,n){if(t===void 0)return e;if(!n)throw new l("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",u.USAGE);const o=t.trim();return o.length===0?e:e.map(r=>r.note===void 0?{...r,note:o}:r)}function D(e){return`${e.path}::${e.scope}`}function Ve(e){return[...e].sort((t,n)=>{const o=t.path.localeCompare(n.path);return o!==0?o:t.scope.localeCompare(n.scope)})}function Ye(e){return[...new Map(e.map(t=>[D(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function Je(e,t=process.cwd()){const n=[...new Set(e)].sort((c,d)=>c.localeCompare(d)),o=[],r=[],i=[],s=[];for(const c of n){if(ee(c)){s.push(c.trim());continue}const d=p.isAbsolute(c)?c:p.resolve(t,c);try{(await me.stat(d)).isFile()?o.push(c):i.push(c)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&_e(a)){r.push(c);continue}i.push(c)}}return{checked:n.length,existing_files:o,missing_paths:r,non_file_paths:i,remote_references:s}}function Be(e,t,n,o){let r=0;for(let s=0;s<e.length;s+=1){const c=_(e[s].path,o);c!==e[s].path&&(r+=1);const d=m(c);d!==e[s].path&&(e[s]={...e[s],path:d})}return{adds:t.map(s=>{const c=_(s.path,o);return c!==s.path&&(r+=1),{...s,path:m(c)}}),removes:n.map(s=>m(_(s,o))),count:r}}function m(e){return e.replaceAll("\\","/")}function z(e){return`${e.scope}\0${m(e.path)}`}function Xe(e,t,n){const o=new Map(e.map(s=>[z(s),s.note])),r=new Map(t.map(s=>[z(s),s.note])),i=new Map;for(const s of n){const c=z(s);i.has(c)||i.set(c,{path:m(s.path),scope:s.scope,outcome:Qe(o.has(c),o.get(c),r.get(c))})}return[...i.values()]}function Qe(e,t,n){return e?n===t?"unchanged":t===void 0?"note_added":n?.startsWith(`${t}${K}`)?"note_appended":"note_replaced":"added"}function et(e,t,n){const o=e.merged.findIndex(s=>s.path===t.path&&s.scope===t.scope),r=e.merged[o];if(r===void 0){e.merged.push(t),t.note!==void 0&&e.notedHere.add(t);return}const i=Oe(r.note,t.note,n);if(i.conflict)e.conflicts.push({path:t.path,scope:t.scope,existing_note:r.note,requested_note:t.note,source:e.notedHere.has(r)?"this_write":"stored"});else if(i.note!==r.note){const s={...r,note:i.note};e.merged[o]=s,e.notedHere.add(s)}}function tt(e,t,n,o,r){const i=Ye(e),s={merged:[...i],notedHere:new Set,conflicts:[]};for(const a of t)et(s,a,r);const{merged:c}=s,d=Xe(i,c,t);if(n.length>0)for(let a=c.length-1;a>=0;a-=1)n.includes(c[a].path)&&c.splice(a,1);return{entries:o?c:Ve(c),outcomes:d,conflicts:s.conflicts}}async function ce(e){const t=e.mutation?.entries??e.artifacts,n=e.options.validatePaths?e.artifacts:t,{counts:o,receipts:r}=ct(e.mutation);return{id:e.id,artifacts:t,changed:e.changed,count:t.length,...o,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed&&n.length>0?await Je(n.map(i=>i.path),e.workspaceRoot):void 0,...r}}function nt(e,t,n){const o=new Map;for(const i of t){const s=D(i);o.set(s,(o.get(s)??0)+1)}let r=0;for(const i of e){const s=D({...i,path:m(_(i.path,n))}),c=o.get(s)??0;c>0?o.set(s,c-1):r+=1}return r}function ot(e,t){const n=/[\n\r]|^\s*[-*+`]/u.test(e)?[]:ke(e),o=n.findIndex(f=>f.key?.toLowerCase()==="note");if(o<0)return;const r=n.slice(0,o).map(f=>f.raw.trim()),i=new Set(n.slice(0,o).map(f=>f.key?.toLowerCase())),s=[n[o].value];let c;for(const f of n.slice(o+1)){const g=f.key?.toLowerCase();if((g==="path"||g==="scope")&&!i.has(g)){r.push(f.raw.trim()),i.add(g);continue}c??=f.key===void 0?void 0:{segment:f.text.trim(),key:f.key},s.push(f.text)}if(c===void 0)return;const d=s.join(",").trim(),a=[...r,`note=${JSON.stringify(d)}`].join(",");try{j([a],t)}catch{return}return{entry:a,note:d,...c}}function rt(e,t){return e.findIndex(n=>{try{return j([n],t),!1}catch{return!0}})+1}function $(e,t,n){return(t??[]).flatMap(o=>[e,n!==void 0&&o.trim()==="-"?`${n}=-`:o])}function ae(e){const{options:t}=e,n=e.noteConflict??t.noteConflict;return[...Ie(e.global),...e.guards.map(o=>`--expect-hash=${o}`),e.config.metadataKey,e.id,...$("--add",e.entries.map((o,r)=>r===e.position-1?e.rewritten:o),"path"),...$("--add-glob",e.resolved.addGlob,"pattern"),...$("--remove",e.resolved.remove,"path"),...$("--migrate",e.resolved.migrate),...t.note===void 0?[]:["--note",t.note],...n===void 0?[]:["--note-conflict",n],...e.config.supportsAppendStable&&t.appendStable===!0?["--append-stable"]:[],...t.validatePaths===!0?["--validate-paths"]:[],...t.fullHistory===!0?["--full-history"]:[],...t.author?["--author",t.author]:[],...t.message?["--message",t.message]:[],...t.force===!0?["--force"]:[]]}function it(e){return F.some(t=>t===e.toLowerCase())?`If "${e}" was meant as a key, give it once per entry.`:`If "${e}" was meant as a key, it is not one of: ${F.join(", ")}.`}function st(e){try{return j(e.entries,e.config.bareNoun)}catch(t){const n=e.entries,o=t,r=rt(n,e.config.bareNoun),i=ot(n[r-1],e.config.bareNoun);if(i===void 0)throw t;const s=oe(e.pmRoot),c=s===void 0?void 0:ae({...e,entries:n,position:r,rewritten:i.entry,guards:s});throw new l(`--add read the note segment "${i.segment}" as a new key "${i.key}", so the ${e.config.bareNoun} link was refused (${o.message})`,u.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:n[r-1],required:`Retry with the note quoted so its commas stay prose (${c===void 0?`as ${i.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${it(i.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...c===void 0?{}:{nextSteps:[T(c)]},details:{entry_index:r,misread_segment:i.segment,misread_key:i.key,note:i.note,rewritten_entry:i.entry,cause:o.context.code??"invalid_argument_value"},...c===void 0?{}:{recovery:{suggested_retry:T(c),suggested_retry_args:c}}})}}function ct(e){return e===void 0?{counts:{},receipts:{}}:{counts:{total_count:e.total_count,returned_count:e.returned_count,has_more:e.has_more},receipts:{mutation_receipt:e.mutation_receipt,omission_receipt:e.omission_receipt}}}async function at(e){const{settings:t,config:n}=e,o=await be(e.pmRoot,e.id,t.id_prefix,t.item_format,e.typeToFolder);if(!o)throw new l(`Item ${e.id} not found`,u.NOT_FOUND);const i=(await $e(o,{schema:t.schema})).document.metadata[n.metadataKey]??[],s=e.writeRequested?ie({collectionKey:n.metadataKey,stored:i,written:[],removedCount:0,fullHistory:e.options.fullHistory===!0}):void 0;return ce({id:o.id,artifacts:i,changed:!1,options:e.options,workspaceRoot:e.workspaceRoot,mutation:s})}async function Lt(e,t,n,o){const{metadataKey:r}=o,i=we(),s=Se(process.cwd(),n.path),c=Ce(s),d=process.cwd();await he(s);const a=await Le(s),f=xe(a,ye()),g=await i.resolveList(t.add,"--add"),S=await i.resolveList(t.addGlob,"--add-glob"),C=await i.resolveList(t.remove,"--remove"),L=await i.resolveList(t.migrate,"--migrate"),H=st({id:e,pmRoot:s,entries:g,resolved:{addGlob:S,remove:C,migrate:L},options:t,global:n,config:o}).map(h=>({...h,path:q(h.path,c,d)})),R=qe(S),de=await We(R,c,d),W=H.length>0||R.length>0,I=Ze([...H,...de],t.note,W),ue=Ne(t.noteConflict,W),N=De(C).map(h=>q(h,c,d)),y=ze(L);if(He(I,N,y),!(I.length>0||N.length>0||y.length>0))return at({id:e,pmRoot:s,settings:a,typeToFolder:f.type_to_folder,options:t,workspaceRoot:c,config:o,writeRequested:R.length>0});const le=Re(t.author,a.author_default);let Z=[],V=0,Y=[];const v=await Ee({pmRoot:s,settings:a,id:e,op:o.op,author:le,message:t.message,force:t.force,skipNoop:!0,mutate(h){const P=h.metadata,w=P[r]??[],B=[...w],A=Be(B,I,N,y),k=tt(B,A.adds,A.removes,o.supportsAppendStable&&t.appendStable===!0,ue);if(k.conflicts.length>0){const Q=oe(s);throw Pe({itemId:h.metadata.id,noun:o.bareNoun,conflicts:k.conflicts,retryArgs:pe=>Q===void 0?void 0:ae({id:h.metadata.id,entries:g??[],position:0,rewritten:"",resolved:{addGlob:S,remove:C,migrate:L},options:t,global:n,config:o,guards:Q,noteConflict:pe}),render:T})}const x=k.entries;Y=k.outcomes,x.length>0?P[r]=x:delete P[r];const X=!te(w,x);return Z=w,V=nt(w,x,y),{changedFields:X?[r]:[],warnings:X&&A.count>0?[`path_migrations_applied:${A.count}`]:[]}}}),O=v.item[r]??[],J=v.warnings.find(h=>h.startsWith("path_migrations_applied:")),fe=J?Number(J.slice(24)):0;return ce({id:v.item.id,artifacts:O,changed:v.changedFields.includes(r),migrationsApplied:fe,options:t,workspaceRoot:c,mutation:ie({collectionKey:r,stored:O,written:Me(Z,O),removedCount:V,fullHistory:t.fullHistory===!0,linkOutcomes:Y})})}function Rt(e,t){const n={};for(const[o,r]of Object.entries(e))n[o==="artifacts"?t:o]=r;return n}export{Te as LINKED_ARTIFACT_ADD_GLOB_KEYS,F as LINKED_ARTIFACT_ADD_KEYS,Ke as LINKED_ARTIFACT_MIGRATE_KEYS,G as LINKED_ARTIFACT_NOTE_CONFLICT_MODES,K as LINKED_ARTIFACT_NOTE_JOINER,Ge as LINKED_ARTIFACT_REMOVE_KEYS,q as anchorLinkedPath,_ as applyPathMigrations,Ze as applyStandaloneNote,D as artifactKey,He as assertLinkedArtifactMutationIsUnambiguous,Pe as buildNoteConflictError,Ye as dedupeLinkedArtifacts,se as ensureScope,We as expandAddGlobEntries,ot as findMisreadNoteSegment,ct as linkedCollectionMutationFields,M as looksLikeStructuredPathEntry,U as normalizeLinkedPath,j as parseAddEntries,qe as parseAddGlobEntries,ze as parseMigrateEntries,Ne as parseNoteConflictMode,De as parseRemoveEntries,ie as projectLinkedCollectionMutation,Rt as renameArtifactsResultKey,Oe as reviseLinkedNote,Lt as runLinkedArtifacts,Ve as sortLinkedArtifacts,Je as validateLinkedPaths,Me as writtenLinkedEntries};
|
|
3
3
|
//# sourceMappingURL=linked-artifacts.js.map
|
package/dist/sdk/mcp/apps.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
import{PM_MCP_ERROR_CODES as s,PmMcpProtocolError as p,isMcpRecord as c}from"./protocol.js";const r="io.modelcontextprotocol/ui",o="2026-01-26",l="text/html;profile=mcp-app",d=Object.freeze({specVersion:o,mimeTypes:[l]});function f(e){const i=e.clientCapabilities.extensions;if(!c(i))return!1;const t=i[r];if(t===void 0)return!1;if(!c(t))throw new p("Invalid MCP Apps client capability",s.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[r]:d}}});const n=t.mimeTypes,a=t.specVersion;if(!Array.isArray(n)||!n.includes(l)||a!==void 0&&a!==o)throw new p("Unsupported MCP Apps client capability",s.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[r]:d}}});return!0}const g={csp:{connectDomains:[],resourceDomains:[],frameDomains:[]},permissions:{},prefersBorder:!0},m=Object.freeze([{id:"context",name:"Context explorer",description:"Inspect bounded project context, provenance, omissions, and token accounting.",toolName:"pm_context",uri:"ui://pm/context.html"},{id:"graph",name:"Relationship graph",description:"Explore typed relationships, explaining paths, and graph-governance evidence.",toolName:"pm_graph",uri:"ui://pm/graph.html"},{id:"plan",name:"Plan and milestone view",description:"Review durable plan steps, dependencies, decisions, discoveries, and validation state.",toolName:"pm_plan",uri:"ui://pm/plan.html"},{id:"assurance",name:"Assurance dashboard",description:"Inspect validation verdicts, evidence, omissions, and actionable recovery paths.",toolName:"pm_validate",uri:"ui://pm/assurance.html"},{id:"operations",name:"Long-operation view",description:"Inspect durable test and operation results without creating a second task store.",toolName:"pm_test",uri:"ui://pm/operations.html"}].map(e=>({...e,toolMeta:{resourceUri:e.uri,visibility:["model","app"]},resourceMeta:g})));function v(e){return m.find(i=>i.uri===e)}function x(e){const i=new Map(m.map(t=>[t.toolName,t]));return e.map(t=>{const n=i.get(t.name);return n?{...t,_meta:{...t._meta,ui:n.toolMeta}}:{...t}})}function u(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function b(e){const i=u(e.name),t=u(e.description),n=JSON.stringify({name:`pm-${e.id}-view`,version:o}),a=JSON.stringify(o);return`<!doctype html>
|
|
2
2
|
<html lang="en">
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
5
5
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
6
|
-
<title>${
|
|
6
|
+
<title>${i}</title>
|
|
7
7
|
<style>
|
|
8
8
|
:root{color-scheme:light dark;--ink:#172554;--muted:#526078;--panel:#f8fafc;--line:#cbd5e1;--signal:#0f766e;--accent:#4338ca;--danger:#b91c1c;font-family:Inter,ui-sans-serif,system-ui,sans-serif}
|
|
9
9
|
@media(prefers-color-scheme:dark){:root{--ink:#e0e7ff;--muted:#a8b3c7;--panel:#111827;--line:#334155;--signal:#5eead4;--accent:#a5b4fc;--danger:#fca5a5}}
|
|
@@ -12,14 +12,14 @@
|
|
|
12
12
|
</head>
|
|
13
13
|
<body>
|
|
14
14
|
<main>
|
|
15
|
-
<header><div class="status" id="status" role="status" aria-live="polite">Connecting to host</div><h1>${
|
|
15
|
+
<header><div class="status" id="status" role="status" aria-live="polite">Connecting to host</div><h1>${i}</h1><p>${t}</p></header>
|
|
16
16
|
<section aria-labelledby="summary-title"><h2 id="summary-title">Authoritative result</h2><pre id="result" tabindex="0">Waiting for the host tool result\u2026</pre></section>
|
|
17
17
|
<section aria-labelledby="input-title"><h2 id="input-title">Invocation context</h2><pre id="input" tabindex="0">No tool input received.</pre></section>
|
|
18
18
|
<button type="button" id="copy">Copy visible evidence</button>
|
|
19
19
|
</main>
|
|
20
20
|
<script>
|
|
21
|
-
(()=>{"use strict";const MAX=24000,status=document.querySelector("#status"),result=document.querySelector("#result"),input=document.querySelector("#input"),pending=new Map();let nextId=1;const render=(node,value)=>{let text;try{text=typeof value==="string"?value:JSON.stringify(value,null,2)}catch{text="Result could not be serialized."}if(text.length>MAX)text=text.slice(0,MAX)+"\\n\\n[View truncated at "+MAX+" characters; use the authoritative pm tool with a cursor or narrower projection.]";node.textContent=text};const send=(message)=>window.parent.postMessage(message,"*");window.addEventListener("message",event=>{if(event.source!==window.parent||!event.data||event.data.jsonrpc!=="2.0")return;const message=event.data;if(message.id!==undefined&&pending.has(message.id)){pending.get(message.id)(message);pending.delete(message.id);return}if(message.method==="ui/notifications/tool-input"||message.method==="ui/notifications/tool-input-partial"){render(input,message.params?.arguments??message.params);status.textContent="Input received"}else if(message.method==="ui/notifications/tool-result"){render(result,message.params);status.textContent="Current tool result"}else if(message.method==="ui/notifications/tool-cancelled"){status.textContent="Tool call cancelled";status.classList.add("notice")}else if(message.method==="ui/notifications/host-context-changed"&&message.params?.theme){document.documentElement.style.colorScheme=message.params.theme}});const request=(method,params)=>new Promise(resolve=>{const id=nextId++;pending.set(id,resolve);send({jsonrpc:"2.0",id,method,params})});document.querySelector("#copy").addEventListener("click",async()=>{const text=result.textContent+"\\n\\n"+input.textContent;try{await navigator.clipboard.writeText(text);status.textContent="Visible evidence copied"}catch{status.textContent="Clipboard permission unavailable";status.classList.add("notice")}});request("ui/initialize",{appInfo:${
|
|
21
|
+
(()=>{"use strict";const MAX=24000,status=document.querySelector("#status"),result=document.querySelector("#result"),input=document.querySelector("#input"),pending=new Map();let nextId=1;const render=(node,value)=>{let text;try{text=typeof value==="string"?value:JSON.stringify(value,null,2)}catch{text="Result could not be serialized."}if(text.length>MAX)text=text.slice(0,MAX)+"\\n\\n[View truncated at "+MAX+" characters; use the authoritative pm tool with a cursor or narrower projection.]";node.textContent=text};const send=(message)=>window.parent.postMessage(message,"*");window.addEventListener("message",event=>{if(event.source!==window.parent||!event.data||event.data.jsonrpc!=="2.0")return;const message=event.data;if(message.id!==undefined&&pending.has(message.id)){pending.get(message.id)(message);pending.delete(message.id);return}if(message.method==="ui/notifications/tool-input"||message.method==="ui/notifications/tool-input-partial"){render(input,message.params?.arguments??message.params);status.textContent="Input received"}else if(message.method==="ui/notifications/tool-result"){render(result,message.params);status.textContent="Current tool result"}else if(message.method==="ui/notifications/tool-cancelled"){status.textContent="Tool call cancelled";status.classList.add("notice")}else if(message.method==="ui/notifications/host-context-changed"&&message.params?.theme){document.documentElement.style.colorScheme=message.params.theme}});const request=(method,params)=>new Promise(resolve=>{const id=nextId++;pending.set(id,resolve);send({jsonrpc:"2.0",id,method,params})});document.querySelector("#copy").addEventListener("click",async()=>{const text=result.textContent+"\\n\\n"+input.textContent;try{await navigator.clipboard.writeText(text);status.textContent="Visible evidence copied"}catch{status.textContent="Clipboard permission unavailable";status.classList.add("notice")}});request("ui/initialize",{appInfo:${n},appCapabilities:{},protocolVersion:${a}}).then(message=>{if(message.error){status.textContent="Host rejected MCP App initialization";status.classList.add("notice");return}send({jsonrpc:"2.0",method:"ui/notifications/initialized"});status.textContent="Connected \u2014 awaiting authoritative result"})})();
|
|
22
22
|
</script>
|
|
23
23
|
</body>
|
|
24
|
-
</html>`}export{PM_MCP_APPS_EXTENSION,PM_MCP_APPS_SERVER_CAPABILITY,PM_MCP_APPS_SPEC_VERSION,PM_MCP_APP_CONTRACTS,PM_MCP_APP_MIME_TYPE,decoratePmMcpToolsWithApps,findPmMcpAppByUri,hasPmMcpAppsCapability,renderPmMcpAppHtml};
|
|
24
|
+
</html>`}export{r as PM_MCP_APPS_EXTENSION,d as PM_MCP_APPS_SERVER_CAPABILITY,o as PM_MCP_APPS_SPEC_VERSION,m as PM_MCP_APP_CONTRACTS,l as PM_MCP_APP_MIME_TYPE,x as decoratePmMcpToolsWithApps,v as findPmMcpAppByUri,f as hasPmMcpAppsCapability,b as renderPmMcpAppHtml};
|
|
25
25
|
//# sourceMappingURL=apps.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]="a7c30d99-a0e4-552e-be61-0c54a455e211")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{createHash,timingSafeEqual}from"node:crypto";import{isMcpRecord}from"./protocol.js";class PmMcpAuthorizationError extends Error{httpStatus;challenge;constructor(message,httpStatus,challenge){super(message),this.name="PmMcpAuthorizationError",this.httpStatus=httpStatus,this.challenge=challenge}}const TRACE_PARENT_PATTERN=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/u,TRACE_STATE_SIMPLE_KEY_PATTERN=/^[a-z][a-z0-9_*/-]{0,255}$/u,TRACE_STATE_TENANT_KEY_PATTERN=/^(?:[a-z0-9][a-z0-9_*/-]{0,240})@[a-z][a-z0-9_*/-]{0,13}$/u,TRACE_STATE_VALUE_PATTERN=/^[\x20-\x2B\x2D-\x3C\x3E-\x7E]{0,255}[\x21-\x2B\x2D-\x3C\x3E-\x7E]$/u,SCOPE_PATTERN=/^[\x21\x23-\x5B\x5D-\x7E]+$/u,BAGGAGE_KEY_PATTERN=/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/u,BAGGAGE_VALUE_PATTERN=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/u,INVALID_PERCENT_ENCODING_PATTERN=/%(?![0-9A-Fa-f]{2})/u,MAX_TRACE_STATE_BYTES=512,MAX_TRACE_STATE_MEMBERS=32,MAX_BAGGAGE_MEMBERS=180,MAX_BAGGAGE_BYTES=8192,MAX_BEARER_TOKEN_BYTES=8192,MCP_TRACE_CONTEXT_STORAGE=new AsyncLocalStorage;function requireAbsoluteAuthorizationUrl(value,field,allowLocalHttp=!1){if(new RegExp("\\p{Cc}","u").test(value))throw new PmMcpAuthorizationError(`Invalid ${field}`,401);let parsed;try{parsed=new URL(value)}catch{throw new PmMcpAuthorizationError(`Invalid ${field}`,401)}const local=parsed.hostname==="127.0.0.1"||parsed.hostname==="localhost";if(parsed.hash.length>0||parsed.protocol!=="https:"&&!(allowLocalHttp&&local&&parsed.protocol==="http:"))throw new PmMcpAuthorizationError(`Invalid ${field}`,401);return parsed}function readHeader(headers,name){const expected=name.toLowerCase();for(const[candidate,value]of Object.entries(headers))if(!(candidate.toLowerCase()!==expected||value===void 0))return typeof value=="string"?value:value.join(", ")}function buildMcpProtectedResourceMetadata(input){const resource=requireAbsoluteAuthorizationUrl(input.resource,"protected resource URI",!0).href.replace(/\/$/u,"");if(input.authorizationServers.length===0)throw new PmMcpAuthorizationError("Protected resource metadata requires an authorization server",401);const authorizationServers=input.authorizationServers.map(issuer=>requireAbsoluteAuthorizationUrl(issuer,"authorization server issuer").href.replace(/\/$/u,"")),scopes=[...new Set(input.scopes??[])];if(scopes.some(scope=>!SCOPE_PATTERN.test(scope)))throw new PmMcpAuthorizationError("Invalid authorization scope",401);return{resource,authorization_servers:authorizationServers,...scopes.length>0?{scopes_supported:scopes.sort()}:{}}}function buildMcpAuthorizationDiscoveryUrls(issuer){const parsed=requireAbsoluteAuthorizationUrl(issuer,"authorization server issuer"),suffix=parsed.pathname.replace(/^\/+|\/+$/gu,""),origin=parsed.origin;return suffix?[`${origin}/.well-known/oauth-authorization-server/${suffix}`,`${origin}/.well-known/openid-configuration/${suffix}`,`${origin}/${suffix}/.well-known/openid-configuration`]:[`${origin}/.well-known/oauth-authorization-server`,`${origin}/.well-known/openid-configuration`]}function validateMcpAuthorizationServerMetadata(value,expectedIssuer){if(!isMcpRecord(value)||typeof value.issuer!="string")throw new PmMcpAuthorizationError("Invalid authorization server metadata",401);const expected=requireAbsoluteAuthorizationUrl(expectedIssuer,"expected issuer").href.replace(/\/$/u,"");if(requireAbsoluteAuthorizationUrl(value.issuer,"metadata issuer").href.replace(/\/$/u,"")!==expected)throw new PmMcpAuthorizationError("Authorization server issuer mismatch",401);if(!Array.isArray(value.code_challenge_methods_supported)||!value.code_challenge_methods_supported.includes("S256"))throw new PmMcpAuthorizationError("Authorization server does not support required S256 PKCE",401);const requiredUrl=field=>{const candidate=value[field];if(typeof candidate!="string")throw new PmMcpAuthorizationError(`Authorization server metadata requires ${field}`,401);return requireAbsoluteAuthorizationUrl(candidate,field).href},optionalUrl=field=>{const candidate=value[field];return typeof candidate=="string"?requireAbsoluteAuthorizationUrl(candidate,field).href:void 0},authorizationEndpoint=requiredUrl("authorization_endpoint"),tokenEndpoint=requiredUrl("token_endpoint"),registrationEndpoint=optionalUrl("registration_endpoint");return{issuer:expected,authorization_endpoint:authorizationEndpoint,token_endpoint:tokenEndpoint,code_challenge_methods_supported:[...new Set(value.code_challenge_methods_supported.filter(entry=>typeof entry=="string"))],...value.client_id_metadata_document_supported===!0?{client_id_metadata_document_supported:!0}:{},...registrationEndpoint?{registration_endpoint:registrationEndpoint}:{}}}function selectMcpClientRegistrationMode(input){return input.hasPreRegisteredClient?"pre_registered":input.metadata.client_id_metadata_document_supported?"client_id_metadata_document":input.metadata.registration_endpoint?"dynamic":"user_supplied"}function validateMcpAuthorizationResponseIssuer(input){if(input.responseIssuer===void 0){if(input.issuerParameterSupported)throw new PmMcpAuthorizationError("Authorization response omitted the advertised issuer",401);return}if(input.responseIssuer!==input.expectedIssuer)throw new PmMcpAuthorizationError("Authorization response issuer mismatch",401)}function validateMcpClientMetadataDocument(value,documentUrl){const expected=requireAbsoluteAuthorizationUrl(documentUrl,"client metadata document URL");if(expected.pathname==="/"||!isMcpRecord(value)||value.client_id!==expected.href||typeof value.client_name!="string"||value.client_name.trim().length===0||!Array.isArray(value.redirect_uris)||value.redirect_uris.length===0)throw new PmMcpAuthorizationError("Invalid Client ID Metadata Document",401);for(const redirect of value.redirect_uris){if(typeof redirect!="string")throw new PmMcpAuthorizationError("Invalid client redirect URI",401);requireAbsoluteAuthorizationUrl(redirect,"client redirect URI",!0)}return structuredClone(value)}function buildMcpDynamicRegistrationMetadata(input){if(input.redirectUris.length===0||input.clientName.trim().length===0)throw new PmMcpAuthorizationError("Invalid dynamic client registration metadata",401);const redirectUris=input.redirectUris.map(redirect=>requireAbsoluteAuthorizationUrl(redirect,"redirect URI",!0).href);return{application_type:input.applicationType,client_name:input.clientName.trim().slice(0,128),redirect_uris:redirectUris,grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}class PmMcpIssuerCredentialStore{#credentials=new Map;set(issuer,credential){const key=requireAbsoluteAuthorizationUrl(issuer,"credential issuer").href;this.#credentials.set(key,structuredClone(credential))}get(issuer){const key=requireAbsoluteAuthorizationUrl(issuer,"credential issuer").href,credential=this.#credentials.get(key);return credential?structuredClone(credential):void 0}delete(issuer){const key=requireAbsoluteAuthorizationUrl(issuer,"credential issuer").href;return this.#credentials.delete(key)}}function validateMcpTraceFields(meta){const traceparent=meta.traceparent,tracestate=meta.tracestate;if(traceparent!==void 0){const match=typeof traceparent=="string"?TRACE_PARENT_PATTERN.exec(traceparent):null;if(!match)throw new PmMcpAuthorizationError("Invalid MCP traceparent",403);const traceId=match[1],parentId=match[2];if(/^0+$/u.test(traceId)||/^0+$/u.test(parentId))throw new PmMcpAuthorizationError("Invalid MCP traceparent",403)}if(tracestate!==void 0&&(typeof tracestate!="string"||!isValidMcpTraceState(tracestate)))throw new PmMcpAuthorizationError("Invalid MCP tracestate",403);return{...typeof traceparent=="string"?{traceparent}:{},...typeof tracestate=="string"?{tracestate}:{}}}function trimOptionalWhitespace(value){return value.replace(/^[ \t]*|[ \t]*$/gu,"")}function isValidMcpTraceStateKey(key){return TRACE_STATE_SIMPLE_KEY_PATTERN.test(key)||TRACE_STATE_TENANT_KEY_PATTERN.test(key)}function isValidMcpTraceState(value){if(Buffer.byteLength(value,"utf8")>MAX_TRACE_STATE_BYTES)return!1;const members=value.split(",");if(members.length>MAX_TRACE_STATE_MEMBERS)return!1;const keys=new Set;for(const source of members){const member=trimOptionalWhitespace(source);if(member.length===0)continue;const separator=member.indexOf("="),key=separator>0?member.slice(0,separator):"",memberValue=separator>0?member.slice(separator+1):"";if(!isValidMcpTraceStateKey(key)||!TRACE_STATE_VALUE_PATTERN.test(memberValue)||keys.has(key))return!1;keys.add(key)}return!0}function isValidMcpBaggageValue(value){return BAGGAGE_VALUE_PATTERN.test(value)&&!INVALID_PERCENT_ENCODING_PATTERN.test(value)}function isValidMcpBaggageProperty(source){const property=trimOptionalWhitespace(source),separator=property.indexOf("="),key=trimOptionalWhitespace(separator>=0?property.slice(0,separator):property),value=separator>=0?trimOptionalWhitespace(property.slice(separator+1)):void 0;return BAGGAGE_KEY_PATTERN.test(key)&&(value===void 0||isValidMcpBaggageValue(value))}function parseMcpBaggageMember(source){const serialized=trimOptionalWhitespace(source),segments=serialized.split(";"),pair=segments[0],properties=segments.slice(1),separator=pair.indexOf("="),key=trimOptionalWhitespace(separator>0?pair.slice(0,separator):""),value=separator>0?trimOptionalWhitespace(pair.slice(separator+1)):"";if(!(!BAGGAGE_KEY_PATTERN.test(key)||!isValidMcpBaggageValue(value)||!properties.every(isValidMcpBaggageProperty)))return{key,serialized}}function filterMcpBaggage(baggage,allowlistEntries){if(baggage===void 0)return;if(typeof baggage!="string"||Buffer.byteLength(baggage,"utf8")>MAX_BAGGAGE_BYTES)throw new PmMcpAuthorizationError("Invalid MCP baggage",403);const allowlist=new Set(allowlistEntries),sources=baggage.split(",");if(sources.length>MAX_BAGGAGE_MEMBERS)throw new PmMcpAuthorizationError("Invalid MCP baggage",403);const entries=[];for(const source of sources){const entry=parseMcpBaggageMember(source);if(!entry)throw new PmMcpAuthorizationError("Invalid MCP baggage",403);allowlist.has(entry.key)&&entries.push(entry.serialized)}return entries.length>0?entries.join(","):void 0}function extractMcpTraceContext(params,options={}){const meta=isMcpRecord(params)&&isMcpRecord(params._meta)?params._meta:{},allowedBaggage=filterMcpBaggage(meta.baggage,options.baggageAllowlist??[]);return{...validateMcpTraceFields(meta),...allowedBaggage?{baggage:allowedBaggage}:{}}}function runWithMcpTraceContext(context,callback){return MCP_TRACE_CONTEXT_STORAGE.run(structuredClone(context),callback)}function getActiveMcpTraceContext(){const context=MCP_TRACE_CONTEXT_STORAGE.getStore();return context?{...context}:void 0}async function authorizeMcpHttpRequest(input){const resourceMetadataUrl=requireAbsoluteAuthorizationUrl(input.policy.resourceMetadataUrl,"protected resource metadata URL",!0).href,requiredScopes=[...new Set(input.policy.requiredScopes??[])];if(requiredScopes.some(scope=>!SCOPE_PATTERN.test(scope)))throw new PmMcpAuthorizationError("Invalid authorization scope",401);const challenge=`Bearer resource_metadata="${resourceMetadataUrl}"`;if(new URL(input.requestUrl,input.policy.resource).searchParams.has("access_token"))throw new PmMcpAuthorizationError("Access tokens must not appear in URI query parameters",401,challenge);const match=readHeader(input.headers,"authorization")?.match(/^Bearer ([^\s]+)$/iu);if(!match)throw new PmMcpAuthorizationError("Missing or malformed bearer token",401,challenge);const token=match[1];if(Buffer.byteLength(token,"utf8")>MAX_BEARER_TOKEN_BYTES)throw new PmMcpAuthorizationError("Missing or malformed bearer token",401,challenge);let claims;try{claims=await input.policy.verifyAccessToken(token)}catch{throw new PmMcpAuthorizationError("Invalid bearer token",401,challenge)}const audiences=Array.isArray(claims.audience)?claims.audience:[claims.audience];if(claims.issuer!==input.policy.issuer||!audiences.includes(input.policy.resource))throw new PmMcpAuthorizationError("Bearer token issuer or audience mismatch",401,challenge);const missingScopes=requiredScopes.filter(scope=>!claims.scopes.includes(scope));if(missingScopes.length>0)throw new PmMcpAuthorizationError("Bearer token has insufficient scope",403,`${challenge}, scope="${missingScopes.join(" ")}"`);return{...claims,audience:[...audiences],scopes:[...claims.scopes]}}function createMcpStaticBearerVerifier(input){const expected=createHash("sha256").update(input.token).digest();return token=>{const observed=createHash("sha256").update(token).digest();if(!timingSafeEqual(expected,observed))throw new PmMcpAuthorizationError("Invalid bearer token",401);return structuredClone(input.claims)}}export{PmMcpAuthorizationError,PmMcpIssuerCredentialStore,authorizeMcpHttpRequest,buildMcpAuthorizationDiscoveryUrls,buildMcpDynamicRegistrationMetadata,buildMcpProtectedResourceMetadata,createMcpStaticBearerVerifier,extractMcpTraceContext,getActiveMcpTraceContext,runWithMcpTraceContext,selectMcpClientRegistrationMode,validateMcpAuthorizationResponseIssuer,validateMcpAuthorizationServerMetadata,validateMcpClientMetadataDocument};
|
|
1
|
+
import{AsyncLocalStorage as x}from"node:async_hooks";import{createHash as g,timingSafeEqual as y}from"node:crypto";import{isMcpRecord as h}from"./protocol.js";class s extends Error{httpStatus;challenge;constructor(n,r,t){super(n),this.name="PmMcpAuthorizationError",this.httpStatus=r,this.challenge=t}}const M=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/u,T=/^[a-z][a-z0-9_*/-]{0,255}$/u,z=/^(?:[a-z0-9][a-z0-9_*/-]{0,240})@[a-z][a-z0-9_*/-]{0,13}$/u,C=/^[\x20-\x2B\x2D-\x3C\x3E-\x7E]{0,255}[\x21-\x2B\x2D-\x3C\x3E-\x7E]$/u,m=/^[\x21\x23-\x5B\x5D-\x7E]+$/u,w=/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/u,R=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/u,S=/%(?![0-9A-Fa-f]{2})/u,I=512,$=32,P=180,k=8192,v=8192,A=new x;function c(e,n,r=!1){if(new RegExp("\\p{Cc}","u").test(e))throw new s(`Invalid ${n}`,401);let t;try{t=new URL(e)}catch{throw new s(`Invalid ${n}`,401)}const o=t.hostname==="127.0.0.1"||t.hostname==="localhost";if(t.hash.length>0||t.protocol!=="https:"&&!(r&&o&&t.protocol==="http:"))throw new s(`Invalid ${n}`,401);return t}function B(e,n){const r=n.toLowerCase();for(const[t,o]of Object.entries(e))if(!(t.toLowerCase()!==r||o===void 0))return typeof o=="string"?o:o.join(", ")}function K(e){const n=c(e.resource,"protected resource URI",!0).href.replace(/\/$/u,"");if(e.authorizationServers.length===0)throw new s("Protected resource metadata requires an authorization server",401);const r=e.authorizationServers.map(o=>c(o,"authorization server issuer").href.replace(/\/$/u,"")),t=[...new Set(e.scopes??[])];if(t.some(o=>!m.test(o)))throw new s("Invalid authorization scope",401);return{resource:n,authorization_servers:r,...t.length>0?{scopes_supported:t.sort()}:{}}}function X(e){const n=c(e,"authorization server issuer"),r=n.pathname.replace(/^\/+|\/+$/gu,""),t=n.origin;return r?[`${t}/.well-known/oauth-authorization-server/${r}`,`${t}/.well-known/openid-configuration/${r}`,`${t}/${r}/.well-known/openid-configuration`]:[`${t}/.well-known/oauth-authorization-server`,`${t}/.well-known/openid-configuration`]}function Y(e,n){if(!h(e)||typeof e.issuer!="string")throw new s("Invalid authorization server metadata",401);const r=c(n,"expected issuer").href.replace(/\/$/u,"");if(c(e.issuer,"metadata issuer").href.replace(/\/$/u,"")!==r)throw new s("Authorization server issuer mismatch",401);if(!Array.isArray(e.code_challenge_methods_supported)||!e.code_challenge_methods_supported.includes("S256"))throw new s("Authorization server does not support required S256 PKCE",401);const o=d=>{const l=e[d];if(typeof l!="string")throw new s(`Authorization server metadata requires ${d}`,401);return c(l,d).href},i=d=>{const l=e[d];return typeof l=="string"?c(l,d).href:void 0},a=o("authorization_endpoint"),p=o("token_endpoint"),u=i("registration_endpoint");return{issuer:r,authorization_endpoint:a,token_endpoint:p,code_challenge_methods_supported:[...new Set(e.code_challenge_methods_supported.filter(d=>typeof d=="string"))],...e.client_id_metadata_document_supported===!0?{client_id_metadata_document_supported:!0}:{},...u?{registration_endpoint:u}:{}}}function j(e){return e.hasPreRegisteredClient?"pre_registered":e.metadata.client_id_metadata_document_supported?"client_id_metadata_document":e.metadata.registration_endpoint?"dynamic":"user_supplied"}function H(e){if(e.responseIssuer===void 0){if(e.issuerParameterSupported)throw new s("Authorization response omitted the advertised issuer",401);return}if(e.responseIssuer!==e.expectedIssuer)throw new s("Authorization response issuer mismatch",401)}function F(e,n){const r=c(n,"client metadata document URL");if(r.pathname==="/"||!h(e)||e.client_id!==r.href||typeof e.client_name!="string"||e.client_name.trim().length===0||!Array.isArray(e.redirect_uris)||e.redirect_uris.length===0)throw new s("Invalid Client ID Metadata Document",401);for(const t of e.redirect_uris){if(typeof t!="string")throw new s("Invalid client redirect URI",401);c(t,"client redirect URI",!0)}return structuredClone(e)}function W(e){if(e.redirectUris.length===0||e.clientName.trim().length===0)throw new s("Invalid dynamic client registration metadata",401);const n=e.redirectUris.map(r=>c(r,"redirect URI",!0).href);return{application_type:e.applicationType,client_name:e.clientName.trim().slice(0,128),redirect_uris:n,grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}class Z{#e=new Map;set(n,r){const t=c(n,"credential issuer").href;this.#e.set(t,structuredClone(r))}get(n){const r=c(n,"credential issuer").href,t=this.#e.get(r);return t?structuredClone(t):void 0}delete(n){const r=c(n,"credential issuer").href;return this.#e.delete(r)}}function U(e){const n=e.traceparent,r=e.tracestate;if(n!==void 0){const t=typeof n=="string"?M.exec(n):null;if(!t)throw new s("Invalid MCP traceparent",403);const o=t[1],i=t[2];if(/^0+$/u.test(o)||/^0+$/u.test(i))throw new s("Invalid MCP traceparent",403)}if(r!==void 0&&(typeof r!="string"||!N(r)))throw new s("Invalid MCP tracestate",403);return{...typeof n=="string"?{traceparent:n}:{},...typeof r=="string"?{tracestate:r}:{}}}function f(e){return e.replace(/^[ \t]*|[ \t]*$/gu,"")}function b(e){return T.test(e)||z.test(e)}function N(e){if(Buffer.byteLength(e,"utf8")>I)return!1;const n=e.split(",");if(n.length>$)return!1;const r=new Set;for(const t of n){const o=f(t);if(o.length===0)continue;const i=o.indexOf("="),a=i>0?o.slice(0,i):"",p=i>0?o.slice(i+1):"";if(!b(a)||!C.test(p)||r.has(a))return!1;r.add(a)}return!0}function E(e){return R.test(e)&&!S.test(e)}function G(e){const n=f(e),r=n.indexOf("="),t=f(r>=0?n.slice(0,r):n),o=r>=0?f(n.slice(r+1)):void 0;return w.test(t)&&(o===void 0||E(o))}function L(e){const n=f(e),r=n.split(";"),t=r[0],o=r.slice(1),i=t.indexOf("="),a=f(i>0?t.slice(0,i):""),p=i>0?f(t.slice(i+1)):"";if(!(!w.test(a)||!E(p)||!o.every(G)))return{key:a,serialized:n}}function D(e,n){if(e===void 0)return;if(typeof e!="string"||Buffer.byteLength(e,"utf8")>k)throw new s("Invalid MCP baggage",403);const r=new Set(n),t=e.split(",");if(t.length>P)throw new s("Invalid MCP baggage",403);const o=[];for(const i of t){const a=L(i);if(!a)throw new s("Invalid MCP baggage",403);r.has(a.key)&&o.push(a.serialized)}return o.length>0?o.join(","):void 0}function J(e,n={}){const r=h(e)&&h(e._meta)?e._meta:{},t=D(r.baggage,n.baggageAllowlist??[]);return{...U(r),...t?{baggage:t}:{}}}function Q(e,n){return A.run(structuredClone(e),n)}function ee(){const e=A.getStore();return e?{...e}:void 0}async function te(e){const n=c(e.policy.resourceMetadataUrl,"protected resource metadata URL",!0).href,r=[...new Set(e.policy.requiredScopes??[])];if(r.some(_=>!m.test(_)))throw new s("Invalid authorization scope",401);const t=`Bearer resource_metadata="${n}"`;if(new URL(e.requestUrl,e.policy.resource).searchParams.has("access_token"))throw new s("Access tokens must not appear in URI query parameters",401,t);const a=B(e.headers,"authorization")?.match(/^Bearer ([^\s]+)$/iu);if(!a)throw new s("Missing or malformed bearer token",401,t);const p=a[1];if(Buffer.byteLength(p,"utf8")>v)throw new s("Missing or malformed bearer token",401,t);let u;try{u=await e.policy.verifyAccessToken(p)}catch{throw new s("Invalid bearer token",401,t)}const d=Array.isArray(u.audience)?u.audience:[u.audience];if(u.issuer!==e.policy.issuer||!d.includes(e.policy.resource))throw new s("Bearer token issuer or audience mismatch",401,t);const l=r.filter(_=>!u.scopes.includes(_));if(l.length>0)throw new s("Bearer token has insufficient scope",403,`${t}, scope="${l.join(" ")}"`);return{...u,audience:[...d],scopes:[...u.scopes]}}function re(e){const n=g("sha256").update(e.token).digest();return r=>{const t=g("sha256").update(r).digest();if(!y(n,t))throw new s("Invalid bearer token",401);return structuredClone(e.claims)}}export{s as PmMcpAuthorizationError,Z as PmMcpIssuerCredentialStore,te as authorizeMcpHttpRequest,X as buildMcpAuthorizationDiscoveryUrls,W as buildMcpDynamicRegistrationMetadata,K as buildMcpProtectedResourceMetadata,re as createMcpStaticBearerVerifier,J as extractMcpTraceContext,ee as getActiveMcpTraceContext,Q as runWithMcpTraceContext,j as selectMcpClientRegistrationMode,H as validateMcpAuthorizationResponseIssuer,Y as validateMcpAuthorizationServerMetadata,F as validateMcpClientMetadataDocument};
|
|
2
2
|
//# sourceMappingURL=authorization.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]="98283845-5c48-5901-b54c-c8cc8138427b")}catch{}})();import{createHash,createHmac,randomBytes,timingSafeEqual}from"node:crypto";import{PM_COMMAND_CAPABILITY_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier}from"../agent-capability-contracts.js";import{PmCliError}from"../runtime-primitives.js";const PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION="dev.unbrained.pm/progressive-tool-discovery",PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY=Object.freeze({version:1,discoveryTool:"pm_discover",canonicalResult:"structuredContent.result",compatibilityText:"pointer"}),PM_MCP_ENTRY_TOOL_NAMES=Object.freeze(["pm_discover","pm_next","pm_context","pm_search","pm_get"]),DISCOVERY_WEIGHTS=Object.freeze({lexical:.4,semantic:.2,graph:.1,permission:.15,freshness:.05,usage:.1}),DISCOVERY_CACHE_INVALIDATIONS=Object.freeze(["profile_changed","tool_contract_changed","workspace_extension_changed","authorization_changed","ranking_signal_changed","cursor_integrity_key_rotated"]),TIER_RANK={core:0,standard:1,full:2,internal:3},SELECTABLE_TIERS=Object.freeze(["core","standard","full"]),MCP_TOOL_PROFILES=new Set(["core","standard","full","custom"]),CAPABILITY_FAMILIES=new Set(PM_COMMAND_CAPABILITY_CONTRACTS.map(({family})=>family)),PROCESS_CURSOR_INTEGRITY_KEY=randomBytes(32);function boundedDiscoveryString(value,field){if(typeof value!="string")throw new PmCliError(`pm tool discovery ${field} must be a string of at most 4096 Unicode characters.`,64);const iterator=value[Symbol.iterator]();let count=0;for(let next=iterator.next();!next.done;next=iterator.next())if(count+=1,count>4096)throw new PmCliError(`pm tool discovery ${field} must be a string of at most 4096 Unicode characters.`,64);return value}function discoveryLimit(value){if(!Number.isInteger(value)||Number(value)<1||Number(value)>100)throw new PmCliError("pm tool discovery limit must be from 1 through 100.",64);return Number(value)}function discoveryOutputBudget(value){if(value!=="unbounded"&&(!Number.isInteger(value)||Number(value)<128))throw new PmCliError("pm tool discovery outputBudget must be unbounded or an integer of at least 128.",64);return value==="unbounded"?value:Number(value)}function discoveryIncludeSchema(value){if(value!==void 0&&typeof value!="boolean")throw new PmCliError("pm tool discovery includeSchema must be a boolean.",64);return value===!0}function validateDiscoveryOptionsContainer(value){if(value===null||typeof value!="object"||Array.isArray(value))throw new PmCliError("pm tool discovery options must be an object.",64)}function validateDiscoveryCandidates(candidates){if(!Array.isArray(candidates))throw new PmCliError("pm tool discovery candidates must be an array.",64);for(const[index,candidate]of candidates.entries()){if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))throw new PmCliError(`pm tool discovery candidate ${index} must be an object.`,64);if(typeof candidate.name!="string"||candidate.name.trim().length===0)throw new PmCliError(`pm tool discovery candidate ${index} name must be a non-empty string.`,64);if(typeof candidate.description!="string"||candidate.description.trim().length===0)throw new PmCliError(`pm tool discovery candidate ${index} description must be a non-empty string.`,64);if(candidate.inputSchema===null||typeof candidate.inputSchema!="object"||Array.isArray(candidate.inputSchema))throw new PmCliError(`pm tool discovery candidate ${index} inputSchema must be an object.`,64);if(candidate.authorized!==void 0&&typeof candidate.authorized!="boolean")throw new PmCliError(`pm tool discovery candidate ${index} authorized must be a boolean.`,64)}}function parsePmToolDiscoveryOptions(input){if(validateDiscoveryOptionsContainer(input),input.family!==void 0&&(typeof input.family!="string"||!CAPABILITY_FAMILIES.has(input.family)))throw new PmCliError("pm tool discovery family must be a declared capability family.",64);if(input.tier!==void 0&&(typeof input.tier!="string"||!SELECTABLE_TIERS.includes(input.tier)))throw new PmCliError("pm tool discovery tier must be core, standard, or full.",64);return{...input.query!==void 0?{query:boundedDiscoveryString(input.query,"query")}:{},...input.family!==void 0?{family:input.family}:{},...input.tier!==void 0?{tier:input.tier}:{},...input.limit!==void 0?{limit:discoveryLimit(input.limit)}:{},...input.cursor!==void 0?{cursor:boundedDiscoveryString(input.cursor,"cursor")}:{},...input.includeSchema!==void 0?{includeSchema:discoveryIncludeSchema(input.includeSchema)}:{},...input.outputBudget!==void 0?{outputBudget:discoveryOutputBudget(input.outputBudget)}:{}}}function normalizedUnitInterval(value){return value===void 0||!Number.isFinite(value)?0:Math.min(1,Math.max(0,value))}function normalizedSearchTokens(value){return[...new Set(value.toLowerCase().match(/[a-z0-9]+/gu)??[])].sort()}function lexicalRelevance(query,text){const queryTokens=normalizedSearchTokens(query);if(queryTokens.length===0)return 0;const targetTokens=new Set(normalizedSearchTokens(text)),matched=queryTokens.filter(token=>targetTokens.has(token)).length,exactBonus=text.toLowerCase().includes(query.toLowerCase())?.25:0;return Math.min(1,matched/queryTokens.length+exactBonus)}function semanticRelevance(query,text){const queryTokens=normalizedSearchTokens(query);if(queryTokens.length===0)return 0;const target=text.toLowerCase(),targetTokens=normalizedSearchTokens(text),related=queryTokens.filter(queryToken=>targetTokens.some(targetToken=>targetToken.startsWith(queryToken)||queryToken.startsWith(targetToken))).length,phraseBonus=target.includes(query.toLowerCase())?.2:0;return Math.min(1,related/queryTokens.length+phraseBonus)}function hashDiscoveryValue(value){return createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0,24)}function cursorSignature(fingerprint,offset,integrityKey){return createHmac("sha256",integrityKey).update(JSON.stringify({version:1,fingerprint,offset})).digest("base64url")}function encodeDiscoveryCursor(fingerprint,offset,integrityKey){const cursor={version:1,offset,signature:cursorSignature(fingerprint,offset,integrityKey)};return Buffer.from(JSON.stringify(cursor),"utf8").toString("base64url")}function decodeDiscoveryCursor(value,fingerprint,total,integrityKey){if(value===void 0)return 0;try{const decoded=JSON.parse(Buffer.from(value,"base64url").toString("utf8")),offset=decoded.offset;if(decoded.version!==1||typeof offset!="number"||!Number.isInteger(offset)||offset<0||offset>total||typeof decoded.signature!="string")throw new Error("cursor fields do not match the request");const expectedSignature=Buffer.from(cursorSignature(fingerprint,offset,integrityKey),"base64url"),suppliedSignature=Buffer.from(decoded.signature,"base64url");if(suppliedSignature.length!==expectedSignature.length||!timingSafeEqual(suppliedSignature,expectedSignature))throw new Error("cursor signature does not match the request");return offset}catch(error){throw new PmCliError("Invalid or stale pm tool discovery cursor; restart discovery without cursor.",64,{reason:String(error)})}}function appliedSignal(value,weight,source){return{value:normalizedUnitInterval(value),weight,available:source!=="unavailable",source}}function hostOrComputedSignal(hostValue,computedValue,weight){return appliedSignal(hostValue??computedValue,weight,hostValue===void 0?"computed":"host")}function buildRankedRow(candidate,query,includeSchema){const command=Object.hasOwn(PM_MCP_TOOL_COMMAND_CONTRACTS,candidate.name)?PM_MCP_TOOL_COMMAND_CONTRACTS[candidate.name]:"help",family=resolvePmCommandCapabilityFamily(command),searchableText=`${candidate.name} ${candidate.description} ${command} ${family}`,lexical=lexicalRelevance(query,searchableText),queryTokens=new Set(normalizedSearchTokens(query)),signals={lexical:appliedSignal(lexical,DISCOVERY_WEIGHTS.lexical,"computed"),semantic:hostOrComputedSignal(candidate.signals?.semantic,semanticRelevance(query,searchableText),DISCOVERY_WEIGHTS.semantic),graph:hostOrComputedSignal(candidate.signals?.graph,queryTokens.has(family)||queryTokens.has(command)?1:0,DISCOVERY_WEIGHTS.graph),permission:appliedSignal(1,DISCOVERY_WEIGHTS.permission,"authorization"),freshness:hostOrComputedSignal(candidate.signals?.freshness,1,DISCOVERY_WEIGHTS.freshness),usage:hostOrComputedSignal(candidate.signals?.usage,PM_MCP_ENTRY_TOOL_NAMES.includes(candidate.name)?1:0,DISCOVERY_WEIGHTS.usage)},score=Object.values(signals).reduce((total,signal)=>total+signal.value*signal.weight,0);return{name:candidate.name,description:candidate.description,command,tier:resolvePmCommandVisibilityTier(command),family,score:Number(score.toFixed(6)),signals,...includeSchema?{input_schema:structuredClone(candidate.inputSchema)}:{}}}function validateDiscoveryFilters(options){if(options.cursorIntegrityKey!==void 0&&(!(options.cursorIntegrityKey instanceof Uint8Array)||options.cursorIntegrityKey.byteLength<32))throw new PmCliError("pm tool discovery cursorIntegrityKey must contain at least 32 bytes.",64);if(options.tier!==void 0&&(typeof options.tier!="string"||!SELECTABLE_TIERS.includes(options.tier)))throw new PmCliError("pm tool discovery tier must be core, standard, or full.",64);if(options.family!==void 0&&(typeof options.family!="string"||!CAPABILITY_FAMILIES.has(options.family)))throw new PmCliError("pm tool discovery family must be a declared capability family.",64);if(options.profile!==void 0&&(typeof options.profile!="string"||!MCP_TOOL_PROFILES.has(options.profile)))throw new PmCliError("pm tool discovery profile must be core, standard, full, or custom.",64)}function resolveDiscoveryRequest(options){const query=boundedDiscoveryString(options.query===void 0?"":options.query,"query").trim().replace(/\s+/gu," ");boundedDiscoveryString(options.cursor===void 0?"":options.cursor,"cursor");const limit=discoveryLimit(options.limit===void 0?10:options.limit),budget=discoveryOutputBudget(options.outputBudget===void 0?1200:options.outputBudget);return validateDiscoveryFilters(options),{query,includeSchema:discoveryIncludeSchema(options.includeSchema),limit,budget,maximumTier:TIER_RANK[options.tier??"full"],profile:options.profile===void 0?"core":options.profile}}function estimateDiscoveryResultTokens(resultWithoutCost,budget,serializedToolRowsBytes){const toolRowsBytes=serializedToolRowsBytes??resultWithoutCost.tools.reduce((total,row,index)=>total+(index===0?0:1)+Buffer.byteLength(JSON.stringify(row),"utf8"),0),emptyToolsResult={...resultWithoutCost,tools:[]};let estimatedTokens=0;for(let iteration=0;iteration<4;iteration+=1){const envelopeBytes=Buffer.byteLength(JSON.stringify({...emptyToolsResult,token_cost:{estimated_tokens:estimatedTokens,budget,within_budget:!0}}),"utf8"),nextEstimate=Math.ceil((envelopeBytes+toolRowsBytes)/4);if(nextEstimate===estimatedTokens)break;estimatedTokens=nextEstimate}return estimatedTokens}function rankedDiscoveryRows(candidates,options,request){return candidates.filter(candidate=>candidate.authorized!==!1).map(candidate=>buildRankedRow(candidate,request.query,request.includeSchema)).filter(row=>row.tier!=="internal"&&TIER_RANK[row.tier]<=request.maximumTier&&(options.family===void 0||row.family===options.family)).sort((left,right)=>right.score-left.score||(left.name<right.name?-1:left.name>right.name?1:0))}function rowsWithinDiscoveryBudget(candidates,budget,buildResultWithoutCost){if(budget==="unbounded")return[...candidates];const selected=[];let serializedToolRowsBytes=0;for(const[index,row]of candidates.entries()){const candidateRowsBytes=serializedToolRowsBytes+(index===0?0:1)+Buffer.byteLength(JSON.stringify(row),"utf8");if(estimateDiscoveryResultTokens(buildResultWithoutCost(index+1),budget,candidateRowsBytes)>budget)break;selected.push(row),serializedToolRowsBytes=candidateRowsBytes}return selected}function discoverPmTools(candidates,options={}){validateDiscoveryCandidates(candidates),validateDiscoveryOptionsContainer(options);const request=resolveDiscoveryRequest(options),cursorIntegrityKey=options.cursorIntegrityKey??PROCESS_CURSOR_INTEGRITY_KEY,ranked=rankedDiscoveryRows(candidates,options,request),fingerprint=hashDiscoveryValue({query:request.query,family:options.family??null,tier:options.tier??"full",includeSchema:request.includeSchema,profile:request.profile,ranked}),offset=decodeDiscoveryCursor(options.cursor,fingerprint,ranked.length,cursorIntegrityKey),pageCandidates=ranked.slice(offset,offset+request.limit),omitted=[];request.includeSchema||omitted.push({name:"input_schema",reason:"compact_projection",restore_with:"Set includeSchema=true."}),offset+request.limit<ranked.length&&omitted.push({name:"tools",reason:"limit",restore_with:"Continue with next_cursor or increase limit."});const base={result_type:"pm_tool_discovery",contract_version:1,query:request.query,profile:request.profile,total:ranked.length,ranking_policy:{version:1,formula:"weighted_sum_then_name",weights:DISCOVERY_WEIGHTS},cache:{key:hashDiscoveryValue({fingerprint,cursorIntegrityKey:createHash("sha256").update(cursorIntegrityKey).digest("hex"),limit:request.limit,offset,budget:request.budget}),ttl_ms:3e4,scope:"private",invalidates_on:DISCOVERY_CACHE_INVALIDATIONS}},buildResultWithoutCost=(selected2,selectedCount=selected2.length)=>{const endOffset=offset+selectedCount,hasMore=endOffset<ranked.length,resultOmissions=[...omitted];return selectedCount<pageCandidates.length&&resultOmissions.push({name:"tools",reason:"token_budget",restore_with:"Continue with next_cursor or increase outputBudget."}),{...base,tools:[...selected2],returned:selectedCount,has_more:hasMore,...hasMore?{next_cursor:encodeDiscoveryCursor(fingerprint,endOffset,cursorIntegrityKey)}:{},omission_receipt:{has_omissions:resultOmissions.length>0,omitted:resultOmissions}}},buildResult=selected2=>{const resultWithoutCost=buildResultWithoutCost(selected2),estimatedTokens=estimateDiscoveryResultTokens(resultWithoutCost,request.budget);return{...resultWithoutCost,token_cost:{estimated_tokens:estimatedTokens,budget:request.budget,within_budget:request.budget==="unbounded"||estimatedTokens<=request.budget}}},selected=rowsWithinDiscoveryBudget(pageCandidates,request.budget,selectedCount=>buildResultWithoutCost([],selectedCount)),result=buildResult(selected);if(pageCandidates.length>0&&selected.length===0){const oneRowCost=buildResult([pageCandidates[0]]).token_cost.estimated_tokens;throw new PmCliError(`pm tool discovery outputBudget is too small to return a tool; increase it to at least ${oneRowCost}.`,64,{required:String(oneRowCost)})}if(request.budget!=="unbounded"&&result.token_cost.estimated_tokens>request.budget)throw new PmCliError(`pm tool discovery outputBudget is too small; at least ${result.token_cost.estimated_tokens} estimated tokens are required for this page.`,64,{required:String(result.token_cost.estimated_tokens)});return result}export{PM_MCP_ENTRY_TOOL_NAMES,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION,PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY,discoverPmTools,parsePmToolDiscoveryOptions};
|
|
1
|
+
import{createHash as T,createHmac as D,randomBytes as q,timingSafeEqual as z}from"node:crypto";import{PM_COMMAND_CAPABILITY_CONTRACTS as j,PM_MCP_TOOL_COMMAND_CONTRACTS as I,resolvePmCommandCapabilityFamily as $,resolvePmCommandVisibilityTier as Y}from"../agent-capability-contracts.js";import{PmCliError as c}from"../runtime-primitives.js";const ue="dev.unbrained.pm/progressive-tool-discovery",ae=Object.freeze({version:1,discoveryTool:"pm_discover",canonicalResult:"structuredContent.result",compatibilityText:"pointer"}),K=Object.freeze(["pm_discover","pm_next","pm_context","pm_search","pm_get"]),d=Object.freeze({lexical:.4,semantic:.2,graph:.1,permission:.15,freshness:.05,usage:.1}),V=Object.freeze(["profile_changed","tool_contract_changed","workspace_extension_changed","authorization_changed","ranking_signal_changed","cursor_integrity_key_rotated"]),R={core:0,standard:1,full:2,internal:3},k=Object.freeze(["core","standard","full"]),J=new Set(["core","standard","full","custom"]),E=new Set(j.map(({family:e})=>e)),W=q(32);function p(e,r){if(typeof e!="string")throw new c(`pm tool discovery ${r} must be a string of at most 4096 Unicode characters.`,64);const t=e[Symbol.iterator]();let o=0;for(let n=t.next();!n.done;n=t.next())if(o+=1,o>4096)throw new c(`pm tool discovery ${r} must be a string of at most 4096 Unicode characters.`,64);return e}function x(e){if(!Number.isInteger(e)||Number(e)<1||Number(e)>100)throw new c("pm tool discovery limit must be from 1 through 100.",64);return Number(e)}function B(e){if(e!=="unbounded"&&(!Number.isInteger(e)||Number(e)<128))throw new c("pm tool discovery outputBudget must be unbounded or an integer of at least 128.",64);return e==="unbounded"?e:Number(e)}function N(e){if(e!==void 0&&typeof e!="boolean")throw new c("pm tool discovery includeSchema must be a boolean.",64);return e===!0}function A(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new c("pm tool discovery options must be an object.",64)}function F(e){if(!Array.isArray(e))throw new c("pm tool discovery candidates must be an array.",64);for(const[r,t]of e.entries()){if(t===null||typeof t!="object"||Array.isArray(t))throw new c(`pm tool discovery candidate ${r} must be an object.`,64);if(typeof t.name!="string"||t.name.trim().length===0)throw new c(`pm tool discovery candidate ${r} name must be a non-empty string.`,64);if(typeof t.description!="string"||t.description.trim().length===0)throw new c(`pm tool discovery candidate ${r} description must be a non-empty string.`,64);if(t.inputSchema===null||typeof t.inputSchema!="object"||Array.isArray(t.inputSchema))throw new c(`pm tool discovery candidate ${r} inputSchema must be an object.`,64);if(t.authorized!==void 0&&typeof t.authorized!="boolean")throw new c(`pm tool discovery candidate ${r} authorized must be a boolean.`,64)}}function le(e){if(A(e),e.family!==void 0&&(typeof e.family!="string"||!E.has(e.family)))throw new c("pm tool discovery family must be a declared capability family.",64);if(e.tier!==void 0&&(typeof e.tier!="string"||!k.includes(e.tier)))throw new c("pm tool discovery tier must be core, standard, or full.",64);return{...e.query!==void 0?{query:p(e.query,"query")}:{},...e.family!==void 0?{family:e.family}:{},...e.tier!==void 0?{tier:e.tier}:{},...e.limit!==void 0?{limit:x(e.limit)}:{},...e.cursor!==void 0?{cursor:p(e.cursor,"cursor")}:{},...e.includeSchema!==void 0?{includeSchema:N(e.includeSchema)}:{},...e.outputBudget!==void 0?{outputBudget:B(e.outputBudget)}:{}}}function U(e){return e===void 0||!Number.isFinite(e)?0:Math.min(1,Math.max(0,e))}function y(e){return[...new Set(e.toLowerCase().match(/[a-z0-9]+/gu)??[])].sort()}function G(e,r){const t=y(e);if(t.length===0)return 0;const o=new Set(y(r)),n=t.filter(s=>o.has(s)).length,i=r.toLowerCase().includes(e.toLowerCase())?.25:0;return Math.min(1,n/t.length+i)}function H(e,r){const t=y(e);if(t.length===0)return 0;const o=r.toLowerCase(),n=y(r),i=t.filter(u=>n.some(a=>a.startsWith(u)||u.startsWith(a))).length,s=o.includes(e.toLowerCase())?.2:0;return Math.min(1,i/t.length+s)}function M(e){return T("sha256").update(JSON.stringify(e)).digest("hex").slice(0,24)}function P(e,r,t){return D("sha256",t).update(JSON.stringify({version:1,fingerprint:e,offset:r})).digest("base64url")}function Q(e,r,t){const o={version:1,offset:r,signature:P(e,r,t)};return Buffer.from(JSON.stringify(o),"utf8").toString("base64url")}function X(e,r,t,o){if(e===void 0)return 0;try{const n=JSON.parse(Buffer.from(e,"base64url").toString("utf8")),i=n.offset;if(n.version!==1||typeof i!="number"||!Number.isInteger(i)||i<0||i>t||typeof n.signature!="string")throw new Error("cursor fields do not match the request");const s=Buffer.from(P(r,i,o),"base64url"),u=Buffer.from(n.signature,"base64url");if(u.length!==s.length||!z(u,s))throw new Error("cursor signature does not match the request");return i}catch(n){throw new c("Invalid or stale pm tool discovery cursor; restart discovery without cursor.",64,{reason:String(n)})}}function v(e,r,t){return{value:U(e),weight:r,available:t!=="unavailable",source:t}}function _(e,r,t){return v(e??r,t,e===void 0?"computed":"host")}function Z(e,r,t){const o=Object.hasOwn(I,e.name)?I[e.name]:"help",n=$(o),i=`${e.name} ${e.description} ${o} ${n}`,s=G(r,i),u=new Set(y(r)),a={lexical:v(s,d.lexical,"computed"),semantic:_(e.signals?.semantic,H(r,i),d.semantic),graph:_(e.signals?.graph,u.has(n)||u.has(o)?1:0,d.graph),permission:v(1,d.permission,"authorization"),freshness:_(e.signals?.freshness,1,d.freshness),usage:_(e.signals?.usage,K.includes(e.name)?1:0,d.usage)},w=Object.values(a).reduce((g,f)=>g+f.value*f.weight,0);return{name:e.name,description:e.description,command:o,tier:Y(o),family:n,score:Number(w.toFixed(6)),signals:a,...t?{input_schema:structuredClone(e.inputSchema)}:{}}}function ee(e){if(e.cursorIntegrityKey!==void 0&&(!(e.cursorIntegrityKey instanceof Uint8Array)||e.cursorIntegrityKey.byteLength<32))throw new c("pm tool discovery cursorIntegrityKey must contain at least 32 bytes.",64);if(e.tier!==void 0&&(typeof e.tier!="string"||!k.includes(e.tier)))throw new c("pm tool discovery tier must be core, standard, or full.",64);if(e.family!==void 0&&(typeof e.family!="string"||!E.has(e.family)))throw new c("pm tool discovery family must be a declared capability family.",64);if(e.profile!==void 0&&(typeof e.profile!="string"||!J.has(e.profile)))throw new c("pm tool discovery profile must be core, standard, full, or custom.",64)}function te(e){const t=p(e.query===void 0?"":e.query,"query").trim().replace(/\s+/gu," ");p(e.cursor===void 0?"":e.cursor,"cursor");const o=x(e.limit===void 0?10:e.limit),n=B(e.outputBudget===void 0?1200:e.outputBudget);return ee(e),{query:t,includeSchema:N(e.includeSchema),limit:o,budget:n,maximumTier:R[e.tier??"full"],profile:e.profile===void 0?"core":e.profile}}function L(e,r,t){const o=t??e.tools.reduce((s,u,a)=>s+(a===0?0:1)+Buffer.byteLength(JSON.stringify(u),"utf8"),0),n={...e,tools:[]};let i=0;for(let s=0;s<4;s+=1){const u=Buffer.byteLength(JSON.stringify({...n,token_cost:{estimated_tokens:i,budget:r,within_budget:!0}}),"utf8"),a=Math.ceil((u+o)/4);if(a===i)break;i=a}return i}function re(e,r,t){return e.filter(o=>o.authorized!==!1).map(o=>Z(o,t.query,t.includeSchema)).filter(o=>o.tier!=="internal"&&R[o.tier]<=t.maximumTier&&(r.family===void 0||o.family===r.family)).sort((o,n)=>n.score-o.score||(o.name<n.name?-1:o.name>n.name?1:0))}function oe(e,r,t){if(r==="unbounded")return[...e];const o=[];let n=0;for(const[i,s]of e.entries()){const u=n+(i===0?0:1)+Buffer.byteLength(JSON.stringify(s),"utf8");if(L(t(i+1),r,u)>r)break;o.push(s),n=u}return o}function de(e,r={}){F(e),A(r);const t=te(r),o=r.cursorIntegrityKey??W,n=re(e,r,t),i=M({query:t.query,family:r.family??null,tier:r.tier??"full",includeSchema:t.includeSchema,profile:t.profile,ranked:n}),s=X(r.cursor,i,n.length,o),u=n.slice(s,s+t.limit),a=[];t.includeSchema||a.push({name:"input_schema",reason:"compact_projection",restore_with:"Set includeSchema=true."}),s+t.limit<n.length&&a.push({name:"tools",reason:"limit",restore_with:"Continue with next_cursor or increase limit."});const w={result_type:"pm_tool_discovery",contract_version:1,query:t.query,profile:t.profile,total:n.length,ranking_policy:{version:1,formula:"weighted_sum_then_name",weights:d},cache:{key:M({fingerprint:i,cursorIntegrityKey:T("sha256").update(o).digest("hex"),limit:t.limit,offset:s,budget:t.budget}),ttl_ms:3e4,scope:"private",invalidates_on:V}},g=(l,m=l.length)=>{const h=s+m,O=h<n.length,S=[...a];return m<u.length&&S.push({name:"tools",reason:"token_budget",restore_with:"Continue with next_cursor or increase outputBudget."}),{...w,tools:[...l],returned:m,has_more:O,...O?{next_cursor:Q(i,h,o)}:{},omission_receipt:{has_omissions:S.length>0,omitted:S}}},f=l=>{const m=g(l),h=L(m,t.budget);return{...m,token_cost:{estimated_tokens:h,budget:t.budget,within_budget:t.budget==="unbounded"||h<=t.budget}}},C=oe(u,t.budget,l=>g([],l)),b=f(C);if(u.length>0&&C.length===0){const l=f([u[0]]).token_cost.estimated_tokens;throw new c(`pm tool discovery outputBudget is too small to return a tool; increase it to at least ${l}.`,64,{required:String(l)})}if(t.budget!=="unbounded"&&b.token_cost.estimated_tokens>t.budget)throw new c(`pm tool discovery outputBudget is too small; at least ${b.token_cost.estimated_tokens} estimated tokens are required for this page.`,64,{required:String(b.token_cost.estimated_tokens)});return b}export{K as PM_MCP_ENTRY_TOOL_NAMES,ue as PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION,ae as PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY,de as discoverPmTools,le as parsePmToolDiscoveryOptions};
|
|
2
2
|
//# sourceMappingURL=discovery.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
`)}function
|
|
3
|
-
`}}return{kind:"exit",exitCode:0,stdout:
|
|
4
|
-
`,stderr:""}}export{resolvePmMcpExecutableInvocation};
|
|
1
|
+
import{PM_MCP_LEGACY_PROTOCOL_VERSIONS as r,PM_MCP_SUPPORTED_PROTOCOL_VERSIONS as s}from"./protocol.js";const a=new Set(["--help","-h","--version","-V"]);function p(e,i){const t=[`Usage: ${e==="stdio"?"pm-mcp":"pm-mcp-http"} [--help | --version]`,"",e==="stdio"?"JSON-RPC over stdin/stdout. With no arguments, starts the stdio server.":"Streamable HTTP POST /mcp. With no arguments, starts the HTTP server.","","Options:"," -h, --help Print help and exit before transport startup."," -V, --version Print the package version and exit.","","Environment:"," PM_PATH Tracker root (otherwise discovered from cwd)."," PM_GLOBAL_PATH Global settings root."," PM_MCP_PROFILE core (default), standard, full, or custom."," PM_MCP_TOOLS Comma-separated tool allowlist for custom profile."," PM_MCP_DISCOVERY_CURSOR_KEY Shared discovery cursor secret, at least 32 UTF-8 bytes."," PM_MCP_BAGGAGE_ALLOWLIST Comma-separated permitted trace baggage keys."];return e==="http"&&t.push(" PM_MCP_HTTP_HOST Bind host (default 127.0.0.1)."," PM_MCP_HTTP_PORT Bind port, 0..65535 (default 3000)."," PM_MCP_HTTP_ALLOWED_ORIGINS Comma-separated exact browser origins (default none)."," PM_MCP_HTTP_BEARER_TOKEN Deployment token for the bundled verifier."," PM_MCP_HTTP_AUTH_ISSUER Exact HTTPS authorization-server issuer."," PM_MCP_HTTP_RESOURCE Canonical resource/audience URI."," PM_MCP_HTTP_SCOPES Space-separated scopes (default pm:read pm:write).","","Non-loopback HTTP requires bearer token, issuer, and resource together."),t.push("",`MCP protocol: ${s.join(", ")}.`,e==="stdio"?`Legacy initialize compatibility: ${r.join(", ")}.`:"HTTP requires modern per-request metadata; legacy initialize is stdio-only.","",e==="stdio"?"Client configuration:":"Example loopback server:",e==="stdio"?JSON.stringify({mcpServers:{pm:{command:"npx",args:["--yes","--package",`@unbrained/pm-cli@${i}`,"pm-mcp"]}}}):`PM_MCP_HTTP_PORT=3000 npx --yes --package @unbrained/pm-cli@${i} pm-mcp-http`,...e==="http"?["HTTP client configuration:",JSON.stringify({mcpServers:{pm:{url:"http://127.0.0.1:3000/mcp"}}})]:[],"","Configuration: https://github.com/unbraind/pm-cli/blob/main/docs/MCP_REMOTE_TRANSPORT_SECURITY.md",""),t.join(`
|
|
2
|
+
`)}function d(e,i,n){if(e.length===0)return{kind:"serve"};const t=e.find(o=>!a.has(o));if(t!==void 0){const o=i==="stdio"?"pm-mcp":"pm-mcp-http";return{kind:"exit",exitCode:64,stdout:"",stderr:`Unsupported argument ${JSON.stringify(t)}. Run ${o} --help.
|
|
3
|
+
`}}return{kind:"exit",exitCode:0,stdout:e.includes("--help")||e.includes("-h")?p(i,n):`${n}
|
|
4
|
+
`,stderr:""}}export{d as resolvePmMcpExecutableInvocation};
|
|
5
5
|
//# sourceMappingURL=executable.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]="15b81dd0-ef1a-58be-b6ee-5975b6778993")}catch{}})();import{createHash,createHmac,timingSafeEqual}from"node:crypto";import{PM_MCP_ERROR_CODES,PM_MCP_META_KEYS,PmMcpProtocolError,isMcpRecord}from"./protocol.js";const PM_MCP_INPUT_REQUEST_METHODS=["elicitation/create","roots/list","sampling/createMessage"];class PmMcpInputRequiredError extends Error{inputRequests;requestState;constructor(input){super("MCP operation requires additional input"),this.name="PmMcpInputRequiredError",this.inputRequests=input.inputRequests,this.requestState=input.requestState}}const INPUT_KEY_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/u,MAX_INPUT_REQUESTS=32,MAX_INPUT_PAYLOAD_BYTES=64*1024,MAX_REQUEST_STATE_BYTES=16*1024,DEFAULT_SCHEMA_BOUNDS={maxBytes:256*1024,maxDepth:32,maxNodes:4096};function inputCapability(method){return method==="elicitation/create"?"elicitation":method==="sampling/createMessage"?"sampling":"roots"}function assertBoundedJson(value,maximumBytes,field){let serialized;try{serialized=JSON.stringify(value)}catch{throw new PmMcpProtocolError(`Invalid ${field}: value is not JSON serializable`,PM_MCP_ERROR_CODES.invalidParams,{field})}if(Buffer.byteLength(serialized,"utf8")>maximumBytes)throw new PmMcpProtocolError(`Invalid ${field}: payload exceeds the protocol bound`,PM_MCP_ERROR_CODES.invalidParams,{field,maximumBytes})}function parseMcpInputRequests(value,requestContext){if(!isMcpRecord(value))throw new PmMcpProtocolError("Invalid MCP inputRequests",PM_MCP_ERROR_CODES.invalidParams,{field:"inputRequests",expected:"object"});const entries=Object.entries(value);if(entries.length===0||entries.length>MAX_INPUT_REQUESTS)throw new PmMcpProtocolError("Invalid MCP inputRequests count",PM_MCP_ERROR_CODES.invalidParams,{minimum:1,maximum:MAX_INPUT_REQUESTS,observed:entries.length});const parsed={};for(const[key,request]of entries){if(!INPUT_KEY_PATTERN.test(key)||!isMcpRecord(request))throw new PmMcpProtocolError("Invalid MCP input request entry",PM_MCP_ERROR_CODES.invalidParams,{field:`inputRequests.${key}`});const method=request.method;if(typeof method!="string"||!PM_MCP_INPUT_REQUEST_METHODS.includes(method))throw new PmMcpProtocolError("Unsupported MCP input request method",PM_MCP_ERROR_CODES.invalidParams,{field:`inputRequests.${key}.method`,method:method??null});const capability=inputCapability(method);if(!Object.prototype.hasOwnProperty.call(requestContext.clientCapabilities,capability))throw new PmMcpProtocolError("Missing required client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{[capability]:{}}});if(!isMcpRecord(request.params))throw new PmMcpProtocolError("Invalid MCP input request parameters",PM_MCP_ERROR_CODES.invalidParams,{field:`inputRequests.${key}.params`,expected:"object"});parsed[key]={method,params:structuredClone(request.params)}}return assertBoundedJson(parsed,MAX_INPUT_PAYLOAD_BYTES,"inputRequests"),parsed}function parseMcpInputResponses(value){if(!isMcpRecord(value))throw new PmMcpProtocolError("Invalid MCP inputResponses",PM_MCP_ERROR_CODES.invalidParams,{field:"inputResponses",expected:"object"});const entries=Object.entries(value);if(entries.length>MAX_INPUT_REQUESTS)throw new PmMcpProtocolError("Invalid MCP inputResponses count",PM_MCP_ERROR_CODES.invalidParams,{maximum:MAX_INPUT_REQUESTS,observed:entries.length});const parsed={};for(const[key,response]of entries){if(!INPUT_KEY_PATTERN.test(key)||!isMcpRecord(response))throw new PmMcpProtocolError("Invalid MCP input response entry",PM_MCP_ERROR_CODES.invalidParams,{field:`inputResponses.${key}`});parsed[key]=structuredClone(response)}return assertBoundedJson(parsed,MAX_INPUT_PAYLOAD_BYTES,"inputResponses"),parsed}function buildMcpInputRequiredResult(input){const requestState=input.requestState?.trim();if(requestState&&Buffer.byteLength(requestState,"utf8")>MAX_REQUEST_STATE_BYTES)throw new PmMcpProtocolError("Invalid MCP requestState: payload exceeds the protocol bound",PM_MCP_ERROR_CODES.invalidParams,{field:"requestState",maximumBytes:MAX_REQUEST_STATE_BYTES});const inputRequests=input.inputRequests===void 0?void 0:parseMcpInputRequests(input.inputRequests,input.requestContext);if(inputRequests===void 0&&!requestState)throw new PmMcpProtocolError("InputRequiredResult requires inputRequests or requestState",PM_MCP_ERROR_CODES.invalidParams,{requiredAnyOf:["inputRequests","requestState"]});return{resultType:"input_required",...inputRequests?{inputRequests}:{},...requestState?{requestState}:{},_meta:{[PM_MCP_META_KEYS.serverInfo]:{...input.serverInfo}}}}function requestStateSecret(secret){const bytes=Buffer.from(secret);if(bytes.byteLength<32)throw new PmMcpProtocolError("MCP requestState signing key must contain at least 32 bytes",PM_MCP_ERROR_CODES.invalidParams,{minimumBytes:32});return bytes}function sealMcpRequestState(payload,secret){if(!Number.isSafeInteger(payload.expiresAt)||payload.expiresAt<=0||payload.method.trim().length===0||payload.parameterDigest.trim().length===0||payload.principal.trim().length===0)throw new PmMcpProtocolError("Invalid MCP requestState payload",PM_MCP_ERROR_CODES.invalidParams);const encoded=Buffer.from(JSON.stringify({version:1,...payload}),"utf8");if(encoded.byteLength>MAX_REQUEST_STATE_BYTES/2)throw new PmMcpProtocolError("MCP requestState payload exceeds the protocol bound",PM_MCP_ERROR_CODES.invalidParams,{maximumBytes:MAX_REQUEST_STATE_BYTES/2});const body=encoded.toString("base64url"),signature=createHmac("sha256",requestStateSecret(secret)).update(body).digest("base64url");return`${body}.${signature}`}function parseMcpRequestStatePayload(decoded){if(!isMcpRecord(decoded)||decoded.version!==1)throw new PmMcpProtocolError("Invalid MCP requestState payload",PM_MCP_ERROR_CODES.invalidParams,{field:"requestState"});const{expiresAt,method,parameterDigest,principal,state}=decoded;if(typeof expiresAt!="number"||!Number.isSafeInteger(expiresAt))throw new PmMcpProtocolError("Invalid MCP requestState payload",PM_MCP_ERROR_CODES.invalidParams,{field:"requestState"});if(typeof method!="string"||typeof parameterDigest!="string"||typeof principal!="string")throw new PmMcpProtocolError("Invalid MCP requestState payload",PM_MCP_ERROR_CODES.invalidParams,{field:"requestState"});return{expiresAt,method,parameterDigest,principal,state}}function openMcpRequestState(value,secret,expected){const[body,signature,extra]=value.split(".");if(!body||!signature||extra!==void 0)throw new PmMcpProtocolError("Invalid MCP requestState encoding",PM_MCP_ERROR_CODES.invalidParams,{field:"requestState"});const observed=Buffer.from(signature,"base64url"),calculated=createHmac("sha256",requestStateSecret(secret)).update(body).digest();if(observed.byteLength!==calculated.byteLength||!timingSafeEqual(observed,calculated))throw new PmMcpProtocolError("Invalid MCP requestState signature",PM_MCP_ERROR_CODES.invalidParams,{field:"requestState"});let decoded;try{decoded=JSON.parse(Buffer.from(body,"base64url").toString("utf8"))}catch{decoded=null}const payload=parseMcpRequestStatePayload(decoded),{expiresAt,method,parameterDigest,principal}=payload;if(expiresAt<(expected.nowMs??Date.now()))throw new PmMcpProtocolError("Expired MCP requestState",PM_MCP_ERROR_CODES.invalidParams,{field:"requestState",expiredAt:expiresAt});if(method!==expected.method||parameterDigest!==expected.parameterDigest||principal!==expected.principal)throw new PmMcpProtocolError("MCP requestState binding mismatch",PM_MCP_ERROR_CODES.invalidParams,{field:"requestState"});return payload}function digestMcpRequestParameters(value){return assertBoundedJson(value,MAX_INPUT_PAYLOAD_BYTES,"request parameters"),createHash("sha256").update(JSON.stringify(value)).digest("hex")}class PmMcpRequestStateReplayGuard{#consumed=new Set;#maximumEntries;constructor(maximumEntries=4096){if(!Number.isSafeInteger(maximumEntries)||maximumEntries<1)throw new PmMcpProtocolError("Invalid MCP replay guard capacity",PM_MCP_ERROR_CODES.invalidParams,{maximumEntries});this.#maximumEntries=maximumEntries}consume(value){const digest=createHash("sha256").update(value).digest("hex");if(this.#consumed.has(digest))throw new PmMcpProtocolError("MCP requestState replay detected",PM_MCP_ERROR_CODES.invalidParams,{field:"requestState"});if(this.#consumed.size>=this.#maximumEntries){const oldest=this.#consumed.values().next().value;this.#consumed.delete(oldest)}this.#consumed.add(digest)}}function parseMcpCachePolicy(value){if(!Number.isSafeInteger(value.ttlMs)||value.ttlMs<0||value.cacheScope!=="public"&&value.cacheScope!=="private")throw new PmMcpProtocolError("Invalid MCP cache policy",PM_MCP_ERROR_CODES.invalidParams,{ttlMs:value.ttlMs,cacheScope:value.cacheScope});return{ttlMs:value.ttlMs,cacheScope:value.cacheScope}}function withMcpCachePolicy(payload,policy){return{...payload,...parseMcpCachePolicy(policy)}}function decodeJsonPointerToken(value){return value.replaceAll("~1","/").replaceAll("~0","~")}function resolveLocalJsonSchemaReference(root,reference){if(reference==="#")return root;if(!reference.startsWith("#/"))return;let current=root;for(const token of reference.slice(2).split("/").map(decodeJsonPointerToken)){if(!isMcpRecord(current)&&!Array.isArray(current)||!Object.prototype.hasOwnProperty.call(current,token))return;current=current[token]}return current}function resolveMcpJsonSchemaBounds(bounds){const maximumBytes=bounds.maxBytes??DEFAULT_SCHEMA_BOUNDS.maxBytes,maximumDepth=bounds.maxDepth??DEFAULT_SCHEMA_BOUNDS.maxDepth,maximumNodes=bounds.maxNodes??DEFAULT_SCHEMA_BOUNDS.maxNodes;if(!Number.isSafeInteger(maximumBytes)||maximumBytes<2)throw new PmMcpProtocolError("Invalid MCP JSON Schema work bounds",PM_MCP_ERROR_CODES.invalidParams);if(!Number.isSafeInteger(maximumDepth)||maximumDepth<1)throw new PmMcpProtocolError("Invalid MCP JSON Schema work bounds",PM_MCP_ERROR_CODES.invalidParams);if(!Number.isSafeInteger(maximumNodes)||maximumNodes<1)throw new PmMcpProtocolError("Invalid MCP JSON Schema work bounds",PM_MCP_ERROR_CODES.invalidParams);return{maximumBytes,maximumDepth,maximumNodes}}function enqueueMcpJsonSchemaChildren(current,pending){const entries=Array.isArray(current.value)?current.value:isMcpRecord(current.value)?Object.values(current.value):[];for(const entry of entries)pending.push({value:entry,depth:current.depth+1})}function assertMcpJsonSchemaReference(root,value){if(!isMcpRecord(value)||typeof value.$ref!="string")return;const reference=value.$ref;if(reference.startsWith("#")&&resolveLocalJsonSchemaReference(root,reference)===void 0)throw new PmMcpProtocolError("MCP JSON Schema contains an unresolved local reference",PM_MCP_ERROR_CODES.invalidParams,{reference})}function validateMcpJsonSchema(schema,bounds={}){const{maximumBytes,maximumDepth,maximumNodes}=resolveMcpJsonSchemaBounds(bounds);if(typeof schema!="boolean"&&!isMcpRecord(schema))throw new PmMcpProtocolError("Invalid MCP JSON Schema root",PM_MCP_ERROR_CODES.invalidParams,{expected:"object or boolean"});assertBoundedJson(schema,maximumBytes,"JSON Schema");const pending=[{value:schema,depth:0}];let visited=0;for(;pending.length>0;){const current=pending.pop();if(visited+=1,visited>maximumNodes||current.depth>maximumDepth)throw new PmMcpProtocolError("MCP JSON Schema exceeds validation work bounds",PM_MCP_ERROR_CODES.invalidParams,{maximumDepth,maximumNodes});assertMcpJsonSchemaReference(schema,current.value),enqueueMcpJsonSchemaChildren(current,pending)}return structuredClone(schema)}export{PM_MCP_INPUT_REQUEST_METHODS,PmMcpInputRequiredError,PmMcpRequestStateReplayGuard,buildMcpInputRequiredResult,digestMcpRequestParameters,openMcpRequestState,parseMcpCachePolicy,parseMcpInputRequests,parseMcpInputResponses,sealMcpRequestState,validateMcpJsonSchema,withMcpCachePolicy};
|
|
1
|
+
import{createHash as q,createHmac as M,timingSafeEqual as x}from"node:crypto";import{PM_MCP_ERROR_CODES as i,PM_MCP_META_KEYS as R,PmMcpProtocolError as s,isMcpRecord as c}from"./protocol.js";const I=["elicitation/create","roots/list","sampling/createMessage"];class j extends Error{inputRequests;requestState;constructor(t){super("MCP operation requires additional input"),this.name="PmMcpInputRequiredError",this.inputRequests=t.inputRequests,this.requestState=t.requestState}}const v=/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/u,l=32,h=64*1024,p=16*1024,S={maxBytes:256*1024,maxDepth:32,maxNodes:4096};function N(e){return e==="elicitation/create"?"elicitation":e==="sampling/createMessage"?"sampling":"roots"}function f(e,t,n){let r;try{r=JSON.stringify(e)}catch{throw new s(`Invalid ${n}: value is not JSON serializable`,i.invalidParams,{field:n})}if(Buffer.byteLength(r,"utf8")>t)throw new s(`Invalid ${n}: payload exceeds the protocol bound`,i.invalidParams,{field:n,maximumBytes:t})}function O(e,t){if(!c(e))throw new s("Invalid MCP inputRequests",i.invalidParams,{field:"inputRequests",expected:"object"});const n=Object.entries(e);if(n.length===0||n.length>l)throw new s("Invalid MCP inputRequests count",i.invalidParams,{minimum:1,maximum:l,observed:n.length});const r={};for(const[a,o]of n){if(!v.test(a)||!c(o))throw new s("Invalid MCP input request entry",i.invalidParams,{field:`inputRequests.${a}`});const u=o.method;if(typeof u!="string"||!I.includes(u))throw new s("Unsupported MCP input request method",i.invalidParams,{field:`inputRequests.${a}.method`,method:u??null});const d=N(u);if(!Object.prototype.hasOwnProperty.call(t.clientCapabilities,d))throw new s("Missing required client capability",i.missingRequiredClientCapability,{requiredCapabilities:{[d]:{}}});if(!c(o.params))throw new s("Invalid MCP input request parameters",i.invalidParams,{field:`inputRequests.${a}.params`,expected:"object"});r[a]={method:u,params:structuredClone(o.params)}}return f(r,h,"inputRequests"),r}function k(e){if(!c(e))throw new s("Invalid MCP inputResponses",i.invalidParams,{field:"inputResponses",expected:"object"});const t=Object.entries(e);if(t.length>l)throw new s("Invalid MCP inputResponses count",i.invalidParams,{maximum:l,observed:t.length});const n={};for(const[r,a]of t){if(!v.test(r)||!c(a))throw new s("Invalid MCP input response entry",i.invalidParams,{field:`inputResponses.${r}`});n[r]=structuredClone(a)}return f(n,h,"inputResponses"),n}function L(e){const t=e.requestState?.trim();if(t&&Buffer.byteLength(t,"utf8")>p)throw new s("Invalid MCP requestState: payload exceeds the protocol bound",i.invalidParams,{field:"requestState",maximumBytes:p});const n=e.inputRequests===void 0?void 0:O(e.inputRequests,e.requestContext);if(n===void 0&&!t)throw new s("InputRequiredResult requires inputRequests or requestState",i.invalidParams,{requiredAnyOf:["inputRequests","requestState"]});return{resultType:"input_required",...n?{inputRequests:n}:{},...t?{requestState:t}:{},_meta:{[R.serverInfo]:{...e.serverInfo}}}}function y(e){const t=Buffer.from(e);if(t.byteLength<32)throw new s("MCP requestState signing key must contain at least 32 bytes",i.invalidParams,{minimumBytes:32});return t}function z(e,t){if(!Number.isSafeInteger(e.expiresAt)||e.expiresAt<=0||e.method.trim().length===0||e.parameterDigest.trim().length===0||e.principal.trim().length===0)throw new s("Invalid MCP requestState payload",i.invalidParams);const n=Buffer.from(JSON.stringify({version:1,...e}),"utf8");if(n.byteLength>p/2)throw new s("MCP requestState payload exceeds the protocol bound",i.invalidParams,{maximumBytes:p/2});const r=n.toString("base64url"),a=M("sha256",y(t)).update(r).digest("base64url");return`${r}.${a}`}function _(e){if(!c(e)||e.version!==1)throw new s("Invalid MCP requestState payload",i.invalidParams,{field:"requestState"});const{expiresAt:t,method:n,parameterDigest:r,principal:a,state:o}=e;if(typeof t!="number"||!Number.isSafeInteger(t))throw new s("Invalid MCP requestState payload",i.invalidParams,{field:"requestState"});if(typeof n!="string"||typeof r!="string"||typeof a!="string")throw new s("Invalid MCP requestState payload",i.invalidParams,{field:"requestState"});return{expiresAt:t,method:n,parameterDigest:r,principal:a,state:o}}function Y(e,t,n){const[r,a,o]=e.split(".");if(!r||!a||o!==void 0)throw new s("Invalid MCP requestState encoding",i.invalidParams,{field:"requestState"});const u=Buffer.from(a,"base64url"),d=M("sha256",y(t)).update(r).digest();if(u.byteLength!==d.byteLength||!x(u,d))throw new s("Invalid MCP requestState signature",i.invalidParams,{field:"requestState"});let m;try{m=JSON.parse(Buffer.from(r,"base64url").toString("utf8"))}catch{m=null}const P=_(m),{expiresAt:w,method:g,parameterDigest:b,principal:C}=P;if(w<(n.nowMs??Date.now()))throw new s("Expired MCP requestState",i.invalidParams,{field:"requestState",expiredAt:w});if(g!==n.method||b!==n.parameterDigest||C!==n.principal)throw new s("MCP requestState binding mismatch",i.invalidParams,{field:"requestState"});return P}function H(e){return f(e,h,"request parameters"),q("sha256").update(JSON.stringify(e)).digest("hex")}class Q{#e=new Set;#t;constructor(t=4096){if(!Number.isSafeInteger(t)||t<1)throw new s("Invalid MCP replay guard capacity",i.invalidParams,{maximumEntries:t});this.#t=t}consume(t){const n=q("sha256").update(t).digest("hex");if(this.#e.has(n))throw new s("MCP requestState replay detected",i.invalidParams,{field:"requestState"});if(this.#e.size>=this.#t){const r=this.#e.values().next().value;this.#e.delete(r)}this.#e.add(n)}}function A(e){if(!Number.isSafeInteger(e.ttlMs)||e.ttlMs<0||e.cacheScope!=="public"&&e.cacheScope!=="private")throw new s("Invalid MCP cache policy",i.invalidParams,{ttlMs:e.ttlMs,cacheScope:e.cacheScope});return{ttlMs:e.ttlMs,cacheScope:e.cacheScope}}function X(e,t){return{...e,...A(t)}}function E(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function J(e,t){if(t==="#")return e;if(!t.startsWith("#/"))return;let n=e;for(const r of t.slice(2).split("/").map(E)){if(!c(n)&&!Array.isArray(n)||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function B(e){const t=e.maxBytes??S.maxBytes,n=e.maxDepth??S.maxDepth,r=e.maxNodes??S.maxNodes;if(!Number.isSafeInteger(t)||t<2)throw new s("Invalid MCP JSON Schema work bounds",i.invalidParams);if(!Number.isSafeInteger(n)||n<1)throw new s("Invalid MCP JSON Schema work bounds",i.invalidParams);if(!Number.isSafeInteger(r)||r<1)throw new s("Invalid MCP JSON Schema work bounds",i.invalidParams);return{maximumBytes:t,maximumDepth:n,maximumNodes:r}}function T(e,t){const n=Array.isArray(e.value)?e.value:c(e.value)?Object.values(e.value):[];for(const r of n)t.push({value:r,depth:e.depth+1})}function D(e,t){if(!c(t)||typeof t.$ref!="string")return;const n=t.$ref;if(n.startsWith("#")&&J(e,n)===void 0)throw new s("MCP JSON Schema contains an unresolved local reference",i.invalidParams,{reference:n})}function K(e,t={}){const{maximumBytes:n,maximumDepth:r,maximumNodes:a}=B(t);if(typeof e!="boolean"&&!c(e))throw new s("Invalid MCP JSON Schema root",i.invalidParams,{expected:"object or boolean"});f(e,n,"JSON Schema");const o=[{value:e,depth:0}];let u=0;for(;o.length>0;){const d=o.pop();if(u+=1,u>a||d.depth>r)throw new s("MCP JSON Schema exceeds validation work bounds",i.invalidParams,{maximumDepth:r,maximumNodes:a});D(e,d.value),T(d,o)}return structuredClone(e)}export{I as PM_MCP_INPUT_REQUEST_METHODS,j as PmMcpInputRequiredError,Q as PmMcpRequestStateReplayGuard,L as buildMcpInputRequiredResult,H as digestMcpRequestParameters,Y as openMcpRequestState,A as parseMcpCachePolicy,O as parseMcpInputRequests,k as parseMcpInputResponses,z as sealMcpRequestState,K as validateMcpJsonSchema,X as withMcpCachePolicy};
|
|
2
2
|
//# sourceMappingURL=interactions.js.map
|
package/dist/sdk/mcp/protocol.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
const d="2026-07-28",C=["2025-11-25","2025-06-18"],l=[d],n={headerMismatch:-32020,missingRequiredClientCapability:-32021,unsupportedProtocolVersion:-32022,invalidParams:-32602},r={clientCapabilities:"io.modelcontextprotocol/clientCapabilities",clientInfo:"io.modelcontextprotocol/clientInfo",logLevel:"io.modelcontextprotocol/logLevel",protocolVersion:"io.modelcontextprotocol/protocolVersion",serverInfo:"io.modelcontextprotocol/serverInfo"},f=["debug","info","notice","warning","error","critical","alert","emergency"];class s extends Error{code;data;constructor(t,i,o={}){super(t),this.name="PmMcpProtocolError",this.code=i,this.data=o}}function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function m(e){if(e===void 0)return;if(!c(e))throw new s("Invalid MCP clientInfo metadata",n.invalidParams,{field:r.clientInfo,expected:"object"});const t=typeof e.name=="string"?e.name.trim():"",i=typeof e.version=="string"?e.version.trim():"";if(t.length===0||i.length===0)throw new s("Invalid MCP clientInfo metadata",n.invalidParams,{field:r.clientInfo,required:["name","version"]});const o={name:t.slice(0,128),version:i.slice(0,128)};return typeof e.description=="string"&&e.description.trim()&&(o.description=e.description.trim().slice(0,1024)),typeof e.websiteUrl=="string"&&e.websiteUrl.trim()&&(o.websiteUrl=e.websiteUrl.trim().slice(0,2048)),o}function u(e){if(e!==void 0){if(typeof e!="string"||!f.includes(e))throw new s("Invalid MCP logLevel metadata",n.invalidParams,{field:r.logLevel,allowed:[...f]});return e}}function b(e){const t=c(e)?e._meta:void 0;if(!c(t))throw new s("Missing required MCP request metadata",n.invalidParams,{required:[r.protocolVersion,r.clientCapabilities]});const i=t[r.protocolVersion];if(typeof i!="string"||!l.includes(i))throw new s("Unsupported protocol version",n.unsupportedProtocolVersion,{supported:[...l],requested:typeof i=="string"?i:null});const o=t[r.clientCapabilities];if(!c(o))throw new s("Invalid MCP client capabilities metadata",n.invalidParams,{field:r.clientCapabilities,expected:"object"});const a=m(t[r.clientInfo]),p=u(t[r.logLevel]);return{protocolVersion:d,clientCapabilities:o,...a?{clientInfo:a}:{},...p?{logLevel:p}:{}}}function g(e,t){if(t!==e.protocolVersion)throw new s("MCP protocol header does not match request metadata",n.headerMismatch,{header:t??null,metadata:e.protocolVersion})}function x(e,t){const i=t.filter(o=>!Object.prototype.hasOwnProperty.call(e.clientCapabilities,o));if(i.length>0)throw new s("Missing required client capability",n.missingRequiredClientCapability,{requiredCapabilities:Object.fromEntries(i.map(o=>[o,{}]))})}function h(e,t){const i=e.clientCapabilities.extensions;return c(i)&&c(i[t])}function M(e,t){const i=c(e._meta)?e._meta:{};return{...e,_meta:{...i,[r.serverInfo]:{...t}}}}function P(e,t){return M({...e,resultType:"complete"},t)}function w(e){const t=e.ttlMs??6e4;if(!Number.isFinite(t)||t<0)throw new s("Invalid MCP discovery cache TTL",n.invalidParams,{ttlMs:t});return P({supportedVersions:[...l],capabilities:structuredClone(e.capabilities),ttlMs:t,cacheScope:"public",...e.instructions?{instructions:e.instructions}:{}},e.serverInfo)}function _(e,t){if(c(e)&&typeof e.resultType=="string")return e.resultType;if(t==="legacy")return"complete";throw new s("Modern MCP result is missing resultType",n.invalidParams,{required:"resultType"})}export{n as PM_MCP_ERROR_CODES,C as PM_MCP_LEGACY_PROTOCOL_VERSIONS,f as PM_MCP_LOG_LEVELS,r as PM_MCP_META_KEYS,d as PM_MCP_PROTOCOL_VERSION,l as PM_MCP_SUPPORTED_PROTOCOL_VERSIONS,s as PmMcpProtocolError,x as assertMcpClientCapabilities,g as assertMcpProtocolHeader,M as attachMcpServerInfo,P as buildMcpCompleteResult,w as buildMcpDiscoverResult,h as hasMcpClientExtension,_ as interpretMcpResultType,c as isMcpRecord,m as parseMcpImplementation,b as resolveMcpRequestContext};
|
|
2
2
|
//# sourceMappingURL=protocol.js.map
|
package/dist/sdk/mcp/skills.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
`)).digest("hex");
|
|
3
|
-
`)).digest("hex").slice(0,16)}#
|
|
1
|
+
import{createHash as $}from"node:crypto";import{lstat as T,readdir as M,readFile as j}from"node:fs/promises";import p from"node:path";import{parseDocument as N}from"yaml";import{isFileAbsentError as K}from"../../core/fs/fs-utils.js";import{PM_MCP_ERROR_CODES as D,PM_MCP_PROTOCOL_VERSION as V,PmMcpProtocolError as P,isMcpRecord as b}from"./protocol.js";const w="io.modelcontextprotocol/skills",_="SEP-2640@a3e147ca2710f68214247aecc729731ee1ae8d03",q=Object.freeze({revision:_,status:"draft",directoryRead:!0});function te(a,t=!1){const i=a.clientCapabilities.extensions,e=b(i)?i[w]:void 0;if(!b(e)||e.revision!==_||t&&e.directoryRead!==!0)throw new P("Missing or incompatible Skills over MCP draft capability",D.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[w]:q}}})}const u=Object.freeze({maxFilesPerSkill:512,maxFileBytes:16*1024*1024,maxSkillBytes:16*1024*1024,defaultPageSize:20,maxPageSize:100}),C=100,U=32*1024*1024,Y=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,L=new Set(Array.from({length:u.maxPageSize},(a,t)=>t+1));function l(a,t){throw new P(a,-32602,t)}function I(a,t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t),a.endsWith(".md")?"text/markdown":"text/plain"}catch{return"application/octet-stream"}}function G(a,t){const i=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(a);i||l(`Skill ${t} is missing YAML frontmatter.`);const e=N(i[1],{prettyErrors:!1,strict:!0,uniqueKeys:!0});e.errors.length>0&&l(`Skill ${t} has invalid YAML frontmatter.`,{errors:e.errors.map(n=>n.message)});let r;try{r=e.toJS({maxAliasCount:0})}catch(n){l(`Skill ${t} has unsupported YAML aliases.`,{error:String(n)})}return(typeof r!="object"||r===null||Array.isArray(r))&&l(`Skill ${t} frontmatter must be an object.`),r}async function J(a,t,i,e){return i>u.maxFileBytes&&l(`Skill resource exceeds the per-file limit: ${t}.`),e.files+=1,e.files>u.maxFilesPerSkill&&l(`Skill exceeds ${u.maxFilesPerSkill} files.`),e.skillBytes+=i,e.skillBytes>u.maxSkillBytes&&l(`Skill exceeds the aggregate byte limit: ${t}.`),e.originBytes.value+=i,e.originBytes.value>U&&l(`Skill origin exceeds the aggregate byte limit: ${t}.`),j(a)}async function R(a,t,i){const e=p.join(a,t),r=await M(e,{withFileTypes:!0}),n=[];for(const c of r.sort((s,o)=>s.name.localeCompare(o.name))){const s=p.posix.join(t.split(p.sep).join("/"),c.name),o=p.join(a,...s.split("/")),m=await T(o);m.isSymbolicLink()&&l(`Skill resource must not be a symbolic link: ${s}.`),m.isDirectory()?n.push(...await R(a,s,i)):m.isFile()?n.push({relative:s,bytes:await J(o,s,m.size,i)}):l(`Skill resource must be a regular file or directory: ${s}.`)}return n}async function v(a,t,i){const e=new Map;let r;try{r=await M(a,{withFileTypes:!0})}catch(s){if(K(s))return e;throw s}const n=r.filter(s=>s.isDirectory()&&Y.test(s.name)).sort((s,o)=>s.name.localeCompare(o.name));n.length>C&&l(`Skill origin exceeds ${C} directories.`);const c={value:0};for(const s of n){const o=await R(p.join(a,s.name),"",{files:0,skillBytes:0,originBytes:c}),m=o.reduce((f,S)=>f+S.bytes.byteLength,0),g=o.find(f=>f.relative==="SKILL.md");if(!g)continue;const d=G(g.bytes.toString("utf8"),s.name);d.name!==s.name&&l(`Skill directory ${s.name} must match frontmatter name.`,{actual:d.name??null,expected:s.name}),(typeof d.description!="string"||d.description.trim().length===0)&&l(`Skill ${s.name} requires a non-empty frontmatter description.`,{required:["description"]});const k=o.map(f=>({uri:`skill://${s.name}/${f.relative}`,digest:`sha256:${$("sha256").update(f.bytes).digest("hex")}`,size:f.bytes.byteLength})),y=$("sha256").update(k.map(f=>`${f.uri}:${f.digest}`).join(`
|
|
2
|
+
`)).digest("hex");e.set(s.name,{uri:`skill://${s.name}/SKILL.md`,frontmatter:d,resources:k,_meta:{contractVersion:1,extensionRevision:_,origin:t,packageVersion:i,protocolVersion:V,trust:"untrusted",estimatedTokens:Math.ceil(m/4)},files:new Map(o.map(f=>[f.relative,f.bytes])),fingerprint:y})}return e}function E(a){const{files:t,fingerprint:i,...e}=a;return e}class z{#e;#t;constructor(t){this.#e=t,this.#t=$("sha256").update([...t.entries()].sort(([i],[e])=>i.localeCompare(e)).map(([i,e])=>`${i}:${e.fingerprint}`).join(`
|
|
3
|
+
`)).digest("hex").slice(0,16)}#i(t,i){if(!t)return 0;try{const e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return(typeof e!="object"||e===null||!("fingerprint"in e)||e.fingerprint!==this.#t||!("scope"in e)||e.scope!==i||!("offset"in e)||!Number.isInteger(e.offset)||Number(e.offset)<0)&&l("Skill cursor is invalid or stale."),Number(e.offset)}catch(e){if(e instanceof P)throw e;return l("Skill cursor is invalid or stale.")}}#s(t,i){return Buffer.from(JSON.stringify({fingerprint:this.#t,offset:t,scope:i})).toString("base64url")}static async load(t){const i=await v(p.join(t.packageRoot,".agents","skills"),"package",t.packageVersion);if(t.workspaceRoot){const e=p.resolve(t.packageRoot,".agents","skills"),r=p.resolve(t.workspaceRoot,".agents","skills");if(r!==e){const n=await v(r,"workspace",t.packageVersion);for(const[c,s]of n)i.set(c,s)}}return new z(i)}list(t={}){const i=t.limit??u.defaultPageSize;L.has(i)||l(`Skill list limit must be an integer from 1 to ${u.maxPageSize}.`);const e=this.#i(t.cursor,"skills/list"),r=[...this.#e.values()].sort((o,m)=>o.uri.localeCompare(m.uri)),n=r.slice(e,e+i),c=e+n.length,s=c<r.length;return{skills:n.map(E),hasMore:s,...s?{nextCursor:this.#s(c,"skills/list")}:{}}}get(t){const i=/^skill:\/\/([a-z0-9]+(?:-[a-z0-9]+)*)\/SKILL\.md$/u.exec(t),e=i?this.#e.get(i[1]):void 0;return e||l(`Unknown pm MCP skill: ${t}.`,{field:"uri"}),E(e)}read(t){const i=/^skill:\/\/([a-z0-9]+(?:-[a-z0-9]+)*)\/(.+)$/u.exec(t),e=i?this.#e.get(i[1]):void 0,r=i?.[2]??"",n=e&&r?e.files.get(r):void 0,c=e?.resources.find(m=>m.uri===t);(!e||!n||!c)&&l(`Unknown pm MCP skill resource: ${t}.`,{field:"uri"});const s={digest:c.digest,origin:e._meta.origin,trust:"untrusted"},o=I(r,n);return o!=="application/octet-stream"?{contents:[{uri:t,mimeType:o,text:n.toString("utf8"),_meta:s}]}:{contents:[{uri:t,mimeType:o,blob:n.toString("base64"),_meta:s}]}}readDirectory(t,i={}){const e=/^skill:\/\/([a-z0-9]+(?:-[a-z0-9]+)*)(?:\/(.+))?$/u.exec(t),r=e?this.#e.get(e[1]):void 0;r||l(`Unknown pm MCP skill directory: ${t}.`,{field:"uri"});const n=(e?.[2]??"").replace(/\/$/u,""),c=n.length>0?`${n}/`:"",s=`skill://${e[1]}`,o=new Map;for(const S of r.resources){const x=S.uri.slice(`${s}/`.length);if(!x.startsWith(c))continue;const B=x.slice(c.length),[h,...O]=B.split("/"),A=`${s}/${c}${h}`,F=r.files.get(`${c}${h}`);o.set(h,{uri:A,name:h,mimeType:O.length>0?"inode/directory":I(h,F)})}n.length>0&&o.size===0&&l(`Unknown pm MCP skill directory: ${t}.`,{field:"uri"});const m=i.limit??u.maxPageSize;L.has(m)||l(`Skill directory limit must be an integer from 1 to ${u.maxPageSize}.`);const g=this.#i(i.cursor,t),d=[...o.values()].sort((S,x)=>S.uri.localeCompare(x.uri)),k=d.slice(g,g+m),y=g+k.length,f=y<d.length;return{resources:k,hasMore:f,...f?{nextCursor:this.#s(y,t)}:{}}}}export{_ as PM_MCP_SKILLS_DRAFT_REVISION,w as PM_MCP_SKILLS_EXTENSION,q as PM_MCP_SKILLS_SERVER_CAPABILITY,u as PM_MCP_SKILL_LIMITS,z as PmMcpSkillRegistry,te as assertPmMcpSkillsCapability};
|
|
4
4
|
//# sourceMappingURL=skills.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{PM_MCP_ERROR_CODES as c,PmMcpProtocolError as a,attachMcpServerInfo as h,isMcpRecord as p}from"./protocol.js";const u="io.modelcontextprotocol/subscriptionId",l=256,f=2048,m=5e3;function C(s,e){return new Promise((t,i)=>{const r=setTimeout(()=>i(new Error("MCP subscription sink write timed out")),m);r.unref(),Promise.resolve().then(()=>s(e)).then(()=>{clearTimeout(r),t()},o=>{clearTimeout(r),i(o instanceof Error?o:new Error(String(o)))})})}function d(s,e){if(s!==void 0){if(typeof s!="boolean")throw new a("Invalid MCP subscription filter",c.invalidParams,{field:`notifications.${e}`,expected:"boolean"});return s||void 0}}function g(s){if(!p(s))throw new a("Invalid MCP subscription filter",c.invalidParams,{field:"notifications",expected:"object"});const e=d(s.toolsListChanged,"toolsListChanged"),t=d(s.promptsListChanged,"promptsListChanged"),i=d(s.resourcesListChanged,"resourcesListChanged");let r;if(s.resourceSubscriptions!==void 0){if(!Array.isArray(s.resourceSubscriptions)||s.resourceSubscriptions.length>l)throw new a("Invalid MCP resource subscriptions",c.invalidParams,{field:"notifications.resourceSubscriptions",maximum:l});const o=new Set;for(const n of s.resourceSubscriptions){if(typeof n!="string"||n.trim().length===0||Buffer.byteLength(n,"utf8")>f)throw new a("Invalid MCP resource subscription URI",c.invalidParams,{field:"notifications.resourceSubscriptions",maximumBytes:f});o.add(n)}o.size>0&&(r=[...o].sort())}return{...e?{toolsListChanged:e}:{},...t?{promptsListChanged:t}:{},...i?{resourcesListChanged:i}:{},...r?{resourceSubscriptions:r}:{}}}function w(s,e){return{...s.toolsListChanged&&e.tools?.listChanged?{toolsListChanged:!0}:{},...s.promptsListChanged&&e.prompts?.listChanged?{promptsListChanged:!0}:{},...s.resourcesListChanged&&e.resources?.listChanged?{resourcesListChanged:!0}:{},...s.resourceSubscriptions&&e.resources?.subscribe?{resourceSubscriptions:[...s.resourceSubscriptions]}:{}}}class b{#s;#e=new Map;#i;constructor(e){this.#s=structuredClone(e.capabilities),this.#i={...e.serverInfo}}get size(){return this.#e.size}async open(e){if(this.#e.has(e.id))throw new a("MCP subscription id is already active",c.invalidParams,{subscriptionId:e.id});const t=w(g(e.notifications),this.#s),i={filter:t,sink:e.sink,writeQueue:Promise.resolve()};this.#e.set(e.id,i);try{await this.#t(e.id,i,{jsonrpc:"2.0",method:"notifications/subscriptions/acknowledged",params:{_meta:{[u]:e.id},notifications:structuredClone(t)}},!0)}catch(r){throw this.#e.delete(e.id),r}return structuredClone(t)}async emitListChanged(e){const t=`${e}ListChanged`,i=`notifications/${e}/list_changed`,r=[];for(const[o,n]of this.#e)n.filter[t]===!0&&r.push(this.#t(o,n,{jsonrpc:"2.0",method:i,params:{_meta:{[u]:o}}}));return(await Promise.all(r)).filter(Boolean).length}async emitResourceUpdated(e){const t=[];for(const[i,r]of this.#e)r.filter.resourceSubscriptions?.includes(e)&&t.push(this.#t(i,r,{jsonrpc:"2.0",method:"notifications/resources/updated",params:{_meta:{[u]:i},uri:e}}));return(await Promise.all(t)).filter(Boolean).length}async#t(e,t,i,r=!1){const o=t.writeQueue.then(async()=>{if(this.#e.get(e)!==t)return!1;try{return await C(t.sink,i),!0}catch(n){if(this.#e.get(e)===t&&this.#e.delete(e),r)throw n;return!1}});return t.writeQueue=o.then(()=>{},()=>{}),o}close(e){if(this.#e.delete(e))return{...h({resultType:"complete",_meta:{[u]:e}},this.#i)}}closeAll(){const e=[];for(const t of this.#e.keys()){const i=this.close(t);e.push({id:t,result:i})}return e}}export{u as PM_MCP_SUBSCRIPTION_ID_META_KEY,b as PmMcpSubscriptionRegistry,g as parseMcpSubscriptionFilter,w as resolveMcpAcknowledgedSubscriptionFilter};
|
|
2
2
|
//# sourceMappingURL=subscriptions.js.map
|