@unbrained/pm-cli 2026.11.7 → 2026.11.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +69 -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-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3A5DJZCC.js +116 -0
- package/dist/cli-bundle/chunks/chunk-4BMPGUTG.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-RFI4O6NU.js → chunk-7GC6WIDR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-VM6OGNQC.js → chunk-7V6I6X4G.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MQOZNGPS.js → chunk-AFZS6WFV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OIBSKKCO.js → chunk-C4MQFWCM.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-CP43BHX3.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-WS2N4TQW.js → chunk-DOHZKPPC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ETHAZC3F.js → chunk-HESIRIVX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JZWFZH2K.js → chunk-JAE5MWLX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KPAVZILX.js → chunk-L5BU5FYN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3DI6CEF3.js → chunk-LI2HP5OX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D53G3NOE.js → chunk-LLTRUVKK.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-BQ5O3CBF.js → chunk-MKW5LGVQ.js} +69 -65
- package/dist/cli-bundle/chunks/chunk-NH7QX2M2.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-OJZG7Y6S.js → chunk-NKO42JMT.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XSEDESNW.js → chunk-PE6CZ3PE.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-RC6SSFOF.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-TGQPCNAD.js → chunk-S4IZIMAO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-WXVMPLBY.js → chunk-XBUZENP4.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-YGUUJHSR.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-F3B2ULHB.js → chunk-YUTFMHSG.js} +6 -6
- package/dist/cli-bundle/chunks/{chunk-QG6FLDM4.js → chunk-Z3LWNF7C.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-SPEKTFBB.js → item-revision-TUGZYYXX.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-2RRBAQN3.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-LUXUKISJ.js → mutation-admission-FJ3D66PV.js} +2 -2
- package/dist/cli-bundle/chunks/register-list-query-GXP77CX7.js +11 -0
- package/dist/cli-bundle/chunks/register-mutation-XJ2DROUM.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-AHDWE2G3.js → register-operations-O5LERXM7.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-7BGG3CI3.js → register-setup-4VOTYLL2.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-S5BYWLGY.js → stage-ZDJL3FGL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-2A3QZELL.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JRJOFMI7.js → chunk-3HFENALW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4UOXVFJZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LW4TN5ZM.js → chunk-5YPX3QKU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4EXRRSDS.js → chunk-6U5HP6L3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-DIEBSC76.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BIDF4KO7.js → chunk-I4YUZW3J.js} +8 -8
- package/dist/cli-bundle/focused-chunks/{chunk-AJ2I377F.js → chunk-KBRSA4OK.js} +26 -26
- package/dist/cli-bundle/focused-chunks/{chunk-IYJRFJHT.js → chunk-KNF2QTEZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-LTPT5TE7.js +24 -0
- package/dist/cli-bundle/focused-chunks/chunk-O7K3X4LH.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-P4EHEH4C.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-P6TG33FV.js +82 -0
- package/dist/cli-bundle/focused-chunks/chunk-PL6EO4GJ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LTTMERPN.js → chunk-PSLDGAEY.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-SZ2BKK3M.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-TSHRBPTI.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-ULTSMJYF.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-UNNLBJRI.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-UUVRYIKA.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-G2VIY6XA.js → chunk-WPXMPGTY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-Z2QWZRSL.js +26 -0
- package/dist/cli-bundle/focused-chunks/item-revision-XNSRDTFB.js +2 -0
- package/dist/cli-bundle/focused-chunks/item-transaction-Q2Z7DDCR.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-QWC6MLTZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/stage-NKH5SKSZ.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 +5 -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 +10 -1
- package/dist/core/output/output.js +7 -7
- 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/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/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/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/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 +20 -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-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/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 +1 -1
- package/docs/READ_OUTPUT_CONTRACTS.md +78 -0
- 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 +2 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/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-O6TIOKCM.js +0 -9
- package/dist/cli-bundle/chunks/chunk-WYIDX67P.js +0 -31
- 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-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-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/generated/REFUSAL_CLOSURE_CENSUS.md +0 -472
|
@@ -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]="fa6c2d48-6285-56f1-adf7-0da4f5f1edcc")}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. 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
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { GlobalOptions } from "../core/shared/command-types.js";
|
|
2
|
+
import { PmCliError } from "../core/shared/errors.js";
|
|
2
3
|
import { mutateItem } from "../core/store/item-store.js";
|
|
3
4
|
/** Common persisted shape shared by comments, notes, and learnings. */
|
|
4
5
|
export interface AnnotationEntry {
|
|
@@ -27,7 +28,21 @@ includeMeta?:boolean;
|
|
|
27
28
|
fullHistory?:boolean;
|
|
28
29
|
/** Append only when no entry has the same resolved author and text. */
|
|
29
30
|
ifAbsent?:boolean;
|
|
31
|
+
/**
|
|
32
|
+
* For `--edit`/`--delete`: the `created_at` of the entry the caller read at
|
|
33
|
+
* that index. The write is refused when the addressed entry has a different
|
|
34
|
+
* `created_at`; this compares timestamps, not entry identities.
|
|
35
|
+
*/
|
|
36
|
+
expectAt?:string;
|
|
30
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* One listed annotation entry carrying its absolute one-based position in the
|
|
40
|
+
* stored collection: the address `--edit` and `--delete` accept, whatever
|
|
41
|
+
* page, limit or filter delivered the row (pm-hka7ep).
|
|
42
|
+
*/
|
|
43
|
+
export type IndexedAnnotationEntry<TEntry = AnnotationEntry> = {
|
|
44
|
+
index:number;
|
|
45
|
+
} & TEntry;
|
|
31
46
|
/** Identifies the single annotation mutation represented by a bounded response. */
|
|
32
47
|
export interface AnnotationMutationReceipt {
|
|
33
48
|
/** Mutation applied to the annotation collection. */
|
|
@@ -128,7 +143,7 @@ text:string;
|
|
|
128
143
|
export type AnnotationCommandResult<TKey extends string,TEntry extends AnnotationEntry> = {
|
|
129
144
|
id:string;
|
|
130
145
|
count:number;
|
|
131
|
-
} & Record<TKey,TEntry
|
|
146
|
+
} & Record<TKey,Array<IndexedAnnotationEntry<TEntry>>> & {
|
|
132
147
|
total_count?:number;
|
|
133
148
|
returned_count?:number;
|
|
134
149
|
has_more?:boolean;
|
|
@@ -155,6 +170,34 @@ export declare function assertAnnotationStdinTransportAvailable(options:Annotati
|
|
|
155
170
|
export declare function resolveAnnotationInput(options:AnnotationSourceOptions,noun:string):Promise<AnnotationInput>;
|
|
156
171
|
/** Implements wrap ownership conflict for the public runtime surface of this module. */
|
|
157
172
|
export declare function wrapOwnershipConflict(error:unknown,guidance:OwnershipConflictGuidance):never;
|
|
173
|
+
/** Refusal code for annotation text that is an option token a parser bound as a text flag's value; the refusals spell it literally for the error catalog. */
|
|
174
|
+
export declare const ANNOTATION_FLAG_LIKE_VALUE_CODE = "annotation_flag_like_value";
|
|
175
|
+
/** Whether annotation text is an option token such as `--file` or `--file=x`; `text=` escapes literal dash-leading text. */
|
|
176
|
+
export declare function isFlagLikeAnnotationValue(raw:string):boolean;
|
|
177
|
+
/** Inputs for the refusal raised when annotation text is an option token. */
|
|
178
|
+
export interface FlagLikeAnnotationValueRefusalInput {
|
|
179
|
+
/** Annotation collection key: `comments`, `notes`, or `learnings`. */
|
|
180
|
+
collectionKey:string;
|
|
181
|
+
/** Text option that received the token, such as `--add`. */
|
|
182
|
+
textFlag:string;
|
|
183
|
+
/** The option token received as annotation text. */
|
|
184
|
+
value:string;
|
|
185
|
+
/** Command the examples start with, such as `pm comments <id>`. */
|
|
186
|
+
commandPrefix:string;
|
|
187
|
+
/** Executable retry of the caller's invocation, when the caller knows one. */
|
|
188
|
+
retryArgs?:string[];
|
|
189
|
+
/** Positional text that followed the token and that the source option cannot be combined with. */
|
|
190
|
+
conflictingOperand?:string;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Build the refusal for annotation text that is an option token. A source
|
|
194
|
+
* option (`--file`, `--stdin`) is named in its own form so the agent learns
|
|
195
|
+
* that it works without the text flag; any other token keeps the stdin and
|
|
196
|
+
* `text=` escape guidance. A supplied retry is carried as recovery with the
|
|
197
|
+
* text flag as `field` and the token as the suggested flag, which lets the
|
|
198
|
+
* CLI rewrite it as a minimal edit of the typed argv.
|
|
199
|
+
*/
|
|
200
|
+
export declare function createFlagLikeAnnotationValueRefusal(input:FlagLikeAnnotationValueRefusalInput):PmCliError;
|
|
158
201
|
/** Implements run annotation command for the public runtime surface of this module. */
|
|
159
202
|
export declare function runAnnotationCommand<TKey extends string,TEntry extends AnnotationEntry>(id:string,options:AnnotationCommandOptions,global:GlobalOptions,config:AnnotationCommandConfig<TKey,TEntry>):Promise<AnnotationCommandResult<TKey,TEntry>>;
|
|
160
203
|
/** Implements resolve annotation index for the public runtime surface of this module. */
|
package/dist/sdk/annotations.js
CHANGED
|
@@ -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]="35773218-9c35-51d9-a19b-e9094bd23b66")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{readFile}from"node:fs/promises";import{isFileAbsentError}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{createStdinTokenResolver,parseCsvKv,shouldResolveMutationStdinTokens,transferMutationStdinTokenPolicy}from"../core/item/parse.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{parseLimit}from"../core/shared/numeric-parsers.js";import{nowIso}from"../core/shared/time.js";import{resolveAuthor}from"../core/shared/author.js";import{locateItem,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";function normalizeAnnotationTransportOptions(options){const normalized={...options,...options.full===!0?{fullHistory:!0}:{}};return delete normalized.full,transferMutationStdinTokenPolicy(options,normalized)}function assertAnnotationEntryMutable(entry,operation){if(typeof entry=="object"&&entry!==null&&"format"in entry&&entry.format==="json")throw new PmCliError(`Structured context events are append-only and cannot be ${operation}.`,EXIT_CODE.USAGE,{code:"structured_event_immutable"})}function limitAnnotationEntries(values,limit){return limit===void 0?values:limit===0?[]:values.slice(Math.max(0,values.length-limit))}function readAnnotationEntries(source,collectionKey){const value=source[collectionKey];return Array.isArray(value)?value:[]}function parseAnnotationTextInput(raw,options={}){const trimmed=raw.trim();if(!trimmed)return"";const textPrefixMatch=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(trimmed);if(options.stripPlainTextPrefix===!0&&textPrefixMatch&&!trimmed.startsWith("```"))return trimmed.slice(textPrefixMatch[0].length).trim()||trimmed;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(trimmed)||trimmed.startsWith("```")))return trimmed;try{const kv=parseCsvKv(trimmed,"--add");return Object.keys(kv).map(key=>key.trim().toLowerCase()).some(key=>key!=="text")?trimmed:kv.text?.trim()||trimmed}catch{return trimmed}}function isErrnoError(error){return typeof error=="object"&&error!==null&&"code"in error}function assertAnnotationStdinTransportAvailable(options,optionName){if(!shouldResolveMutationStdinTokens(options))throw new PmCliError(`${optionName} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,EXIT_CODE.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function resolveAnnotationTextSource(options,noun){if(+(options.add!==void 0)+ +(options.stdin===!0)+ +(typeof options.file=="string")>1)throw new PmCliError(`Specify ${noun} text using only one input source: --add, --stdin, or --file`,EXIT_CODE.USAGE);const stdinResolver=createStdinTokenResolver(),resolveStdinTokens=shouldResolveMutationStdinTokens(options);if(options.add!==void 0)return{value:await stdinResolver.resolveValue(options.add,"--add",resolveStdinTokens)??"",rawValue:options.add,emptyFlag:"--add"};if(options.stdin===!0)return assertAnnotationStdinTransportAvailable(options,"--stdin"),{value:await stdinResolver.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof options.file!="string")return;const filePath=options.file.trim();if(!filePath)throw new PmCliError("--file path cannot be empty",EXIT_CODE.USAGE);if(filePath==="-")return assertAnnotationStdinTransportAvailable(options,"--file -"),{value:await stdinResolver.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await readFile(filePath,"utf8"),emptyFlag:"--file"}}catch(error){if(isErrnoError(error)&&isFileAbsentError(error))throw new PmCliError(`--file path not found: ${filePath}. Use --file - to read stdin.`,EXIT_CODE.USAGE);const detail=error instanceof Error?error.message:String(error);throw new PmCliError(`Failed to read --file path "${filePath}": ${detail}. Use --file - to read stdin.`,EXIT_CODE.USAGE)}}async function resolveAnnotationInput(options,noun){if(options.edit!==void 0&&options.delete!==void 0)throw new PmCliError("Specify only one of --edit or --delete",EXIT_CODE.USAGE);if(options.delete!==void 0){if(options.add!==void 0||options.stdin===!0||typeof options.file=="string")throw new PmCliError("--delete cannot be combined with replacement text",EXIT_CODE.USAGE);if(!Number.isInteger(options.delete)||options.delete<1)throw new PmCliError("--delete must be a positive integer",EXIT_CODE.USAGE);return{mode:"delete",index:options.delete}}if(options.edit!==void 0&&(!Number.isInteger(options.edit)||options.edit<1))throw new PmCliError("--edit must be a positive integer",EXIT_CODE.USAGE);const resolved=await resolveAnnotationTextSource(options,noun);if(options.edit!==void 0){if(!resolved)throw new PmCliError("--edit requires replacement text from --add, --stdin, or --file",EXIT_CODE.USAGE);return{mode:"edit",index:options.edit,...resolved}}return resolved?{mode:"add",...resolved}:{mode:"list"}}function wrapOwnershipConflict(error,guidance){throw error instanceof PmCliError&&error.exitCode===EXIT_CODE.CONFLICT&&error.message.includes("is assigned to")&&error.message.includes("Use --force to override")?new PmCliError(error.message,error.exitCode,{code:"ownership_conflict",required:guidance.required,examples:guidance.examples,nextSteps:guidance.nextSteps}):error}function annotationStdinHint(collectionKey){return collectionKey==="comments"?"--stdin":"--add -"}function assertAnnotationAddValueIsNotFlagLike(raw,config){if((config.input.emptyFlag??"--add")!=="--add")return;const trimmed=raw.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(trimmed))return;const stdinHint=annotationStdinHint(config.collectionKey),commandPrefix=config.input.mode==="edit"?`pm ${config.collectionKey} <id> --edit <index>`:`pm ${config.collectionKey} <id>`;throw new PmCliError(`--add value "${trimmed}" looks like an option, not annotation text. Use ${stdinHint} to read stdin, or use text=${trimmed} for literal dash-leading text.`,EXIT_CODE.USAGE,{code:"annotation_flag_like_value",required:`Use ${stdinHint} for stdin input, pass plain text, or use text=${trimmed} when the text really starts with "-".`,examples:[`${commandPrefix} ${stdinHint}`,`${commandPrefix} --add text=${trimmed}`]})}function assertAnnotationMessageHasTextSource(config,options){if(options.ifAbsent===!0&&!["add","stdin","file"].includes(config.input.mode))throw new PmCliError(`--if-absent requires a ${config.collectionKey.replace(/s$/,"")} append`,EXIT_CODE.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(config.input.mode!=="list"||options.message===void 0)return;const noun=config.collectionKey.replace(/s$/,"");throw new PmCliError(`--message labels a ${noun} mutation but does not provide ${noun} text. Pass text positionally or with --add, --stdin, or --file.`,EXIT_CODE.USAGE,{code:"annotation_message_without_text",required:`Provide ${noun} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${config.collectionKey} <id> --add "text" --message "why"`,`pm ${config.collectionKey} <id> ${annotationStdinHint(config.collectionKey)}`]})}function appendAnnotationEntry(document,collectionKey,author,text,ifAbsent,createEntry){const entries=readAnnotationEntries(document.metadata,collectionKey),existingIndex=ifAbsent?entries.findIndex(entry=>entry.author===author&&entry.text===text):-1;return existingIndex>=0?{changedFields:[],entryIndex:existingIndex+1}:(entries.push(createEntry({created_at:nowIso(),author,text})),document.metadata[collectionKey]=entries,{changedFields:[collectionKey],entryIndex:entries.length})}async function runAnnotationCommand(id,options,global2,config){assertAnnotationMessageHasTextSource(config,options);const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),limit=parseLimit(options.limit);if(config.input.mode==="list"){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);const loaded=await readLocatedItem(located,{schema:settings.schema}),allEntries2=readAnnotationEntries(loaded.document.metadata,config.collectionKey);return renderAnnotationResult(located.id,config.collectionKey,allEntries2,limit,options.includeMeta===!0)}const author=resolveAuthor(options.author,settings.author_default);if(config.input.mode==="delete"){const op=config.deleteOp??config.op;let result2;try{result2=await mutateItem({pmRoot,settings,id,op,author,message:options.message,force:options.force,bypassAssigneeConflict:config.bypassOwnershipConflict,mutate(document){const entries=readAnnotationEntries(document.metadata,config.collectionKey),arrayIndex=resolveAnnotationIndex(config.input.index,entries.length,config.collectionKey);return assertAnnotationEntryMutable(entries[arrayIndex],"deleted"),entries.splice(arrayIndex,1),document.metadata[config.collectionKey]=entries,{changedFields:[config.collectionKey]}}})}catch(error){wrapOwnershipConflict(error,config.conflictGuidance)}const allEntries2=readAnnotationEntries(result2.item,config.collectionKey);return renderAnnotationResult(result2.item.id,config.collectionKey,allEntries2,limit,options.includeMeta===!0,{action:"delete",entryIndex:config.input.index},options.fullHistory===!0)}const rawText=config.input.rawValue??config.input.value??"";assertAnnotationAddValueIsNotFlagLike(rawText,config);const text=config.parseText(config.input.value??"");if(!text.trim())throw new PmCliError(`${config.input.emptyFlag??"--add"} text cannot be empty`,EXIT_CODE.USAGE);if(config.input.mode==="edit"){const op=config.editOp??config.op;let result2;try{result2=await mutateItem({pmRoot,settings,id,op,author,message:options.message,force:options.force,bypassAssigneeConflict:config.bypassOwnershipConflict,mutate(document){const entries=readAnnotationEntries(document.metadata,config.collectionKey),arrayIndex=resolveAnnotationIndex(config.input.index,entries.length,config.collectionKey),existing=entries[arrayIndex];return assertAnnotationEntryMutable(existing,"edited"),entries[arrayIndex]={...existing,text,edited_at:nowIso()},document.metadata[config.collectionKey]=entries,{changedFields:[config.collectionKey]}}})}catch(error){wrapOwnershipConflict(error,config.conflictGuidance)}const allEntries2=readAnnotationEntries(result2.item,config.collectionKey);return renderAnnotationResult(result2.item.id,config.collectionKey,allEntries2,limit,options.includeMeta===!0,{action:"edit",entryIndex:config.input.index,entry:allEntries2[config.input.index-1]},options.fullHistory===!0)}let result,entryIndex=0;try{result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,bypassAssigneeConflict:config.bypassOwnershipConflict,skipNoop:options.ifAbsent===!0,mutate(document){const appended=appendAnnotationEntry(document,config.collectionKey,author,text,options.ifAbsent===!0,config.createEntry);return entryIndex=appended.entryIndex,{changedFields:appended.changedFields}}})}catch(error){wrapOwnershipConflict(error,config.conflictGuidance)}const allEntries=readAnnotationEntries(result.item,config.collectionKey);return renderAnnotationResult(result.item.id,config.collectionKey,allEntries,limit,options.includeMeta===!0,{action:"add",entryIndex,entry:allEntries[entryIndex-1],changedCount:options.ifAbsent===!0?Math.min(result.changedFields.length,1):void 0},options.fullHistory===!0)}function resolveAnnotationIndex(oneBasedIndex,count,collectionKey){if(oneBasedIndex===void 0||!Number.isInteger(oneBasedIndex)||oneBasedIndex<1||oneBasedIndex>count){const singular=collectionKey.replace(/s$/,""),label=`${singular.charAt(0).toUpperCase()}${singular.slice(1)}`,noun=count===1?`1 ${singular}`:`${count} ${collectionKey}`;throw new PmCliError(`${label} index ${oneBasedIndex??"(missing)"} out of range (item has ${noun})`,EXIT_CODE.USAGE)}return oneBasedIndex-1}function renderAnnotationMutationReceipts(collectionKey,mutation,historyOmitted){return mutation===void 0?{}:{mutation_receipt:{action:mutation.action,entry_index:mutation.entryIndex,changed_count:mutation.changedCount??1,full_history_included:!historyOmitted},omission_receipt:{has_omissions:historyOmitted,omitted_field_group_count:historyOmitted?1:0,omitted_field_groups:historyOmitted?[{name:`${collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function renderAnnotationResult(id,collectionKey,allEntries,limit,includeMeta,mutation,fullHistory=!1){const entries=mutation===void 0||fullHistory?limitAnnotationEntries(allEntries,mutation!==void 0&&fullHistory?void 0:limit):mutation.entry===void 0?[]:[mutation.entry],historyOmitted=mutation!==void 0&&entries.length<allEntries.length;return{id,[collectionKey]:entries,count:entries.length,...mutation?.changedCount===void 0?{}:{changed:mutation.changedCount===1},...[includeMeta,mutation!==void 0].includes(!0)?{total_count:allEntries.length,returned_count:entries.length,has_more:historyOmitted||entries.length<allEntries.length,...limit!==void 0?{limit}:{}}:{},...renderAnnotationMutationReceipts(collectionKey,mutation,historyOmitted)}}export{assertAnnotationStdinTransportAvailable,isErrnoError,limitAnnotationEntries,normalizeAnnotationTransportOptions,parseAnnotationTextInput,readAnnotationEntries,resolveAnnotationIndex,resolveAnnotationInput,runAnnotationCommand,wrapOwnershipConflict};
|
|
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]="3f833046-5961-57e6-a680-c1f23abf26c3")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{readFile}from"node:fs/promises";import{isFileAbsentError}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{createStdinTokenResolver,parseCsvKv,shouldResolveMutationStdinTokens,transferMutationStdinTokenPolicy}from"../core/item/parse.js";import{renderPmCommand}from"../core/shared/command-line.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{parseLimit}from"../core/shared/numeric-parsers.js";import{nowIso}from"../core/shared/time.js";import{resolveAuthor}from"../core/shared/author.js";import{locateItem,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{CANONICALLY_ORDERED_LOG_COLLECTIONS,compareLogValues}from"../core/item/item-format.js";function normalizeAnnotationTransportOptions(options){const normalized={...options,...options.full===!0?{fullHistory:!0}:{}};return delete normalized.full,transferMutationStdinTokenPolicy(options,normalized)}function assertAnnotationEntryMutable(entry,operation){if(typeof entry=="object"&&entry!==null&&"format"in entry&&entry.format==="json")throw new PmCliError(`Structured context events are append-only and cannot be ${operation}.`,EXIT_CODE.USAGE,{code:"structured_event_immutable"})}function limitAnnotationEntries(values,limit){return limit===void 0?values:limit===0?[]:values.slice(Math.max(0,values.length-limit))}function readAnnotationEntries(source,collectionKey){const value=source[collectionKey];return Array.isArray(value)?value:[]}function parseAnnotationTextInput(raw,options={}){const trimmed=raw.trim();if(!trimmed)return"";const textPrefixMatch=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(trimmed);if(options.stripPlainTextPrefix===!0&&textPrefixMatch&&!trimmed.startsWith("```"))return trimmed.slice(textPrefixMatch[0].length).trim()||trimmed;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(trimmed)||trimmed.startsWith("```")))return trimmed;try{const kv=parseCsvKv(trimmed,"--add");return Object.keys(kv).map(key=>key.trim().toLowerCase()).some(key=>key!=="text")?trimmed:kv.text?.trim()||trimmed}catch{return trimmed}}function isErrnoError(error){return typeof error=="object"&&error!==null&&"code"in error}function assertAnnotationStdinTransportAvailable(options,optionName){if(!shouldResolveMutationStdinTokens(options))throw new PmCliError(`${optionName} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,EXIT_CODE.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function resolveAnnotationTextSource(options,noun){if(+(options.add!==void 0)+ +(options.stdin===!0)+ +(typeof options.file=="string")>1)throw new PmCliError(`Specify ${noun} text using only one input source: --add, --stdin, or --file`,EXIT_CODE.USAGE);const stdinResolver=createStdinTokenResolver(),resolveStdinTokens=shouldResolveMutationStdinTokens(options);if(options.add!==void 0)return{value:await stdinResolver.resolveValue(options.add,"--add",resolveStdinTokens)??"",rawValue:options.add,emptyFlag:"--add"};if(options.stdin===!0)return assertAnnotationStdinTransportAvailable(options,"--stdin"),{value:await stdinResolver.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof options.file!="string")return;const filePath=options.file.trim();if(!filePath)throw new PmCliError("--file path cannot be empty",EXIT_CODE.USAGE);if(filePath==="-")return assertAnnotationStdinTransportAvailable(options,"--file -"),{value:await stdinResolver.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await readFile(filePath,"utf8"),emptyFlag:"--file"}}catch(error){if(isErrnoError(error)&&isFileAbsentError(error))throw new PmCliError(`--file path not found: ${filePath}. Use --file - to read stdin.`,EXIT_CODE.USAGE);const detail=error instanceof Error?error.message:String(error);throw new PmCliError(`Failed to read --file path "${filePath}": ${detail}. Use --file - to read stdin.`,EXIT_CODE.USAGE)}}async function resolveAnnotationInput(options,noun){if(options.edit!==void 0&&options.delete!==void 0)throw new PmCliError("Specify only one of --edit or --delete",EXIT_CODE.USAGE);if(options.delete!==void 0){if(options.add!==void 0||options.stdin===!0||typeof options.file=="string")throw new PmCliError("--delete cannot be combined with replacement text",EXIT_CODE.USAGE);if(!Number.isInteger(options.delete)||options.delete<1)throw new PmCliError("--delete must be a positive integer",EXIT_CODE.USAGE);return{mode:"delete",index:options.delete}}if(options.edit!==void 0&&(!Number.isInteger(options.edit)||options.edit<1))throw new PmCliError("--edit must be a positive integer",EXIT_CODE.USAGE);const resolved=await resolveAnnotationTextSource(options,noun);if(options.edit!==void 0){if(!resolved)throw new PmCliError("--edit requires replacement text from --add, --stdin, or --file",EXIT_CODE.USAGE);return{mode:"edit",index:options.edit,...resolved}}return resolved?{mode:"add",...resolved}:{mode:"list"}}function wrapOwnershipConflict(error,guidance){throw error instanceof PmCliError&&error.exitCode===EXIT_CODE.CONFLICT&&error.message.includes("is assigned to")&&error.message.includes("Use --force to override")?new PmCliError(error.message,error.exitCode,{code:"ownership_conflict",required:guidance.required,examples:guidance.examples,nextSteps:guidance.nextSteps}):error}function annotationStdinHint(collectionKey){return collectionKey==="comments"?"--stdin":"--add -"}const ANNOTATION_FLAG_LIKE_VALUE_CODE="annotation_flag_like_value";function isFlagLikeAnnotationValue(raw){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(raw.trim())}function annotationSourceOptionForm(token){return token==="--file"?"--file <path>":token.startsWith("--file=")?token:token==="--stdin"?"--stdin":void 0}function createFlagLikeAnnotationValueRefusal(input){const trimmed=input.value.trim(),noun=input.collectionKey.replace(/s$/,""),sourceForm=annotationSourceOptionForm(trimmed),stdinHint=annotationStdinHint(input.collectionKey),retry=input.retryArgs===void 0?{}:{field:input.textFlag,recovery:{suggested_flags:[trimmed],suggested_retry:renderPmCommand(input.retryArgs),suggested_retry_args:[...input.retryArgs]}};if(sourceForm!==void 0){const sourceFlag=sourceForm.split(/[ =]/,1)[0],source=sourceFlag==="--file"?"that file":"stdin",operandNote=input.conflictingOperand===void 0?"":` "${input.conflictingOperand}" was read as positional text, which ${sourceFlag} cannot be combined with: drop it, or pass it as the text without ${sourceFlag}.`;return new PmCliError(`${input.textFlag} value "${trimmed}" looks like an option, not annotation text: ${input.textFlag} took ${sourceFlag} as its value. Drop ${input.textFlag} and pass ${sourceForm} on its own.${operandNote}`,EXIT_CODE.USAGE,{code:"annotation_flag_like_value",required:`Drop ${input.textFlag}: ${sourceForm} reads the ${noun} text from ${source} by itself. Use ${input.textFlag} text=${trimmed} only when the text really is "${trimmed}".`,examples:[`${input.commandPrefix} ${sourceForm}`,`${input.commandPrefix} ${input.textFlag} text=${trimmed}`],...retry})}return new PmCliError(`${input.textFlag} value "${trimmed}" looks like an option, not annotation text. Use ${stdinHint} to read stdin, or use text=${trimmed} for literal dash-leading text.`,EXIT_CODE.USAGE,{code:"annotation_flag_like_value",required:`Use ${stdinHint} for stdin input, pass plain text, or use text=${trimmed} when the text really starts with "-".`,examples:[`${input.commandPrefix} ${stdinHint}`,`${input.commandPrefix} ${input.textFlag} text=${trimmed}`],...retry})}function assertAnnotationAddValueIsNotFlagLike(raw,config){if(!((config.input.emptyFlag??"--add")!=="--add"||!isFlagLikeAnnotationValue(raw)))throw createFlagLikeAnnotationValueRefusal({collectionKey:config.collectionKey,textFlag:"--add",value:raw,commandPrefix:config.input.mode==="edit"?`pm ${config.collectionKey} <id> --edit <index>`:`pm ${config.collectionKey} <id>`})}function assertAnnotationMessageHasTextSource(config,options){if(options.ifAbsent===!0&&!["add","stdin","file"].includes(config.input.mode))throw new PmCliError(`--if-absent requires a ${config.collectionKey.replace(/s$/,"")} append`,EXIT_CODE.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(assertAnnotationExpectationTargetsEntry(config,options),config.input.mode!=="list"||options.message===void 0)return;const noun=config.collectionKey.replace(/s$/,"");throw new PmCliError(`--message labels a ${noun} mutation but does not provide ${noun} text. Pass text positionally or with --add, --stdin, or --file.`,EXIT_CODE.USAGE,{code:"annotation_message_without_text",required:`Provide ${noun} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${config.collectionKey} <id> --add "text" --message "why"`,`pm ${config.collectionKey} <id> ${annotationStdinHint(config.collectionKey)}`]})}function assertAnnotationExpectationTargetsEntry(config,options){if(options.expectAt!==void 0){if(config.input.mode!=="edit"&&config.input.mode!=="delete")throw new PmCliError(`--expect-at guards an --edit or --delete of one ${config.collectionKey.replace(/s$/,"")}`,EXIT_CODE.USAGE,{code:"annotation_expectation_without_target",required:"Combine --expect-at with --edit <index> or --delete <index>; omit it for list and append operations.",examples:[`pm ${config.collectionKey} <id> --edit <index> --expect-at <created_at> --add "<text>"`,`pm ${config.collectionKey} <id> --delete <index> --expect-at <created_at>`]});if(typeof options.expectAt!="string"||options.expectAt.trim().length===0)throw new PmCliError("--expect-at must be the non-empty created_at timestamp of the entry you read",EXIT_CODE.USAGE,{code:"annotation_expectation_invalid",required:"Pass the created_at value of the row you read at that index, as a string."})}}function assertExpectedAnnotationEntry(id,entries,arrayIndex,config,expectAt){if(expectAt===void 0)return;const actual=entries[arrayIndex].created_at;if(actual===expectAt)return;const matchingIndexes=entries.flatMap((entry,position)=>entry.created_at===expectAt?[position+1]:[]),noun=config.collectionKey.replace(/s$/,""),action=config.input.mode==="delete"?"--delete":"--edit",entryIndex=arrayIndex+1,retarget=matchingIndexes.length===1?` The ${noun} created at ${expectAt} is at index ${matchingIndexes[0]}.`:matchingIndexes.length>1?` ${matchingIndexes.length} ${config.collectionKey} were created at ${expectAt}: indexes ${matchingIndexes.join(", ")}.`:` No ${noun} on ${id} was created at ${expectAt}.`;throw new PmCliError(`${noun.charAt(0).toUpperCase()}${noun.slice(1)} ${entryIndex} on ${id} was created at ${actual}, not ${expectAt}; refusing ${action} of an entry the caller did not read. Nothing was written.${retarget}`,EXIT_CODE.CONFLICT,{code:"annotation_entry_mismatch",item_id:id,details:{collection:config.collectionKey,entry_index:entryIndex,expected_created_at:expectAt,actual_created_at:actual,matching_indexes:matchingIndexes},required:`Address the ${noun} by the index its listing row reports and keep --expect-at set to that row's created_at. When several indexes share the timestamp, inspect those rows before retrying, because the guard compares timestamps, not entry identities.`,why:"A listing page's position or count is not an entry address; only the row's index is, and the expectation checks that the entry at that index still carries the created_at that was read.",examples:[`pm ${config.collectionKey} ${id} --limit 5`,`pm ${config.collectionKey} ${id} ${action} ${matchingIndexes.length===1?matchingIndexes[0]:"<index>"} --expect-at ${expectAt}${action==="--edit"?' --add "<text>"':""}`]})}function appendAnnotationEntry(document,collectionKey,author,text,ifAbsent,createEntry){const entries=readAnnotationEntries(document.metadata,collectionKey),existingIndex=ifAbsent?entries.findIndex(entry=>entry.author===author&&entry.text===text):-1;return existingIndex>=0?{changedFields:[],written:entries,position:existingIndex}:(entries.push(createEntry({created_at:nowIso(),author,text})),document.metadata[collectionKey]=entries,{changedFields:[collectionKey],written:entries,position:entries.length-1})}function canonicalAnnotationAddress(collectionKey,written,position){return CANONICALLY_ORDERED_LOG_COLLECTIONS.has(collectionKey)?written.map((_entry,index)=>index).sort((left,right)=>compareLogValues(written[left],written[right])||left-right).indexOf(position)+1:position+1}async function runAnnotationCommand(id,options,global2,config){assertAnnotationMessageHasTextSource(config,options);const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),limit=parseLimit(options.limit);if(config.input.mode==="list"){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);const loaded=await readLocatedItem(located,{schema:settings.schema}),allEntries2=readAnnotationEntries(loaded.document.metadata,config.collectionKey);return renderAnnotationResult(located.id,config.collectionKey,allEntries2,limit,options.includeMeta===!0)}const author=resolveAuthor(options.author,settings.author_default);if(config.input.mode==="delete"){const op=config.deleteOp??config.op;let result2;try{result2=await mutateItem({pmRoot,settings,id,op,author,message:options.message,force:options.force,bypassAssigneeConflict:config.bypassOwnershipConflict,mutate(document){const entries=readAnnotationEntries(document.metadata,config.collectionKey),arrayIndex=resolveAnnotationIndex(config.input.index,entries.length,config.collectionKey);return assertExpectedAnnotationEntry(id,entries,arrayIndex,config,options.expectAt),assertAnnotationEntryMutable(entries[arrayIndex],"deleted"),entries.splice(arrayIndex,1),document.metadata[config.collectionKey]=entries,{changedFields:[config.collectionKey]}}})}catch(error){wrapOwnershipConflict(error,config.conflictGuidance)}const allEntries2=readAnnotationEntries(result2.item,config.collectionKey);return renderAnnotationResult(result2.item.id,config.collectionKey,allEntries2,limit,options.includeMeta===!0,{action:"delete",entryIndex:config.input.index},options.fullHistory===!0)}const rawText=config.input.rawValue??config.input.value??"";assertAnnotationAddValueIsNotFlagLike(rawText,config);const text=config.parseText(config.input.value??"");if(!text.trim())throw new PmCliError(`${config.input.emptyFlag??"--add"} text cannot be empty`,EXIT_CODE.USAGE);if(config.input.mode==="edit"){const op=config.editOp??config.op;let result2,editedAddress=0;try{result2=await mutateItem({pmRoot,settings,id,op,author,message:options.message,force:options.force,bypassAssigneeConflict:config.bypassOwnershipConflict,mutate(document){const entries=readAnnotationEntries(document.metadata,config.collectionKey),arrayIndex=resolveAnnotationIndex(config.input.index,entries.length,config.collectionKey);assertExpectedAnnotationEntry(id,entries,arrayIndex,config,options.expectAt);const existing=entries[arrayIndex];return assertAnnotationEntryMutable(existing,"edited"),entries[arrayIndex]={...existing,text,edited_at:nowIso()},editedAddress=canonicalAnnotationAddress(config.collectionKey,entries,arrayIndex),document.metadata[config.collectionKey]=entries,{changedFields:[config.collectionKey]}}})}catch(error){wrapOwnershipConflict(error,config.conflictGuidance)}const allEntries2=readAnnotationEntries(result2.item,config.collectionKey),editedIndex=editedAddress;return renderAnnotationResult(result2.item.id,config.collectionKey,allEntries2,limit,options.includeMeta===!0,{action:"edit",entryIndex:editedIndex,entry:allEntries2[editedIndex-1]},options.fullHistory===!0)}let result,entryIndex=0;try{result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,bypassAssigneeConflict:config.bypassOwnershipConflict,skipNoop:options.ifAbsent===!0,mutate(document){const appended=appendAnnotationEntry(document,config.collectionKey,author,text,options.ifAbsent===!0,config.createEntry);return entryIndex=canonicalAnnotationAddress(config.collectionKey,appended.written,appended.position),{changedFields:appended.changedFields}}})}catch(error){wrapOwnershipConflict(error,config.conflictGuidance)}const allEntries=readAnnotationEntries(result.item,config.collectionKey);return renderAnnotationResult(result.item.id,config.collectionKey,allEntries,limit,options.includeMeta===!0,{action:"add",entryIndex,entry:allEntries[entryIndex-1],changedCount:options.ifAbsent===!0?Math.min(result.changedFields.length,1):void 0},options.fullHistory===!0)}function resolveAnnotationIndex(oneBasedIndex,count,collectionKey){if(oneBasedIndex===void 0||!Number.isInteger(oneBasedIndex)||oneBasedIndex<1||oneBasedIndex>count){const singular=collectionKey.replace(/s$/,""),label=`${singular.charAt(0).toUpperCase()}${singular.slice(1)}`,noun=count===1?`1 ${singular}`:`${count} ${collectionKey}`;throw new PmCliError(`${label} index ${oneBasedIndex??"(missing)"} out of range (item has ${noun})`,EXIT_CODE.USAGE)}return oneBasedIndex-1}function renderAnnotationMutationReceipts(collectionKey,mutation,historyOmitted){return mutation===void 0?{}:{mutation_receipt:{action:mutation.action,entry_index:mutation.entryIndex,changed_count:mutation.changedCount??1,full_history_included:!historyOmitted},omission_receipt:{has_omissions:historyOmitted,omitted_field_group_count:historyOmitted?1:0,omitted_field_groups:historyOmitted?[{name:`${collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function indexAnnotationEntry(entry,index){if(Object.prototype.toString.call(entry)!=="[object Object]")return entry;const indexed={index,...entry};return indexed.index=index,indexed}function indexRetainedAnnotationEntries(allEntries,retained){const offset=allEntries.length-retained.length;return retained.map((entry,position)=>indexAnnotationEntry(entry,offset+position+1))}function renderAnnotationResult(id,collectionKey,allEntries,limit,includeMeta,mutation,fullHistory=!1){const entries=mutation===void 0||fullHistory?indexRetainedAnnotationEntries(allEntries,limitAnnotationEntries(allEntries,mutation!==void 0&&fullHistory?void 0:limit)):mutation.entry===void 0?[]:[indexAnnotationEntry(mutation.entry,mutation.entryIndex)],historyOmitted=mutation!==void 0&&entries.length<allEntries.length;return{id,[collectionKey]:entries,count:entries.length,...mutation?.changedCount===void 0?{}:{changed:mutation.changedCount===1},...[includeMeta,mutation!==void 0].includes(!0)?{total_count:allEntries.length,returned_count:entries.length,has_more:historyOmitted||entries.length<allEntries.length,...limit!==void 0?{limit}:{}}:{},...renderAnnotationMutationReceipts(collectionKey,mutation,historyOmitted)}}export{ANNOTATION_FLAG_LIKE_VALUE_CODE,assertAnnotationStdinTransportAvailable,createFlagLikeAnnotationValueRefusal,isErrnoError,isFlagLikeAnnotationValue,limitAnnotationEntries,normalizeAnnotationTransportOptions,parseAnnotationTextInput,readAnnotationEntries,resolveAnnotationIndex,resolveAnnotationInput,runAnnotationCommand,wrapOwnershipConflict};
|
|
2
2
|
//# sourceMappingURL=annotations.js.map
|
package/dist/sdk/authoring.d.ts
CHANGED
|
@@ -16,3 +16,9 @@ export { EXTENSION_CAPABILITY_REGISTRATION_SURFACES,collectUsedExtensionCapabili
|
|
|
16
16
|
export { renderExtensionSurfaceMarkdown,type ExtensionSurfaceMarkdownOptions,} from "../core/extensions/activation-summary-markdown.js";
|
|
17
17
|
export { createExtensionContributionInventory,normalizeExtensionContributionInventory,} from "../core/extensions/contribution-inventory.js";
|
|
18
18
|
export type { AfterCommandAffectedItem,AfterCommandHook,AfterCommandHookContext,BeforeCommandHook,BeforeCommandHookContext,BeforeMutationHook,BeforeMutationHookContext,BeforeMutationHookDecision,CommandDefinition,ExtensionCommandReadOutput,ExtensionCommandArgumentDefinition,CommandHandler,CommandHandlerContext,CommandHandlerResult,ExtensionCommandSdk,CommandOverride,CommandOverrideContext,ExtensionServiceName,Exporter,ExporterArtifactOutputContract,ExporterRegistrationOptions,ExtensionActivationResult,ExtensionApi,ExtensionCommandRegistry,ExtensionDeactivationFailure,ExtensionDeactivationOptions,ExtensionDeactivationResult,ExtensionDiagnostic,ExtensionContributionInventory,ExtensionDiscoveryResult,ExtensionHookRegistry,ExtensionSelfIdentity,ExtensionLoadResult,ExtensionManifest,ExtensionManifestEngines,ExtensionMutationGuardSdk,ExtensionGovernancePolicy,ExtensionPolicyOverride,ExtensionProvenanceMetadata,ExtensionRuntimePermissionDeclaration,ExtensionSearchMode,ExtensionParserRegistry,ExtensionPreflightRegistry,ExtensionRegistrationRegistry,ExtensionRendererRegistry,ExtensionServiceRegistry,FlagValueType,FlagDefinition,ImportExportContext,ImportExportRegistrationOptions,Importer,OnIndexHook,OnIndexHookContext,OnReadHook,OnReadHookContext,OnWriteHook,OnWriteHookContext,OutputRendererFormat,ParserOverride,ParserOverrideContext,ParserOverrideDelta,PreflightOverride,PreflightOverrideContext,PreflightOverrideDelta,PreflightRuntimeDecision,RegisteredExtensionExporter,RegisteredExporterArtifactOutputContract,RegisteredExtensionFlagDefinitions,RegisteredExtensionHook,RegisteredExtensionImporter,RegisteredExtensionProjectProfile,RegisteredExtensionSchemaMigrationDefinition,RegisteredExtensionSearchProvider,RegisteredExtensionServiceOverride,RegisteredExtensionVectorStoreAdapter,RendererOverride,RendererOverrideContext,SchemaFieldDefinition,SchemaItemTypeCommandOptionPolicyDefinition,SchemaItemTypeOptionDefinition,SchemaItemTypeDefinition,SchemaMigrationDefinition,SchemaMigrationRunContext,SchemaMigrationRunner,SearchProviderEmbedBatchContext,SearchProviderEmbedContext,SearchProviderDefinition,SearchProviderHit,SearchProviderQueryContext,SearchProviderQueryResult,ServiceOverride,ServiceOverrideContext,ServiceOverrideDecision,ServiceOverrideOwnership,VectorStoreAdapterDefinition,VectorStoreDeleteContext,VectorStoreQueryContext,VectorStoreQueryHit,VectorStoreUpsertContext,VectorStoreUpsertPoint,} from "../core/extensions/loader.js";
|
|
19
|
+
export { normalizeDirectExtensionCommandOptions,resolveExtensionFlagOptionKey,type LooseCommandFlagDefinition,} from "./extension/command-options.js";
|
|
20
|
+
export type { ExtensionActivationSummary } from "../core/extensions/activation-summary.js";
|
|
21
|
+
export type { ExtensionLayer,ScopedPreflightOverrideDefinition,ScopedRendererOverrideDefinition } from "../core/extensions/extension-types.js";
|
|
22
|
+
export type { CommanderOptionAliasContract } from "./cli-contracts/commander-types.js";
|
|
23
|
+
export type { CliFlagContract } from "./cli-contracts/flag-contracts.js";
|
|
24
|
+
export type { ExactDefinition,FlagAuthoringDefinition,ItemFieldAuthoringDefinition,ItemTypeAuthoringDefinition,MigrationAuthoringDefinition,SearchProviderAuthoringDefinition,VectorStoreAdapterAuthoringDefinition } from "./define.js";
|
package/dist/sdk/authoring.js
CHANGED
|
@@ -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]="c96e4de9-16ef-581a-aa4b-6450917c2c65")}catch{}})();export*from"./compose.js";export*from"./define.js";export*from"./extension-contracts.js";import{RESERVED_ITEM_FIELD_NAMES}from"../core/extensions/item-fields.js";import{PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_RESOURCE_KINDS,collectPackageExtensionDirectories,readPmPackageManifest}from"../core/packages/manifest.js";import{BUILTIN_PROFILES,listProfiles,normalizeProfileName,PROFILE_NAMES,resolveProfile}from"../core/profile/profile-presets.js";import{describeProfileComposition,describeProjectProfile}from"../core/profile/profile-describe.js";import{lintProjectProfile,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS}from"../core/profile/profile-lint.js";import{planProfileApplication}from"../core/profile/profile-plan.js";import{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,collectUsedExtensionCapabilities,reconcileExtensionCapabilityUsage}from"../core/extensions/capability-usage.js";import{renderExtensionSurfaceMarkdown}from"../core/extensions/activation-summary-markdown.js";import{createExtensionContributionInventory,normalizeExtensionContributionInventory}from"../core/extensions/contribution-inventory.js";import{normalizeDirectExtensionCommandOptions,resolveExtensionFlagOptionKey}from"./extension/command-options.js";export{BUILTIN_PROFILES,EXTENSION_CAPABILITY_REGISTRATION_SURFACES,PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_RESOURCE_KINDS,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS,PROFILE_NAMES,RESERVED_ITEM_FIELD_NAMES,collectPackageExtensionDirectories,collectUsedExtensionCapabilities,createExtensionContributionInventory,describeProfileComposition,describeProjectProfile,lintProjectProfile,listProfiles,normalizeDirectExtensionCommandOptions,normalizeExtensionContributionInventory,normalizeProfileName,planProfileApplication,readPmPackageManifest,reconcileExtensionCapabilityUsage,renderExtensionSurfaceMarkdown,resolveExtensionFlagOptionKey,resolveProfile};
|
|
2
2
|
//# sourceMappingURL=authoring.js.map
|