@unbrained/pm-cli 2026.11.7 → 2026.11.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +84 -48
- package/dist/cli/extension-command-help.js +4 -3
- package/dist/cli/help-json-payload.js +1 -1
- package/dist/cli/main.js +1 -1
- package/dist/cli/register-annotations.js +1 -1
- package/dist/cli/register-list-query.js +5 -5
- package/dist/cli/runtime/annotation-option-retry.js +2 -0
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli/runtime/projection-retry.js +1 -1
- package/dist/cli/runtime/read-output-mutation-retry.js +2 -0
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3BMIAI4P.js +8 -0
- package/dist/cli-bundle/chunks/chunk-5VRJPPUC.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-WXVMPLBY.js → chunk-6V4PGJBZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-F3B2ULHB.js → chunk-ASJZMYKM.js} +33 -33
- package/dist/cli-bundle/chunks/chunk-BLUCQ4T4.js +2 -0
- package/dist/cli-bundle/chunks/chunk-ELNWRSGZ.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-RFI4O6NU.js → chunk-EZRLW4R6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OJZG7Y6S.js → chunk-G6Q4VQSI.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-GCPP37N6.js +116 -0
- package/dist/cli-bundle/chunks/{chunk-OIBSKKCO.js → chunk-GDQ2T2OR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KPAVZILX.js → chunk-GZVOOHTO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3DI6CEF3.js → chunk-IGT252ES.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-JK7O7MFO.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-MQOZNGPS.js → chunk-JYQXIC6C.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XSEDESNW.js → chunk-LVDFPGD7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QG6FLDM4.js → chunk-MSJ7IHMJ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BQ5O3CBF.js → chunk-O2M3TNFY.js} +69 -65
- package/dist/cli-bundle/chunks/chunk-UFIM5ZC5.js +6 -0
- package/dist/cli-bundle/chunks/chunk-VATZTJE3.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-WS2N4TQW.js → chunk-XKY4LUXN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-VM6OGNQC.js → chunk-YK5GAWOT.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TGQPCNAD.js → chunk-YV5ALMG2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ETHAZC3F.js → chunk-Z3QEEOAM.js} +2 -2
- package/dist/cli-bundle/chunks/item-revision-Y5CE3EIN.js +2 -0
- package/dist/cli-bundle/chunks/item-transaction-XBIN4KYM.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-LUXUKISJ.js → mutation-admission-TAQN2AKK.js} +2 -2
- package/dist/cli-bundle/chunks/register-list-query-XMQYFUFI.js +11 -0
- package/dist/cli-bundle/chunks/register-mutation-OBVCFLDK.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-AHDWE2G3.js → register-operations-CGNFZ6DR.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-7BGG3CI3.js → register-setup-LFB5ERXH.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-S5BYWLGY.js → stage-NQHF6JPC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-2SQUWQP3.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-4FWMXQN3.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-AH5IST3V.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-4EXRRSDS.js → chunk-ALLOWZSH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IYJRFJHT.js → chunk-C3DO4ZGZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CUGJ2DY2.js +24 -0
- package/dist/cli-bundle/focused-chunks/chunk-HLQOGAWG.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-HNFY3XLC.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IB6TCE7N.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LW4TN5ZM.js → chunk-IS5FLEZW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-J7PWHKZK.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-JU62TKJP.js +82 -0
- package/dist/cli-bundle/focused-chunks/chunk-LDMBNTOG.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-LWMPQRJT.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-MYBKRV5R.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-NUFO3OR6.js +44 -0
- package/dist/cli-bundle/focused-chunks/chunk-NZQYHPUN.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JRJOFMI7.js → chunk-Q45LDP7P.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QWUWNFQO.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-RNZUORGI.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-G2VIY6XA.js → chunk-UIKLNSW3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BIDF4KO7.js → chunk-XLSTFUXM.js} +8 -8
- package/dist/cli-bundle/focused-chunks/item-revision-M6FOLME2.js +2 -0
- package/dist/cli-bundle/focused-chunks/item-transaction-H6VA5JGB.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-PRTQWQK6.js +2 -0
- package/dist/cli-bundle/focused-chunks/stage-7T77PSJD.js +2 -0
- package/dist/cli-bundle/main.js +32 -31
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +4 -4
- package/dist/cli-bundle/sdk-core.js +1 -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 +57 -57
- 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 +12 -12
- package/dist/core/extensions/flag-definition-validation.js +1 -1
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/history/history-stream-policy.d.ts +12 -3
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/projection.d.ts +7 -2
- package/dist/core/history/projection.js +1 -1
- package/dist/core/item/item-format.d.ts +13 -1
- package/dist/core/item/item-format.js +2 -2
- package/dist/core/lock/lock.d.ts +1 -1
- package/dist/core/lock/lock.js +1 -1
- package/dist/core/output/output.d.ts +17 -1
- package/dist/core/output/output.js +7 -7
- package/dist/core/search/corpus.js +1 -1
- package/dist/core/search/providers.d.ts +3 -2
- package/dist/core/search/providers.js +1 -1
- package/dist/core/search/vector-stores.d.ts +3 -2
- package/dist/core/search/vector-stores.js +1 -1
- package/dist/core/sentry/instrument.d.ts +2 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/annotations.d.ts +44 -1
- package/dist/sdk/annotations.js +1 -1
- package/dist/sdk/authoring.d.ts +6 -0
- package/dist/sdk/authoring.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +15 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +6 -0
- package/dist/sdk/cli-contracts/runtime-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/command-line.d.ts +2 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/comments.d.ts +4 -2
- package/dist/sdk/comments.js +1 -1
- package/dist/sdk/completion/bash.js +1 -1
- package/dist/sdk/completion/fish.js +2 -1
- package/dist/sdk/completion/zsh.js +4 -1
- package/dist/sdk/context-intent-contracts.d.ts +5 -1
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/contracts.d.ts +3 -0
- package/dist/sdk/contracts.js +1 -1
- package/dist/sdk/core.d.ts +14 -0
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/corpus-shape.d.ts +2 -2
- package/dist/sdk/corpus-shape.js +1 -1
- package/dist/sdk/define.d.ts +14 -8
- package/dist/sdk/define.js +1 -1
- package/dist/sdk/extension/command-options.d.ts +123 -0
- package/dist/sdk/extension/command-options.js +2 -0
- package/dist/sdk/extension-contracts.d.ts +1 -2
- package/dist/sdk/extension-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/governance.d.ts +8 -0
- package/dist/sdk/governance.js +1 -1
- package/dist/sdk/graph.d.ts +5 -0
- package/dist/sdk/graph.js +1 -1
- package/dist/sdk/index.d.ts +61 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/learnings.d.ts +4 -2
- package/dist/sdk/learnings.js +1 -1
- package/dist/sdk/lifecycle/item-revision.d.ts +6 -0
- package/dist/sdk/lifecycle/item-revision.js +1 -1
- package/dist/sdk/lifecycle/restore.d.ts +1 -1
- package/dist/sdk/merge.d.ts +3 -0
- package/dist/sdk/merge.js +1 -1
- package/dist/sdk/notes.d.ts +4 -2
- package/dist/sdk/notes.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/get-facet-roots.js +2 -0
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/list.d.ts +5 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/search/semantic.d.ts +11 -3
- package/dist/sdk/query/search/semantic.js +1 -1
- package/dist/sdk/query/search-rendering.d.ts +9 -3
- package/dist/sdk/query/search-rendering.js +1 -1
- package/dist/sdk/query.d.ts +11 -0
- package/dist/sdk/query.js +1 -1
- package/dist/sdk/read-output/continuation.d.ts +8 -0
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output/options.d.ts +1 -1
- package/dist/sdk/read-output/options.js +1 -1
- package/dist/sdk/read-output/positional-rows.js +2 -0
- package/dist/sdk/read-output/surfaces.js +1 -1
- package/dist/sdk/read-output/tail-retention.d.ts +34 -0
- package/dist/sdk/read-output/tail-retention.js +2 -0
- package/dist/sdk/read-output-budget.d.ts +14 -2
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.d.ts +24 -4
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-rows.d.ts +7 -3
- package/dist/sdk/read-output-rows.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime.d.ts +26 -3
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/execution.d.ts +29 -2
- package/dist/sdk/test/execution.js +1 -1
- package/dist/sdk/testing.d.ts +14 -1
- package/dist/sdk/testing.js +1 -1
- package/dist/sdk/traceability/source-traceability.d.ts +4 -1
- package/dist/sdk/traceability/source-traceability.js +1 -1
- package/dist/sdk/workspace-recipe.d.ts +2 -2
- package/dist/sdk/workspace-recipe.js +1 -1
- package/docs/AGENT_OUTPUT_ENCODINGS.md +16 -0
- package/docs/ARCHITECTURE.md +2 -1
- package/docs/COMMANDS.md +4 -1
- package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +1 -1
- package/docs/EXTENSIONS.md +1 -1
- package/docs/MCP_OPTION_CONFORMANCE.md +13 -0
- package/docs/README.md +2 -2
- package/docs/READ_OUTPUT_CONTRACTS.md +99 -0
- package/docs/RELEASING.md +27 -5
- package/docs/SDK.md +100 -2
- package/docs/SDK_CONTEXT_INTEGRITY.md +2 -0
- package/docs/agent-task-token-baseline.json +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +6 -6
- package/marketplace.json +1 -1
- package/package.json +3 -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/dist/cli/extension-command-options.js +0 -2
- package/dist/cli-bundle/chunks/chunk-4PPWVIIT.js +0 -2
- package/dist/cli-bundle/chunks/chunk-5KHLV7JU.js +0 -116
- package/dist/cli-bundle/chunks/chunk-COKKWMSC.js +0 -8
- package/dist/cli-bundle/chunks/chunk-D53G3NOE.js +0 -6
- package/dist/cli-bundle/chunks/chunk-JZWFZH2K.js +0 -2
- package/dist/cli-bundle/chunks/chunk-O6TIOKCM.js +0 -9
- package/dist/cli-bundle/chunks/chunk-WYIDX67P.js +0 -31
- package/dist/cli-bundle/chunks/item-revision-SPEKTFBB.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-BT55TQXE.js +0 -2
- package/dist/cli-bundle/chunks/register-list-query-DU4W7VJU.js +0 -11
- package/dist/cli-bundle/chunks/register-mutation-IC2C53QK.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-4LDOL6U7.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-4PW5XWVI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-A46YSPRF.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-AI2PYNFI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-AJ2I377F.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-CWFNQQZE.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-D3U7FOZR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GFF6BITP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IIBWXNW3.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-J5N42SKC.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-KL33JMPC.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LH4C7BLB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LTQEYE2L.js +0 -81
- package/dist/cli-bundle/focused-chunks/chunk-LTTMERPN.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-MESFDQ3H.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-MWTBAI3V.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-TWULNB3N.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-XAC6NP7U.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-XG3TBYQK.js +0 -23
- package/dist/cli-bundle/focused-chunks/chunk-XMZAFKVP.js +0 -91
- package/dist/cli-bundle/focused-chunks/item-revision-ELI6NGMY.js +0 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-GUGAUY77.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-54FI37AA.js +0 -2
- package/dist/cli-bundle/focused-chunks/stage-OHDJ43T2.js +0 -2
- package/docs/ECOSYSTEM_PLANNING_REVIEW.md +0 -274
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +0 -472
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a378018f-b981-5e5e-98a4-45d190039473")}catch{}})();import{getActiveCommandContext,runActiveCommandOverride,runActiveRendererOverride,runActiveServiceOverrideSync,setActiveCommandResult}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{isHostOutputSuppressed}from"./output-control.js";import{projectMutationResult}from"./mutation-projection.js";import{attachReadOutputContracts}from"../../sdk/context-intent-contracts.js";import{attachOutputTokenAccounting}from"../../sdk/output-token-accounting.js";import{propagateContextUsageServingReceipt}from"../../sdk/context-usage.js";import{isReadResultOmittedForBudget,resolveReadOutputEncoding,resolveReadOutputSurface}from"../../sdk/read-output-contracts.js";import{readOutputPositionalRowPaths}from"../../sdk/read-output/positional-rows.js";import{GET_FACET_ROOTS}from"../../sdk/query/get-facet-roots.js";import{withDeliveredOutputRenderer}from"../../sdk/read-output-budget.js";import{encode as encodeToon}from"@toon-format/toon";import{encodePmTableRows}from"../../sdk/output/table-rows.js";import{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope}from"../../sdk/output/list-envelope.js";import{prepareWellFormedOutputText}from"../shared/output-unicode.js";const DECLARED_PROCESS_EXIT_CODES=new Set(Object.values(EXIT_CODE)),COLLECTION_COUNT_ALIASES=new Map([["notes_count","notes"],["tests_count","tests"]]),NATIVE_OUTPUT_MARKER="__pm_native_output";let streamErrorHandlersInstalled=!1;function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function setActiveCommandResultOmitted(source){const omitted={read_output:{result_omitted:!0}};propagateContextUsageServingReceipt(source,omitted),setActiveCommandResult(omitted)}function setActiveCommandDeliveryResult(result,receiptSource,structuredDeliveryPreserved){if(structuredDeliveryPreserved){setActiveCommandResult(result);return}setActiveCommandResultOmitted(receiptSource)}function stripNativeOutputMarker(result){if(!isPlainObject(result)||result[NATIVE_OUTPUT_MARKER]!==!0)return result;const{[NATIVE_OUTPUT_MARKER]:_marker,...rest}=result;return rest}function isBrokenPipeError(error){return typeof error=="object"&&error!==null&&error.code==="EPIPE"}function markStdoutBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.SUCCESS)}function markStderrBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}function markBrokenPipeExitCode(target){if(target==="stdout"){markStdoutBrokenPipeExitCode();return}markStderrBrokenPipeExitCode()}function handleUnhandledStreamError(error){const unhandled=error instanceof Error?error:new Error(String(error));setImmediate(()=>{throw unhandled})}function installStreamErrorHandlers(){streamErrorHandlersInstalled||(streamErrorHandlersInstalled=!0,process.stdout.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stdout");return}handleUnhandledStreamError(error)}),process.stderr.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stderr");return}handleUnhandledStreamError(error)}))}function writeToStream(target,text){installStreamErrorHandlers();try{return target==="stdout"?process.stdout.write(text):process.stderr.write(text),!0}catch(error){if(isBrokenPipeError(error))return markBrokenPipeExitCode(target),!1;throw error}}function writeStdout(text){return writeToStream("stdout",text)}function writeStderr(text){return writeToStream("stderr",text)}function renderScalar(value){return typeof value=="string"?JSON.stringify(value):typeof value=="number"||typeof value=="boolean"?String(value):value===null?"null":JSON.stringify(value)}function indentToon(encoded,depth){const indent=" ".repeat(depth);return encoded.split(`
|
|
2
2
|
`).map(line=>`${indent}${line}`).join(`
|
|
3
|
-
`)}function isNestedTableCandidateBounded(rows){const columns=new Set;let presentCells=0;for(const row of rows){const keys=Object.keys(row);presentCells+=keys.length;for(const key of keys)columns.add(key)}return rows.length*columns.size<=presentCells*2}function renderToonObjectEntry(key,entry,depth,allowNestedTable){const indent=" ".repeat(depth);if(!isPlainObject(entry)&&!Array.isArray(entry))return`${indent}${key}: ${renderScalar(entry)}`;if(Array.isArray(entry)){if(entry.length===0)return`${indent}${key}: []`;const expanded=indentToon(encodeToon({[key]:entry}),depth);return allowNestedTable&&entry.length>=1&&entry.every(isPlainObject)&&isNestedTableCandidateBounded(entry)?[!1,!0].map(compact=>{const table=encodePmTableRows(entry,{compact});return indentToon(encodeToon({[key]:table.rows,[`${key}_encoding`]:table.encoding}),depth)}).reduce((smallest,candidate)=>Buffer.byteLength(candidate)<Buffer.byteLength(smallest)?candidate:smallest,expanded):expanded}return isPlainObject(entry)&&Object.keys(entry).length===0?`${indent}${key}: {}`:`${indent}${key}:
|
|
3
|
+
`)}function isNestedTableCandidateBounded(rows){const columns=new Set;let presentCells=0;for(const row of rows){const keys=Object.keys(row);presentCells+=keys.length;for(const key of keys)columns.add(key)}return rows.length*columns.size<=presentCells*2}function renderToonObjectEntry(key,entry,depth,allowNestedTable){const indent=" ".repeat(depth);if(!isPlainObject(entry)&&!Array.isArray(entry))return`${indent}${key}: ${renderScalar(entry)}`;if(key==="omission_receipt"&&isCompleteOmissionReceipt(entry))return`${indent}${key}: complete`;if(Array.isArray(entry)){if(entry.length===0)return`${indent}${key}: []`;const expanded=indentToon(encodeToon({[key]:entry}),depth);return allowNestedTable&&entry.length>=1&&entry.every(isPlainObject)&&isNestedTableCandidateBounded(entry)?[!1,!0].map(compact=>{const table=encodePmTableRows(entry,{compact});return indentToon(encodeToon({[key]:table.rows,[`${key}_encoding`]:table.encoding}),depth)}).reduce((smallest,candidate)=>Buffer.byteLength(candidate)<Buffer.byteLength(smallest)?candidate:smallest,expanded):expanded}return isPlainObject(entry)&&Object.keys(entry).length===0?`${indent}${key}: {}`:`${indent}${key}:
|
|
4
4
|
${renderToonValue(entry,depth+1)}`}function compactToonArray(values,policy,preserveEmpty){const compactedEntries=values.map(entry=>compactToonValue(entry,policy,preserveEmpty||policy.preserveRowFacts&&isPlainObject(entry))).filter(entry=>entry!==void 0);return compactedEntries.length>0||preserveEmpty?compactedEntries:void 0}function compactToonValue(value,policy={omitDuplicateCountAliases:!0,preserveRowFacts:!0},preserveEmpty=!1){if(value===null)return preserveEmpty?null:void 0;if(Array.isArray(value))return compactToonArray(value,policy,preserveEmpty);if(isPlainObject(value)){const compacted=[],entries=Object.entries(value).filter(([key,entry])=>{const canonicalCount=COLLECTION_COUNT_ALIASES.get(key);return!policy.omitDuplicateCountAliases||canonicalCount===void 0||!isPlainObject(value.collection_counts)||entry!==value.collection_counts[canonicalCount]});for(const[key,entry]of entries){if(key==="omitted_field_groups"&&Array.isArray(entry)&&entry.length===0){compacted.push([key,[]]);continue}const compactedEntry=compactToonValue(entry,policy,preserveEmpty);compactedEntry!==void 0&&compacted.push([key,compactedEntry])}return compacted.length>0||preserveEmpty?Object.fromEntries(compacted):void 0}return value}function renderToonValue(value,depth){const indent=" ".repeat(depth);if(Array.isArray(value))return value.length===0?"[]":indentToon(encodeToon(value),depth);if(isPlainObject(value)){const entries=Object.entries(value);return entries.length===0?"{}":entries.map(([key,entry])=>renderToonObjectEntry(key,entry,depth,!Object.hasOwn(value,`${key}_encoding`)&&!(key==="checks"&&isPlainObject(value.verdict)&&value.verdict.authority==="ok"))).join(`
|
|
5
5
|
`)}return`${indent}${renderScalar(value)}`}function renderDefaultMarkdownResult(value){if(!isPlainObject(value)||value.output_default!=="markdown"||typeof value.view!="string"||!Array.isArray(value.events)||!Array.isArray(value.days))return null;const lines=[`# pm calendar (${value.view})`,""],summary=isPlainObject(value.summary)?value.summary:{};if(lines.push(`- events: ${String(summary.events??0)}`),lines.push(""),value.events.length===0)return lines.push("No calendar events matched the selected filters."),`${lines.join(`
|
|
6
6
|
`)}
|
|
7
7
|
`;for(const event of value.events){if(!isPlainObject(event))continue;const kind=typeof event.kind=="string"?event.kind:"event",title=typeof event.item_title=="string"?event.item_title:"",itemId=typeof event.item_id=="string"?event.item_id:"",reminderText=typeof event.reminder_text=="string"&&event.reminder_text.length>0?` ${event.reminder_text}`:"";lines.push(`- [${kind}] ${itemId} ${title}${reminderText}`.trim())}return`${lines.join(`
|
|
8
8
|
`)}
|
|
9
|
-
`}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!isPlainObject(compacted)||!Array.isArray(compacted.items))return compacted??null;const projected=Object.fromEntries(Object.entries(compacted).filter(([key])=>!LEAN_READ_ENVELOPE_ECHO_KEYS.has(key)));return projected.has_more!==!0&&delete projected.next_cursor,projected}function projectLinkedTestEvidence(value,lean){if(!isPlainObject(value)||!Array.isArray(value.run_results)||!value.run_results.every(isPlainObject))return value;const rows=value.run_results,sharedContext=resolveSharedExecutionContext(rows),runResults=rows.map(row=>{const{execution_context:_executionContext,stdout,stderr,...rest}=row;return sharedContext===void 0?row:!lean||row.status!=="passed"?{...rest,stdout,stderr}:rest});return lean&&isQuietLinkedTestSuccess(value,sharedContext,rows)?projectQuietLinkedTestSuccess(value,sharedContext,runResults):{...value,...sharedContext===void 0?{}:{execution_context:sharedContext},run_results:runResults}}function resolveSharedExecutionContext(rows){const contexts=rows.map(row=>row.execution_context).filter(context=>context!==void 0);if(contexts.length!==rows.length||contexts.length===0)return;const first=JSON.stringify(contexts[0]);return contexts.every(context=>JSON.stringify(context)===first)?contexts[0]:void 0}function isQuietLinkedTestSuccess(value,sharedContext,rows){if(value.ok!==!0||!isPlainObject(sharedContext)||sharedContext.mismatch_detected!==!1||!rows.every(row=>row.status==="passed"))return!1;const categories=value.failure_categories;return!(isPlainObject(categories)&&Object.values(categories).some(count=>count!==0))}function projectQuietLinkedTestSuccess(value,context,runResults){const{failure_categories:_zeroCategories,...rest}=value,trust=isPlainObject(context.trust)?context.trust:{};return{...rest,execution_context:{pm_context_mode:context.pm_context_mode,workspace_context_mode:context.workspace_context_mode,mismatch_detected:!1,...typeof trust.trusted=="boolean"?{trusted:trust.trusted}:{},...trust.reason===void 0?{}:{trust_reason:trust.reason},restore_with:"not retained; a run without --lean reports the full context"},run_results:runResults}}function projectEmptyCheckDetails(value){return!isPlainObject(value)||value.ok!==!0||!isPlainObject(value.verdict)||value.verdict.authority!=="ok"||!Array.isArray(value.checks)?value:{...value,checks:value.checks.map(omitEmptySuccessfulCheckDetails)}}function omitEmptySuccessfulCheckDetails(check){if(!isPlainObject(check)||check.ok!==!0||!isPlainObject(check.details)||Object.keys(check.details).length!==0)return check;const{details:_details,...rest}=check;return rest}function formatBuiltInOutput(result,format,lean=!1){if(result=prepareWellFormedOutputText(result),format==="json"){const value=lean?projectLeanJsonValue(result):result,briefList=isPlainObject(result)&&isPlainObject(result.projection)&&result.projection.mode==="brief"&&Array.isArray(result.items);return`${JSON.stringify(value,null,briefList?void 0:2)}
|
|
10
|
-
`}const compactedToon=compactToonValue(projectEmptyCheckDetails(projectPmBriefSearchEnvelope(projectPmBriefListEnvelope(result))),
|
|
9
|
+
`}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!isPlainObject(compacted)||!Array.isArray(compacted.items))return compacted??null;const projected=Object.fromEntries(Object.entries(compacted).filter(([key])=>!LEAN_READ_ENVELOPE_ECHO_KEYS.has(key)));return projected.has_more!==!0&&delete projected.next_cursor,projected}function projectLinkedTestEvidence(value,lean){if(!isPlainObject(value)||!Array.isArray(value.run_results)||!value.run_results.every(isPlainObject))return value;const rows=value.run_results,sharedContext=resolveSharedExecutionContext(rows),runResults=rows.map(row=>{const{execution_context:_executionContext,stdout,stderr,...rest}=row;return sharedContext===void 0?row:!lean||row.status!=="passed"?{...rest,stdout,stderr}:rest});return lean&&isQuietLinkedTestSuccess(value,sharedContext,rows)?projectQuietLinkedTestSuccess(value,sharedContext,runResults):{...value,...sharedContext===void 0?{}:{execution_context:sharedContext},run_results:runResults}}function resolveSharedExecutionContext(rows){const contexts=rows.map(row=>row.execution_context).filter(context=>context!==void 0);if(contexts.length!==rows.length||contexts.length===0)return;const first=JSON.stringify(contexts[0]);return contexts.every(context=>JSON.stringify(context)===first)?contexts[0]:void 0}function isQuietLinkedTestSuccess(value,sharedContext,rows){if(value.ok!==!0||!isPlainObject(sharedContext)||sharedContext.mismatch_detected!==!1||!rows.every(row=>row.status==="passed"))return!1;const categories=value.failure_categories;return!(isPlainObject(categories)&&Object.values(categories).some(count=>count!==0))}function projectQuietLinkedTestSuccess(value,context,runResults){const{failure_categories:_zeroCategories,...rest}=value,trust=isPlainObject(context.trust)?context.trust:{};return{...rest,execution_context:{pm_context_mode:context.pm_context_mode,workspace_context_mode:context.workspace_context_mode,mismatch_detected:!1,...typeof trust.trusted=="boolean"?{trusted:trust.trusted}:{},...trust.reason===void 0?{}:{trust_reason:trust.reason},restore_with:"not retained; a run without --lean reports the full context"},run_results:runResults}}function projectEmptyCheckDetails(value){return!isPlainObject(value)||value.ok!==!0||!isPlainObject(value.verdict)||value.verdict.authority!=="ok"||!Array.isArray(value.checks)?value:{...value,checks:value.checks.map(omitEmptySuccessfulCheckDetails)}}function omitEmptySuccessfulCheckDetails(check){if(!isPlainObject(check)||check.ok!==!0||!isPlainObject(check.details)||Object.keys(check.details).length!==0)return check;const{details:_details,...rest}=check;return rest}function formatBuiltInOutput(result,format,lean=!1,toon={}){if(result=prepareWellFormedOutputText(result),format==="json"){const value=lean?projectLeanJsonValue(result):result,briefList=isPlainObject(result)&&isPlainObject(result.projection)&&result.projection.mode==="brief"&&Array.isArray(result.items);return`${JSON.stringify(value,null,briefList?void 0:2)}
|
|
10
|
+
`}const compactedToon=restorePositionalRows(result,restoreRequestedEmptyCollections(result,compactToonValue(projectEmptyCheckDetails(projectPmBriefSearchEnvelope(projectPmBriefListEnvelope(result))),TOON_COMPACTION_POLICY),toon.preserveEmptyItemCollections===!0),toon.positionalRowPaths??[]);return compactedToon===void 0?`{}
|
|
11
11
|
`:`${renderToonValue(compactedToon,0)}
|
|
12
|
-
`}function resolveOutputService(effectiveResult,nativeOutput,options,format){const serviceOverride=nativeOutput?{handled:!1,result:effectiveResult,warnings:[]}:runActiveServiceOverrideSync("output_format",{command:options.command,args:options.commandArgs,command_options:options.commandOptions,global:{...options},pm_root:options.pmRoot,format,options:{...options},result:effectiveResult}),legacyPayloadEchoWarning=serviceOverride.warnings.find(warning=>warning.startsWith("extension_output_format_payload_echo_deprecated:"));return legacyPayloadEchoWarning!==void 0&&writeStderr(`Warning: ${legacyPayloadEchoWarning}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
|
|
12
|
+
`}const TOON_COMPACTION_POLICY={omitDuplicateCountAliases:!0,preserveRowFacts:!0};function restoreEmptyCollections(source,compacted,preserveEmpty=!1){if(Array.isArray(source)){if(source.length===0)return[];const kept2=Array.isArray(compacted)?compacted:[],aligned=kept2.length===source.length;let next=0;const rows=source.flatMap(row=>{const rowPreservesEmpty=preserveEmpty||isPlainObject(row),dropped=!aligned&&compactToonValue(row,TOON_COMPACTION_POLICY,rowPreservesEmpty)===void 0,restored=restoreEmptyCollections(row,dropped?void 0:kept2[next++],rowPreservesEmpty);return restored===void 0?[]:[restored]});return rows.length>0?rows:compacted}if(!isPlainObject(source))return compacted;const kept=isPlainObject(compacted)?compacted:{},entries=Object.entries(source).flatMap(([key,value])=>{const restored=restoreEmptyCollections(value,Object.hasOwn(kept,key)?kept[key]:void 0,preserveEmpty);return restored===void 0?[]:[[key,restored]]});return entries.length>0||Object.keys(source).length===0?Object.fromEntries(entries):compacted}function restoreRequestedEmptyCollections(source,compacted,preserve){if(!preserve||!isPlainObject(source))return compacted;const base=isPlainObject(compacted)?compacted:{},restored=new Map(Object.keys(source).filter(key=>key==="item"||GET_FACET_ROOTS.has(key)).map(key=>[key,restoreEmptyCollections(source[key],base[key])]));return mergeRestoredEntries(source,base,restored)}function mergeRestoredEntries(source,base,restored){const entries=Object.entries(base).map(([key,value])=>[key,restored.has(key)?restored.get(key):value]),sourceKeys=Object.keys(source);for(const[key,value]of restored){if(Object.hasOwn(base,key)||value===void 0)continue;const later=new Set(sourceKeys.slice(sourceKeys.indexOf(key)+1)),position=entries.findIndex(([entryKey])=>later.has(entryKey));entries.splice(position===-1?entries.length:position,0,[key,value])}return Object.fromEntries(entries)}function restorePositionalRows(source,compacted,paths){if(!isPlainObject(source))return compacted;const restorable=paths.filter(path=>{const rows=source[path];return Array.isArray(rows)&&rows.some(row=>compactToonValue(row,TOON_COMPACTION_POLICY,isPlainObject(row))===void 0)});if(restorable.length===0)return compacted;const base=isPlainObject(compacted)?compacted:{},restored=new Map(restorable.map(path=>[path,source[path].map(row=>compactToonValue(row,TOON_COMPACTION_POLICY,!0))]));return mergeRestoredEntries(source,base,restored)}const COMPLETE_OMISSION_RECEIPT=JSON.stringify({has_omissions:!1,omitted_field_group_count:0,omitted_field_groups:[]});function isCompleteOmissionReceipt(value){const entries=Object.entries(Object(value)).sort(([left],[right])=>left.localeCompare(right));return JSON.stringify(Object.fromEntries(entries))===COMPLETE_OMISSION_RECEIPT}function resolveOutputService(effectiveResult,nativeOutput,options,format){const serviceOverride=nativeOutput?{handled:!1,result:effectiveResult,warnings:[]}:runActiveServiceOverrideSync("output_format",{command:options.command,args:options.commandArgs,command_options:options.commandOptions,global:{...options},pm_root:options.pmRoot,format,options:{...options},result:effectiveResult}),legacyPayloadEchoWarning=serviceOverride.warnings.find(warning=>warning.startsWith("extension_output_format_payload_echo_deprecated:"));return legacyPayloadEchoWarning!==void 0&&writeStderr(`Warning: ${legacyPayloadEchoWarning}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
|
|
13
13
|
`),serviceOverride.handled&&typeof serviceOverride.result=="string"?{result:serviceOverride.result,rendered:serviceOverride.result.endsWith(`
|
|
14
14
|
`)?serviceOverride.result:`${serviceOverride.result}
|
|
15
|
-
`,structuredDeliveryPreserved:!1}:{result:serviceOverride.handled?serviceOverride.result:effectiveResult,rendered:null,structuredDeliveryPreserved:!serviceOverride.handled||isPlainObject(serviceOverride.result)}}function formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat){const activeCommandContext=getActiveCommandContext(),command=options.command??activeCommandContext?.command,commandOptions={...activeCommandContext?.options,...options.commandOptions,...Object.fromEntries([["outputInclude",options.outputInclude],["outputLimit",options.outputLimit],["outputBudget",options.outputBudget],["outputFormat",options.outputFormat],["outputSession",options.outputSession],["outputCursor",options.outputCursor],["outputRowContract",options.outputRowContract]].filter(entry=>entry[1]!==void 0))},format=resolveReadOutputEncoding(command??"",commandOptions)??defaultFormat,resolvedCommandOptions={...commandOptions,resolvedOutputFormat:format},effectiveOptions={...options,command,commandOptions:resolvedCommandOptions},service=resolveOutputService(effectiveResult,nativeOutput,effectiveOptions,format);if(service.rendered!==null)return
|
|
15
|
+
`,structuredDeliveryPreserved:!1}:{result:serviceOverride.handled?serviceOverride.result:effectiveResult,rendered:null,structuredDeliveryPreserved:!serviceOverride.handled||isPlainObject(serviceOverride.result)}}function formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat){const activeCommandContext=getActiveCommandContext(),command=options.command??activeCommandContext?.command,commandOptions={...activeCommandContext?.options,...options.commandOptions,...Object.fromEntries([["outputInclude",options.outputInclude],["outputLimit",options.outputLimit],["outputBudget",options.outputBudget],["outputFormat",options.outputFormat],["outputSession",options.outputSession],["outputCursor",options.outputCursor],["outputRowContract",options.outputRowContract]].filter(entry=>entry[1]!==void 0))},format=resolveReadOutputEncoding(command??"",commandOptions)??defaultFormat,resolvedCommandOptions={...commandOptions,resolvedOutputFormat:format},effectiveOptions={...options,command,commandOptions:resolvedCommandOptions},service=resolveOutputService(effectiveResult,nativeOutput,effectiveOptions,format),renderNative=nativeRenderer(format,command,resolvedCommandOptions,options.lean===!0);if(service.rendered!==null)return deliverServiceRendering(service.rendered,{format,renderNative,contract:()=>attachReadOutputContracts(command,resolvedCommandOptions,effectiveResult),effectiveResult,quiet:options.quiet===!0});const outputResult=service.result;propagateContextUsageServingReceipt(effectiveResult,outputResult);const projectedOutputResult=command==="test"?projectLinkedTestEvidence(outputResult,options.lean===!0):outputResult;let nativeFallback=!1;return deliverContractedRead({format,contract:()=>attachReadOutputContracts(command,resolvedCommandOptions,projectedOutputResult),renderDelivered:value=>{if(format==="toon"){const markdownDefault=renderDefaultMarkdownResult(value);if(markdownDefault!==null)return{text:markdownDefault,custom:!1}}const rendererOverride=nativeOutput||nativeFallback||isReadResultOmittedForBudget(value)?{rendered:null}:runActiveRendererOverride(format,value);return rendererOverride.rendered!==null?{text:rendererOverride.rendered.endsWith(`
|
|
16
16
|
`)?rendererOverride.rendered:`${rendererOverride.rendered}
|
|
17
|
-
|
|
17
|
+
`,custom:!0}:{text:renderNative(value),custom:!1}},renderNative,useNativeRendering:()=>{nativeFallback=!0},structuredDeliveryPreserved:service.structuredDeliveryPreserved,tokenAccounting:options.tokenAccounting===!0,quiet:options.quiet===!0,effectiveResult})}function nativeRenderer(format,command,commandOptions,lean){if(format==="json")return value=>formatBuiltInOutput(value,"json",lean);const selectedFields=commandOptions.fields,preserveEmptyItemCollections=command==="get"&&typeof selectedFields=="string"&&selectedFields.trim().length>0,positionalRowPaths=readOutputPositionalRowPaths(command===void 0?void 0:resolveReadOutputSurface(command,commandOptions));return value=>formatBuiltInOutput(value,"toon",!1,{preserveEmptyItemCollections,positionalRowPaths})}function deliverServiceRendering(serviceRendered,delivery){const audited=withDeliveredOutputRenderer(delivery.format,value=>isReadResultOmittedForBudget(value)?delivery.renderNative(value):serviceRendered,delivery.contract);return isReadResultOmittedForBudget(audited)?(process.exitCode||=EXIT_CODE.USAGE,setActiveCommandDeliveryResult(audited,delivery.effectiveResult,!delivery.quiet),delivery.renderNative(audited)):(setActiveCommandResultOmitted(delivery.effectiveResult),serviceRendered)}function deliverContractedRead(delivery){let contracted=withDeliveredOutputRenderer(delivery.format,value=>delivery.renderDelivered(value).text,delivery.contract),unaccounted=delivery.renderDelivered(contracted);unaccounted.custom&&receiptsUnderstateDelivery(contracted,unaccounted.text)&&(delivery.useNativeRendering(),contracted=withDeliveredOutputRenderer(delivery.format,delivery.renderNative,delivery.contract),unaccounted={text:delivery.renderNative(contracted),custom:!1}),isReadResultOmittedForBudget(contracted)&&(process.exitCode||=EXIT_CODE.USAGE);let structuredDeliveryPreserved=delivery.structuredDeliveryPreserved&&!unaccounted.custom;if(!delivery.tokenAccounting)return setActiveCommandDeliveryResult(contracted,delivery.effectiveResult,!delivery.quiet&&structuredDeliveryPreserved),unaccounted.text;const renderResolvedOutput=value=>{const delivered=delivery.renderDelivered(value);return delivered.custom&&(structuredDeliveryPreserved=!1),delivered.text},accountedOutputResult=attachOutputTokenAccounting(contracted,renderResolvedOutput),rendered=renderResolvedOutput(accountedOutputResult);return setActiveCommandDeliveryResult(accountedOutputResult,delivery.effectiveResult,!delivery.quiet&&structuredDeliveryPreserved),rendered}const DELIVERED_TOKEN_RECEIPTS=[["read_output","estimated_tokens"],["context_intent","estimated_tokens"],["read_session","spent_this_call_tokens"]];function receiptsUnderstateDelivery(value,text){const deliveredTokens=Math.ceil(Buffer.byteLength(text,"utf8")/4),record=Object(value);return DELIVERED_TOKEN_RECEIPTS.some(([receipt,field])=>{const section=record[receipt],estimate=isPlainObject(section)?section[field]:void 0;return typeof estimate=="number"&&estimate<deliveredTokens})}function formatOutput(result,options){const commandOverride=runActiveCommandOverride(result),suppressedOutput=isHostOutputSuppressed(commandOverride.result)?commandOverride.result:null,nativeResult=commandOverride.result,nativeOutput=isPlainObject(nativeResult)&&nativeResult[NATIVE_OUTPUT_MARKER]===!0,effectiveResult=suppressedOutput?suppressedOutput.result:stripNativeOutputMarker(commandOverride.result);if(setActiveCommandResult(effectiveResult),suppressedOutput)return setActiveCommandResultOmitted(effectiveResult),"";const defaultFormat=options.json===!0||options.json===void 0&&options.defaultOutputFormat==="json"?"json":"toon";return formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat)}function printResult(result,options){isPlainObject(result)&&Number.isInteger(result.exit_code)&&DECLARED_PROCESS_EXIT_CODES.has(Number(result.exit_code))&&(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=Number(result.exit_code));const projected=options.idOnly?projectMutationResult(result,{idOnly:!0}):options.fullChangedFields?result:options.noChangedFields?projectMutationResult(result,{changedFields:"compact"}):projectMutationResult(result,{compactEnvelope:!0}),rendered=formatOutput(projected,options);options.quiet||writeStdout(rendered)}function printError(message){const override=runActiveServiceOverrideSync("error_format",{message}),rendered=override.handled&&typeof override.result=="string"?override.result:message;writeStderr(rendered.endsWith(`
|
|
18
18
|
`)?rendered:`${rendered}
|
|
19
19
|
`)}const outputTestOnly={compactToonValue,renderToonValue};export{formatBuiltInOutput,formatOutput,outputTestOnly,printError,printResult,writeStderr,writeStdout};
|
|
20
20
|
//# sourceMappingURL=output.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]="
|
|
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]="4d563454-0999-5df5-afb9-58503b409436")}catch{}})();import{coercePositiveInteger}from"../shared/primitives.js";const DEFAULT_SEARCH_CORPUS_FIELDS=["title","description","tags","status","type","priority","assignee","parent","goal","value","why_now","risk","confidence","estimated_minutes","acceptance_criteria","resolution","expected_result","actual_result","body","comments","notes","learnings","reminders","events","dependencies","plan"];function resolveSearchCorpusFields(settings){const configured=settings?.search?.corpus_fields;if(!Array.isArray(configured))return[...DEFAULT_SEARCH_CORPUS_FIELDS];const knownFields=new Set(DEFAULT_SEARCH_CORPUS_FIELDS),selected=Array.from(new Set(configured.filter(entry=>typeof entry=="string").map(entry=>entry.trim()).filter(entry=>entry.length>0&&knownFields.has(entry))));return selected.length>0?selected:[...DEFAULT_SEARCH_CORPUS_FIELDS]}const DEFAULT_SEMANTIC_CORPUS_INPUT_MAX_CHARACTERS=8e3,OLLAMA_SEMANTIC_CORPUS_INPUT_MAX_CHARACTERS=3200,SEMANTIC_CORPUS_TRUNCATION_SUFFIX="...[semantic corpus truncated]",SEARCH_EMBEDDING_CORPUS_MAX_CHARACTERS_INVALID_WARNING="search_embedding_corpus_max_characters_invalid:using_provider_default";function compactParts(parts){return parts.map(part=>part==null?"":String(part).trim()).filter(part=>part.length>0).join(" ")}function buildReminderCorpus(item){return(item.reminders??[]).map(reminder=>compactParts([reminder.at,reminder.text]))}function buildEventCorpus(item){return(item.events??[]).map(event=>compactParts([event.start_at,event.end_at,event.title,event.description,event.location,event.all_day===!0?"all day":void 0,event.timezone,event.recurrence?.freq,event.recurrence?.interval,event.recurrence?.count,event.recurrence?.until,event.recurrence?.by_weekday?.join(" "),event.recurrence?.by_month_day?.join(" "),event.recurrence?.exdates?.join(" ")]))}function appendPlanStepFlatCorpus(segments,step){segments.push(step.title,step.body,step.status,step.owner,step.evidence,step.blocked_reason,step.superseded_by);for(const link of step.linked_items??[])segments.push(`${link.kind} ${link.id}`,link.note);for(const file of step.files??[])segments.push(file.path,file.note);for(const test of step.tests??[])segments.push(test.command,test.path,test.note);for(const doc of step.docs??[])segments.push(doc.path,doc.note)}function appendPlanMetadataFlatCorpus(segments,item){for(const decision of item.plan_decisions??[])segments.push(decision.decision,decision.rationale,decision.evidence);for(const discovery of item.plan_discoveries??[])segments.push(discovery.text);for(const check of item.plan_validation??[])segments.push(check.text,check.command,check.expected)}function buildPlanFlatCorpus(item){const segments=[];segments.push(item.plan_mode,item.plan_scope,item.plan_harness,item.plan_resume_context);for(const step of item.plan_steps??[])appendPlanStepFlatCorpus(segments,step);return appendPlanMetadataFlatCorpus(segments,item),segments.filter(segment=>typeof segment=="string"&&segment.length>0).join(" ")}function buildPlanCorpus(item){const steps=(item.plan_steps??[]).map(step=>compactParts([step.order,step.id,step.title,step.body,step.status,step.owner,step.evidence,step.blocked_reason,step.superseded_by,(step.linked_items??[]).map(link=>compactParts([link.kind,link.id,link.note])).join(" "),(step.files??[]).map(file=>compactParts([file.path,file.note])).join(" "),(step.tests??[]).map(test=>compactParts([test.command,test.path,test.note])).join(" "),(step.docs??[]).map(doc=>compactParts([doc.path,doc.note])).join(" ")])),decisions=(item.plan_decisions??[]).map(entry=>compactParts([entry.decision,entry.rationale,entry.evidence,entry.step_id])),discoveries=(item.plan_discoveries??[]).map(entry=>compactParts([entry.text,entry.step_id])),validation=(item.plan_validation??[]).map(entry=>compactParts([entry.text,entry.command,entry.expected]));if([item.plan_mode,item.plan_scope,item.plan_harness,item.plan_resume_context,...steps,...decisions,...discoveries,...validation].some(entry=>entry!==void 0))return{mode:item.plan_mode,scope:item.plan_scope,harness:item.plan_harness,resume_context:item.plan_resume_context,steps,decisions,discoveries,validation}}function annotationTexts(entries){return(entries??[]).flatMap(entry=>Object.prototype.toString.call(entry)==="[object Object]"&&typeof entry.text=="string"?[entry.text]:[])}function isNonEmptyString(value){return typeof value=="string"&&value.trim().length>0}const CORPUS_FIELD_BUILDERS={title:document=>document.metadata.title,description:document=>document.metadata.description,tags:document=>document.metadata.tags,status:document=>document.metadata.status,type:document=>document.metadata.type,priority:document=>typeof document.metadata.priority=="number"?document.metadata.priority:void 0,assignee:document=>isNonEmptyString(document.metadata.assignee)?document.metadata.assignee:void 0,parent:document=>isNonEmptyString(document.metadata.parent)?document.metadata.parent:void 0,goal:document=>isNonEmptyString(document.metadata.goal)?document.metadata.goal:void 0,value:document=>isNonEmptyString(document.metadata.value)?document.metadata.value:void 0,why_now:document=>isNonEmptyString(document.metadata.why_now)?document.metadata.why_now:void 0,risk:document=>isNonEmptyString(document.metadata.risk)?document.metadata.risk:void 0,confidence:document=>document.metadata.confidence!==void 0&&document.metadata.confidence!==null?document.metadata.confidence:void 0,estimated_minutes:document=>typeof document.metadata.estimated_minutes=="number"?document.metadata.estimated_minutes:void 0,acceptance_criteria:document=>isNonEmptyString(document.metadata.acceptance_criteria)?document.metadata.acceptance_criteria:void 0,resolution:document=>isNonEmptyString(document.metadata.resolution)?document.metadata.resolution:void 0,expected_result:document=>isNonEmptyString(document.metadata.expected_result)?document.metadata.expected_result:void 0,actual_result:document=>isNonEmptyString(document.metadata.actual_result)?document.metadata.actual_result:void 0,body:document=>document.body,comments:document=>annotationTexts(document.metadata.comments),notes:document=>annotationTexts(document.metadata.notes),learnings:document=>annotationTexts(document.metadata.learnings),reminders:document=>buildReminderCorpus(document.metadata),events:document=>buildEventCorpus(document.metadata),dependencies:document=>(document.metadata.dependencies??[]).map(entry=>({id:entry.id,kind:entry.kind})),plan:document=>buildPlanCorpus(document.metadata)};function buildSearchCorpus(document,options={}){const fields=options.fields??DEFAULT_SEARCH_CORPUS_FIELDS,corpus={};for(const field of fields){const builder=CORPUS_FIELD_BUILDERS[field];if(!builder)continue;const value=builder(document);value!==void 0&&(corpus[field]=value)}return corpus}function resolveSemanticCorpusInputCharacterLimit(providerName){return providerName?.trim().toLowerCase()==="ollama"?OLLAMA_SEMANTIC_CORPUS_INPUT_MAX_CHARACTERS:DEFAULT_SEMANTIC_CORPUS_INPUT_MAX_CHARACTERS}function resolveSemanticCorpusCharacterLimit(providerName,configuredMaxCharacters){const providerDefaultLimit=resolveSemanticCorpusInputCharacterLimit(providerName),parsed=coercePositiveInteger(configuredMaxCharacters);return parsed!==null?{maxCharacters:parsed,warning:null}:{maxCharacters:providerDefaultLimit,warning:configuredMaxCharacters==null?null:SEARCH_EMBEDDING_CORPUS_MAX_CHARACTERS_INVALID_WARNING}}function buildSemanticCorpusInput(document,options={}){const serialized=JSON.stringify(buildSearchCorpus(document,{fields:options.fields})),maxCharacters=resolveSemanticCorpusCharacterLimit(options.providerName,options.maxCharacters).maxCharacters;if(serialized.length<=maxCharacters)return serialized;if(maxCharacters<=SEMANTIC_CORPUS_TRUNCATION_SUFFIX.length)return SEMANTIC_CORPUS_TRUNCATION_SUFFIX.slice(0,maxCharacters);const keepLength=Math.max(0,maxCharacters-SEMANTIC_CORPUS_TRUNCATION_SUFFIX.length);return`${serialized.slice(0,keepLength)}${SEMANTIC_CORPUS_TRUNCATION_SUFFIX}`}export{DEFAULT_SEARCH_CORPUS_FIELDS,DEFAULT_SEMANTIC_CORPUS_INPUT_MAX_CHARACTERS,OLLAMA_SEMANTIC_CORPUS_INPUT_MAX_CHARACTERS,SEARCH_EMBEDDING_CORPUS_MAX_CHARACTERS_INVALID_WARNING,SEMANTIC_CORPUS_TRUNCATION_SUFFIX,buildEventCorpus,buildPlanCorpus,buildPlanFlatCorpus,buildReminderCorpus,buildSearchCorpus,buildSemanticCorpusInput,resolveSearchCorpusFields,resolveSemanticCorpusCharacterLimit,resolveSemanticCorpusInputCharacterLimit};
|
|
2
2
|
//# sourceMappingURL=corpus.js.map
|
|
@@ -60,7 +60,9 @@ timeout_ms?:number;
|
|
|
60
60
|
/** Value that configures or reports fetcher for this contract. */
|
|
61
61
|
fetcher?:EmbeddingRequestFetcher;
|
|
62
62
|
}
|
|
63
|
-
|
|
63
|
+
/** Settings subset that configures the embedding providers semantic search can call. */
|
|
64
|
+
export type ProviderSettingsInput = {
|
|
65
|
+
/** OpenAI-compatible and Ollama endpoint, credential and model settings. */
|
|
64
66
|
providers?:{
|
|
65
67
|
openai?:{
|
|
66
68
|
base_url?:string;
|
|
@@ -83,4 +85,3 @@ export declare function buildEmbeddingRequestPlan(provider:EmbeddingProviderConf
|
|
|
83
85
|
export declare function normalizeEmbeddingResponse(provider:EmbeddingProviderConfig,response:unknown):number[][];
|
|
84
86
|
/** Implements execute embedding request for the public runtime surface of this module. */
|
|
85
87
|
export declare function executeEmbeddingRequest(provider:EmbeddingProviderConfig,input:string | string[],options?:ExecuteEmbeddingRequestOptions):Promise<number[][]>;
|
|
86
|
-
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5452a392-2477-5028-8aa8-521c6b245f52")}catch{}})();import{executeSearchJsonRequest,normalizeSearchHttpTimeoutMs,resolveSearchHttpFetcher}from"./http-client.js";import{isFiniteNumberArray,toNonEmptyString,trimTrailingSlashes}from"../shared/primitives.js";function resolveProviderConfigSource(activeName,configured){const active=toNonEmptyString(activeName);if(!active)return"unconfigured";const configuredValue=toNonEmptyString(configured);return configuredValue&&configuredValue.toLowerCase()===active.toLowerCase()?"configured":"auto-detected"}function normalizeOpenAiEmbeddingsEndpoint(baseUrl){const normalizedBaseUrl=trimTrailingSlashes(baseUrl),normalizedLower=normalizedBaseUrl.toLowerCase();return normalizedLower.endsWith("/embeddings")?normalizedBaseUrl:normalizedLower.endsWith("/v1")?`${normalizedBaseUrl}/embeddings`:`${normalizedBaseUrl}/v1/embeddings`}function resolveSearchEmbeddingModelOverride(settings){const candidate=settings.search?.embedding_model;return toNonEmptyString(candidate)||null}function resolveOpenAiProvider(settings){const baseUrl=toNonEmptyString(settings.providers?.openai?.base_url),model=toNonEmptyString(settings.providers?.openai?.model);if(!baseUrl||!model)return null;const override=resolveSearchEmbeddingModelOverride(settings),apiKey=toNonEmptyString(settings.providers?.openai?.api_key);return{name:"openai",base_url:baseUrl,model:override??model,...apiKey?{api_key:apiKey}:{}}}function resolveOllamaProvider(settings){const baseUrl=toNonEmptyString(settings.providers?.ollama?.base_url),model=toNonEmptyString(settings.providers?.ollama?.model);if(!baseUrl||!model)return null;const override=resolveSearchEmbeddingModelOverride(settings);return{name:"ollama",base_url:baseUrl,model:override??model}}function normalizeEmbeddingInputs(input){const inputs=(Array.isArray(input)?input:[input]).map(entry=>entry.trim()).filter(entry=>entry.length>0);if(inputs.length===0)throw new Error("Embedding input must include at least one non-empty string");return inputs}function dedupeEmbeddingInputs(inputs){const uniqueInputs=[],originalToUniqueIndex=[],uniqueIndexByInput=new Map;for(const entry of inputs){const existingUniqueIndex=uniqueIndexByInput.get(entry);if(existingUniqueIndex===void 0){const nextUniqueIndex=uniqueInputs.length;uniqueInputs.push(entry),uniqueIndexByInput.set(entry,nextUniqueIndex),originalToUniqueIndex.push(nextUniqueIndex);continue}originalToUniqueIndex.push(existingUniqueIndex)}return{uniqueInputs,originalToUniqueIndex}}function buildOrderedOpenAiEntries(data){const openAiEntries=data.map((entry,position)=>({embedding:entry.embedding,index:entry.index,position}));if(openAiEntries.some(entry=>entry.index!==void 0)){for(const entry of openAiEntries)if(!Number.isInteger(entry.index))throw new TypeError(`OpenAI embedding response entry at position ${entry.position} is missing a valid integer index`);return[...openAiEntries].sort((a,b)=>{const byIndex=a.index-b.index;return byIndex!==0?byIndex:a.position-b.position})}return openAiEntries}function resolveEmbeddingProviders(settings){const openAi=resolveOpenAiProvider(settings),ollama=resolveOllamaProvider(settings),available=[openAi,ollama].filter(entry=>entry!==null),preferredName=toNonEmptyString(settings.search?.provider),preferredKey=preferredName?preferredName.toLowerCase():null;return{active:(preferredKey?available.find(entry=>entry.name===preferredKey):void 0)??available[0]??null,available}}function resolveEmbeddingRequestTarget(provider){const baseUrl=trimTrailingSlashes(provider.base_url);return provider.name==="openai"?{provider:"openai",endpoint:normalizeOpenAiEmbeddingsEndpoint(baseUrl),model:provider.model}:{provider:"ollama",endpoint:`${baseUrl}/api/embed`,model:provider.model}}function buildEmbeddingRequestPlan(provider,input){const normalizedInputs=normalizeEmbeddingInputs(input);return provider.name==="openai"?{target:resolveEmbeddingRequestTarget(provider),method:"POST",headers:{"content-type":"application/json",...provider.api_key?{authorization:`Bearer ${provider.api_key}`}:{}},body:{model:provider.model,input:normalizedInputs.length===1?normalizedInputs[0]:normalizedInputs}}:{target:resolveEmbeddingRequestTarget(provider),method:"POST",headers:{"content-type":"application/json"},body:{model:provider.model,input:normalizedInputs}}}function normalizeEmbeddingResponse(provider,response){if(provider.name==="openai"){const data=response.data;if(!Array.isArray(data)||data.length===0)throw new Error("OpenAI embedding response must include a non-empty data array");return buildOrderedOpenAiEntries(data).map((entry,index)=>{const embedding=entry.embedding;if(!isFiniteNumberArray(embedding))throw new Error(`OpenAI embedding response entry at index ${index} is missing a numeric embedding vector`);return[...embedding]})}const singleEmbedding=response.embedding;if(isFiniteNumberArray(singleEmbedding))return[[...singleEmbedding]];const multipleEmbeddings=response.embeddings;if(Array.isArray(multipleEmbeddings)&&multipleEmbeddings.length>0)return multipleEmbeddings.map((entry,index)=>{if(!isFiniteNumberArray(entry))throw new Error(`Ollama embedding response entry at index ${index} is missing a numeric embedding vector`);return[...entry]});throw new Error("Ollama embedding response must include embedding or embeddings vectors")}async function executeEmbeddingRequest(provider,input,options={}){const timeoutMs=normalizeSearchHttpTimeoutMs(options.timeout_ms,"Embedding request"),fetcher=resolveSearchHttpFetcher(options.fetcher,"Embedding request"),normalizedInputs=normalizeEmbeddingInputs(input),dedupedInputs=dedupeEmbeddingInputs(normalizedInputs),requestPlan=buildEmbeddingRequestPlan(provider,dedupedInputs.uniqueInputs),payload=await executeSearchJsonRequest({endpoint:requestPlan.target.endpoint,method:requestPlan.method,headers:requestPlan.headers,body:requestPlan.body,timeoutMs,fetcher,requestLabel:"Embedding request",responseLabel:"Embedding response"}),vectors=normalizeEmbeddingResponse(provider,payload);if(vectors.length!==dedupedInputs.uniqueInputs.length)throw new Error(`Embedding response cardinality mismatch: expected ${dedupedInputs.uniqueInputs.length} vector(s), received ${vectors.length}`);return dedupedInputs.originalToUniqueIndex.map(uniqueIndex=>[...vectors[uniqueIndex]])}export{buildEmbeddingRequestPlan,executeEmbeddingRequest,normalizeEmbeddingResponse,resolveEmbeddingProviders,resolveEmbeddingRequestTarget,resolveProviderConfigSource};
|
|
2
2
|
//# sourceMappingURL=providers.js.map
|
|
@@ -114,7 +114,9 @@ fetcher?:VectorRequestFetcher;
|
|
|
114
114
|
/** Value that configures or reports warnings for this contract. */
|
|
115
115
|
warnings?:string[];
|
|
116
116
|
}
|
|
117
|
-
|
|
117
|
+
/** Settings subset that configures the vector store semantic search reads and writes. */
|
|
118
|
+
export type VectorSettingsInput = {
|
|
119
|
+
/** Collection name plus Qdrant or LanceDB connection settings. */
|
|
118
120
|
vector_store?:{
|
|
119
121
|
collection_name?:string;
|
|
120
122
|
qdrant?:{
|
|
@@ -144,4 +146,3 @@ export declare function executeVectorUpsert(store:VectorStoreConfig,records:Vect
|
|
|
144
146
|
export declare function executeVectorDelete(store:VectorStoreConfig,ids:string[],options?:ExecuteVectorRequestOptions):Promise<VectorUpsertResult>;
|
|
145
147
|
/** Implements execute vector reset for the public runtime surface of this module. */
|
|
146
148
|
export declare function executeVectorReset(store:VectorStoreConfig,knownIds?:string[],options?:ExecuteVectorRequestOptions,vectorDimension?:number):Promise<VectorUpsertResult>;
|
|
147
|
-
export {};
|
|
@@ -1,3 +1,3 @@
|
|
|
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]="b5f2e49a-fb72-554b-b0a8-dca0adee71f4")}catch{}})();import{mkdir,readFile,stat,unlink}from"node:fs/promises";import{basename,dirname,isAbsolute,join,resolve}from"node:path";import{executeSearchJsonRequest,normalizeSearchHttpTimeoutMs,resolveSearchHttpFetcher}from"./http-client.js";import{isFiniteNumberArray,toErrorMessage,toNonEmptyString,trimTrailingSlashes}from"../shared/primitives.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";const DEFAULT_COLLECTION="pm_items",COLLECTION_SANITIZE_PATTERN=/[^a-zA-Z0-9_-]/g,MAX_COLLECTION_NAME_LENGTH=128,LANCE_DB_LOCAL_SNAPSHOT_DIR=".pm-cli-local-vectors",LANCE_DB_LOCAL_SNAPSHOT_VERSION=1,lanceDbLocalTables=new Map;function resolveStoreCollectionName(store){return(toNonEmptyString(store.collection_name)??DEFAULT_COLLECTION).replaceAll(COLLECTION_SANITIZE_PATTERN,"_").slice(0,MAX_COLLECTION_NAME_LENGTH)}function normalizeVector(value){if(!isFiniteNumberArray(value)||value.length===0)throw new Error("Vector values must be a non-empty numeric array");return[...value]}function normalizeLimit(value){if(!Number.isFinite(value)||value<=0)throw new Error("Vector query limit must be a positive number");return Math.floor(value)}function normalizeQdrantQueryResponse(payload){const result=payload.result;if(!Array.isArray(result))throw new TypeError("Qdrant query response must include a result array");const hits=result.map((entry,index)=>{const idValue=entry.id,idCandidate=typeof idValue=="number"?String(idValue):idValue,id=toNonEmptyString(idCandidate);if(!id)throw new Error(`Qdrant query response entry at index ${index} is missing a non-empty id`);const score=entry.score;if(typeof score!="number"||!Number.isFinite(score))throw new TypeError(`Qdrant query response entry at index ${index} is missing a finite numeric score`);const payloadValue=entry.payload;if(payloadValue!==void 0&&(typeof payloadValue!="object"||payloadValue===null||Array.isArray(payloadValue)))throw new Error(`Qdrant query response entry at index ${index} must provide payload as an object when set`);return{id,score,...payloadValue?{payload:payloadValue}:{}}});return hits.sort((left,right)=>left.score!==right.score?right.score-left.score:left.id.localeCompare(right.id)),hits}function normalizeQdrantUpsertResponse(payload){const nestedStatus=toNonEmptyString(payload.result?.status);if(nestedStatus)return{status:nestedStatus};const topLevelStatus=toNonEmptyString(payload.status);if(topLevelStatus)return{status:topLevelStatus};throw new Error("Qdrant upsert response must include status metadata")}async function executeRemoteVectorPlan(endpoint,plan,timeoutMs,fetcher,requestKind){return await executeSearchJsonRequest({endpoint,method:plan.method,headers:plan.headers,body:plan.body,timeoutMs,fetcher,requestLabel:`Vector ${requestKind} request`,responseLabel:`Vector ${requestKind} response`})}function resolveQdrantStore(settings){const url=toNonEmptyString(settings.vector_store?.qdrant?.url);if(!url)return null;const collectionName=toNonEmptyString(settings.vector_store?.collection_name),apiKey=toNonEmptyString(settings.vector_store?.qdrant?.api_key);return{name:"qdrant",url,...collectionName&&collectionName!==DEFAULT_COLLECTION?{collection_name:collectionName}:{},...apiKey?{api_key:apiKey}:{}}}function resolveWorkspaceRootFromPmRoot(pmRoot){const resolved=resolve(pmRoot),parent=dirname(resolved);return basename(resolved)==="pm"&&basename(parent)===".agents"?dirname(parent):resolved}function anchorLanceDbStorePath(storePath,pmRoot){return!pmRoot||isAbsolute(storePath)?storePath:resolve(resolveWorkspaceRootFromPmRoot(pmRoot),storePath)}function resolveLanceDbStore(settings,pmRoot){const lancedbPath=toNonEmptyString(settings.vector_store?.lancedb?.path);if(!lancedbPath)return null;const collectionName=toNonEmptyString(settings.vector_store?.collection_name);return{name:"lancedb",path:anchorLanceDbStorePath(lancedbPath,pmRoot),...collectionName&&collectionName!==DEFAULT_COLLECTION?{collection_name:collectionName}:{}}}function normalizeVectorRecords(records){if(!Array.isArray(records)||records.length===0)throw new Error("Vector upsert records must include at least one entry");return records.map((record,index)=>{const id=toNonEmptyString(record.id);if(!id)throw new Error(`Vector upsert record at index ${index} is missing a non-empty id`);const vector=normalizeVector(record.vector),payload=record.payload;if(payload!==void 0&&(typeof payload!="object"||payload===null||Array.isArray(payload)))throw new Error(`Vector upsert record at index ${index} must provide payload as an object when set`);return{id,vector,...payload?{payload}:{}}})}function normalizeVectorDeleteIds(ids){if(!Array.isArray(ids)||ids.length===0)throw new Error("Vector delete ids must include at least one entry");const normalizedIds=ids.map((id,index)=>{const normalized=toNonEmptyString(id);if(!normalized)throw new Error(`Vector delete id at index ${index} is missing a non-empty value`);return normalized}).sort((left,right)=>left.localeCompare(right)),uniqueIds=[];for(const id of normalizedIds)uniqueIds.at(-1)!==id&&uniqueIds.push(id);return uniqueIds}function resolveQdrantDeleteTarget(upsertTarget){return upsertTarget.replace(/\/points\?wait=true$/,"/points/delete?wait=true")}function resolveQdrantCollectionTarget(upsertTarget){return upsertTarget.replace(/\/points\?wait=true$/,"")}function buildQdrantJsonHeaders(store){return{"content-type":"application/json",...store.api_key?{"api-key":store.api_key}:{}}}function getLanceDbLocalTableKey(storePath,table){return getLanceDbSnapshotPath(storePath,table)}function getLanceDbSnapshotPath(storePath,table){return join(resolve(storePath),LANCE_DB_LOCAL_SNAPSHOT_DIR,`${table}.json`)}function normalizeSnapshotRecord(entry,index,snapshotPath){const id=toNonEmptyString(entry.id);if(!id)throw new Error(`LanceDB local snapshot '${snapshotPath}' record at index ${index} is missing a non-empty id`);const vector=normalizeVector(entry.vector),payload=entry.payload;if(payload!==void 0&&(typeof payload!="object"||payload===null||Array.isArray(payload)))throw new Error(`LanceDB local snapshot '${snapshotPath}' record '${id}' must provide payload as an object when set`);return{id,vector,...payload?{payload}:{}}}function parseLanceDbSnapshot(snapshotPath,expectedTable,raw){let parsed;try{parsed=JSON.parse(raw)}catch(error){throw new Error(`LanceDB local snapshot at '${snapshotPath}' is not valid JSON: ${toErrorMessage(error)}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error(`LanceDB local snapshot at '${snapshotPath}' must be a JSON object`);if(parsed.version!==LANCE_DB_LOCAL_SNAPSHOT_VERSION)throw new Error(`LanceDB local snapshot at '${snapshotPath}' must include version=${LANCE_DB_LOCAL_SNAPSHOT_VERSION}`);const table=toNonEmptyString(parsed.table);if(!table)throw new Error(`LanceDB local snapshot at '${snapshotPath}' must include a non-empty table value`);if(table!==expectedTable)throw new Error(`LanceDB local snapshot at '${snapshotPath}' table mismatch: expected '${expectedTable}', received '${table}'`);const recordsValue=parsed.records;if(!Array.isArray(recordsValue))throw new TypeError(`LanceDB local snapshot at '${snapshotPath}' must include a records array`);const tableRecords=new Map;for(let index=0;index<recordsValue.length;index+=1){const record=normalizeSnapshotRecord(recordsValue[index],index,snapshotPath);tableRecords.set(record.id,record)}return tableRecords}async function readLanceDbSnapshotStats(snapshotPath){try{const stats=await stat(snapshotPath);return{mtimeMs:stats.mtimeMs,size:stats.size}}catch(error){if(!isFileMissingError(error))throw error;return null}}function resolveMissingLanceDbSnapshotCache(key,cached){if(!cached)return null;if(cached.mtimeMs===null&&cached.size===null&&cached.records.size===0)return cached.records;const loaded=new Map;return lanceDbLocalTables.set(key,{records:loaded,mtimeMs:null,size:null}),loaded}function cachedLanceDbSnapshotMatches(cached,snapshotStats){return cached!==void 0&&snapshotStats!==null&&cached.mtimeMs===snapshotStats.mtimeMs&&cached.size===snapshotStats.size}async function loadLanceDbLocalTable(storePath,table){const key=getLanceDbLocalTableKey(storePath,table),snapshotPath=getLanceDbSnapshotPath(storePath,table),snapshotStats=await readLanceDbSnapshotStats(snapshotPath),cached=lanceDbLocalTables.get(key);if(!snapshotStats){const resolved=resolveMissingLanceDbSnapshotCache(key,cached);if(resolved)return resolved}if(cachedLanceDbSnapshotMatches(cached,snapshotStats))return cached.records;let loaded=new Map;try{const raw=await readFile(snapshotPath,"utf8");loaded=parseLanceDbSnapshot(snapshotPath,table,raw)}catch(error){if(!isFileMissingError(error))throw error}return lanceDbLocalTables.set(key,{records:loaded,mtimeMs:snapshotStats?.mtimeMs??null,size:snapshotStats?.size??null}),loaded}function buildSnapshotRecords(table){const records=[...table.values()];return records.sort((left,right)=>left.id.localeCompare(right.id)),records.map(record=>({id:record.id,vector:[...record.vector],...record.payload?{payload:record.payload}:{}}))}async function removeSnapshotFile(snapshotPath){try{await unlink(snapshotPath)}catch(error){if(!isFileMissingError(error))throw new Error(`LanceDB local snapshot delete failed at '${snapshotPath}': ${toErrorMessage(error)}`)}}async function persistLanceDbLocalTable(storePath,tableName,table){const snapshotPath=getLanceDbSnapshotPath(storePath,tableName);if(table.size===0){await removeSnapshotFile(snapshotPath);return}const snapshotDir=dirname(snapshotPath);try{await mkdir(snapshotDir,{recursive:!0})}catch(error){throw new Error(`LanceDB local snapshot directory create failed at '${snapshotDir}': ${toErrorMessage(error)}`)}const serialized=`${JSON.stringify({version:LANCE_DB_LOCAL_SNAPSHOT_VERSION,table:tableName,records:buildSnapshotRecords(table)})}
|
|
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]="4f917418-051d-5458-9080-fa23cd36c4d1")}catch{}})();import{mkdir,readFile,stat,unlink}from"node:fs/promises";import{basename,dirname,isAbsolute,join,resolve}from"node:path";import{executeSearchJsonRequest,normalizeSearchHttpTimeoutMs,resolveSearchHttpFetcher}from"./http-client.js";import{isFiniteNumberArray,toErrorMessage,toNonEmptyString,trimTrailingSlashes}from"../shared/primitives.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";const DEFAULT_COLLECTION="pm_items",COLLECTION_SANITIZE_PATTERN=/[^a-zA-Z0-9_-]/g,MAX_COLLECTION_NAME_LENGTH=128,LANCE_DB_LOCAL_SNAPSHOT_DIR=".pm-cli-local-vectors",LANCE_DB_LOCAL_SNAPSHOT_VERSION=1,lanceDbLocalTables=new Map;function resolveStoreCollectionName(store){return(toNonEmptyString(store.collection_name)??DEFAULT_COLLECTION).replaceAll(COLLECTION_SANITIZE_PATTERN,"_").slice(0,MAX_COLLECTION_NAME_LENGTH)}function normalizeVector(value){if(!isFiniteNumberArray(value)||value.length===0)throw new Error("Vector values must be a non-empty numeric array");return[...value]}function normalizeLimit(value){if(!Number.isFinite(value)||value<=0)throw new Error("Vector query limit must be a positive number");return Math.floor(value)}function normalizeQdrantQueryResponse(payload){const result=payload.result;if(!Array.isArray(result))throw new TypeError("Qdrant query response must include a result array");const hits=result.map((entry,index)=>{const idValue=entry.id,idCandidate=typeof idValue=="number"?String(idValue):idValue,id=toNonEmptyString(idCandidate);if(!id)throw new Error(`Qdrant query response entry at index ${index} is missing a non-empty id`);const score=entry.score;if(typeof score!="number"||!Number.isFinite(score))throw new TypeError(`Qdrant query response entry at index ${index} is missing a finite numeric score`);const payloadValue=entry.payload;if(payloadValue!==void 0&&(typeof payloadValue!="object"||payloadValue===null||Array.isArray(payloadValue)))throw new Error(`Qdrant query response entry at index ${index} must provide payload as an object when set`);return{id,score,...payloadValue?{payload:payloadValue}:{}}});return hits.sort((left,right)=>left.score!==right.score?right.score-left.score:left.id.localeCompare(right.id)),hits}function normalizeQdrantUpsertResponse(payload){const nestedStatus=toNonEmptyString(payload.result?.status);if(nestedStatus)return{status:nestedStatus};const topLevelStatus=toNonEmptyString(payload.status);if(topLevelStatus)return{status:topLevelStatus};throw new Error("Qdrant upsert response must include status metadata")}async function executeRemoteVectorPlan(endpoint,plan,timeoutMs,fetcher,requestKind){return await executeSearchJsonRequest({endpoint,method:plan.method,headers:plan.headers,body:plan.body,timeoutMs,fetcher,requestLabel:`Vector ${requestKind} request`,responseLabel:`Vector ${requestKind} response`})}function resolveQdrantStore(settings){const url=toNonEmptyString(settings.vector_store?.qdrant?.url);if(!url)return null;const collectionName=toNonEmptyString(settings.vector_store?.collection_name),apiKey=toNonEmptyString(settings.vector_store?.qdrant?.api_key);return{name:"qdrant",url,...collectionName&&collectionName!==DEFAULT_COLLECTION?{collection_name:collectionName}:{},...apiKey?{api_key:apiKey}:{}}}function resolveWorkspaceRootFromPmRoot(pmRoot){const resolved=resolve(pmRoot),parent=dirname(resolved);return basename(resolved)==="pm"&&basename(parent)===".agents"?dirname(parent):resolved}function anchorLanceDbStorePath(storePath,pmRoot){return!pmRoot||isAbsolute(storePath)?storePath:resolve(resolveWorkspaceRootFromPmRoot(pmRoot),storePath)}function resolveLanceDbStore(settings,pmRoot){const lancedbPath=toNonEmptyString(settings.vector_store?.lancedb?.path);if(!lancedbPath)return null;const collectionName=toNonEmptyString(settings.vector_store?.collection_name);return{name:"lancedb",path:anchorLanceDbStorePath(lancedbPath,pmRoot),...collectionName&&collectionName!==DEFAULT_COLLECTION?{collection_name:collectionName}:{}}}function normalizeVectorRecords(records){if(!Array.isArray(records)||records.length===0)throw new Error("Vector upsert records must include at least one entry");return records.map((record,index)=>{const id=toNonEmptyString(record.id);if(!id)throw new Error(`Vector upsert record at index ${index} is missing a non-empty id`);const vector=normalizeVector(record.vector),payload=record.payload;if(payload!==void 0&&(typeof payload!="object"||payload===null||Array.isArray(payload)))throw new Error(`Vector upsert record at index ${index} must provide payload as an object when set`);return{id,vector,...payload?{payload}:{}}})}function normalizeVectorDeleteIds(ids){if(!Array.isArray(ids)||ids.length===0)throw new Error("Vector delete ids must include at least one entry");const normalizedIds=ids.map((id,index)=>{const normalized=toNonEmptyString(id);if(!normalized)throw new Error(`Vector delete id at index ${index} is missing a non-empty value`);return normalized}).sort((left,right)=>left.localeCompare(right)),uniqueIds=[];for(const id of normalizedIds)uniqueIds.at(-1)!==id&&uniqueIds.push(id);return uniqueIds}function resolveQdrantDeleteTarget(upsertTarget){return upsertTarget.replace(/\/points\?wait=true$/,"/points/delete?wait=true")}function resolveQdrantCollectionTarget(upsertTarget){return upsertTarget.replace(/\/points\?wait=true$/,"")}function buildQdrantJsonHeaders(store){return{"content-type":"application/json",...store.api_key?{"api-key":store.api_key}:{}}}function getLanceDbLocalTableKey(storePath,table){return getLanceDbSnapshotPath(storePath,table)}function getLanceDbSnapshotPath(storePath,table){return join(resolve(storePath),LANCE_DB_LOCAL_SNAPSHOT_DIR,`${table}.json`)}function normalizeSnapshotRecord(entry,index,snapshotPath){const id=toNonEmptyString(entry.id);if(!id)throw new Error(`LanceDB local snapshot '${snapshotPath}' record at index ${index} is missing a non-empty id`);const vector=normalizeVector(entry.vector),payload=entry.payload;if(payload!==void 0&&(typeof payload!="object"||payload===null||Array.isArray(payload)))throw new Error(`LanceDB local snapshot '${snapshotPath}' record '${id}' must provide payload as an object when set`);return{id,vector,...payload?{payload}:{}}}function parseLanceDbSnapshot(snapshotPath,expectedTable,raw){let parsed;try{parsed=JSON.parse(raw)}catch(error){throw new Error(`LanceDB local snapshot at '${snapshotPath}' is not valid JSON: ${toErrorMessage(error)}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error(`LanceDB local snapshot at '${snapshotPath}' must be a JSON object`);if(parsed.version!==LANCE_DB_LOCAL_SNAPSHOT_VERSION)throw new Error(`LanceDB local snapshot at '${snapshotPath}' must include version=${LANCE_DB_LOCAL_SNAPSHOT_VERSION}`);const table=toNonEmptyString(parsed.table);if(!table)throw new Error(`LanceDB local snapshot at '${snapshotPath}' must include a non-empty table value`);if(table!==expectedTable)throw new Error(`LanceDB local snapshot at '${snapshotPath}' table mismatch: expected '${expectedTable}', received '${table}'`);const recordsValue=parsed.records;if(!Array.isArray(recordsValue))throw new TypeError(`LanceDB local snapshot at '${snapshotPath}' must include a records array`);const tableRecords=new Map;for(let index=0;index<recordsValue.length;index+=1){const record=normalizeSnapshotRecord(recordsValue[index],index,snapshotPath);tableRecords.set(record.id,record)}return tableRecords}async function readLanceDbSnapshotStats(snapshotPath){try{const stats=await stat(snapshotPath);return{mtimeMs:stats.mtimeMs,size:stats.size}}catch(error){if(!isFileMissingError(error))throw error;return null}}function resolveMissingLanceDbSnapshotCache(key,cached){if(!cached)return null;if(cached.mtimeMs===null&&cached.size===null&&cached.records.size===0)return cached.records;const loaded=new Map;return lanceDbLocalTables.set(key,{records:loaded,mtimeMs:null,size:null}),loaded}function cachedLanceDbSnapshotMatches(cached,snapshotStats){return cached!==void 0&&snapshotStats!==null&&cached.mtimeMs===snapshotStats.mtimeMs&&cached.size===snapshotStats.size}async function loadLanceDbLocalTable(storePath,table){const key=getLanceDbLocalTableKey(storePath,table),snapshotPath=getLanceDbSnapshotPath(storePath,table),snapshotStats=await readLanceDbSnapshotStats(snapshotPath),cached=lanceDbLocalTables.get(key);if(!snapshotStats){const resolved=resolveMissingLanceDbSnapshotCache(key,cached);if(resolved)return resolved}if(cachedLanceDbSnapshotMatches(cached,snapshotStats))return cached.records;let loaded=new Map;try{const raw=await readFile(snapshotPath,"utf8");loaded=parseLanceDbSnapshot(snapshotPath,table,raw)}catch(error){if(!isFileMissingError(error))throw error}return lanceDbLocalTables.set(key,{records:loaded,mtimeMs:snapshotStats?.mtimeMs??null,size:snapshotStats?.size??null}),loaded}function buildSnapshotRecords(table){const records=[...table.values()];return records.sort((left,right)=>left.id.localeCompare(right.id)),records.map(record=>({id:record.id,vector:[...record.vector],...record.payload?{payload:record.payload}:{}}))}async function removeSnapshotFile(snapshotPath){try{await unlink(snapshotPath)}catch(error){if(!isFileMissingError(error))throw new Error(`LanceDB local snapshot delete failed at '${snapshotPath}': ${toErrorMessage(error)}`)}}async function persistLanceDbLocalTable(storePath,tableName,table){const snapshotPath=getLanceDbSnapshotPath(storePath,tableName);if(table.size===0){await removeSnapshotFile(snapshotPath);return}const snapshotDir=dirname(snapshotPath);try{await mkdir(snapshotDir,{recursive:!0})}catch(error){throw new Error(`LanceDB local snapshot directory create failed at '${snapshotDir}': ${toErrorMessage(error)}`)}const serialized=`${JSON.stringify({version:LANCE_DB_LOCAL_SNAPSHOT_VERSION,table:tableName,records:buildSnapshotRecords(table)})}
|
|
2
2
|
`;try{await writeFileAtomic(snapshotPath,serialized)}catch(error){throw new Error(`LanceDB local snapshot write failed at '${snapshotPath}': ${toErrorMessage(error)}`)}}async function resetLanceDbLocalTable(storePath,tableName){const key=getLanceDbLocalTableKey(storePath,tableName),snapshotPath=getLanceDbSnapshotPath(storePath,tableName);await removeSnapshotFile(snapshotPath),lanceDbLocalTables.delete(key)}function l2Norm(vector){let sumSq=0;for(let index=0;index<vector.length;index+=1)sumSq+=vector[index]*vector[index];return Math.sqrt(sumSq)}function cosineSimilarity(left,right){let dotProd=0;for(let index=0;index<left.length;index+=1)dotProd+=left[index]*right[index];const leftNorm=l2Norm(left),rightNorm=l2Norm(right);return leftNorm===0||rightNorm===0?0:dotProd/(leftNorm*rightNorm)}function resolveVectorStores(settings,pmRoot){const qdrant=resolveQdrantStore(settings),lancedb=resolveLanceDbStore(settings,pmRoot),available=[qdrant,lancedb].filter(entry=>entry!==null),preferredName=toNonEmptyString(settings.vector_store?.adapter),preferredKey=preferredName?preferredName.toLowerCase():null;return{active:(preferredKey?available.find(entry=>entry.name===preferredKey):void 0)??available[0]??null,available}}function resolveVectorStoreRequestTarget(store){const collectionName=resolveStoreCollectionName(store);if(store.name==="qdrant"){const baseUrl=trimTrailingSlashes(store.url),encodedCollection2=encodeURIComponent(collectionName);return{store:"qdrant",query_target:`${baseUrl}/collections/${encodedCollection2}/points/search`,upsert_target:`${baseUrl}/collections/${encodedCollection2}/points?wait=true`}}const encodedPath=encodeURIComponent(store.path),encodedCollection=encodeURIComponent(collectionName);return{store:"lancedb",query_target:`lancedb://${encodedPath}#${encodedCollection}`,upsert_target:`lancedb://${encodedPath}#${encodedCollection}`}}function buildVectorQueryPlan(store,vector,limit){const target=resolveVectorStoreRequestTarget(store),normalizedVector=normalizeVector(vector),normalizedLimit=normalizeLimit(limit);return store.name==="qdrant"?{target,method:"POST",headers:buildQdrantJsonHeaders(store),body:{vector:normalizedVector,limit:normalizedLimit,with_payload:!0}}:{target,method:"LOCAL",headers:{},body:{table:resolveStoreCollectionName(store),vector:normalizedVector,limit:normalizedLimit}}}function buildVectorUpsertPlan(store,records){const target=resolveVectorStoreRequestTarget(store),normalizedRecords=normalizeVectorRecords(records);return store.name==="qdrant"?{target,method:"POST",headers:buildQdrantJsonHeaders(store),body:{points:normalizedRecords}}:{target,method:"LOCAL",headers:{},body:{table:resolveStoreCollectionName(store),records:normalizedRecords}}}function buildVectorDeletePlan(store,ids){const target=resolveVectorStoreRequestTarget(store),normalizedIds=normalizeVectorDeleteIds(ids);return store.name==="qdrant"?{target,method:"POST",headers:buildQdrantJsonHeaders(store),body:{points:normalizedIds}}:{target,method:"LOCAL",headers:{},body:{table:resolveStoreCollectionName(store),ids:normalizedIds}}}async function executeVectorQuery(store,vector,limit,options={}){const plan=buildVectorQueryPlan(store,vector,limit);if(plan.method==="LOCAL"){const lanceDbStore=store,queryBody=plan.body,table=await loadLanceDbLocalTable(lanceDbStore.path,queryBody.table);if(table.size===0)return[];const queryVector=normalizeVector(queryBody.vector),queryLimit=normalizeLimit(queryBody.limit),hits=[];let dimensionMismatchCount=0;for(const record of table.values()){if(record.vector.length!==queryVector.length){dimensionMismatchCount++;continue}hits.push({id:record.id,score:cosineSimilarity(queryVector,record.vector),...record.payload?{payload:record.payload}:{}})}return dimensionMismatchCount>0&&options.warnings&&options.warnings.push(`vector_dimension_mismatch:${dimensionMismatchCount} records skipped (expected ${queryVector.length} dimensions)`),hits.sort((left,right)=>left.score!==right.score?right.score-left.score:left.id.localeCompare(right.id)),hits.slice(0,queryLimit)}const timeoutMs=normalizeSearchHttpTimeoutMs(options.timeout_ms,"Vector request"),fetcher=resolveSearchHttpFetcher(options.fetcher,"Vector request"),payload=await executeRemoteVectorPlan(plan.target.query_target,{method:"POST",headers:plan.headers,body:plan.body},timeoutMs,fetcher,"query");return normalizeQdrantQueryResponse(payload)}async function executeVectorUpsert(store,records,options={}){const plan=buildVectorUpsertPlan(store,records);if(plan.method==="LOCAL"){const lanceDbStore=store,upsertBody=plan.body,key=getLanceDbLocalTableKey(lanceDbStore.path,upsertBody.table),table=await loadLanceDbLocalTable(lanceDbStore.path,upsertBody.table);for(const record of upsertBody.records)table.set(record.id,record);await persistLanceDbLocalTable(lanceDbStore.path,upsertBody.table,table);const snapshotPath=getLanceDbSnapshotPath(lanceDbStore.path,upsertBody.table),snapshotStats=await stat(snapshotPath);return lanceDbLocalTables.set(key,{records:table,mtimeMs:snapshotStats.mtimeMs,size:snapshotStats.size}),{status:"ok"}}const timeoutMs=normalizeSearchHttpTimeoutMs(options.timeout_ms,"Vector request"),fetcher=resolveSearchHttpFetcher(options.fetcher,"Vector request"),payload=await executeRemoteVectorPlan(plan.target.upsert_target,{method:"POST",headers:plan.headers,body:plan.body},timeoutMs,fetcher,"upsert");return normalizeQdrantUpsertResponse(payload)}async function executeVectorDelete(store,ids,options={}){const plan=buildVectorDeletePlan(store,ids);if(plan.method==="LOCAL"){const lanceDbStore=store,deleteBody=plan.body,key=getLanceDbLocalTableKey(lanceDbStore.path,deleteBody.table),table=await loadLanceDbLocalTable(lanceDbStore.path,deleteBody.table);if(table.size===0)return{status:"ok"};for(const id of deleteBody.ids)table.delete(id);if(await persistLanceDbLocalTable(lanceDbStore.path,deleteBody.table,table),table.size===0)lanceDbLocalTables.delete(key);else{const snapshotPath=getLanceDbSnapshotPath(lanceDbStore.path,deleteBody.table),snapshotStats=await stat(snapshotPath);lanceDbLocalTables.set(key,{records:table,mtimeMs:snapshotStats.mtimeMs,size:snapshotStats.size})}return{status:"ok"}}const timeoutMs=normalizeSearchHttpTimeoutMs(options.timeout_ms,"Vector request"),fetcher=resolveSearchHttpFetcher(options.fetcher,"Vector request"),payload=await executeRemoteVectorPlan(resolveQdrantDeleteTarget(plan.target.upsert_target),{method:"POST",headers:plan.headers,body:plan.body},timeoutMs,fetcher,"delete");return normalizeQdrantUpsertResponse(payload)}async function executeVectorReset(store,knownIds=[],options={},vectorDimension){if(store.name==="lancedb")return await resetLanceDbLocalTable(store.path,resolveStoreCollectionName(store)),{status:"ok"};if(vectorDimension!==void 0){if(!Number.isInteger(vectorDimension)||vectorDimension<=0)throw new Error("Vector reset dimension must be a positive integer when provided");const target=resolveVectorStoreRequestTarget(store),collectionTarget=resolveQdrantCollectionTarget(target.upsert_target),timeoutMs=normalizeSearchHttpTimeoutMs(options.timeout_ms,"Vector request"),fetcher=resolveSearchHttpFetcher(options.fetcher,"Vector request"),headers=buildQdrantJsonHeaders(store);try{await executeRemoteVectorPlan(collectionTarget,{method:"DELETE",headers,body:{}},timeoutMs,fetcher,"delete")}catch(error){if(!toErrorMessage(error).includes("failed with status 404"))throw error}const payload=await executeRemoteVectorPlan(collectionTarget,{method:"PUT",headers,body:{vectors:{size:vectorDimension,distance:"Cosine"}}},timeoutMs,fetcher,"upsert");return normalizeQdrantUpsertResponse(payload)}const idsToDelete=knownIds.map(id=>id.trim()).filter(id=>id.length>0);return idsToDelete.length===0?{status:"ok"}:await executeVectorDelete(store,idsToDelete,options)}export{buildVectorDeletePlan,buildVectorQueryPlan,buildVectorUpsertPlan,executeVectorDelete,executeVectorQuery,executeVectorReset,executeVectorUpsert,resolveVectorStoreRequestTarget,resolveVectorStores};
|
|
3
3
|
//# sourceMappingURL=vector-stores.js.map
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type * as SentryModuleTypes from "@sentry/node";
|
|
2
2
|
declare function scrubString(value:string,keyHint?:string):string;
|
|
3
3
|
declare function scrubEventData(obj:Record<string,unknown>):Record<string,unknown>;
|
|
4
|
-
|
|
4
|
+
/** Shape of the lazily loaded @sentry/node module, so tests can inject a stand-in loader. */
|
|
5
|
+
export type SentryLike = typeof SentryModuleTypes;
|
|
5
6
|
declare function isKnownNoisyConsoleEvent(event:{
|
|
6
7
|
logger?:string;
|
|
7
8
|
message?:string;
|
|
@@ -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]="93725298-6091-543b-969d-bac38d70be89")}catch{}})();import{createRequire}from"node:module";import{resolvePmCliVersion}from"../packages/root.js";import{resolveTelemetryEnvironmentPolicy,resolveTelemetrySourceAttribution}from"../telemetry/policy.js";import{isPmCliExpectedError}from"../../sdk/errors.js";import{crashReportErrorContext,omitEmbeddedPmCliErrorDetails}from"../shared/error-details.js";import{scrubInlineSensitiveAssignments,SENSITIVE_KEY_PATTERN}from"./sensitive-assignments.js";const OPT_OUT_VALUES=new Set(["1","true","yes","on"]);function isSentryDisabled(){return!!(OPT_OUT_VALUES.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||resolveTelemetryEnvironmentPolicy().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}const ABSOLUTE_PATH_TOKEN_RE=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,FILE_URL_PATH_RE=/file:\/\/\/?[^\s"'`),;]+/giu,WINDOWS_PATH_TOKEN_RE=/\b[A-Za-z]:\\[^\s"'`),;]+/g,PRIVATE_IP_RE=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,PATH_FIELD_KEY_PATTERN=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=15,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=["[starter-extension] activating","[starter-extension] all 8 capabilities registered.","[starter-extension] commands:","[starter] preflight check for workspace","[starter] output_format service override active","[pm-ext-ts-starter] activating","[pm-ext-ts-starter] all capabilities registered.","run `pm init` first to initialise a pm workspace"];function looksLikeFilesystemPath(value){const normalized=value.trim();return normalized.length===0?!1:normalized.startsWith("/")||normalized.startsWith("file://")||/^[A-Za-z]:\\/.test(normalized)||normalized.startsWith("\\\\")?!0:normalized.includes("/home/")}function scrubString(value,keyHint){if(keyHint&&PATH_FIELD_KEY_PATTERN.test(keyHint)&&looksLikeFilesystemPath(value))return"[scrubbed_path]";const scrubbed=scrubInlineSensitiveAssignments(value).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(PRIVATE_IP_RE,"[scrubbed_ip]").replaceAll(FILE_URL_PATH_RE,"[scrubbed_path]").replaceAll(WINDOWS_PATH_TOKEN_RE,"[scrubbed_path]").replaceAll(ABSOLUTE_PATH_TOKEN_RE,(_match,prefix)=>`${prefix}[scrubbed_path]`);return looksLikeFilesystemPath(scrubbed)?"[scrubbed_path]":scrubbed}function scrubEventData(obj){const result={};for(const[key,value]of Object.entries(obj))SENSITIVE_KEY_PATTERN.test(key)||key.startsWith("sentry.message.parameter.")?result[key]="[scrubbed]":typeof value=="string"?result[key]=scrubString(value,key):Array.isArray(value)?result[key]=value.map(entry=>typeof entry=="string"?scrubString(entry,key):entry&&typeof entry=="object"?scrubEventData(entry):entry):value&&typeof value=="object"?result[key]=scrubEventData(value):result[key]=value;return result}function scrubStackFrame(frame){for(const key of["filename","absPath","abs_path","module"]){const rawValue=frame[key];typeof rawValue=="string"&&(frame[key]=scrubString(rawValue,key))}const contextLine=frame.context_line;typeof contextLine=="string"&&(frame.context_line=scrubString(contextLine,"context_line"));for(const key of["pre_context","post_context"]){const context=frame[key];Array.isArray(context)&&(frame[key]=context.map(entry=>typeof entry=="string"?scrubString(entry,key):entry))}frame.vars&&typeof frame.vars=="object"&&(frame.vars=scrubEventData(frame.vars)),frame.data&&typeof frame.data=="object"&&(frame.data=scrubEventData(frame.data))}const requireFromInstrument=createRequire(import.meta.url),defaultSentryLoader=()=>requireFromInstrument("@sentry/node");let _sentry,_initDone=!1,_loadSentry=defaultSentryLoader;const PM_CLI_SENTRY_DSN="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function hasPmCliErrorPrefix(value){return/^\s*PmCliError:/.test(value)}function isKnownNoisyConsoleMessage(value){const normalized=value.trim().toLowerCase();return normalized.length===0?!1:KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS.some(pattern=>normalized.includes(pattern))}function isKnownNoisyConsoleEvent(event){return event.logger!=="console"?!1:typeof event.message=="string"&&isKnownNoisyConsoleMessage(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>typeof entry.value=="string"&&isKnownNoisyConsoleMessage(entry.value))}function isNodeRuntimeWarningEvent(event){if(event.logger!=="console")return!1;const isRuntimeWarning=value=>typeof value=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(value);return isRuntimeWarning(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>isRuntimeWarning(entry.value))}function isExpectedCliErrorEvent(event,originalException){return originalException instanceof Error?isPmCliExpectedError(originalException):!!(event.exception?.values?.some(ex=>ex.type==="PmCliError")||event.exception?.values?.some(ex=>typeof ex.value=="string"&&hasPmCliErrorPrefix(ex.value))||event.logger==="console"&&typeof event.message=="string"&&hasPmCliErrorPrefix(event.message))}function isPmCliErrorBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&hasPmCliErrorPrefix(breadcrumb.message)}function isKnownNoisyConsoleBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&isKnownNoisyConsoleMessage(breadcrumb.message)}function resolveCliVersion(){return resolvePmCliVersion(import.meta.url,["../../.."])??"0.0.0"}function resolveEnvironment(){const explicit=process.env.SENTRY_ENVIRONMENT?.trim();if(explicit&&explicit.length>0)return explicit;if(process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test")return"test";if(process.env.CI)return"ci";const source=resolveTelemetrySourceAttribution().source_context;return source==="user"?"production":source}const DEFAULT_TRACES_SAMPLE_RATE=.2;function resolveTracesSampleRate(){const raw=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!raw)return DEFAULT_TRACES_SAMPLE_RATE;const parsed=Number(raw);return!Number.isFinite(parsed)||parsed<0||parsed>1?DEFAULT_TRACES_SAMPLE_RATE:parsed}function scrubSentryExceptionValues(event){if(event.exception?.values){for(const exception of event.exception.values)if(exception.value&&(exception.value=scrubString(exception.value,"value")),exception.stacktrace?.frames)for(const frame of exception.stacktrace.frames)scrubStackFrame(frame)}}function scrubSentryBreadcrumbs(event){if(event.breadcrumbs)for(const breadcrumb of event.breadcrumbs)breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message)),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data))}function scrubSentryContexts(event){if(event.contexts)for(const[ctxKey,ctx]of Object.entries(event.contexts))ctx&&typeof ctx=="object"&&(event.contexts[ctxKey]=scrubEventData(ctx))}function scrubSentryRecordField(event,key){const target=event,value=target[key];value&&typeof value=="object"&&(target[key]=scrubEventData(value))}function sourceContextEnvironment(source){if(!process.env.SENTRY_ENVIRONMENT?.trim()&&(source==="automation"||source==="test"||source==="dogfood"||source==="user"))return source==="user"?"production":source}function applySourceContextEnvironment(event){const environment=sourceContextEnvironment(event.tags?.["pm.source_context"]);environment&&(event.environment=environment)}function omitProducerDiagnostics(event,originalException){const ownErrorContext=readOwnErrorContextExtra(event.extra);omitEmbeddedPmCliErrorDetails([event.contexts,event.extra,event.breadcrumbs]),rebuildErrorDataContexts(event.contexts,originalException),ownErrorContext!==void 0&&(event.extra.error_context=crashReportErrorContext(ownErrorContext))}function readOwnErrorContextExtra(extra){if(!(typeof extra!="object"||extra===null||!Object.hasOwn(extra,"error_context")))return extra.error_context}function rebuildErrorDataContexts(contexts,originalException){if(typeof contexts!="object"||contexts===null||typeof originalException!="object"||originalException===null)return;const record=contexts,keys=new Set(errorDataContextKeys(originalException)),rebuilt=safeErrorDataEntry(originalException);for(const[key,entry]of Object.entries(record))(keys.has(key)||typeof entry=="object"&&entry!==null&&Object.hasOwn(entry,"context"))&&(record[key]=rebuilt??{})}function errorDataContextKeys(error){try{return[error.name,error.constructor?.name].filter(candidate=>typeof candidate=="string"&&candidate.length>0)}catch{return[]}}function safeErrorDataEntry(error){try{const entry=crashReportErrorContext(error),context=Object.getOwnPropertyDescriptor(error,"context");return context!==void 0&&"value"in context&&(entry.context=crashReportErrorContext(context.value)),entry}catch{return}}const beforeSend=(event,hint)=>{if(isExpectedCliErrorEvent(event,hint?.originalException)||isKnownNoisyConsoleEvent(event))return null;omitProducerDiagnostics(event,hint?.originalException),applySourceContextEnvironment(event),isNodeRuntimeWarningEvent(event)&&(event.level="warning",event.tags={...event.tags,"pm.diagnostic_class":"node_runtime_warning"}),event.message&&(event.message=scrubString(event.message,"message")),event.transaction&&(event.transaction=scrubString(event.transaction,"transaction")),scrubSentryExceptionValues(event),scrubSentryBreadcrumbs(event),scrubSentryRecordField(event,"extra"),scrubSentryContexts(event);for(const key of["request","user","tags"])scrubSentryRecordField(event,key);return event},beforeSendTransaction=event=>(omitProducerDiagnostics(event),applySourceContextEnvironment(event),event.breadcrumbs&&(event.breadcrumbs=event.breadcrumbs.filter(breadcrumb=>!isPmCliErrorBreadcrumb(breadcrumb)&&!isKnownNoisyConsoleBreadcrumb(breadcrumb)),scrubSentryBreadcrumbs(event)),scrubSentryContexts(event),event),beforeSendSpan=span=>scrubEventData(span),beforeSendLog=log=>{if(log.message=scrubString(log.message),log.attributes){const environment=sourceContextEnvironment(log.attributes["pm.source_context"]);environment&&(log.attributes["sentry.environment"]=environment),log.attributes=scrubEventData(log.attributes)}return log};function applySerializedLogEnvironment(attributes){const environment=sourceContextEnvironment(attributes["pm.source_context"]?.value);environment&&(attributes["sentry.environment"]={type:"string",value:environment})}function scrubSentryLogEnvelope(envelope){for(const item of envelope[1])if(item[0].type==="log")for(const log of item[1].items){log.body=scrubString(log.body);const attributes=log.attributes;if(attributes){applySerializedLogEnvironment(attributes);for(const[key,attribute]of Object.entries(attributes)){const value=scrubEventData({[key]:attribute.value})[key];typeof value=="string"&&(attributes[key]={type:"string",value})}}}}const beforeBreadcrumb=breadcrumb=>isPmCliErrorBreadcrumb(breadcrumb)||isKnownNoisyConsoleBreadcrumb(breadcrumb)?null:(breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message,"message")),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data)),breadcrumb);async function ensureSentryInit(){if(_initDone)return _sentry;if(_initDone=!0,isSentryDisabled())return;const SentryModule=_loadSentry(),dsn=process.env.SENTRY_DSN?.trim()||PM_CLI_SENTRY_DSN,release=resolveCliVersion();SentryModule.init({dsn,release:`pm-cli@${release}`,environment:resolveEnvironment(),tracesSampleRate:resolveTracesSampleRate(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,traceLifecycle:"stream",dataCollection:{userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,graphQL:{document:!1,variables:!1},stackFrameVariables:!1,frameContextLines:0},serverName:void 0,integrations:[SentryModule.extraErrorDataIntegration({depth:4,captureErrorCause:!1}),SentryModule.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":release,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend,beforeSendTransaction,beforeSendSpan:SentryModule.withStreamedSpan(beforeSendSpan),beforeSendLog,beforeBreadcrumb});const client=SentryModule.getClient();if(!client)return;const attribution=resolveTelemetrySourceAttribution();return SentryModule.setTags({"pm.version":release,"pm.source_context":attribution.source_context,"pm.source_context_source":attribution.source_context_source}),SentryModule.setAttribute("pm.source_context",attribution.source_context),client.on("beforeEnvelope",scrubSentryLogEnvelope),_sentry=SentryModule,SentryModule}async function ensureSentryCommandTracing(telemetryEnabled){if(telemetryEnabled!==!0||!OPT_OUT_VALUES.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||resolveTracesSampleRate()===0||isSentryDisabled())return!1;try{return await ensureSentryInit()!==void 0}catch{return _sentry=void 0,!1}}function getSentry(){return _sentry}const _testOnly={isExpectedCliErrorEvent,isKnownNoisyConsoleEvent,isNodeRuntimeWarningEvent,isPmCliErrorBreadcrumb,isKnownNoisyConsoleBreadcrumb,scrubString,scrubEventData,resolveTracesSampleRate,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,defaultSentryLoader,setSentryLoaderForTests(loader){_loadSentry=loader??defaultSentryLoader},resetSentryStateForTests(){_sentry=void 0,_initDone=!1}};export{_testOnly,ensureSentryCommandTracing,ensureSentryInit,getSentry};
|
|
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]="28970299-690a-52cd-a715-dcba2e249a67")}catch{}})();import{createRequire}from"node:module";import{resolvePmCliVersion}from"../packages/root.js";import{resolveTelemetryEnvironmentPolicy,resolveTelemetrySourceAttribution}from"../telemetry/policy.js";import{isPmCliExpectedError}from"../../sdk/errors.js";import{crashReportErrorContext,omitEmbeddedPmCliErrorDetails}from"../shared/error-details.js";import{scrubInlineSensitiveAssignments,SENSITIVE_KEY_PATTERN}from"./sensitive-assignments.js";const OPT_OUT_VALUES=new Set(["1","true","yes","on"]);function isSentryDisabled(){return!!(OPT_OUT_VALUES.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||resolveTelemetryEnvironmentPolicy().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}const ABSOLUTE_PATH_TOKEN_RE=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,FILE_URL_PATH_RE=/file:\/\/\/?[^\s"'`),;]+/giu,WINDOWS_PATH_TOKEN_RE=/\b[A-Za-z]:\\[^\s"'`),;]+/g,PRIVATE_IP_RE=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,PATH_FIELD_KEY_PATTERN=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=15,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=["[starter-extension] activating","[starter-extension] all 8 capabilities registered.","[starter-extension] commands:","[starter] preflight check for workspace","[starter] output_format service override active","[pm-ext-ts-starter] activating","[pm-ext-ts-starter] all capabilities registered.","run `pm init` first to initialise a pm workspace"];function looksLikeFilesystemPath(value){const normalized=value.trim();return normalized.length===0?!1:normalized.startsWith("/")||normalized.startsWith("file://")||/^[A-Za-z]:\\/.test(normalized)||normalized.startsWith("\\\\")?!0:normalized.includes("/home/")}function scrubString(value,keyHint){if(keyHint&&PATH_FIELD_KEY_PATTERN.test(keyHint)&&looksLikeFilesystemPath(value))return"[scrubbed_path]";const scrubbed=scrubInlineSensitiveAssignments(value).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(PRIVATE_IP_RE,"[scrubbed_ip]").replaceAll(FILE_URL_PATH_RE,"[scrubbed_path]").replaceAll(WINDOWS_PATH_TOKEN_RE,"[scrubbed_path]").replaceAll(ABSOLUTE_PATH_TOKEN_RE,(_match,prefix)=>`${prefix}[scrubbed_path]`);return looksLikeFilesystemPath(scrubbed)?"[scrubbed_path]":scrubbed}function scrubEventData(obj){const result={};for(const[key,value]of Object.entries(obj))SENSITIVE_KEY_PATTERN.test(key)||key.startsWith("sentry.message.parameter.")?result[key]="[scrubbed]":typeof value=="string"?result[key]=scrubString(value,key):Array.isArray(value)?result[key]=value.map(entry=>typeof entry=="string"?scrubString(entry,key):entry&&typeof entry=="object"?scrubEventData(entry):entry):value&&typeof value=="object"?result[key]=scrubEventData(value):result[key]=value;return result}function scrubStackFrame(frame){for(const key of["filename","absPath","abs_path","module"]){const rawValue=frame[key];typeof rawValue=="string"&&(frame[key]=scrubString(rawValue,key))}const contextLine=frame.context_line;typeof contextLine=="string"&&(frame.context_line=scrubString(contextLine,"context_line"));for(const key of["pre_context","post_context"]){const context=frame[key];Array.isArray(context)&&(frame[key]=context.map(entry=>typeof entry=="string"?scrubString(entry,key):entry))}frame.vars&&typeof frame.vars=="object"&&(frame.vars=scrubEventData(frame.vars)),frame.data&&typeof frame.data=="object"&&(frame.data=scrubEventData(frame.data))}const requireFromInstrument=createRequire(import.meta.url),defaultSentryLoader=()=>requireFromInstrument("@sentry/node");let _sentry,_initDone=!1,_loadSentry=defaultSentryLoader;const PM_CLI_SENTRY_DSN="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function hasPmCliErrorPrefix(value){return/^\s*PmCliError:/.test(value)}function isKnownNoisyConsoleMessage(value){const normalized=value.trim().toLowerCase();return normalized.length===0?!1:KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS.some(pattern=>normalized.includes(pattern))}function isKnownNoisyConsoleEvent(event){return event.logger!=="console"?!1:typeof event.message=="string"&&isKnownNoisyConsoleMessage(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>typeof entry.value=="string"&&isKnownNoisyConsoleMessage(entry.value))}function isNodeRuntimeWarningEvent(event){if(event.logger!=="console")return!1;const isRuntimeWarning=value=>typeof value=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(value);return isRuntimeWarning(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>isRuntimeWarning(entry.value))}function isExpectedCliErrorEvent(event,originalException){return originalException instanceof Error?isPmCliExpectedError(originalException):!!(event.exception?.values?.some(ex=>ex.type==="PmCliError")||event.exception?.values?.some(ex=>typeof ex.value=="string"&&hasPmCliErrorPrefix(ex.value))||event.logger==="console"&&typeof event.message=="string"&&hasPmCliErrorPrefix(event.message))}function isPmCliErrorBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&hasPmCliErrorPrefix(breadcrumb.message)}function isKnownNoisyConsoleBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&isKnownNoisyConsoleMessage(breadcrumb.message)}function resolveCliVersion(){return resolvePmCliVersion(import.meta.url,["../../.."])??"0.0.0"}function resolveEnvironment(){const explicit=process.env.SENTRY_ENVIRONMENT?.trim();if(explicit&&explicit.length>0)return explicit;if(process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test")return"test";if(process.env.CI)return"ci";const source=resolveTelemetrySourceAttribution().source_context;return source==="user"?"production":source}const DEFAULT_TRACES_SAMPLE_RATE=.2;function resolveTracesSampleRate(){const raw=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!raw)return DEFAULT_TRACES_SAMPLE_RATE;const parsed=Number(raw);return!Number.isFinite(parsed)||parsed<0||parsed>1?DEFAULT_TRACES_SAMPLE_RATE:parsed}function scrubSentryExceptionValues(event){if(event.exception?.values){for(const exception of event.exception.values)if(exception.value&&(exception.value=scrubString(exception.value,"value")),exception.stacktrace?.frames)for(const frame of exception.stacktrace.frames)scrubStackFrame(frame)}}function scrubSentryBreadcrumbs(event){if(event.breadcrumbs)for(const breadcrumb of event.breadcrumbs)breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message)),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data))}function scrubSentryContexts(event){if(event.contexts)for(const[ctxKey,ctx]of Object.entries(event.contexts))ctx&&typeof ctx=="object"&&(event.contexts[ctxKey]=scrubEventData(ctx))}function scrubSentryRecordField(event,key){const target=event,value=target[key];value&&typeof value=="object"&&(target[key]=scrubEventData(value))}function sourceContextEnvironment(source){if(!process.env.SENTRY_ENVIRONMENT?.trim()&&(source==="automation"||source==="test"||source==="dogfood"||source==="user"))return source==="user"?"production":source}function applySourceContextEnvironment(event){const environment=sourceContextEnvironment(event.tags?.["pm.source_context"]);environment&&(event.environment=environment)}function omitProducerDiagnostics(event,originalException){const ownErrorContext=readOwnErrorContextExtra(event.extra);omitEmbeddedPmCliErrorDetails([event.contexts,event.extra,event.breadcrumbs]),rebuildErrorDataContexts(event.contexts,originalException),ownErrorContext!==void 0&&(event.extra.error_context=crashReportErrorContext(ownErrorContext))}function readOwnErrorContextExtra(extra){if(!(typeof extra!="object"||extra===null||!Object.hasOwn(extra,"error_context")))return extra.error_context}function rebuildErrorDataContexts(contexts,originalException){if(typeof contexts!="object"||contexts===null||typeof originalException!="object"||originalException===null)return;const record=contexts,keys=new Set(errorDataContextKeys(originalException)),rebuilt=safeErrorDataEntry(originalException);for(const[key,entry]of Object.entries(record))(keys.has(key)||typeof entry=="object"&&entry!==null&&Object.hasOwn(entry,"context"))&&(record[key]=rebuilt??{})}function errorDataContextKeys(error){try{return[error.name,error.constructor?.name].filter(candidate=>typeof candidate=="string"&&candidate.length>0)}catch{return[]}}function safeErrorDataEntry(error){try{const entry=crashReportErrorContext(error),context=Object.getOwnPropertyDescriptor(error,"context");return context!==void 0&&"value"in context&&(entry.context=crashReportErrorContext(context.value)),entry}catch{return}}const beforeSend=(event,hint)=>{if(isExpectedCliErrorEvent(event,hint?.originalException)||isKnownNoisyConsoleEvent(event))return null;omitProducerDiagnostics(event,hint?.originalException),applySourceContextEnvironment(event),isNodeRuntimeWarningEvent(event)&&(event.level="warning",event.tags={...event.tags,"pm.diagnostic_class":"node_runtime_warning"}),event.message&&(event.message=scrubString(event.message,"message")),event.transaction&&(event.transaction=scrubString(event.transaction,"transaction")),scrubSentryExceptionValues(event),scrubSentryBreadcrumbs(event),scrubSentryRecordField(event,"extra"),scrubSentryContexts(event);for(const key of["request","user","tags"])scrubSentryRecordField(event,key);return event},beforeSendTransaction=event=>(omitProducerDiagnostics(event),applySourceContextEnvironment(event),event.breadcrumbs&&(event.breadcrumbs=event.breadcrumbs.filter(breadcrumb=>!isPmCliErrorBreadcrumb(breadcrumb)&&!isKnownNoisyConsoleBreadcrumb(breadcrumb)),scrubSentryBreadcrumbs(event)),scrubSentryContexts(event),event),beforeSendSpan=span=>scrubEventData(span),beforeSendLog=log=>{if(log.message=scrubString(log.message),log.attributes){const environment=sourceContextEnvironment(log.attributes["pm.source_context"]);environment&&(log.attributes["sentry.environment"]=environment),log.attributes=scrubEventData(log.attributes)}return log};function applySerializedLogEnvironment(attributes){const environment=sourceContextEnvironment(attributes["pm.source_context"]?.value);environment&&(attributes["sentry.environment"]={type:"string",value:environment})}function scrubSentryLogEnvelope(envelope){for(const item of envelope[1])if(item[0].type==="log")for(const log of item[1].items){log.body=scrubString(log.body);const attributes=log.attributes;if(attributes){applySerializedLogEnvironment(attributes);for(const[key,attribute]of Object.entries(attributes)){const value=scrubEventData({[key]:attribute.value})[key];typeof value=="string"&&(attributes[key]={type:"string",value})}}}}const beforeBreadcrumb=breadcrumb=>isPmCliErrorBreadcrumb(breadcrumb)||isKnownNoisyConsoleBreadcrumb(breadcrumb)?null:(breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message,"message")),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data)),breadcrumb);async function ensureSentryInit(){if(_initDone)return _sentry;if(_initDone=!0,isSentryDisabled())return;const SentryModule=_loadSentry(),dsn=process.env.SENTRY_DSN?.trim()||PM_CLI_SENTRY_DSN,release=resolveCliVersion();SentryModule.init({dsn,release:`pm-cli@${release}`,environment:resolveEnvironment(),tracesSampleRate:resolveTracesSampleRate(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,traceLifecycle:"stream",dataCollection:{userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,graphQL:{document:!1,variables:!1},stackFrameVariables:!1,frameContextLines:0},serverName:void 0,integrations:[SentryModule.extraErrorDataIntegration({depth:4,captureErrorCause:!1}),SentryModule.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":release,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend,beforeSendTransaction,beforeSendSpan:SentryModule.withStreamedSpan(beforeSendSpan),beforeSendLog,beforeBreadcrumb});const client=SentryModule.getClient();if(!client)return;const attribution=resolveTelemetrySourceAttribution();return SentryModule.setTags({"pm.version":release,"pm.source_context":attribution.source_context,"pm.source_context_source":attribution.source_context_source}),SentryModule.setAttribute("pm.source_context",attribution.source_context),client.on("beforeEnvelope",scrubSentryLogEnvelope),_sentry=SentryModule,SentryModule}async function ensureSentryCommandTracing(telemetryEnabled){if(telemetryEnabled!==!0||!OPT_OUT_VALUES.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||resolveTracesSampleRate()===0||isSentryDisabled())return!1;try{return await ensureSentryInit()!==void 0}catch{return _sentry=void 0,!1}}function getSentry(){return _sentry}const _testOnly={isExpectedCliErrorEvent,isKnownNoisyConsoleEvent,isNodeRuntimeWarningEvent,isPmCliErrorBreadcrumb,isKnownNoisyConsoleBreadcrumb,scrubString,scrubEventData,resolveTracesSampleRate,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,defaultSentryLoader,setSentryLoaderForTests(loader){_loadSentry=loader??defaultSentryLoader},resetSentryStateForTests(){_sentry=void 0,_initDone=!1}};export{_testOnly,ensureSentryCommandTracing,ensureSentryInit,getSentry};
|
|
2
2
|
//# sourceMappingURL=instrument.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]="cf9867e5-2739-5bb0-b2f0-c432199942b6")}catch{}})();import{WORKFLOW_POLICY_ACTIONS,GRAPH_SUBCOMMAND_VALUES,PM_DISCOVERABLE_TOOL_ACTIONS}from"../sdk/cli-contracts/enum-contracts.js";import{buildPmActionToolInputSchema}from"../sdk/cli-contracts/tool-schema.js";import{RUNTIME_STATUS_ROLE_VALUES}from"../types.js";const CANONICAL_OUTPUT_SESSION_TOOL_PROPERTY=buildPmActionToolInputSchema("list").properties.outputSession,READ_OUTPUT_TOOL_PROPERTIES={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...CANONICAL_OUTPUT_SESSION_TOOL_PROPERTY},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},workflowPolicyOptionProperties={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},TOOL_SCHEMA_BASE={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},idSchema={type:"string",description:"pm item id, for example pm-abc1."},PM_RUN_ACTION_DESCRIPTION=`Operation name (one of): ${PM_DISCOVERABLE_TOOL_ACTIONS.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,LIST_TOP_LEVEL_OPTION_PROPERTIES={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},SEARCH_TOP_LEVEL_OPTION_PROPERTIES={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function objectSchema(properties,required=[]){return{...TOOL_SCHEMA_BASE,properties:{...TOOL_SCHEMA_BASE.properties,...properties},required}}const RAW_TOOLS=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:objectSchema({action:{type:"string",enum:[...PM_DISCOVERABLE_TOOL_ACTIONS],description:PM_RUN_ACTION_DESCRIPTION},id:idSchema,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...READ_OUTPUT_TOOL_PROPERTIES},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:objectSchema({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:objectSchema({query:{type:"string"},options:{type:"object"},...SEARCH_TOP_LEVEL_OPTION_PROPERTIES},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:objectSchema({options:{type:"object"},...LIST_TOP_LEVEL_OPTION_PROPERTIES})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:objectSchema({id:idSchema,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:objectSchema({verify:{type:"boolean",description:"Verify complete selected authoritative history chains."},since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:objectSchema({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:idSchema,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:objectSchema({id:idSchema,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:objectSchema({id:idSchema,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:objectSchema({id:idSchema,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:objectSchema({id:idSchema,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:objectSchema({subcommand:{type:"string",enum:[...GRAPH_SUBCOMMAND_VALUES]},id:idSchema,target:idSchema,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:objectSchema({...workflowPolicyOptionProperties,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...WORKFLOW_POLICY_ACTIONS],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...RUNTIME_STATUS_ROLE_VALUES]},description:`Lifecycle roles for add-status: ${RUNTIME_STATUS_ROLE_VALUES.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:workflowPolicyOptionProperties}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:objectSchema({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:objectSchema({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:objectSchema({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],NARROW_TOOL_ACTIONS={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},TOOLS=RAW_TOOLS.map(tool=>{const action=NARROW_TOOL_ACTIONS[tool.name];if(!action)return tool;const properties=tool.inputSchema.properties,required=tool.inputSchema.required.map(String);return{...tool,inputSchema:buildPmActionToolInputSchema(action,{properties,required})}});function buildMcpToolContracts(){return TOOLS.map(tool=>{const schemaRequired=tool.inputSchema.required,required=Array.isArray(schemaRequired)?schemaRequired.map(entry=>String(entry)).sort((left,right)=>left.localeCompare(right)):[];return{name:tool.name,description:tool.description,required,input_schema:tool.inputSchema}}).sort((left,right)=>left.name.localeCompare(right.name))}export{NARROW_TOOL_ACTIONS,TOOLS,TOOL_SCHEMA_BASE,buildMcpToolContracts};
|
|
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]="78b20f7a-4ae7-5811-9ab7-049a07d844e5")}catch{}})();import{WORKFLOW_POLICY_ACTIONS,GRAPH_SUBCOMMAND_VALUES,PM_DISCOVERABLE_TOOL_ACTIONS}from"../sdk/cli-contracts/enum-contracts.js";import{buildPmActionToolInputSchema}from"../sdk/cli-contracts/tool-schema.js";import{RUNTIME_STATUS_ROLE_VALUES}from"../types.js";const CANONICAL_OUTPUT_SESSION_TOOL_PROPERTY=buildPmActionToolInputSchema("list").properties.outputSession,READ_OUTPUT_TOOL_PROPERTIES={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...CANONICAL_OUTPUT_SESSION_TOOL_PROPERTY},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},workflowPolicyOptionProperties={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},TOOL_SCHEMA_BASE={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},idSchema={type:"string",description:"pm item id, for example pm-abc1."},PM_RUN_ACTION_DESCRIPTION=`Operation name (one of): ${PM_DISCOVERABLE_TOOL_ACTIONS.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,LIST_TOP_LEVEL_OPTION_PROPERTIES={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},SEARCH_TOP_LEVEL_OPTION_PROPERTIES={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function objectSchema(properties,required=[]){return{...TOOL_SCHEMA_BASE,properties:{...TOOL_SCHEMA_BASE.properties,...properties},required}}const RAW_TOOLS=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:objectSchema({action:{type:"string",enum:[...PM_DISCOVERABLE_TOOL_ACTIONS],description:PM_RUN_ACTION_DESCRIPTION},id:idSchema,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...READ_OUTPUT_TOOL_PROPERTIES},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:objectSchema({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:objectSchema({query:{type:"string"},options:{type:"object"},...SEARCH_TOP_LEVEL_OPTION_PROPERTIES},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:objectSchema({options:{type:"object"},...LIST_TOP_LEVEL_OPTION_PROPERTIES})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:objectSchema({id:idSchema,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:objectSchema({verify:{type:"boolean",description:"Verify complete selected authoritative history chains."},since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:objectSchema({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:idSchema,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:objectSchema({id:idSchema,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:objectSchema({id:idSchema,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:objectSchema({id:idSchema,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:objectSchema({id:idSchema,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:'List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls return the newest comments that fit the output budget, with total_count/has_more metadata and a next_cursor that pages back to older comments through outputCursor; without options.limit or outputLimit, outputBudget "unbounded" returns the complete listing at once. Pass options.limit=N for only the newest N comments (next_cursor pages within that window when the budget trims it; has_more reports older comments beyond it without a cursor) or options.limit=0 for summary-only metadata; options.full=true returns the complete history after a write. Rows carry their absolute index; pair edit/delete with options.expectAt to refuse a different entry.',inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:objectSchema({subcommand:{type:"string",enum:[...GRAPH_SUBCOMMAND_VALUES]},id:idSchema,target:idSchema,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:objectSchema({...workflowPolicyOptionProperties,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...WORKFLOW_POLICY_ACTIONS],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...RUNTIME_STATUS_ROLE_VALUES]},description:`Lifecycle roles for add-status: ${RUNTIME_STATUS_ROLE_VALUES.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:workflowPolicyOptionProperties}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:objectSchema({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:objectSchema({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:objectSchema({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],NARROW_TOOL_ACTIONS={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},TOOLS=RAW_TOOLS.map(tool=>{const action=NARROW_TOOL_ACTIONS[tool.name];if(!action)return tool;const properties=tool.inputSchema.properties,required=tool.inputSchema.required.map(String);return{...tool,inputSchema:buildPmActionToolInputSchema(action,{properties,required})}});function buildMcpToolContracts(){return TOOLS.map(tool=>{const schemaRequired=tool.inputSchema.required,required=Array.isArray(schemaRequired)?schemaRequired.map(entry=>String(entry)).sort((left,right)=>left.localeCompare(right)):[];return{name:tool.name,description:tool.description,required,input_schema:tool.inputSchema}}).sort((left,right)=>left.name.localeCompare(right.name))}export{NARROW_TOOL_ACTIONS,TOOLS,TOOL_SCHEMA_BASE,buildMcpToolContracts};
|
|
2
2
|
//# sourceMappingURL=tool-definitions.js.map
|