@unbrained/pm-cli 2026.9.12 → 2026.9.14
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 +2 -2
- package/CHANGELOG.md +42 -0
- package/dist/cli/command-namespaces.js +1 -1
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/error-guidance.js +1 -1
- package/dist/cli/extension-command-help.d.ts +2 -2
- package/dist/cli/extension-command-help.js +2 -2
- package/dist/cli/main.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +146 -146
- package/dist/cli-bundle/chunks/chunk-33PER336.js +236 -0
- package/dist/cli-bundle/chunks/{chunk-3ZJDGTYC.js → chunk-5JIJAWIF.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-A2Q64TGR.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-YU75JRTW.js → chunk-B6W5LIXK.js} +43 -43
- package/dist/cli-bundle/chunks/{chunk-GKY655T7.js → chunk-BY3ID7QI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7KF6HCRC.js → chunk-D5AJQU7F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7H33WPDF.js → chunk-DBHQIS6Z.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TAGDYARO.js → chunk-GQMILIC5.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-2JAY4LFI.js → chunk-NYE6EREL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-67H4PKQ5.js → chunk-O7SRS7Y3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-X6POOZKD.js → chunk-XEV7BHH3.js} +29 -29
- package/dist/cli-bundle/chunks/{chunk-I6VQUHK6.js → chunk-ZYRN2OG3.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-KEZPDR6X.js → register-list-query-B2U36YWL.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-HEXA3ZDM.js → register-mutation-GX42CQYR.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-TEZT65JF.js → register-operations-ZV34KX5E.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-IIL74WUG.js → register-setup-W4OS7IZW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LWJBBM6X.js → chunk-6WZBO4VQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TTRB47KM.js → chunk-7BUJABHB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2BQ4JSJQ.js → chunk-C5NQVXKE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CMCSUANO.js +20 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IURELABV.js → chunk-CPQQIVDL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EIXGDI77.js → chunk-D4FQV6TY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YNBACVQ2.js → chunk-ENJH7CBZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KK7KSXUP.js → chunk-FHQLQOUZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PERRTPIY.js → chunk-FNLAQJES.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GGDO6VBT.js +30 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7EKXAUKF.js → chunk-KWP3QTN7.js} +53 -53
- package/dist/cli-bundle/focused-chunks/{chunk-SDQOOL34.js → chunk-LFGTCEHX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5PSYV3AT.js → chunk-N23WTRCC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5CRND7UA.js → chunk-O4EROPO3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-UFSMYVZF.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MFVABYEU.js → chunk-ZFNRD7EN.js} +2 -2
- package/dist/cli-bundle/main.js +20 -20
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +28 -28
- 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 +42 -42
- 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 +8 -8
- package/dist/core/output/output.js +3 -3
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/telemetry/consent.d.ts +1 -1
- package/dist/core/telemetry/consent.js +2 -2
- package/dist/core/telemetry/policy.d.ts +10 -0
- package/dist/core/telemetry/policy.js +2 -0
- package/dist/core/telemetry/runtime.d.ts +43 -14
- package/dist/core/telemetry/runtime.js +5 -4
- package/dist/sdk/agent/command-suggestions.d.ts +6 -0
- package/dist/sdk/agent/command-suggestions.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.d.ts +2 -2
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +7 -3
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/completion.js +1 -1
- package/dist/sdk/governance/health.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/telemetry.d.ts +5 -0
- package/dist/sdk/telemetry.js +1 -1
- package/docs/AGENT_UX_CONTRACTS.md +10 -2
- package/docs/CLI_GRAMMAR.md +59 -0
- package/docs/COMMAND_NAMESPACES.md +7 -4
- package/docs/CONFIGURATION.md +48 -3
- package/docs/generated/AGENT_CAPABILITY_ROUTING.md +4 -4
- package/docs/generated/AGENT_COMMAND_SURFACE.md +11 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +12 -1
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +2 -2
- package/marketplace.json +2 -2
- package/package.json +5 -5
- 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/extensions/guide-shell/index.ts +13 -26
- 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-codex/.codex-plugin/plugin.json +1 -1
- package/dist/cli-bundle/chunks/chunk-DEGRLB6Y.js +0 -235
- package/dist/cli-bundle/chunks/chunk-PTX2JRFR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-BIOWOU6S.js +0 -30
- package/dist/cli-bundle/focused-chunks/chunk-GAKFECOQ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VWMP6W7Y.js +0 -20
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
-
`)}catch{}}function isSensitiveKey(key){const normalized=key.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_");const tokens=normalized.split("_").filter(token=>token.length>0);return REDACTION_INPUT_KEYS.has(normalized)||SENSITIVE_KEYWORDS.some(keyword=>normalized===keyword||normalized.endsWith(`_${keyword}`)||tokens.includes(keyword))}function redactInlineSensitiveAssignments(input){const withoutAssignments=input.replaceAll(INLINE_SENSITIVE_ASSIGNMENT_PATTERN,(_match,key,delimiter)=>`${key}${delimiter}[redacted]`);return withoutAssignments.replaceAll(INLINE_SENSITIVE_FLAG_PATTERN,(_match,flag,delimiter)=>`${flag}${delimiter}[redacted]`)}function redactAbsolutePathTokens(input){return input.replaceAll(ABSOLUTE_PATH_TOKEN_PATTERN,(_match,prefix)=>`${prefix}[redacted_path]`)}function isAsciiLetterOrDigitCode(code){const isUpper=code>=65&&code<=90;const isLower=code>=97&&code<=122;const isDigit=code>=48&&code<=57;return isUpper||isLower||isDigit}function isEmailLocalCharacter(character){if(!character){return false}const code=character.charCodeAt(0);if(isAsciiLetterOrDigitCode(code)){return true}return character==="."||character==="_"||character==="%"||character==="+"||character==="-"}function isEmailDomainCharacter(character){if(!character){return false}const code=character.charCodeAt(0);if(isAsciiLetterOrDigitCode(code)){return true}return character==="."||character==="-"}function looksLikeEmailToken(token){const atIndex=token.indexOf("@");if(atIndex<=0||atIndex!==token.lastIndexOf("@")||atIndex===token.length-1){return false}const localPart=token.slice(0,atIndex);const domainPart=token.slice(atIndex+1);const lastDot=domainPart.lastIndexOf(".");if(lastDot<=0||lastDot===domainPart.length-1){return false}if(domainPart.length-(lastDot+1)<2){return false}for(const character of localPart){if(!isEmailLocalCharacter(character)){return false}}for(const character of domainPart){if(!isEmailDomainCharacter(character)){return false}}return true}function redactEmailTokens(input){let redacted="";let cursor=0;while(cursor<input.length){const atIndex=input.indexOf("@",cursor);if(atIndex<0){redacted+=input.slice(cursor);break}let start=atIndex-1;while(start>=cursor&&isEmailLocalCharacter(input[start])){start-=1}start+=1;let end=atIndex+1;while(end<input.length&&isEmailDomainCharacter(input[end])){end+=1}const candidate=input.slice(start,end);if(looksLikeEmailToken(candidate)){redacted+=input.slice(cursor,start);redacted+="[redacted_email]";cursor=end;continue}redacted+=input.slice(cursor,atIndex+1);cursor=atIndex+1}return redacted}function sanitizeCommonSensitiveTokens(input){const withoutEmails=redactEmailTokens(input);const withoutBearer=withoutEmails.replaceAll(BEARER_TOKEN_PATTERN,"bearer [redacted_token]");return withoutBearer.replaceAll(PRIVATE_IP_PATTERN,"[redacted_ip]")}function sanitizeStringRedacted(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input);const withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);const withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets);const trimmed=withoutAbsolutePaths.trim();if(trimmed.startsWith("/")&&trimmed.length>1){return"[redacted_path]"}if(withoutAbsolutePaths.length>512){return`${withoutAbsolutePaths.slice(0,509)}...`}return withoutAbsolutePaths}function sanitizeStringMax(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input);const withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);const withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets);const trimmed=withoutAbsolutePaths.trim();if(trimmed.startsWith("/")&&trimmed.length>1){return"[redacted_path]"}if(withoutAbsolutePaths.length>2048){return`${withoutAbsolutePaths.slice(0,2045)}...`}return withoutAbsolutePaths}function sanitizeString(input,captureLevel="redacted"){if(captureLevel==="max"){return sanitizeStringMax(input)}return sanitizeStringRedacted(input)}function sanitizeValue(value,keyHint,captureLevel="redacted",depth=0){if(keyHint&&isSensitiveKey(keyHint)){return"[redacted]"}if(value===null||value===void 0){return value}if(typeof value==="string"){return sanitizeString(value,captureLevel)}if(typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>sanitizeValue(entry,void 0,captureLevel,depth+1))}if(typeof value==="object"){const record=value;const sanitized={};for(const[key,nested]of Object.entries(record)){sanitized[key]=sanitizeValue(nested,key,captureLevel,depth+1)}return sanitized}return String(value)}function sanitizeCommandArgs(args,captureLevel="redacted"){const sanitized=[];let nextIsSensitiveValue=false;for(const rawArg of args){const arg=sanitizeString(rawArg,captureLevel);if(nextIsSensitiveValue){sanitized.push("[redacted]");nextIsSensitiveValue=false;continue}if(arg.startsWith("--")){const withoutPrefix=arg.slice(2);const delimiterIndex=withoutPrefix.indexOf("=");if(delimiterIndex>=0){const key=withoutPrefix.slice(0,delimiterIndex);const value=withoutPrefix.slice(delimiterIndex+1);if(isSensitiveKey(key)){sanitized.push(`--${key}=[redacted]`)}else{sanitized.push(`--${key}=${sanitizeString(value,captureLevel)}`)}continue}if(isSensitiveKey(withoutPrefix)){sanitized.push(`--${withoutPrefix}`);nextIsSensitiveValue=true;continue}}sanitized.push(arg)}return sanitized}function normalizeCaptureLevel(value){const normalized=value?.trim().toLowerCase();if(normalized==="minimal"||normalized==="redacted"||normalized==="max"){return normalized}return"redacted"}function parseBooleanTrueLike(value){return BOOLEAN_TRUE_VALUES.has((value??"").trim().toLowerCase())}function resolveTelemetryHttpTimeoutMs(){const rawConfigured=process.env[PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV]?.trim();if(!rawConfigured){return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}const configured=Number(rawConfigured);if(!Number.isFinite(configured)){return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}return Math.min(TELEMETRY_HTTP_TIMEOUT_MAX_MS,Math.max(TELEMETRY_HTTP_TIMEOUT_MIN_MS,Math.trunc(configured)))}async function postTelemetryJson(endpoint,headers,body){const url=new URL(endpoint);if(globalThis.fetch!==NATIVE_FETCH){const controller=new AbortController;let timeout;const deadline=new Promise((_resolve,reject)=>{timeout=setTimeout(()=>{controller.abort();reject(new Error("telemetry_http_timeout"))},resolveTelemetryHttpTimeoutMs())});try{const response=await Promise.race([globalThis.fetch(endpoint,{method:"POST",headers,body,signal:controller.signal}),deadline]);return response.status}finally{clearTimeout(timeout)}}const request=url.protocol==="https:"?httpsRequest:url.protocol==="http:"?httpRequest:void 0;if(!request){throw new Error(`telemetry_http_protocol_unsupported_${url.protocol}`)}return new Promise((resolve,reject)=>{const timeoutMs=resolveTelemetryHttpTimeoutMs();const requestOptions={method:"POST",headers:{...headers,"content-length":Buffer.byteLength(body)},signal:AbortSignal.timeout(timeoutMs),autoSelectFamilyAttemptTimeout:Math.min(5e3,timeoutMs)};const clientRequest=request(url,requestOptions,response=>{response.once("error",reject);response.once("end",()=>resolve(response.statusCode));response.resume()});clientRequest.once("error",reject);clientRequest.end(body)})}function normalizePmVersion(value){const trimmed=typeof value==="string"?value.trim():"";return trimmed.length>0?trimmed:"0.0.0"}function normalizeTelemetryErrorCode(value){const normalized=value?.trim();return normalized&&normalized.length>0?normalized:void 0}function normalizeTelemetryExitCode(exitCode,ok){if(Number.isFinite(exitCode)){return Math.max(0,Math.trunc(exitCode))}return ok?0:1}function normalizeTelemetryErrorCategory(params){if(params.ok){return void 0}if(typeof params.errorCategory==="string"&¶ms.errorCategory.trim().length>0){return params.errorCategory}if(typeof params.errorCode==="string"&¶ms.errorCode.trim().length>0){return resolveTelemetryErrorCategory(params.errorCode)}return"unknown"}function resolveTelemetrySourceContext(globalOptions){const override=(process.env[PM_TELEMETRY_SOURCE_CONTEXT_ENV]??"").trim().toLowerCase();if(PM_TELEMETRY_SOURCE_CONTEXT_SET.has(override)){return{source_context:override,source_context_source:"env_override"}}const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"){return{source_context:"test",source_context_source:"inferred"}}const nonTty=process.stdin.isTTY!==true||process.stdout.isTTY!==true;const ci=parseBooleanTrueLike(process.env.CI);const scriptLikeMode=globalOptions.json===true||globalOptions.quiet===true;if(nonTty||ci||scriptLikeMode){return{source_context:"automation",source_context_source:"inferred"}}return{source_context:"user",source_context_source:"inferred"}}function hashWithInstallationId(installationId,value){return crypto.createHash("sha256").update(`${installationId}:${value}`).digest("hex")}function buildAuthorContextPayloadFields(captureLevel,installationId){const author=(readAuthorEnvironment()??"").trim();const agent=detectAgentIdentity({env:process.env,argv:process.argv});const hasAgentContext=agent.harness!==void 0||agent.model!==void 0;if(captureLevel==="minimal"){return{has_author_context:author.length>0,has_agent_context:hasAgentContext}}return{...author.length>0?{author_context_hash:hashWithInstallationId(installationId,author)}:{},...agent.harness?{agent_harness_hash:hashWithInstallationId(installationId,agent.harness)}:{},...agent.model?{agent_model_hash:hashWithInstallationId(installationId,agent.model)}:{},...agent.model_source?{agent_model_source:agent.model_source}:{}}}function normalizeForHash(value,depth=0){if(value===null||value===void 0){return value}if(typeof value==="string"||typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>normalizeForHash(entry,depth+1))}if(typeof value==="object"){const record=value;const normalized={};const sortedKeys=Object.keys(record).sort((left,right)=>left.localeCompare(right));for(const key of sortedKeys){normalized[key]=normalizeForHash(record[key],depth+1)}return normalized}return String(value)}function hashTelemetryValue(installationId,value){return hashWithInstallationId(installationId,JSON.stringify(normalizeForHash(value)))}function hashCommandArgs(installationId,args){return{hashes:args.map(arg=>hashWithInstallationId(installationId,arg)),digest:hashWithInstallationId(installationId,args.join("\0"))}}function hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage){const normalizedMessage=sanitizeString(typeof errorMessage==="string"?errorMessage:"","redacted");const normalizedCode=typeof errorCode2==="string"&&errorCode2.length>0?errorCode2:"unknown_error";const fingerprintSource=`${command}\0${normalizedCode}\0${normalizedMessage}`;return hashWithInstallationId(installationId,fingerprintSource)}function telemetryDisabledByEnvironment(){return PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_TELEMETRY_DISABLED_ENV]??"").trim().toLowerCase())||PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_NO_TELEMETRY_ENV]??"").trim().toLowerCase())}function resolveOtelTracesEndpoint(){if(PM_TELEMETRY_OTEL_DISABLED_VALUES.has((process.env[PM_TELEMETRY_OTEL_DISABLED_ENV]??"").trim().toLowerCase())){return null}const directEndpoint=(process.env[OTEL_TRACES_ENDPOINT_ENV]??"").trim();if(directEndpoint.length>0){try{return new URL(directEndpoint).toString()}catch{return null}}const baseEndpoint=(process.env[OTEL_BASE_ENDPOINT_ENV]??"").trim();if(baseEndpoint.length===0){return null}try{const url=new URL(baseEndpoint);const normalizedPath=url.pathname.replace(/\/+$/,"");if(!normalizedPath.endsWith("/v1/traces")){url.pathname=`${normalizedPath.length===0?"":normalizedPath}/v1/traces`}return url.toString()}catch{return null}}function isoToUnixNano(iso){const parsedMs=Date.parse(iso);const epochMs=Number.isNaN(parsedMs)?Date.now():parsedMs;return`${BigInt(epochMs)*1000000n}`}function otlpStringAttribute(key,value){return{key,value:{stringValue:value}}}function otlpBoolAttribute(key,value){return{key,value:{boolValue:value}}}function otlpIntAttribute(key,value){return{key,value:{intValue:String(Math.max(0,Math.trunc(value)))}}}function buildOtelSpanRequest(activeCommand,outcome,finishedAtIso,durationMs){if(typeof activeCommand.otel_traces_endpoint!=="string"||activeCommand.otel_traces_endpoint.trim().length===0||typeof activeCommand.otel_trace_id!=="string"||activeCommand.otel_trace_id.length===0||typeof activeCommand.otel_span_id!=="string"||activeCommand.otel_span_id.length===0){return null}const serviceNameCandidate=sanitizeString((process.env[OTEL_SERVICE_NAME_ENV]??"").trim());const serviceName=serviceNameCandidate.length>0?serviceNameCandidate:"pm-cli";const normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok);const normalizedErrorCode=normalizeTelemetryErrorCode(outcome.error_code);const normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category});const attributes=[otlpStringAttribute("pm.command",sanitizeString(activeCommand.command)),otlpStringAttribute("pm.version",activeCommand.pm_version),otlpStringAttribute("pm.source_context",activeCommand.source_context),otlpStringAttribute("pm.source_context_source",activeCommand.source_context_source),otlpStringAttribute("pm.installation_id",activeCommand.installation_id),otlpStringAttribute("pm.session_id",PROCESS_SESSION_ID),otlpStringAttribute("pm.pm_root_hash",activeCommand.pm_root_hash),otlpStringAttribute("pm.cwd_hash",activeCommand.cwd_hash),otlpBoolAttribute("pm.ok",outcome.ok),otlpIntAttribute("pm.exit_code",normalizedExitCode),otlpIntAttribute("pm.duration_ms",durationMs)];if(typeof normalizedErrorCode==="string"){attributes.push(otlpStringAttribute("pm.error_code",normalizedErrorCode))}if(typeof normalizedErrorCategory==="string"){attributes.push(otlpStringAttribute("pm.error_category",normalizedErrorCategory))}if(typeof outcome.error==="string"&&outcome.error.trim().length>0){attributes.push(otlpStringAttribute("pm.error",sanitizeString(outcome.error)))}const payload={resourceSpans:[{resource:{attributes:[otlpStringAttribute("service.name",serviceName)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:activeCommand.otel_trace_id,spanId:activeCommand.otel_span_id,name:`pm.command.${sanitizeString(activeCommand.command)}`,kind:1,startTimeUnixNano:isoToUnixNano(activeCommand.started_at),endTimeUnixNano:isoToUnixNano(finishedAtIso),attributes,status:{code:outcome.ok?1:2,message:outcome.ok?"":sanitizeString(typeof outcome.error==="string"?outcome.error:"command_failed")}}]}]}]};return{endpoint:activeCommand.otel_traces_endpoint,payload}}function summarizeResult(result,captureLevel="redacted"){if(result===null||result===void 0){return{type:"nullish"}}if(typeof result==="string"){return{type:"string",value:sanitizeString(result,captureLevel)}}if(typeof result==="number"||typeof result==="boolean"){return{type:typeof result,value:result}}if(Array.isArray(result)){return{type:"array",length:result.length,sample:result.slice(0,5).map(entry=>sanitizeValue(entry,void 0,captureLevel))}}if(typeof result==="object"){const record=result;const keys=Object.keys(record).sort((left,right)=>left.localeCompare(right));const sanitized={};let previewBytes=0;for(const key of keys.slice(0,25)){const sanitizedValue=sanitizeValue(record[key],key,captureLevel);if(sanitizedValue===void 0)continue;const entrySize=JSON.stringify(sanitizedValue).length;if(previewBytes+entrySize>TELEMETRY_RESULT_PREVIEW_MAX_BYTES){sanitized[key]="[preview_truncated]";break}previewBytes+=entrySize;sanitized[key]=sanitizedValue}return{type:"object",key_count:keys.length,keys_preview:keys.slice(0,50),preview:sanitized}}return{type:typeof result,value:String(result)}}function buildCommandStartPayload(params){const{captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId}=params;const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);const hashedArgs=hashCommandArgs(installationId,context.args);const commandInvocationDigest=hashWithInstallationId(installationId,`${context.command}\0${context.args.join("\0")}`);const commandOptionsDigest=hashTelemetryValue(installationId,context.options);const globalOptionsDigest=hashTelemetryValue(installationId,context.global);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options_digest:commandOptionsDigest,global_options_digest:globalOptionsDigest,...authorContextFields}}return{pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,...authorContextFields,command_args:sanitizeCommandArgs(context.args,captureLevel),command_args_hashes:hashedArgs.hashes,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options:sanitizeValue(context.options,void 0,captureLevel),command_options_digest:commandOptionsDigest,global_options:sanitizeValue(context.global,void 0,captureLevel),global_options_digest:globalOptionsDigest,pm_root_hash:pmRootHash,cwd_hash:cwdHash,capture_level:captureLevel,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}function buildCommandFinishPayload(params){const{captureLevel,pmVersion,sourceContext,outcome,durationMs,startedAt,command,installationId,commandTaxonomy,exitCode,errorCode:errorCode2,errorCategory,commandResolution,resolutionStage}=params;const errorFingerprint=outcome.ok===false?hashTelemetryErrorFingerprint(installationId,command,errorCode2,outcome.error):void 0;const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,"redacted"):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,captureLevel):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,started_at:startedAt,result_summary:summarizeResult(outcome.result,captureLevel)}}function buildCommandErrorPayload(params){const{captureLevel,pmVersion,sourceContext,command,commandTaxonomy,commandResolution,resolutionStage,args,options,pmRootHash,cwdHash,installationId,errorCode:errorCode2,errorMessage,errorCategory,exitCode}=params;const attemptedArgHashes=hashCommandArgs(installationId,args);const attemptedCommandDigest=hashWithInstallationId(installationId,command);const attemptedOptionsDigest=hashTelemetryValue(installationId,options);const errorFingerprint=hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,attempted_command_digest:attemptedCommandDigest,attempted_args_digest:attemptedArgHashes.digest,attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,"redacted"),error_fingerprint:errorFingerprint,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,attempted_command:sanitizeString(command,captureLevel),attempted_command_digest:attemptedCommandDigest,attempted_args:sanitizeCommandArgs(args,captureLevel),attempted_args_hashes:attemptedArgHashes.hashes,attempted_args_digest:attemptedArgHashes.digest,attempted_options:sanitizeValue(options,void 0,captureLevel),attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,captureLevel),error_fingerprint:errorFingerprint,pm_root_hash:pmRootHash,cwd_hash:cwdHash,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}async function ensureInstallationId(globalPmRoot){const settings=await readSettings(globalPmRoot);let changed=false;if(settings.telemetry.installation_id.trim().length===0){settings.telemetry.installation_id=crypto.randomUUID();changed=true}if(changed){await writeSettings(globalPmRoot,settings,"telemetry:install_id")}return{installationId:settings.telemetry.installation_id,endpoint:settings.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(settings.telemetry.retention_days))}}async function enqueueTelemetryEvent(globalPmRoot,event){const queued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event,attempts:0};let serialized=JSON.stringify(queued);if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){const trimmed={...event,payload:{...event.payload,result_summary:{truncated:true,reason:"payload_size_exceeded",original_bytes:serialized.length}}};const trimmedQueued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event:trimmed,attempts:0};serialized=JSON.stringify(trimmedQueued)}await withQueueMutation(async()=>{await appendLineAtomic(queuePath(globalPmRoot),serialized)})}function parseQueueLines(raw){const entries=[];for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}try{const parsed=JSON.parse(trimmed);if(parsed&&typeof parsed==="object"&&parsed.event&&typeof parsed.event==="object"&&typeof parsed.attempts==="number"&&(parsed.client_schema_version===void 0||typeof parsed.client_schema_version==="number"&&Number.isFinite(parsed.client_schema_version))){entries.push(parsed)}}catch{}}return entries}function nextRetryIso(attempts){const delay=Math.min(TELEMETRY_RETRY_BASE_DELAY_MS*2**Math.max(attempts-1,0),TELEMETRY_MAX_RETRY_DELAY_MS);return new Date(Date.now()+delay).toISOString()}function isDueForRetryAt(nextAttemptAfter){if(typeof nextAttemptAfter!=="string"||nextAttemptAfter.trim().length===0){return true}const dueAtMs=Date.parse(nextAttemptAfter);if(Number.isNaN(dueAtMs)){return true}return dueAtMs<=Date.now()}function isDueForRetry(entry){return isDueForRetryAt(entry.next_attempt_after)}function retentionCutoffMs(retentionDays){const normalizedDays=Number.isFinite(retentionDays)?Math.max(1,Math.trunc(retentionDays)):1;return Date.now()-normalizedDays*MILLISECONDS_PER_DAY}function isExpiredQueueEntry(entry,cutoffMs){const occurredAt=entry.event?.occurred_at;if(typeof occurredAt!=="string"||occurredAt.trim().length===0){return false}const occurredAtMs=Date.parse(occurredAt);if(Number.isNaN(occurredAtMs)){return false}return occurredAtMs<cutoffMs}function pruneExpiredQueueEntries(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays);const retained=[];let prunedCount=0;for(const entry of entries){const serializedSize=JSON.stringify(entry).length;const oversized=serializedSize>TELEMETRY_MAX_EVENT_BYTES;if(oversized||isExpiredQueueEntry(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}return{entries:retained,prunedCount}}async function rewriteQueue(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join("\n");const contents=serialized.length>0?`${serialized}
|
|
3
|
-
`:"";for(let attempt=0;;attempt+=1){try{await writeFileAtomic(queuePath(globalPmRoot),contents);return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error)){throw error}await sleep(retryDelay)}}}function isRetryableQueueRewriteError(error){if(typeof error!=="object"||error===null||!("code"in error)){return false}const code=error.code;return code==="EACCES"||code==="EBUSY"||code==="EPERM"}function sleep(milliseconds){return new Promise(resolve=>{setTimeout(resolve,milliseconds)})}async function enqueuePendingOtelSpan(globalPmRoot,request){const pending={id:crypto.randomUUID(),endpoint:request.endpoint,payload:request.payload,enqueued_at:nowIso(),attempts:0};const serialized=JSON.stringify(pending);if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){return}await withQueueMutation(async()=>{await appendLineAtomic(otelSpansQueuePath(globalPmRoot),serialized)})}function backfillPendingOtelSpanId(entry){const material=JSON.stringify([entry.endpoint,entry.enqueued_at,entry.payload]);return crypto.createHash("sha256").update(material).digest("hex").slice(0,32)}function parsePendingOtelSpanLines(raw){const entries=[];for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}try{const parsed=JSON.parse(trimmed);if(parsed&&typeof parsed==="object"&&typeof parsed.endpoint==="string"&&parsed.endpoint.trim().length>0&&"payload"in parsed&&typeof parsed.attempts==="number"&&Number.isFinite(parsed.attempts)){if(typeof parsed.id!=="string"||parsed.id.length===0){parsed.id=backfillPendingOtelSpanId(parsed)}entries.push(parsed)}}catch{}}return entries}function isExpiredPendingOtelSpan(entry,cutoffMs){if(typeof entry.enqueued_at!=="string"||entry.enqueued_at.trim().length===0){return false}const enqueuedAtMs=Date.parse(entry.enqueued_at);if(Number.isNaN(enqueuedAtMs)){return false}return enqueuedAtMs<cutoffMs}function prunePendingOtelSpans(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays);const retained=[];let prunedCount=0;for(const entry of entries){const oversized=JSON.stringify(entry).length>TELEMETRY_MAX_EVENT_BYTES;if(oversized||isExpiredPendingOtelSpan(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}if(retained.length>TELEMETRY_OTEL_SPANS_MAX_PENDING){const overflow=retained.length-TELEMETRY_OTEL_SPANS_MAX_PENDING;prunedCount+=overflow;return{entries:retained.slice(overflow),prunedCount}}return{entries:retained,prunedCount}}async function rewritePendingOtelSpans(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join("\n");const contents=serialized.length>0?`${serialized}
|
|
4
|
-
`:"";for(let attempt=0;;attempt+=1){try{await writeFileAtomic(otelSpansQueuePath(globalPmRoot),contents);return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error)){throw error}await sleep(retryDelay)}}}async function reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates){return withQueueMutation(async()=>{const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));const current=raw===null?[]:parsePendingOtelSpanLines(raw);const reconciled=[];for(const entry of current){if(succeededIds.has(entry.id)){continue}const failure=failedUpdates.get(entry.id);reconciled.push(failure?{...entry,attempts:failure.attempts,next_attempt_after:failure.next_attempt_after}:entry)}const{entries:retained}=prunePendingOtelSpans(reconciled,retentionDays);await rewritePendingOtelSpans(globalPmRoot,retained);return retained.length})}async function flushPendingOtelSpans(globalPmRoot,retentionDays){const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));if(raw===null||raw.trim().length===0){await writeRuntimeState(globalPmRoot,{pending_otel_spans:0});return}const entries=parsePendingOtelSpanLines(raw);const{entries:retained,prunedCount}=prunePendingOtelSpans(entries,retentionDays);const due=retained.filter(entry=>isDueForRetryAt(entry.next_attempt_after)).slice(0,TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE);if(due.length===0){const remaining2=prunedCount>0?await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,new Set,new Map):retained.length;await writeRuntimeState(globalPmRoot,{pending_otel_spans:remaining2});return}const attemptTime=nowIso();const succeededIds=new Set;const failedUpdates=new Map;let succeededCount=0;let lastError;await Promise.all(due.map(async span=>{try{const status=await postTelemetryJson(span.endpoint,{"content-type":"application/json"},JSON.stringify(span.payload));if(status<200||status>=300){throw new Error(`local_otel_export_http_${status}`)}succeededIds.add(span.id);succeededCount+=1}catch(error){lastError=error instanceof Error?sanitizeString(error.message,"redacted"):"local_otel_export_failed";const nextAttempts=span.attempts+1;failedUpdates.set(span.id,{attempts:nextAttempts,next_attempt_after:nextRetryIso(nextAttempts)})}}));const remaining=await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates);const statePatch={pending_otel_spans:remaining,last_otel_attempt_at:attemptTime};if(succeededCount>0){statePatch.last_otel_success_at=attemptTime}if(lastError!==void 0){statePatch.last_otel_failure_at=attemptTime;statePatch.last_otel_failure_error=lastError}else if(remaining===0){statePatch.last_otel_failure_at=void 0;statePatch.last_otel_failure_error=void 0}await writeRuntimeState(globalPmRoot,statePatch)}async function flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays){try{await flushQueue(globalPmRoot,endpoint,retentionDays)}catch{}try{await flushPendingOtelSpans(globalPmRoot,retentionDays)}catch{}}async function cleanupTelemetryQueueTempOrphans(globalPmRoot,maxAgeMs=TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS){try{const dirPath=telemetryRuntimeDirectory(globalPmRoot);const entries=await readdir(dirPath,{withFileTypes:true});const cutoffMs=Date.now()-Math.max(0,maxAgeMs);await Promise.all(entries.filter(entry=>entry.isFile()&&/^\.events\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(entry.name)).map(async entry=>{const candidate=path.join(dirPath,entry.name);const candidateStats=await stat(candidate);if(candidateStats.mtimeMs<cutoffMs){await rm(candidate,{force:true})}}))}catch{}}async function withQueueMutation(operation){const run=_queueMutationPromise.catch(()=>{}).then(operation);_queueMutationPromise=run.catch(()=>{});return run}async function readCurrentQueueEntries(globalPmRoot){const raw=await readFileIfExists(queuePath(globalPmRoot));if(raw===null||raw.trim().length===0){return[]}return parseQueueLines(raw)}async function removeFlushedEntriesFromCurrentQueue(globalPmRoot,flushedIds,retentionDays){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot);const{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays);const remaining=retainedEntries.filter(entry=>!flushedIds.has(entry.event.event_id));await rewriteQueue(globalPmRoot,remaining);return remaining})}async function markFailedEntriesInCurrentQueue(globalPmRoot,failedIds,attemptTime,retentionDays){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot);const{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays);const retried=retainedEntries.map(entry=>{if(!failedIds.has(entry.event.event_id)){return entry}const attempts=entry.attempts+1;return{...entry,attempts,last_attempt_at:attemptTime,next_attempt_after:nextRetryIso(attempts)}});await rewriteQueue(globalPmRoot,retried);return retried})}async function flushQueue(globalPmRoot,endpoint,retentionDays){await cleanupTelemetryQueueTempOrphans(globalPmRoot);const normalizedEndpoint=endpoint.trim();if(normalizedEndpoint.length===0){return}const raw=await readFileIfExists(queuePath(globalPmRoot));if(raw===null||raw.trim().length===0){await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const queueEntries=parseQueueLines(raw);if(queueEntries.length===0){await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const{entries:retainedEntries,prunedCount}=pruneExpiredQueueEntries(queueEntries,retentionDays);if(retainedEntries.length===0){await rewriteQueue(globalPmRoot,[]);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const dueEntries=retainedEntries.filter(entry=>isDueForRetry(entry)).slice(0,TELEMETRY_FLUSH_BATCH_SIZE);if(dueEntries.length===0){if(prunedCount>0){await rewriteQueue(globalPmRoot,retainedEntries)}await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:retainedEntries.length});return}const dueIds=new Set(dueEntries.map(entry=>entry.event.event_id));const attemptTime=nowIso();const requestHeaders={"content-type":"application/json"};const ingestKey=process.env.PM_TELEMETRY_INGEST_KEY?.trim();if(ingestKey){requestHeaders["x-pm-telemetry-key"]=ingestKey}try{const status=await postTelemetryJson(normalizedEndpoint,requestHeaders,JSON.stringify({schema_version:TELEMETRY_SCHEMA_VERSION,events:dueEntries.map(entry=>entry.event)}));if(status<200||status>=300){throw new Error(`telemetry_flush_http_${status}`)}}catch(error){const retried=await markFailedEntriesInCurrentQueue(globalPmRoot,dueIds,attemptTime,retentionDays);const errorMessage=(()=>{if(error instanceof Error){return sanitizeString(error.message,"redacted")}return"telemetry_flush_failed"})();await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:retried.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage});return}try{const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,dueIds,retentionDays);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.length,last_attempted_flush_at:attemptTime,last_successful_flush_at:attemptTime,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(error){const errorMessage=(()=>{if(error instanceof Error){return sanitizeString(error.message,"redacted")}return"telemetry_flush_failed"})();const currentEntries=await readCurrentQueueEntries(globalPmRoot).catch(()=>retainedEntries);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:currentEntries.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage})}}async function acquireTelemetryFlushLock(globalPmRoot){const lockPath=flushLockPath(globalPmRoot);await mkdir(path.dirname(lockPath),{recursive:true});try{await mkdir(lockPath);return true}catch(error){if(typeof error!=="object"||error===null||!("code"in error)||error.code!=="EEXIST"){throw error}}try{const lockStats=await stat(lockPath);if(Date.now()-lockStats.mtimeMs<TELEMETRY_FLUSH_LOCK_STALE_MS){return false}await rm(lockPath,{recursive:true,force:true});await mkdir(lockPath);return true}catch{return false}}function isFreshDirectoryLock(lockPath,staleMs){try{return Date.now()-statSync(lockPath).mtimeMs<staleMs}catch{return false}}function removeDirectoryLockBestEffort(lockPath){try{rmSync(lockPath,{recursive:true,force:true})}catch{}}function errorCode(error){if(typeof error!=="object"||error===null||!("code"in error)){return void 0}const code=error.code;return typeof code==="string"?code:void 0}function createDirectoryLock(lockPath){try{mkdirSync(lockPath);return true}catch(error){const code=errorCode(error);if(code==="EEXIST"){return false}if(!isFileMissingError(error)){return false}}try{mkdirSync(path.dirname(lockPath),{recursive:true});mkdirSync(lockPath);return true}catch{return false}}function acquireTelemetryFlushSpawnGate(globalPmRoot){if(isFreshDirectoryLock(flushLockPath(globalPmRoot),TELEMETRY_FLUSH_LOCK_STALE_MS)){return false}const lockPath=flushSpawnLockPath(globalPmRoot);try{if(Date.now()-statSync(lockPath).mtimeMs<TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS){return false}removeDirectoryLockBestEffort(lockPath)}catch(error){if(!isFileMissingError(error)){return false}}return createDirectoryLock(lockPath)}function releaseTelemetryFlushSpawnGate(globalPmRoot){removeDirectoryLockBestEffort(flushSpawnLockPath(globalPmRoot))}const _testOnly={acquireTelemetryFlushSpawnGate,acquireTelemetryFlushLock,buildAuthorContextPayloadFields,buildCommandErrorPayload,buildCommandFinishPayload,buildCommandStartPayload,buildOtelSpanRequest,createDirectoryLock,enqueuePendingOtelSpan,enqueueTelemetryEvent,errorCode,flushPendingOtelSpans,flushQueue,flushQueueWithProcessLock,flushTelemetryArtifacts,hashTelemetryErrorFingerprint,hashTelemetryValue,isEmailDomainCharacter,isEmailLocalCharacter,isExpiredPendingOtelSpan,isExpiredQueueEntry,isFreshDirectoryLock,isDueForRetry,isDueForRetryAt,isRetryableQueueRewriteError,looksLikeEmailToken,otelSpansQueuePath,parseBooleanTrueLike,postTelemetryJson,parsePendingOtelSpanLines,prunePendingOtelSpans,reconcilePendingOtelSpansAfterFlush,retentionCutoffMs,resolveOtelTracesEndpoint,resolveTelemetryHttpTimeoutMs,rewritePendingOtelSpans,normalizeForHash,normalizeCaptureLevel,normalizePmVersion,normalizeTelemetryErrorCategory,normalizeTelemetryErrorCode,normalizeTelemetryExitCode,parseQueueLines,pruneExpiredQueueEntries,readRuntimeState,readCurrentQueueEntries,releaseTelemetryFlushSpawnGate,removeFlushedEntriesFromCurrentQueue,removeDirectoryLockBestEffort,resolveTelemetrySourceContext,rewriteQueue,sanitizeCommandArgs,sanitizeStringMax,sanitizeStringRedacted,sanitizeValue,scheduleTelemetryFlush,shouldFlushInline,sleep,summarizeResult,telemetryFlushRunnerPath,withQueueMutation,flushLockPath,flushSpawnLockPath,runtimeStatePath,writeRuntimeState};async function flushQueueWithProcessLock(globalPmRoot,endpoint,retentionDays){const acquired=await acquireTelemetryFlushLock(globalPmRoot);releaseTelemetryFlushSpawnGate(globalPmRoot);if(!acquired){return}try{await flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays)}finally{try{await rm(flushLockPath(globalPmRoot),{recursive:true,force:true})}catch{}}}function scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays){if(shouldFlushInline()){const previousFlush=_lastFlushPromise;const nextFlush=flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays);_lastFlushPromise=Promise.allSettled([previousFlush,nextFlush]).then(()=>{});return}try{const acquiredSpawnGate=acquireTelemetryFlushSpawnGate(globalPmRoot);if(!acquiredSpawnGate){return}const child=spawn(process.execPath,[telemetryFlushRunnerPath()],{detached:true,stdio:"ignore",cwd:os.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:globalPmRoot,[PM_TELEMETRY_FLUSH_CHILD_ENV]:"1"}});child.on("error",()=>{releaseTelemetryFlushSpawnGate(globalPmRoot)});child.unref()}catch{releaseTelemetryFlushSpawnGate(globalPmRoot)}}async function flushTelemetryQueueNow(globalPmRoot=resolveGlobalPmRoot(process.cwd())){if(telemetryDisabledByEnvironment()){return}try{const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const{endpoint,retentionDays}=await ensureInstallationId(globalPmRoot);await flushQueueWithProcessLock(globalPmRoot,endpoint,retentionDays)}catch{}}async function startTelemetryCommand(context){if(telemetryDisabledByEnvironment()){return null}if(context.command==="telemetry"&&context.args.some(token=>token.trim().toLowerCase()==="clear")){return null}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return null}const captureLevel=normalizeCaptureLevel(settings.telemetry.capture_level);const{installationId,endpoint,retentionDays}=await ensureInstallationId(globalPmRoot);const pmVersion=normalizePmVersion(context.pm_version);const sourceContext=resolveTelemetrySourceContext(context.global);const pmRootHash=hashWithInstallationId(installationId,context.pm_root);const cwdHash=hashWithInstallationId(installationId,process.cwd());const otelTracesEndpoint=resolveOtelTracesEndpoint();const occurredAt=nowIso();const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_start",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:context.command,payload:buildCommandStartPayload({captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId})};await enqueueTelemetryEvent(globalPmRoot,event);scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays);const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);return{started_at:occurredAt,started_at_ms:Date.now(),command:context.command,command_taxonomy:commandTaxonomy,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,installation_id:installationId,pm_root_hash:pmRootHash,cwd_hash:cwdHash,endpoint,retention_days:retentionDays,global_pm_root:globalPmRoot,capture_level:captureLevel,otel_traces_endpoint:otelTracesEndpoint??void 0,otel_trace_id:otelTracesEndpoint?crypto.randomBytes(16).toString("hex"):void 0,otel_span_id:otelTracesEndpoint?crypto.randomBytes(8).toString("hex"):void 0}}catch{return null}}async function finishTelemetryCommand(activeCommand,outcome){if(!activeCommand){return}try{const finishedAt=nowIso();const durationMs=Math.max(0,Date.now()-activeCommand.started_at_ms);const normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:outcome.ok,errorCode:outcome.error_code,errorMessage:outcome.error,exitCode:outcome.exit_code}));const normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category});const normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok);const commandResolution=outcome.command_resolution??deriveTelemetryCommandResolution({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory});const resolutionStage=outcome.resolution_stage??"execute";const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_finish",occurred_at:finishedAt,installation_id:activeCommand.installation_id,session_id:PROCESS_SESSION_ID,command:activeCommand.command,payload:buildCommandFinishPayload({captureLevel:activeCommand.capture_level,pmVersion:activeCommand.pm_version,sourceContext:{source_context:activeCommand.source_context,source_context_source:activeCommand.source_context_source},outcome,durationMs,startedAt:activeCommand.started_at,command:activeCommand.command,installationId:activeCommand.installation_id,commandTaxonomy:activeCommand.command_taxonomy,exitCode:normalizedExitCode,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,commandResolution,resolutionStage})};await enqueueTelemetryEvent(activeCommand.global_pm_root,event);const otelRequest=buildOtelSpanRequest(activeCommand,{...outcome,exit_code:normalizedExitCode,error_code:normalizedErrorCode,error_category:normalizedErrorCategory},finishedAt,durationMs);if(otelRequest){await enqueuePendingOtelSpan(activeCommand.global_pm_root,otelRequest)}scheduleTelemetryFlush(activeCommand.global_pm_root,activeCommand.endpoint,activeCommand.retention_days)}catch{}}async function emitTelemetryErrorEvent(context){if(telemetryDisabledByEnvironment()){return}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const captureLevel=normalizeCaptureLevel(settings.telemetry.capture_level);const{installationId,endpoint,retentionDays}=await ensureInstallationId(globalPmRoot);const pmVersion=normalizePmVersion(context.pm_version);const sourceContext=resolveTelemetrySourceContext(context.global);const pmRootHash=hashWithInstallationId(installationId,context.pm_root);const cwdHash=hashWithInstallationId(installationId,process.cwd());const occurredAt=nowIso();const normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:false,errorCode:context.error_code,errorMessage:context.error_message,exitCode:context.exit_code}));const normalizedErrorCategory=context.error_category??resolveTelemetryErrorCategory(normalizedErrorCode);const normalizedExitCode=normalizeTelemetryExitCode(context.exit_code,false);const normalizedCommand=context.command.trim().length>0?context.command:"<unknown>";const commandTaxonomy=deriveTelemetryCommandTaxonomy(normalizedCommand);const commandResolution=context.command_resolution??deriveTelemetryCommandResolution({ok:false,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory});const resolutionStage=context.resolution_stage??"unknown";const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_error",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:sanitizeString(normalizedCommand,"redacted"),payload:buildCommandErrorPayload({captureLevel,pmVersion,sourceContext,command:normalizedCommand,commandTaxonomy,commandResolution,resolutionStage,args:context.args,options:context.options,pmRootHash,cwdHash,installationId,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,exitCode:normalizedExitCode,errorMessage:context.error_message})};await enqueueTelemetryEvent(globalPmRoot,event);scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays)}catch{}}export{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,TELEMETRY_SCHEMA_VERSION,_testOnly,emitTelemetryErrorEvent,finishTelemetryCommand,flushTelemetryQueueNow,startTelemetryCommand,waitForPendingFlush};
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="da54e7d1-5a09-53b8-85df-6a6def6fe54f")}catch(e2){}})();import crypto from"node:crypto";import{spawn}from"node:child_process";import{mkdirSync,rmSync,statSync}from"node:fs";import{mkdir,readdir,rm,stat}from"node:fs/promises";import{request as httpRequest}from"node:http";import{request as httpsRequest}from"node:https";import os from"node:os";import path from"node:path";import{acquireLock}from"../lock/lock.js";import{runWithIsolatedExtensionRuntime}from"../extensions/index.js";import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,resolveTelemetryEnvironmentPolicy,resolveTelemetryReadSampleRate}from"./policy.js";import{resolvePmPackageRootFromModule}from"../packages/root.js";import{isFileMissingError,appendLineAtomic,readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{resolveTelemetryErrorCategory}from"../shared/constants.js";import{nowIso}from"../shared/time.js";import{detectAgentIdentity,readAuthorEnvironment}from"../shared/author.js";import{resolveGlobalPmRoot}from"../store/paths.js";import{readSettings,writeSettings}from"../store/settings.js";import{deriveTelemetryCommandResolution,deriveTelemetryCommandTaxonomy,inferTelemetryErrorCode}from"./observability.js";const TELEMETRY_QUEUE_RELATIVE_PATH=path.join("runtime","telemetry","events.jsonl");const TELEMETRY_STATE_RELATIVE_PATH=path.join("runtime","telemetry","state.json");const TELEMETRY_OTEL_SPANS_RELATIVE_PATH=path.join("runtime","telemetry","otel-spans.jsonl");const TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE=8;const TELEMETRY_OTEL_SPANS_MAX_PENDING=500;const TELEMETRY_SCHEMA_VERSION=1;const TELEMETRY_CLIENT_SCHEMA_VERSION=1;const TELEMETRY_FLUSH_BATCH_SIZE=100;const TELEMETRY_MAX_RETRY_DELAY_MS=36e5;const TELEMETRY_RETRY_BASE_DELAY_MS=3e4;const TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS=2e4;const TELEMETRY_HTTP_TIMEOUT_MIN_MS=1e3;const TELEMETRY_HTTP_TIMEOUT_MAX_MS=25e3;const TELEMETRY_FOREGROUND_LOCK_WAIT_MS=250;const MILLISECONDS_PER_DAY=864e5;const TELEMETRY_MAX_EVENT_BYTES=65536;const TELEMETRY_SANITIZE_MAX_DEPTH=6;const TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS=20;const TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS=15;const TELEMETRY_RESULT_PREVIEW_MAX_BYTES=8192;const TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS=[25,50,100,200];const TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS=60*60*1e3;const TELEMETRY_FLUSH_LOCK_STALE_MS=6e4;const TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS=6e4;const OTEL_TRACES_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT";const OTEL_BASE_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_ENDPOINT";const OTEL_SERVICE_NAME_ENV="OTEL_SERVICE_NAME";const PM_TELEMETRY_OTEL_DISABLED_ENV="PM_TELEMETRY_OTEL_DISABLED";const PM_TELEMETRY_OTEL_DISABLED_VALUES=new Set(["1","true","yes","on"]);const PM_TELEMETRY_INLINE_FLUSH_ENV="PM_TELEMETRY_INLINE_FLUSH";const PM_TELEMETRY_FLUSH_CHILD_ENV="PM_TELEMETRY_FLUSH_CHILD";const PM_TELEMETRY_SOURCE_CONTEXT_ENV="PM_TELEMETRY_SOURCE_CONTEXT";const PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV="PM_TELEMETRY_HTTP_TIMEOUT_MS";const NATIVE_FETCH=globalThis.fetch;import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES as PM_TELEMETRY_SOURCE_CONTEXT_VALUES2}from"./policy.js";let sourceContextWarningEmitted=false;let _lastFlushPromise=Promise.resolve();let _queueMutationPromise=Promise.resolve();const deferredReadStarts=new WeakMap;async function waitForPendingFlush(){await _lastFlushPromise;await _queueMutationPromise}const PM_TELEMETRY_SOURCE_CONTEXT_SET=new Set(PM_TELEMETRY_SOURCE_CONTEXT_VALUES);const BOOLEAN_TRUE_VALUES=new Set(["1","true","yes","on"]);const TELEMETRY_HARNESSES=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]);const PROCESS_SESSION_ID=crypto.randomUUID();const SENSITIVE_KEYWORDS=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"];const REDACTION_INPUT_KEYS=new Set(["literal","literals","regex","regexes","replacement","replacements"]);const SENSITIVE_INLINE_KEY_PATTERN="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)";const INLINE_SENSITIVE_ASSIGNMENT_PATTERN=new RegExp(`\\b(${SENSITIVE_INLINE_KEY_PATTERN})\\s*([:=])\\s*([^\\s,;]+)`,"giu");const INLINE_SENSITIVE_FLAG_PATTERN=new RegExp(`(--${SENSITIVE_INLINE_KEY_PATTERN})(=|\\s+)([^\\s,;]+)`,"giu");const ABSOLUTE_PATH_TOKEN_PATTERN=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g;const BEARER_TOKEN_PATTERN=/bearer\s+[a-z0-9._=-]+/giu;const PRIVATE_IP_PATTERN=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function queuePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_QUEUE_RELATIVE_PATH)}function otelSpansQueuePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_OTEL_SPANS_RELATIVE_PATH)}function telemetryRuntimeDirectory(globalPmRoot){return path.dirname(queuePath(globalPmRoot))}function runtimeStatePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_STATE_RELATIVE_PATH)}function flushLockPath(globalPmRoot){return path.join(globalPmRoot,"runtime","telemetry","flush.lock")}function flushSpawnLockPath(globalPmRoot){return path.join(globalPmRoot,"runtime","telemetry","flush.spawn.lock")}function telemetryFlushRunnerPath(){return path.join(resolvePmPackageRootFromModule(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function shouldFlushInline(){if(parseBooleanTrueLike(process.env[PM_TELEMETRY_INLINE_FLUSH_ENV])){return true}if(parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])){return true}const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();return typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"}async function readRuntimeState(globalPmRoot){const raw=await readFileIfExists(runtimeStatePath(globalPmRoot));if(!raw||raw.trim().length===0){return{}}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){return{}}return parsed}catch{return{}}}async function writeRuntimeState(globalPmRoot,patch){try{const current=await readRuntimeState(globalPmRoot);const next={...current,...patch};const normalized=Object.fromEntries(Object.entries(next).filter(([,value])=>value!==void 0).sort((left,right)=>left[0].localeCompare(right[0])));await writeFileAtomic(runtimeStatePath(globalPmRoot),`${JSON.stringify(normalized,null,2)}
|
|
2
|
+
`)}catch{}}function isSensitiveKey(key){const normalized=key.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_");const tokens=normalized.split("_").filter(token=>token.length>0);return REDACTION_INPUT_KEYS.has(normalized)||SENSITIVE_KEYWORDS.some(keyword=>normalized===keyword||normalized.endsWith(`_${keyword}`)||tokens.includes(keyword))}function redactInlineSensitiveAssignments(input){const withoutAssignments=input.replaceAll(INLINE_SENSITIVE_ASSIGNMENT_PATTERN,(_match,key,delimiter)=>`${key}${delimiter}[redacted]`);return withoutAssignments.replaceAll(INLINE_SENSITIVE_FLAG_PATTERN,(_match,flag,delimiter)=>`${flag}${delimiter}[redacted]`)}function redactAbsolutePathTokens(input){return input.replaceAll(ABSOLUTE_PATH_TOKEN_PATTERN,(_match,prefix)=>`${prefix}[redacted_path]`)}function isAsciiLetterOrDigitCode(code){const isUpper=code>=65&&code<=90;const isLower=code>=97&&code<=122;const isDigit=code>=48&&code<=57;return isUpper||isLower||isDigit}function isEmailLocalCharacter(character){if(!character){return false}const code=character.charCodeAt(0);if(isAsciiLetterOrDigitCode(code)){return true}return character==="."||character==="_"||character==="%"||character==="+"||character==="-"}function isEmailDomainCharacter(character){if(!character){return false}const code=character.charCodeAt(0);if(isAsciiLetterOrDigitCode(code)){return true}return character==="."||character==="-"}function looksLikeEmailToken(token){const atIndex=token.indexOf("@");if(atIndex<=0||atIndex!==token.lastIndexOf("@")||atIndex===token.length-1){return false}const localPart=token.slice(0,atIndex);const domainPart=token.slice(atIndex+1);const lastDot=domainPart.lastIndexOf(".");if(lastDot<=0||lastDot===domainPart.length-1){return false}if(domainPart.length-(lastDot+1)<2){return false}for(const character of localPart){if(!isEmailLocalCharacter(character)){return false}}for(const character of domainPart){if(!isEmailDomainCharacter(character)){return false}}return true}function redactEmailTokens(input){let redacted="";let cursor=0;while(cursor<input.length){const atIndex=input.indexOf("@",cursor);if(atIndex<0){redacted+=input.slice(cursor);break}let start=atIndex-1;while(start>=cursor&&isEmailLocalCharacter(input[start])){start-=1}start+=1;let end=atIndex+1;while(end<input.length&&isEmailDomainCharacter(input[end])){end+=1}const candidate=input.slice(start,end);if(looksLikeEmailToken(candidate)){redacted+=input.slice(cursor,start);redacted+="[redacted_email]";cursor=end;continue}redacted+=input.slice(cursor,atIndex+1);cursor=atIndex+1}return redacted}function sanitizeCommonSensitiveTokens(input){const withoutEmails=redactEmailTokens(input);const withoutBearer=withoutEmails.replaceAll(BEARER_TOKEN_PATTERN,"bearer [redacted_token]");return withoutBearer.replaceAll(PRIVATE_IP_PATTERN,"[redacted_ip]")}function sanitizeStringRedacted(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input);const withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);const withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets);const trimmed=withoutAbsolutePaths.trim();if(trimmed.startsWith("/")&&trimmed.length>1){return"[redacted_path]"}if(withoutAbsolutePaths.length>512){return`${withoutAbsolutePaths.slice(0,509)}...`}return withoutAbsolutePaths}function sanitizeStringMax(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input);const withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);const withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets);const trimmed=withoutAbsolutePaths.trim();if(trimmed.startsWith("/")&&trimmed.length>1){return"[redacted_path]"}if(withoutAbsolutePaths.length>2048){return`${withoutAbsolutePaths.slice(0,2045)}...`}return withoutAbsolutePaths}function sanitizeString(input,captureLevel="redacted"){if(captureLevel==="max"){return sanitizeStringMax(input)}return sanitizeStringRedacted(input)}function sanitizeValue(value,keyHint,captureLevel="redacted",depth=0){if(keyHint&&isSensitiveKey(keyHint)){return"[redacted]"}if(value===null||value===void 0){return value}if(typeof value==="string"){return sanitizeString(value,captureLevel)}if(typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>sanitizeValue(entry,void 0,captureLevel,depth+1))}if(typeof value==="object"){const record=value;const sanitized={};for(const[key,nested]of Object.entries(record)){sanitized[key]=sanitizeValue(nested,key,captureLevel,depth+1)}return sanitized}return String(value)}function sanitizeCommandArgs(args,captureLevel="redacted"){const sanitized=[];let nextIsSensitiveValue=false;for(const rawArg of args){const arg=sanitizeString(rawArg,captureLevel);if(nextIsSensitiveValue){sanitized.push("[redacted]");nextIsSensitiveValue=false;continue}if(arg.startsWith("--")){const withoutPrefix=arg.slice(2);const delimiterIndex=withoutPrefix.indexOf("=");if(delimiterIndex>=0){const key=withoutPrefix.slice(0,delimiterIndex);const value=withoutPrefix.slice(delimiterIndex+1);if(isSensitiveKey(key)){sanitized.push(`--${key}=[redacted]`)}else{sanitized.push(`--${key}=${sanitizeString(value,captureLevel)}`)}continue}if(isSensitiveKey(withoutPrefix)){sanitized.push(`--${withoutPrefix}`);nextIsSensitiveValue=true;continue}}sanitized.push(arg)}return sanitized}function normalizeCaptureLevel(value){const normalized=value?.trim().toLowerCase();if(normalized==="minimal"||normalized==="redacted"||normalized==="max"){return normalized}return"redacted"}function parseBooleanTrueLike(value){return BOOLEAN_TRUE_VALUES.has((value??"").trim().toLowerCase())}function resolveTelemetryHttpTimeoutMs(){const rawConfigured=process.env[PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV]?.trim();if(!rawConfigured){return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}const configured=Number(rawConfigured);if(!Number.isFinite(configured)){return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}return Math.min(TELEMETRY_HTTP_TIMEOUT_MAX_MS,Math.max(TELEMETRY_HTTP_TIMEOUT_MIN_MS,Math.trunc(configured)))}async function postTelemetryJson(endpoint,headers,body){const url=new URL(endpoint);if(globalThis.fetch!==NATIVE_FETCH){const controller=new AbortController;let timeout;const deadline=new Promise((_resolve,reject)=>{timeout=setTimeout(()=>{controller.abort();reject(new Error("telemetry_http_timeout"))},resolveTelemetryHttpTimeoutMs())});try{const response=await Promise.race([globalThis.fetch(endpoint,{method:"POST",headers,body,signal:controller.signal}),deadline]);return response.status}finally{clearTimeout(timeout)}}const request=url.protocol==="https:"?httpsRequest:url.protocol==="http:"?httpRequest:void 0;if(!request){throw new Error(`telemetry_http_protocol_unsupported_${url.protocol}`)}return new Promise((resolve,reject)=>{const timeoutMs=resolveTelemetryHttpTimeoutMs();const requestOptions={method:"POST",headers:{...headers,"content-length":Buffer.byteLength(body)},signal:AbortSignal.timeout(timeoutMs),autoSelectFamilyAttemptTimeout:Math.min(5e3,timeoutMs)};const clientRequest=request(url,requestOptions,response=>{response.once("error",reject);response.once("end",()=>resolve(response.statusCode));response.resume()});clientRequest.once("error",reject);clientRequest.end(body)})}function normalizePmVersion(value){const trimmed=typeof value==="string"?value.trim():"";return trimmed.length>0?trimmed:"0.0.0"}function normalizeTelemetryErrorCode(value){const normalized=value?.trim();return normalized&&normalized.length>0?normalized:void 0}function normalizeTelemetryExitCode(exitCode,ok){if(Number.isFinite(exitCode)){return Math.max(0,Math.trunc(exitCode))}return ok?0:1}function normalizeTelemetryErrorCategory(params){if(params.ok){return void 0}if(typeof params.errorCategory==="string"&¶ms.errorCategory.trim().length>0){return params.errorCategory}if(typeof params.errorCode==="string"&¶ms.errorCode.trim().length>0){return resolveTelemetryErrorCategory(params.errorCode)}return"unknown"}function resolveTelemetrySourceContext(globalOptions){const override=(process.env[PM_TELEMETRY_SOURCE_CONTEXT_ENV]??"").trim().toLowerCase();if(PM_TELEMETRY_SOURCE_CONTEXT_SET.has(override)){return{source_context:override,source_context_source:"env_override"}}const source=override.length>0?"env_override_rejected":"inferred";if(source==="env_override_rejected"&&!sourceContextWarningEmitted&&!globalOptions.quiet){sourceContextWarningEmitted=true;process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${PM_TELEMETRY_SOURCE_CONTEXT_VALUES.join("|")}; ignoring override.
|
|
3
|
+
`)}return{source_context:inferTelemetrySourceContext(globalOptions),source_context_source:source}}function inferTelemetrySourceContext(globalOptions){const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"){return"test"}const nonTty=process.stdin.isTTY!==true||process.stdout.isTTY!==true;const ci=parseBooleanTrueLike(process.env.CI);const scriptLikeMode=globalOptions.json===true||globalOptions.quiet===true;if(nonTty||ci||scriptLikeMode){return"automation"}return"user"}function hashWithInstallationId(installationId,value){return crypto.createHash("sha256").update(`${installationId}:${value}`).digest("hex")}function buildAuthorContextPayloadFields(captureLevel,installationId){const author=(readAuthorEnvironment()??"").trim();const agent=detectAgentIdentity({env:process.env,argv:process.argv});const hasAgentContext=agent.harness!==void 0||agent.model!==void 0;if(captureLevel==="minimal"){return{has_author_context:author.length>0,has_agent_context:hasAgentContext}}return{agent_harness:agent.harness?TELEMETRY_HARNESSES.has(agent.harness)?agent.harness:"other":"none",ci:parseBooleanTrueLike(process.env.CI),...author.length>0?{author_context_hash:hashWithInstallationId(installationId,author)}:{},...agent.harness?{agent_harness_hash:hashWithInstallationId(installationId,agent.harness)}:{},...agent.model?{agent_model_hash:hashWithInstallationId(installationId,agent.model)}:{},...agent.model_source?{agent_model_source:agent.model_source}:{}}}function normalizeForHash(value,depth=0){if(value===null||value===void 0){return value}if(typeof value==="string"||typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>normalizeForHash(entry,depth+1))}if(typeof value==="object"){const record=value;const normalized={};const sortedKeys=Object.keys(record).sort((left,right)=>left.localeCompare(right));for(const key of sortedKeys){normalized[key]=normalizeForHash(record[key],depth+1)}return normalized}return String(value)}function hashTelemetryValue(installationId,value){return hashWithInstallationId(installationId,JSON.stringify(normalizeForHash(value)))}function hashCommandArgs(installationId,args){return{hashes:args.map(arg=>hashWithInstallationId(installationId,arg)),digest:hashWithInstallationId(installationId,args.join("\0"))}}function hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage){const normalizedMessage=sanitizeString(typeof errorMessage==="string"?errorMessage:"","redacted");const normalizedCode=typeof errorCode2==="string"&&errorCode2.length>0?errorCode2:"unknown_error";const fingerprintSource=`${command}\0${normalizedCode}\0${normalizedMessage}`;return hashWithInstallationId(installationId,fingerprintSource)}function resolveOtelTracesEndpoint(){if(PM_TELEMETRY_OTEL_DISABLED_VALUES.has((process.env[PM_TELEMETRY_OTEL_DISABLED_ENV]??"").trim().toLowerCase())){return null}const directEndpoint=(process.env[OTEL_TRACES_ENDPOINT_ENV]??"").trim();if(directEndpoint.length>0){try{return new URL(directEndpoint).toString()}catch{return null}}const baseEndpoint=(process.env[OTEL_BASE_ENDPOINT_ENV]??"").trim();if(baseEndpoint.length===0){return null}try{const url=new URL(baseEndpoint);const normalizedPath=url.pathname.replace(/\/+$/,"");if(!normalizedPath.endsWith("/v1/traces")){url.pathname=`${normalizedPath.length===0?"":normalizedPath}/v1/traces`}return url.toString()}catch{return null}}function isoToUnixNano(iso){const parsedMs=Date.parse(iso);const epochMs=Number.isNaN(parsedMs)?Date.now():parsedMs;return`${BigInt(epochMs)*1000000n}`}function otlpStringAttribute(key,value){return{key,value:{stringValue:value}}}function otlpBoolAttribute(key,value){return{key,value:{boolValue:value}}}function otlpIntAttribute(key,value){return{key,value:{intValue:String(Math.max(0,Math.trunc(value)))}}}function buildOtelSpanRequest(activeCommand,outcome,finishedAtIso,durationMs,sampleRate=1){const endpoint=activeCommand.otel_traces_endpoint;if(typeof endpoint!=="string"||endpoint.trim().length===0||[activeCommand.otel_trace_id,activeCommand.otel_span_id].some(id=>typeof id!=="string"||id.length===0)){return null}const serviceNameCandidate=sanitizeString((process.env[OTEL_SERVICE_NAME_ENV]??"").trim());const serviceName=serviceNameCandidate.length>0?serviceNameCandidate:"pm-cli";const normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok);const normalizedErrorCode=normalizeTelemetryErrorCode(outcome.error_code);const normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category});const attributes=[otlpStringAttribute("pm.command",sanitizeString(activeCommand.command)),otlpStringAttribute("pm.version",activeCommand.pm_version),otlpStringAttribute("pm.source_context",activeCommand.source_context),otlpStringAttribute("pm.source_context_source",activeCommand.source_context_source),otlpStringAttribute("pm.installation_id",activeCommand.installation_id),otlpStringAttribute("pm.session_id",PROCESS_SESSION_ID),otlpStringAttribute("pm.pm_root_hash",activeCommand.pm_root_hash),otlpStringAttribute("pm.cwd_hash",activeCommand.cwd_hash),otlpBoolAttribute("pm.ok",outcome.ok),otlpIntAttribute("pm.exit_code",normalizedExitCode),otlpIntAttribute("pm.duration_ms",durationMs),otlpStringAttribute("pm.sample_rate",String(sampleRate))];if(typeof normalizedErrorCode==="string"){attributes.push(otlpStringAttribute("pm.error_code",normalizedErrorCode))}if(typeof normalizedErrorCategory==="string"){attributes.push(otlpStringAttribute("pm.error_category",normalizedErrorCategory))}if(typeof outcome.error==="string"&&outcome.error.trim().length>0){attributes.push(otlpStringAttribute("pm.error",sanitizeString(outcome.error)))}const payload={resourceSpans:[{resource:{attributes:[otlpStringAttribute("service.name",serviceName)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:activeCommand.otel_trace_id,spanId:activeCommand.otel_span_id,name:`pm.command.${sanitizeString(activeCommand.command)}`,kind:1,startTimeUnixNano:isoToUnixNano(activeCommand.started_at),endTimeUnixNano:isoToUnixNano(finishedAtIso),attributes,status:{code:outcome.ok?1:2,message:outcome.ok?"":sanitizeString(typeof outcome.error==="string"?outcome.error:"command_failed")}}]}]}]};return{endpoint,payload}}function summarizeResult(result,captureLevel="redacted"){if(result===null||result===void 0){return{type:"nullish"}}if(typeof result==="string"){return{type:"string",value:sanitizeString(result,captureLevel)}}if(typeof result==="number"||typeof result==="boolean"){return{type:typeof result,value:result}}if(Array.isArray(result)){return{type:"array",length:result.length,sample:result.slice(0,5).map(entry=>sanitizeValue(entry,void 0,captureLevel))}}if(typeof result==="object"){const record=result;const keys=Object.keys(record).sort((left,right)=>left.localeCompare(right));const sanitized={};let previewBytes=0;for(const key of keys.slice(0,25)){const sanitizedValue=sanitizeValue(record[key],key,captureLevel);if(sanitizedValue===void 0)continue;const entrySize=JSON.stringify(sanitizedValue).length;if(previewBytes+entrySize>TELEMETRY_RESULT_PREVIEW_MAX_BYTES){sanitized[key]="[preview_truncated]";break}previewBytes+=entrySize;sanitized[key]=sanitizedValue}return{type:"object",key_count:keys.length,keys_preview:keys.slice(0,50),preview:sanitized}}return{type:typeof result,value:String(result)}}function buildCommandStartPayload(params){const{captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId}=params;const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);const hashedArgs=hashCommandArgs(installationId,context.args);const commandInvocationDigest=hashWithInstallationId(installationId,`${context.command}\0${context.args.join("\0")}`);const commandOptionsDigest=hashTelemetryValue(installationId,context.options);const globalOptionsDigest=hashTelemetryValue(installationId,context.global);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options_digest:commandOptionsDigest,global_options_digest:globalOptionsDigest,...authorContextFields}}return{pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,...authorContextFields,command_args:sanitizeCommandArgs(context.args,captureLevel),command_args_hashes:hashedArgs.hashes,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options:sanitizeValue(context.options,void 0,captureLevel),command_options_digest:commandOptionsDigest,global_options:sanitizeValue(context.global,void 0,captureLevel),global_options_digest:globalOptionsDigest,pm_root_hash:pmRootHash,cwd_hash:cwdHash,capture_level:captureLevel,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}function buildCommandFinishPayload(params){const{captureLevel,pmVersion,sourceContext,outcome,durationMs,startedAt,command,installationId,commandTaxonomy,exitCode,errorCode:errorCode2,errorCategory,commandResolution,resolutionStage}=params;const errorFingerprint=outcome.ok===false?hashTelemetryErrorFingerprint(installationId,command,errorCode2,outcome.error):void 0;const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,"redacted"):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,captureLevel):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,started_at:startedAt,result_summary:summarizeResult(outcome.result,captureLevel)}}function buildCommandErrorPayload(params){const{captureLevel,pmVersion,sourceContext,command,commandTaxonomy,commandResolution,resolutionStage,args,options,pmRootHash,cwdHash,installationId,errorCode:errorCode2,errorMessage,errorCategory,exitCode}=params;const attemptedArgHashes=hashCommandArgs(installationId,args);const attemptedCommandDigest=hashWithInstallationId(installationId,command);const attemptedOptionsDigest=hashTelemetryValue(installationId,options);const errorFingerprint=hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,attempted_command_digest:attemptedCommandDigest,attempted_args_digest:attemptedArgHashes.digest,attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,"redacted"),error_fingerprint:errorFingerprint,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,attempted_command:sanitizeString(command,captureLevel),attempted_command_digest:attemptedCommandDigest,attempted_args:sanitizeCommandArgs(args,captureLevel),attempted_args_hashes:attemptedArgHashes.hashes,attempted_args_digest:attemptedArgHashes.digest,attempted_options:sanitizeValue(options,void 0,captureLevel),attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,captureLevel),error_fingerprint:errorFingerprint,pm_root_hash:pmRootHash,cwd_hash:cwdHash,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}async function ensureInstallationId(globalPmRoot){const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled||resolveTelemetryEnvironmentPolicy().telemetry_disabled)return null;if(settings.telemetry.installation_id.trim().length===0){settings.telemetry.installation_id=crypto.randomUUID();await writeSettings(globalPmRoot,settings,"telemetry:install_id")}return{installationId:settings.telemetry.installation_id,endpoint:settings.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(settings.telemetry.retention_days)),captureLevel:normalizeCaptureLevel(settings.telemetry.capture_level)}}async function appendTelemetryEvent(globalPmRoot,event){const queued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event,attempts:0};let serialized=JSON.stringify(queued);if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){const trimmed={...event,payload:{...event.payload,result_summary:{truncated:true,reason:"payload_size_exceeded",original_bytes:serialized.length}}};const trimmedQueued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event:trimmed,attempts:0};serialized=JSON.stringify(trimmedQueued)}await appendLineAtomic(queuePath(globalPmRoot),serialized)}async function enqueueTelemetryEvent(globalPmRoot,event){await withQueueMutation(()=>appendTelemetryEvent(globalPmRoot,event),globalPmRoot)}function parseQueueLines(raw){const entries=[];for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}try{const parsed=JSON.parse(trimmed);if(parsed&&typeof parsed==="object"&&parsed.event&&typeof parsed.event==="object"&&typeof parsed.attempts==="number"&&(parsed.client_schema_version===void 0||typeof parsed.client_schema_version==="number"&&Number.isFinite(parsed.client_schema_version))){entries.push(parsed)}}catch{}}return entries}function nextRetryIso(attempts){const delay=Math.min(TELEMETRY_RETRY_BASE_DELAY_MS*2**Math.max(attempts-1,0),TELEMETRY_MAX_RETRY_DELAY_MS);return new Date(Date.now()+delay).toISOString()}function isDueForRetryAt(nextAttemptAfter){if(typeof nextAttemptAfter!=="string"||nextAttemptAfter.trim().length===0){return true}const dueAtMs=Date.parse(nextAttemptAfter);if(Number.isNaN(dueAtMs)){return true}return dueAtMs<=Date.now()}function isDueForRetry(entry){return isDueForRetryAt(entry.next_attempt_after)}function retentionCutoffMs(retentionDays){const normalizedDays=Number.isFinite(retentionDays)?Math.max(1,Math.trunc(retentionDays)):1;return Date.now()-normalizedDays*MILLISECONDS_PER_DAY}function isExpiredQueueEntry(entry,cutoffMs){const occurredAt=entry.event?.occurred_at;if(typeof occurredAt!=="string"||occurredAt.trim().length===0){return false}const occurredAtMs=Date.parse(occurredAt);if(Number.isNaN(occurredAtMs)){return false}return occurredAtMs<cutoffMs}function pruneExpiredQueueEntries(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays);const retained=[];let prunedCount=0;for(const entry of entries){const serializedSize=JSON.stringify(entry).length;const oversized=serializedSize>TELEMETRY_MAX_EVENT_BYTES;if(oversized||isExpiredQueueEntry(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}return{entries:retained,prunedCount}}async function rewriteQueue(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join("\n");const contents=serialized.length>0?`${serialized}
|
|
4
|
+
`:"";for(let attempt=0;;attempt+=1){try{await writeFileAtomic(queuePath(globalPmRoot),contents);return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error)){throw error}await sleep(retryDelay)}}}function isRetryableQueueRewriteError(error){if(typeof error!=="object"||error===null||!("code"in error)){return false}const code=error.code;return code==="EACCES"||code==="EBUSY"||code==="EPERM"}function sleep(milliseconds){return new Promise(resolve=>{setTimeout(resolve,milliseconds)})}async function appendPendingOtelSpan(globalPmRoot,request){const pending={id:crypto.randomUUID(),endpoint:request.endpoint,payload:request.payload,enqueued_at:nowIso(),attempts:0};const serialized=JSON.stringify(pending);if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){return}await appendLineAtomic(otelSpansQueuePath(globalPmRoot),serialized)}async function enqueuePendingOtelSpan(globalPmRoot,request){await withQueueMutation(()=>appendPendingOtelSpan(globalPmRoot,request),globalPmRoot)}function backfillPendingOtelSpanId(entry){const material=JSON.stringify([entry.endpoint,entry.enqueued_at,entry.payload]);return crypto.createHash("sha256").update(material).digest("hex").slice(0,32)}function parsePendingOtelSpanLines(raw){const entries=[];for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}try{const parsed=JSON.parse(trimmed);if(parsed&&typeof parsed==="object"&&typeof parsed.endpoint==="string"&&parsed.endpoint.trim().length>0&&"payload"in parsed&&typeof parsed.attempts==="number"&&Number.isFinite(parsed.attempts)){if(typeof parsed.id!=="string"||parsed.id.length===0){parsed.id=backfillPendingOtelSpanId(parsed)}entries.push(parsed)}}catch{}}return entries}function isExpiredPendingOtelSpan(entry,cutoffMs){if(typeof entry.enqueued_at!=="string"||entry.enqueued_at.trim().length===0){return false}const enqueuedAtMs=Date.parse(entry.enqueued_at);if(Number.isNaN(enqueuedAtMs)){return false}return enqueuedAtMs<cutoffMs}function prunePendingOtelSpans(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays);const retained=[];let prunedCount=0;for(const entry of entries){const oversized=JSON.stringify(entry).length>TELEMETRY_MAX_EVENT_BYTES;if(oversized||isExpiredPendingOtelSpan(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}if(retained.length>TELEMETRY_OTEL_SPANS_MAX_PENDING){const overflow=retained.length-TELEMETRY_OTEL_SPANS_MAX_PENDING;prunedCount+=overflow;return{entries:retained.slice(overflow),prunedCount}}return{entries:retained,prunedCount}}async function rewritePendingOtelSpans(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join("\n");const contents=serialized.length>0?`${serialized}
|
|
5
|
+
`:"";for(let attempt=0;;attempt+=1){try{await writeFileAtomic(otelSpansQueuePath(globalPmRoot),contents);return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error)){throw error}await sleep(retryDelay)}}}async function reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates){return withQueueMutation(async()=>{const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));const current=raw===null?[]:parsePendingOtelSpanLines(raw);const reconciled=[];for(const entry of current){if(succeededIds.has(entry.id)){continue}const failure=failedUpdates.get(entry.id);reconciled.push(failure?{...entry,attempts:failure.attempts,next_attempt_after:failure.next_attempt_after}:entry)}const{entries:retained}=prunePendingOtelSpans(reconciled,retentionDays);await rewritePendingOtelSpans(globalPmRoot,retained);return retained.length},globalPmRoot)}async function flushPendingOtelSpans(globalPmRoot,retentionDays){const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));if(raw===null||raw.trim().length===0){await writeRuntimeState(globalPmRoot,{pending_otel_spans:0});return}const entries=parsePendingOtelSpanLines(raw);const{entries:retained,prunedCount}=prunePendingOtelSpans(entries,retentionDays);const due=retained.filter(entry=>isDueForRetryAt(entry.next_attempt_after)).slice(0,TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE);if(due.length===0){const remaining2=prunedCount>0?await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,new Set,new Map):retained.length;await writeRuntimeState(globalPmRoot,{pending_otel_spans:remaining2});return}const attemptTime=nowIso();const succeededIds=new Set;const failedUpdates=new Map;let succeededCount=0;let lastError;await Promise.all(due.map(async span=>{try{const status=await postTelemetryJson(span.endpoint,{"content-type":"application/json"},JSON.stringify(span.payload));if(status<200||status>=300){throw new Error(`local_otel_export_http_${status}`)}succeededIds.add(span.id);succeededCount+=1}catch(error){lastError=error instanceof Error?sanitizeString(error.message,"redacted"):"local_otel_export_failed";const nextAttempts=span.attempts+1;failedUpdates.set(span.id,{attempts:nextAttempts,next_attempt_after:nextRetryIso(nextAttempts)})}}));const remaining=await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates);const statePatch={pending_otel_spans:remaining,last_otel_attempt_at:attemptTime};if(succeededCount>0){statePatch.last_otel_success_at=attemptTime}if(lastError!==void 0){statePatch.last_otel_failure_at=attemptTime;statePatch.last_otel_failure_error=lastError}else if(remaining===0){statePatch.last_otel_failure_at=void 0;statePatch.last_otel_failure_error=void 0}await writeRuntimeState(globalPmRoot,statePatch)}async function flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays){try{await flushQueue(globalPmRoot,endpoint,retentionDays)}catch{}try{await flushPendingOtelSpans(globalPmRoot,retentionDays)}catch{}}async function cleanupTelemetryQueueTempOrphans(globalPmRoot,maxAgeMs=TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS){try{const dirPath=telemetryRuntimeDirectory(globalPmRoot);const entries=await readdir(dirPath,{withFileTypes:true});const cutoffMs=Date.now()-Math.max(0,maxAgeMs);await Promise.all(entries.filter(entry=>entry.isFile()&&/^\.events\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(entry.name)).map(async entry=>{const candidate=path.join(dirPath,entry.name);const candidateStats=await stat(candidate);if(candidateStats.mtimeMs<cutoffMs){await rm(candidate,{force:true})}}))}catch{}}async function withQueueMutation(operation,globalPmRoot=resolveGlobalPmRoot(process.cwd()),waitMs=5e3){const run=_queueMutationPromise.catch(()=>{}).then(()=>runWithIsolatedExtensionRuntime(async()=>{const release=await acquireLock(globalPmRoot,"telemetry-queue",60,"telemetry",false,false,waitMs);try{return await operation()}finally{await release()}}));_queueMutationPromise=run.catch(()=>{});return run}async function readCurrentQueueEntries(globalPmRoot){const raw=await readFileIfExists(queuePath(globalPmRoot));if(raw===null||raw.trim().length===0){return[]}return parseQueueLines(raw)}async function removeFlushedEntriesFromCurrentQueue(globalPmRoot,flushedIds,retentionDays){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot);const{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays);const remaining=retainedEntries.filter(entry=>!flushedIds.has(entry.event.event_id));await rewriteQueue(globalPmRoot,remaining);return remaining},globalPmRoot)}async function markFailedEntriesInCurrentQueue(globalPmRoot,failedIds,attemptTime,retentionDays){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot);const{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays);const retried=retainedEntries.map(entry=>{if(!failedIds.has(entry.event.event_id)){return entry}const attempts=entry.attempts+1;return{...entry,attempts,last_attempt_at:attemptTime,next_attempt_after:nextRetryIso(attempts)}});await rewriteQueue(globalPmRoot,retried);return retried},globalPmRoot)}async function flushQueue(globalPmRoot,endpoint,retentionDays){await cleanupTelemetryQueueTempOrphans(globalPmRoot);const normalizedEndpoint=endpoint.trim();if(normalizedEndpoint.length===0){return}const raw=await readFileIfExists(queuePath(globalPmRoot));if(raw===null||raw.trim().length===0){await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const queueEntries=parseQueueLines(raw);if(queueEntries.length===0){await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const{entries:retainedEntries,prunedCount}=pruneExpiredQueueEntries(queueEntries,retentionDays);if(retainedEntries.length===0){const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,new Set,retentionDays);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.length});return}const dueEntries=retainedEntries.filter(entry=>isDueForRetry(entry)).slice(0,TELEMETRY_FLUSH_BATCH_SIZE);if(dueEntries.length===0){const remaining=prunedCount>0?await removeFlushedEntriesFromCurrentQueue(globalPmRoot,new Set,retentionDays):retainedEntries;await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.length});return}const dueIds=new Set(dueEntries.map(entry=>entry.event.event_id));const attemptTime=nowIso();const requestHeaders={"content-type":"application/json"};const ingestKey=process.env.PM_TELEMETRY_INGEST_KEY?.trim();if(ingestKey){requestHeaders["x-pm-telemetry-key"]=ingestKey}try{const status=await postTelemetryJson(normalizedEndpoint,requestHeaders,JSON.stringify({schema_version:TELEMETRY_SCHEMA_VERSION,events:dueEntries.map(entry=>entry.event)}));if(status<200||status>=300){throw new Error(`telemetry_flush_http_${status}`)}}catch(error){const retried=await markFailedEntriesInCurrentQueue(globalPmRoot,dueIds,attemptTime,retentionDays);const errorMessage=(()=>{if(error instanceof Error){return sanitizeString(error.message,"redacted")}return"telemetry_flush_failed"})();await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:retried.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage});return}try{const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,dueIds,retentionDays);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.length,last_attempted_flush_at:attemptTime,last_successful_flush_at:attemptTime,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(error){const errorMessage=(()=>{if(error instanceof Error){return sanitizeString(error.message,"redacted")}return"telemetry_flush_failed"})();const currentEntries=await readCurrentQueueEntries(globalPmRoot).catch(()=>retainedEntries);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:currentEntries.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage})}}async function acquireTelemetryFlushLock(globalPmRoot){const lockPath=flushLockPath(globalPmRoot);await mkdir(path.dirname(lockPath),{recursive:true});try{await mkdir(lockPath);return true}catch(error){if(typeof error!=="object"||error===null||!("code"in error)||error.code!=="EEXIST"){throw error}}try{const lockStats=await stat(lockPath);if(Date.now()-lockStats.mtimeMs<TELEMETRY_FLUSH_LOCK_STALE_MS){return false}await rm(lockPath,{recursive:true,force:true});await mkdir(lockPath);return true}catch{return false}}function isFreshDirectoryLock(lockPath,staleMs){try{return Date.now()-statSync(lockPath).mtimeMs<staleMs}catch{return false}}function removeDirectoryLockBestEffort(lockPath){try{rmSync(lockPath,{recursive:true,force:true})}catch{}}function errorCode(error){if(typeof error!=="object"||error===null||!("code"in error)){return void 0}const code=error.code;return typeof code==="string"?code:void 0}function createDirectoryLock(lockPath){try{mkdirSync(lockPath);return true}catch(error){const code=errorCode(error);if(code==="EEXIST"){return false}if(!isFileMissingError(error)){return false}}try{mkdirSync(path.dirname(lockPath),{recursive:true});mkdirSync(lockPath);return true}catch{return false}}function acquireTelemetryFlushSpawnGate(globalPmRoot){if(isFreshDirectoryLock(flushLockPath(globalPmRoot),TELEMETRY_FLUSH_LOCK_STALE_MS)){return false}const lockPath=flushSpawnLockPath(globalPmRoot);try{if(Date.now()-statSync(lockPath).mtimeMs<TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS){return false}removeDirectoryLockBestEffort(lockPath)}catch(error){if(!isFileMissingError(error)){return false}}return createDirectoryLock(lockPath)}function releaseTelemetryFlushSpawnGate(globalPmRoot){removeDirectoryLockBestEffort(flushSpawnLockPath(globalPmRoot))}const _testOnly={acquireTelemetryFlushSpawnGate,acquireTelemetryFlushLock,buildAuthorContextPayloadFields,buildCommandErrorPayload,buildCommandFinishPayload,buildCommandStartPayload,buildOtelSpanRequest,createDirectoryLock,enqueuePendingOtelSpan,enqueueTelemetryEvent,errorCode,flushPendingOtelSpans,flushQueue,flushQueueWithProcessLock,flushTelemetryArtifacts,hashTelemetryErrorFingerprint,hashTelemetryValue,isEmailDomainCharacter,isEmailLocalCharacter,isExpiredPendingOtelSpan,isExpiredQueueEntry,isFreshDirectoryLock,isDueForRetry,isDueForRetryAt,isRetryableQueueRewriteError,looksLikeEmailToken,otelSpansQueuePath,parseBooleanTrueLike,postTelemetryJson,parsePendingOtelSpanLines,prunePendingOtelSpans,reconcilePendingOtelSpansAfterFlush,retentionCutoffMs,resolveOtelTracesEndpoint,resolveTelemetryHttpTimeoutMs,rewritePendingOtelSpans,normalizeForHash,normalizeCaptureLevel,normalizePmVersion,normalizeTelemetryErrorCategory,normalizeTelemetryErrorCode,normalizeTelemetryExitCode,parseQueueLines,pruneExpiredQueueEntries,readRuntimeState,readCurrentQueueEntries,releaseTelemetryFlushSpawnGate,removeFlushedEntriesFromCurrentQueue,removeDirectoryLockBestEffort,resolveTelemetrySourceContext,rewriteQueue,sanitizeCommandArgs,sanitizeStringMax,sanitizeStringRedacted,sanitizeValue,scheduleTelemetryFlush,shouldFlushInline,sleep,summarizeResult,telemetryFlushRunnerPath,withQueueMutation,flushLockPath,flushSpawnLockPath,runtimeStatePath,writeRuntimeState};async function flushQueueWithProcessLock(globalPmRoot,endpoint,retentionDays){const acquired=await acquireTelemetryFlushLock(globalPmRoot);releaseTelemetryFlushSpawnGate(globalPmRoot);if(!acquired){return}try{await flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays)}finally{try{await rm(flushLockPath(globalPmRoot),{recursive:true,force:true})}catch{}}}function scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays){if(shouldFlushInline()){const previousFlush=_lastFlushPromise;const nextFlush=flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays);_lastFlushPromise=Promise.allSettled([previousFlush,nextFlush]).then(()=>{});return}try{const acquiredSpawnGate=acquireTelemetryFlushSpawnGate(globalPmRoot);if(!acquiredSpawnGate){return}const child=spawn(process.execPath,[telemetryFlushRunnerPath()],{detached:true,stdio:"ignore",cwd:os.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:globalPmRoot,[PM_TELEMETRY_FLUSH_CHILD_ENV]:"1"}});child.on("error",()=>{releaseTelemetryFlushSpawnGate(globalPmRoot)});child.unref()}catch{releaseTelemetryFlushSpawnGate(globalPmRoot)}}async function flushTelemetryQueueNow(globalPmRoot=resolveGlobalPmRoot(process.cwd())){if(resolveTelemetryEnvironmentPolicy().telemetry_disabled){return}try{const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const installation=await withQueueMutation(()=>ensureInstallationId(globalPmRoot),globalPmRoot);if(!installation)return;await flushQueueWithProcessLock(globalPmRoot,installation.endpoint,installation.retentionDays)}catch{}}async function startTelemetryCommand(context){if(resolveTelemetryEnvironmentPolicy().telemetry_disabled){return null}if(context.command==="telemetry"&&context.args.some(token=>token.trim().toLowerCase()==="clear")){return null}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return null}const activeCommand=await withQueueMutation(async()=>{const installation=await ensureInstallationId(globalPmRoot);if(!installation)return null;const{installationId,endpoint,retentionDays,captureLevel}=installation;const pmVersion=normalizePmVersion(context.pm_version);const sourceContext=resolveTelemetrySourceContext(context.global);const pmRootHash=hashWithInstallationId(installationId,context.pm_root);const cwdHash=hashWithInstallationId(installationId,process.cwd());const otelTracesEndpoint=resolveOtelTracesEndpoint();const occurredAt=nowIso();const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_start",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:context.command,payload:buildCommandStartPayload({captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId})};const sampleRate=resolveTelemetryReadSampleRate(context.command,context.global.noExtensions===true);if(sampleRate===1){await appendTelemetryEvent(globalPmRoot,event)}const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);const active={...sampleRate<1?{sample_rate:sampleRate}:{},started_at:occurredAt,started_at_ms:Date.now(),command:context.command,command_taxonomy:commandTaxonomy,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,installation_id:installationId,pm_root_hash:pmRootHash,cwd_hash:cwdHash,endpoint,retention_days:retentionDays,global_pm_root:globalPmRoot,capture_level:captureLevel,otel_traces_endpoint:otelTracesEndpoint??void 0,otel_trace_id:otelTracesEndpoint?crypto.randomBytes(16).toString("hex"):void 0,otel_span_id:otelTracesEndpoint?crypto.randomBytes(8).toString("hex"):void 0};if(sampleRate<1)deferredReadStarts.set(active,event);return active},globalPmRoot,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);if(activeCommand&&activeCommand.sample_rate===void 0){scheduleTelemetryFlush(globalPmRoot,activeCommand.endpoint,activeCommand.retention_days)}return activeCommand}catch{return null}}async function finishTelemetryCommand(activeCommand,outcome){if(!activeCommand||resolveTelemetryEnvironmentPolicy().telemetry_disabled){return}try{const captured=await withQueueMutation(async()=>{const settings=await readSettings(activeCommand.global_pm_root);if(resolveTelemetryEnvironmentPolicy().telemetry_disabled||!settings.telemetry.enabled||settings.telemetry.installation_id!==activeCommand.installation_id){deferredReadStarts.delete(activeCommand);return false}const deferredStart=deferredReadStarts.get(activeCommand);const sampleRate=outcome.ok?activeCommand.sample_rate??1:1;if(deferredStart){deferredReadStarts.delete(activeCommand);if(crypto.randomBytes(6).readUIntBE(0,6)/2**48>=sampleRate)return false;deferredStart.payload.sample_rate=sampleRate;await appendTelemetryEvent(activeCommand.global_pm_root,deferredStart)}const finishedAt=nowIso();const durationMs=Math.max(0,Date.now()-activeCommand.started_at_ms);const normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:outcome.ok,errorCode:outcome.error_code,errorMessage:outcome.error,exitCode:outcome.exit_code}));const normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category});const normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok);const commandResolution=outcome.command_resolution??deriveTelemetryCommandResolution({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory});const resolutionStage=outcome.resolution_stage??"execute";const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_finish",occurred_at:finishedAt,installation_id:activeCommand.installation_id,session_id:PROCESS_SESSION_ID,command:activeCommand.command,payload:{...deferredStart?{sample_rate:sampleRate}:{},...buildCommandFinishPayload({captureLevel:activeCommand.capture_level,pmVersion:activeCommand.pm_version,sourceContext:{source_context:activeCommand.source_context,source_context_source:activeCommand.source_context_source},outcome,durationMs,startedAt:activeCommand.started_at,command:activeCommand.command,installationId:activeCommand.installation_id,commandTaxonomy:activeCommand.command_taxonomy,exitCode:normalizedExitCode,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,commandResolution,resolutionStage})}};await appendTelemetryEvent(activeCommand.global_pm_root,event);const otelRequest=buildOtelSpanRequest(activeCommand,{...outcome,exit_code:normalizedExitCode,error_code:normalizedErrorCode,error_category:normalizedErrorCategory},finishedAt,durationMs,sampleRate);if(otelRequest){await appendPendingOtelSpan(activeCommand.global_pm_root,otelRequest)}return true},activeCommand.global_pm_root,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);if(!captured)return;scheduleTelemetryFlush(activeCommand.global_pm_root,activeCommand.endpoint,activeCommand.retention_days)}catch{}}async function emitTelemetryErrorEvent(context){if(resolveTelemetryEnvironmentPolicy().telemetry_disabled){return}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const captured=await withQueueMutation(async()=>{const installation=await ensureInstallationId(globalPmRoot);if(!installation)return null;const{installationId,captureLevel}=installation;const pmVersion=normalizePmVersion(context.pm_version);const sourceContext=resolveTelemetrySourceContext(context.global);const pmRootHash=hashWithInstallationId(installationId,context.pm_root);const cwdHash=hashWithInstallationId(installationId,process.cwd());const occurredAt=nowIso();const normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:false,errorCode:context.error_code,errorMessage:context.error_message,exitCode:context.exit_code}));const normalizedErrorCategory=context.error_category??resolveTelemetryErrorCategory(normalizedErrorCode);const normalizedExitCode=normalizeTelemetryExitCode(context.exit_code,false);const normalizedCommand=context.command.trim().length>0?context.command:"<unknown>";const commandTaxonomy=deriveTelemetryCommandTaxonomy(normalizedCommand);const commandResolution=context.command_resolution??deriveTelemetryCommandResolution({ok:false,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory});const resolutionStage=context.resolution_stage??"unknown";const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_error",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:sanitizeString(normalizedCommand,"redacted"),payload:buildCommandErrorPayload({captureLevel,pmVersion,sourceContext,command:normalizedCommand,commandTaxonomy,commandResolution,resolutionStage,args:context.args,options:context.options,pmRootHash,cwdHash,installationId,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,exitCode:normalizedExitCode,errorMessage:context.error_message})};await appendTelemetryEvent(globalPmRoot,event);return installation},globalPmRoot,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);if(captured)scheduleTelemetryFlush(globalPmRoot,captured.endpoint,captured.retentionDays)}catch{}}export{PM_TELEMETRY_SOURCE_CONTEXT_VALUES2 as PM_TELEMETRY_SOURCE_CONTEXT_VALUES,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,TELEMETRY_SCHEMA_VERSION,_testOnly,emitTelemetryErrorEvent,finishTelemetryCommand,flushTelemetryQueueNow,startTelemetryCommand,waitForPendingFlush,withQueueMutation as withTelemetryQueueMutation};
|
|
5
6
|
//# sourceMappingURL=runtime.js.map
|
|
@@ -2,3 +2,9 @@
|
|
|
2
2
|
export declare function scoreCommandPathMatch(commandPath: string, queryToken: string): number;
|
|
3
3
|
/** Rank available command paths for one guessed token. */
|
|
4
4
|
export declare function rankCommandPaths(commandPaths: string[], queryToken: string): string[];
|
|
5
|
+
/**
|
|
6
|
+
* Replace migration-only prefixes with installed canonical paths and required flags.
|
|
7
|
+
* A query token prefers known semantic matches over weaker spelling guesses after
|
|
8
|
+
* unavailable replacements have been removed.
|
|
9
|
+
*/
|
|
10
|
+
export declare function canonicalizeCommandSuggestions(candidates: readonly string[], availablePaths: readonly string[], queryToken?: string): string[];
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="925e5fec-4cc0-5315-a331-03cb128893f0")}catch(e2){}})();import{levenshteinDistanceWithinLimit}from"../../core/shared/levenshtein.js";import{PM_COMMAND_ALIAS_CONTRACTS,resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";const COMMAND_SYNONYMS={add:["create","append"],fetch:["get"],inspect:["get","health"],log:["history","comments","notes"],ls:["list"],pause:["release"],read:["get"],remove:["delete"],rm:["delete"],show:["get"],start:["start-task"]};function scoreCommandPathMatch(commandPath,queryToken){const normalizedPath=commandPath.trim().toLowerCase();const normalizedToken=queryToken.trim().toLowerCase();if(normalizedToken.length===0)return Number.POSITIVE_INFINITY;const segments=normalizedPath.split(" ");const semanticIndex=COMMAND_SYNONYMS[normalizedToken]?.indexOf(resolvePmCommandOperation(normalizedPath));if(semanticIndex!==void 0&&semanticIndex>=0)return semanticIndex;if(normalizedPath===normalizedToken)return 10;if(segments.includes(normalizedToken))return 11;if(segments.some(segment=>segment.startsWith(normalizedToken)))return 12;const maxDistance=normalizedToken.length>=5?2:1;let bestDistance=Number.POSITIVE_INFINITY;for(const segment of segments){const distance=levenshteinDistanceWithinLimit(segment,normalizedToken,maxDistance);if(distance!==null)bestDistance=Math.min(bestDistance,distance)}if(Number.isFinite(bestDistance))return 20+bestDistance;if(normalizedPath.includes(normalizedToken))return 30;return Number.POSITIVE_INFINITY}function rankCommandPaths(commandPaths,queryToken){return commandPaths.map(path=>({path,score:scoreCommandPathMatch(path,queryToken)})).filter(entry=>Number.isFinite(entry.score)).sort((left,right)=>{if(left.score!==right.score)return left.score-right.score;if(left.path===right.path)return 0;return left.path<right.path?-1:1}).map(entry=>entry.path)}function canonicalizeCommandSuggestions(candidates,availablePaths,queryToken){const available=new Set(availablePaths);const aliases=PM_COMMAND_ALIAS_CONTRACTS.filter(alias=>alias.lifecycle==="deprecated").slice().sort((left,right)=>right.alias.length-left.alias.length);const preferred=[];const resolved=candidates.flatMap(candidate=>{const alias=aliases.find(entry=>candidate===entry.alias||candidate.startsWith(`${entry.alias} `));let canonical=candidate;if(alias){const suffix=candidate.slice(alias.alias.length);if(!available.has(`${alias.canonical}${suffix}`))return[];canonical=`${alias.canonical_argv.join(" ")}${suffix}`}if(queryToken!==void 0&&scoreCommandPathMatch(candidate,queryToken)<10)preferred.push(canonical);return[canonical]});return[...new Set(preferred.length>0?preferred:resolved)]}export{canonicalizeCommandSuggestions,rankCommandPaths,scoreCommandPathMatch};
|
|
2
2
|
//# sourceMappingURL=command-suggestions.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e1db7644-e481-5049-a773-fcffa09f1779")}catch(e2){}})();import{findBootstrapCommandTokenIndex}from"../cli-contracts/bootstrap-command-scanner.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";const ITEM_ID_ALIAS_COMMANDS=new Set(["append","claim","close","close-task","comments","copy","delete","deps","docs","files","focus","get","history","history-compact","history-redact","history-repair","learnings","notes","pause-task","release","restore","start-task","test","update"]);const ITEM_ID_ALIAS_SUBCOMMANDS=new Map([["files","discover"],["item","complete"]]);const TRAILING_POSITIONAL_COUNTS=new Map([["append",1],["close",1],["close-task",1],["comments",1],["item complete",1],["learnings",1],["notes",1],["restore",1]]);function supportsItemIdAlias(commandName){const normalized=resolvePmCommandOperation(commandName?.trim().toLowerCase()??"");return ITEM_ID_ALIAS_COMMANDS.has(normalized)||ITEM_ID_ALIAS_SUBCOMMANDS.has(normalized)}function resolveNamespacedItemAddressIndex(argv,commandIndex,commandName){const fallback=ITEM_ID_ALIAS_COMMANDS.has(commandName)?commandIndex+1:void 0;const leafOffset=findBootstrapCommandTokenIndex(argv.slice(commandIndex+1));if(leafOffset===void 0)return fallback;const leafIndex=commandIndex+1+leafOffset;const candidate=`${commandName} ${argv[leafIndex]}`;const operation=resolvePmCommandOperation(candidate);if(operation===candidate)return commandName==="item"&&argv[leafIndex]==="complete"?leafIndex+1:fallback;return supportsItemIdAlias(operation)?resolveItemAddressIndex(argv,leafIndex,operation):void 0}function resolveItemAddressIndex(argv,commandIndex,commandName){if(["history","context","ctx","update","close","item"].includes(commandName)){return resolveNamespacedItemAddressIndex(argv,commandIndex,commandName)}const declaredSubcommand=ITEM_ID_ALIAS_SUBCOMMANDS.get(commandName);if(declaredSubcommand===void 0)return commandIndex+1;const usesDeclaredSubcommand=argv[commandIndex+1]?.toLowerCase()===declaredSubcommand;return commandIndex+(usesDeclaredSubcommand?2:1)}function buildFlagContractMap(commandPath){const contractsByFlag=new Map;for(const contract of resolveSubcommandFlagContractsForCommand(commandPath)){for(const flag of[contract.flag,contract.short,...contract.aliases??[]]){if(flag)contractsByFlag.set(flag,contract)}}return contractsByFlag}function collectNamedItemIds(argv){const namedIds=[];for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--id"){namedIds.push({index,consumed:2,value:argv[index+1]});index+=1}else if(token.startsWith("--id=")){namedIds.push({index,consumed:1,value:token.slice("--id=".length)})}}return namedIds}function consumesSeparateFlagValue(token,nextToken,contractsByFlag){const separatorIndex=token.indexOf("=");if(separatorIndex>=0||nextToken===void 0||nextToken.startsWith("-")){return false}const contract=contractsByFlag.get(token);return contract!==void 0&&contract.value_type!=="boolean"}function hasPositionalItemId(argv,addressIndex,commandPath,namedIndex,contractsByFlag){let trailingPositionals=0;for(let index=addressIndex;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--id"){index+=1;continue}if(token.startsWith("--id="))continue;if(!token.startsWith("-")){if(index<namedIndex)return true;trailingPositionals+=1;continue}if(consumesSeparateFlagValue(token,argv[index+1],contractsByFlag)){index+=1}}return trailingPositionals>(TRAILING_POSITIONAL_COUNTS.get(resolvePmCommandOperation(commandPath))??0)}function normalizeItemAddressInvocation(argv){const commandIndex=findBootstrapCommandTokenIndex(argv);const commandName=commandIndex===void 0?void 0:argv[commandIndex]?.toLowerCase();if(commandName!=="context"&&commandName!=="ctx"&&!supportsItemIdAlias(commandName)){return{argv:[...argv],changed:false,conflict:false}}const addressIndex=resolveItemAddressIndex(argv,commandIndex,commandName);if(addressIndex===void 0){return{argv:[...argv],changed:false,conflict:false}}const commandPath=addressIndex>commandIndex+1?`${resolvePmCommandOperation(argv.slice(commandIndex,addressIndex-1).join(" "))} ${argv[addressIndex-1]}`:commandName;const contractsByFlag=buildFlagContractMap(commandPath);const namedIds=collectNamedItemIds(argv);const named=namedIds[0];if(!named||!named.value?.trim()){return{argv:[...argv],changed:false,conflict:false}}if(namedIds.length>1||hasPositionalItemId(argv,addressIndex,commandPath,named.index,contractsByFlag)){return{argv:[...argv],changed:false,conflict:true,itemId:named.value}}const withoutNamed=[...argv.slice(0,named.index),...argv.slice(named.index+named.consumed)];const normalizedCommandIndex=findBootstrapCommandTokenIndex(withoutNamed);const normalizedAddressIndex=resolveItemAddressIndex(withoutNamed,normalizedCommandIndex,commandName);withoutNamed.splice(normalizedAddressIndex,0,named.value);return{argv:withoutNamed,changed:true,conflict:false,itemId:named.value}}export{normalizeItemAddressInvocation,supportsItemIdAlias};
|
|
2
2
|
//# sourceMappingURL=item-addressing.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6d931940-2d41-557a-8913-875848774ed0")}catch(e2){}})();import{PM_CORE_COMMAND_NAMES}from"./cli-contracts/enum-contracts.js";import{PM_COMMAND_ALIAS_CONTRACTS,PM_NAMESPACED_COMMAND_ALIASES,resolvePmCommandOperation}from"./cli-contracts/command-aliases.js";const CORE_COMMANDS=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate"]);const STANDARD_COMMANDS=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]);const COMMANDS_BY_FAMILY=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])});const EXTENSION_COMMANDS=new Set(["extension","install","package","packages","upgrade"]);function resolvePmCommandCapabilityFamily(command){const normalized=resolvePmCommandOperation(command.trim().toLowerCase());if(normalized==="ops")return"quality";for(const[family,commands]of Object.entries(COMMANDS_BY_FAMILY)){if(commands.has(normalized))return family}return EXTENSION_COMMANDS.has(normalized)?"extensions":"internal"}const PM_COMMAND_CAPABILITY_CONTRACTS=Object.freeze([...PM_CORE_COMMAND_NAMES.flatMap(command=>command==="item"?["item-reopen"]:[command,...PM_NAMESPACED_COMMAND_ALIASES.filter(alias=>alias.alias===command).map(alias=>alias.canonical)]).map(command=>({command,tier:CORE_COMMANDS.has(resolvePmCommandOperation(command))?"core":STANDARD_COMMANDS.has(resolvePmCommandOperation(command))?"standard":"full",family:resolvePmCommandCapabilityFamily(command)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"}]);const PM_COMMAND_VISIBILITY_CONTRACTS=PM_COMMAND_CAPABILITY_CONTRACTS;const PM_CORE_HELP_BUDGET=Object.freeze({max_lines:50,max_utf8_bytes:6e3});const PM_CORE_HELP_OPTION_FLAGS=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function measurePmCoreHelp(text){const lines=text===""?0:text.split(/\r?\n/).length;const utf8Bytes=Buffer.byteLength(text,"utf8");return{lines,utf8_bytes:utf8Bytes,within_budget:lines<=PM_CORE_HELP_BUDGET.max_lines&&utf8Bytes<=PM_CORE_HELP_BUDGET.max_utf8_bytes}}const TIER_ORDER={core:0,standard:1,full:2,internal:3};const COMMAND_TIER_BY_NAME=new Map(PM_COMMAND_VISIBILITY_CONTRACTS.map(({command,tier})=>[command,tier]));function resolvePmCommandVisibilityTier(command,extensionTier="standard"){return COMMAND_TIER_BY_NAME.get(command.trim().toLowerCase())??extensionTier}function listPmCommandsForTier(tier){return listPmCommandsForTierFromContracts(tier,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmCommandsForTierFromContracts(tier,contracts){const maximum=TIER_ORDER[tier];return contracts.filter(entry=>entry.tier!=="internal"&&TIER_ORDER[entry.tier]<=maximum).map(entry=>entry.command)}function listPmCommandsForFamily(family){return listPmCommandsForFamilyFromContracts(family,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmCommandsForFamilyFromContracts(family,contracts){return contracts.filter(entry=>entry.family===family).map(entry=>entry.command)}const CAPABILITY_FAMILY_ORDER=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"];const CAPABILITY_ROUTING_EXCLUDED_ALIASES=new Set([...PM_COMMAND_ALIAS_CONTRACTS.filter(alias=>alias.hidden).map(alias=>alias.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function listPmCommandCapabilityGroups(contracts=PM_COMMAND_CAPABILITY_CONTRACTS){return CAPABILITY_FAMILY_ORDER.map(family=>({family,commands:listPmCommandsForFamilyFromContracts(family,contracts).filter(command=>contracts.find(entry=>entry.command===command)?.tier!=="internal"&&!CAPABILITY_ROUTING_EXCLUDED_ALIASES.has(command))})).filter(({commands})=>commands.length>0)}const PM_MCP_TOOL_COMMAND_CONTRACTS=Object.freeze({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_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function listPmMcpToolsForProfile(availableTools,profile){return listPmMcpToolsForProfileFromContracts(availableTools,profile,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmMcpToolsForProfileFromContracts(availableTools,profile,contracts){if(profile==="full")return[...availableTools];const visibleCommands=new Set(listPmCommandsForTierFromContracts(profile,contracts));return availableTools.filter(tool=>{const command=PM_MCP_TOOL_COMMAND_CONTRACTS[tool];return command!==void 0&&visibleCommands.has(command)})}const PM_MCP_RESOURCE_CONTRACTS=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]);const PM_MCP_PROMPT_CONTRACTS=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:true},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:false}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:true}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:true},{name:"evidence",description:"Exact verification and outcome evidence.",required:true}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function renderPmCommandVisibilityMarkdown(){return renderPmCommandVisibilityMarkdownFromContracts(PM_COMMAND_CAPABILITY_CONTRACTS)}function renderPmCommandVisibilityMarkdownFromContracts(contracts){const rows=contracts.map(({command,tier,family})=>`| \`${command}\` | ${tier} | ${family} |`);return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...rows,""].join("\n")}function renderPmCapabilityRoutingMarkdown(contracts=PM_COMMAND_CAPABILITY_CONTRACTS){const rows=listPmCommandCapabilityGroups(contracts).map(({family,commands})=>`| ${family} | ${commands.map(command=>`\`${command}\``).join(", ")} |`);return["# Generated agent capability routing","","Tracker: `pm-kxci8x`.","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Capability family | Commands |","| --- | --- |",...rows,""].join("\n")}export{PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_CORE_HELP_BUDGET,PM_CORE_HELP_OPTION_FLAGS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,listPmCommandCapabilityGroups,listPmCommandsForFamily,listPmCommandsForFamilyFromContracts,listPmCommandsForTier,listPmCommandsForTierFromContracts,listPmMcpToolsForProfile,listPmMcpToolsForProfileFromContracts,measurePmCoreHelp,renderPmCapabilityRoutingMarkdown,renderPmCommandVisibilityMarkdown,renderPmCommandVisibilityMarkdownFromContracts,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier};
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="235bac43-67ba-5fad-9ec2-e392aeb7feda")}catch(e2){}})();import{PM_CORE_COMMAND_NAMES}from"./cli-contracts/enum-contracts.js";import{PM_COMMAND_ALIAS_CONTRACTS,PM_NAMESPACED_COMMAND_ALIASES,resolvePmCommandOperation}from"./cli-contracts/command-aliases.js";const CORE_COMMANDS=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate"]);const STANDARD_COMMANDS=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]);const COMMANDS_BY_FAMILY=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])});const EXTENSION_COMMANDS=new Set(["extension","install","package","packages","upgrade"]);function resolvePmCommandCapabilityFamily(command){const normalized=resolvePmCommandOperation(command.trim().toLowerCase());if(normalized==="ops")return"quality";for(const[family,commands]of Object.entries(COMMANDS_BY_FAMILY)){if(commands.has(normalized))return family}return EXTENSION_COMMANDS.has(normalized)?"extensions":"internal"}const PM_COMMAND_CAPABILITY_CONTRACTS=Object.freeze([...PM_CORE_COMMAND_NAMES.flatMap(command=>command==="item"?["item","item-reopen"]:[command,...PM_NAMESPACED_COMMAND_ALIASES.filter(alias=>alias.alias===command).map(alias=>alias.canonical)]).map(command=>({command,tier:CORE_COMMANDS.has(resolvePmCommandOperation(command))?"core":STANDARD_COMMANDS.has(resolvePmCommandOperation(command))?"standard":"full",family:resolvePmCommandCapabilityFamily(command)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"},{command:"item test worker",tier:"internal",family:"internal"}]);const PM_COMMAND_VISIBILITY_CONTRACTS=PM_COMMAND_CAPABILITY_CONTRACTS;const PM_CORE_HELP_BUDGET=Object.freeze({max_lines:50,max_utf8_bytes:6e3});const PM_CORE_HELP_OPTION_FLAGS=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function measurePmCoreHelp(text){const lines=text===""?0:text.split(/\r?\n/).length;const utf8Bytes=Buffer.byteLength(text,"utf8");return{lines,utf8_bytes:utf8Bytes,within_budget:lines<=PM_CORE_HELP_BUDGET.max_lines&&utf8Bytes<=PM_CORE_HELP_BUDGET.max_utf8_bytes}}const TIER_ORDER={core:0,standard:1,full:2,internal:3};const COMMAND_TIER_BY_NAME=new Map(PM_COMMAND_VISIBILITY_CONTRACTS.map(({command,tier})=>[command,tier]));function resolvePmCommandVisibilityTier(command,extensionTier="standard"){return COMMAND_TIER_BY_NAME.get(command.trim().toLowerCase())??COMMAND_TIER_BY_NAME.get(resolvePmCommandOperation(command.trim().toLowerCase()))??extensionTier}function listPmCommandsForTier(tier){return listPmCommandsForTierFromContracts(tier,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmCommandsForTierFromContracts(tier,contracts){const maximum=TIER_ORDER[tier];return contracts.filter(entry=>entry.tier!=="internal"&&TIER_ORDER[entry.tier]<=maximum).map(entry=>entry.command)}function listPmCommandsForFamily(family){return listPmCommandsForFamilyFromContracts(family,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmCommandsForFamilyFromContracts(family,contracts){return contracts.filter(entry=>entry.family===family).map(entry=>entry.command)}const CAPABILITY_FAMILY_ORDER=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"];const CAPABILITY_ROUTING_EXCLUDED_ALIASES=new Set([...PM_COMMAND_ALIAS_CONTRACTS.filter(alias=>alias.hidden).map(alias=>alias.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function listPmCommandCapabilityGroups(contracts=PM_COMMAND_CAPABILITY_CONTRACTS){return CAPABILITY_FAMILY_ORDER.map(family=>({family,commands:listPmCommandsForFamilyFromContracts(family,contracts).filter(command=>contracts.find(entry=>entry.command===command)?.tier!=="internal"&&!CAPABILITY_ROUTING_EXCLUDED_ALIASES.has(command))})).filter(({commands})=>commands.length>0)}const PM_MCP_TOOL_COMMAND_CONTRACTS=Object.freeze({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_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function listPmMcpToolsForProfile(availableTools,profile){return listPmMcpToolsForProfileFromContracts(availableTools,profile,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmMcpToolsForProfileFromContracts(availableTools,profile,contracts){if(profile==="full")return[...availableTools];const visibleCommands=new Set(listPmCommandsForTierFromContracts(profile,contracts));return availableTools.filter(tool=>{const command=PM_MCP_TOOL_COMMAND_CONTRACTS[tool];return command!==void 0&&visibleCommands.has(command)})}const PM_MCP_RESOURCE_CONTRACTS=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]);const PM_MCP_PROMPT_CONTRACTS=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:true},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:false}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:true}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:true},{name:"evidence",description:"Exact verification and outcome evidence.",required:true}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function renderPmCommandVisibilityMarkdown(){return renderPmCommandVisibilityMarkdownFromContracts(PM_COMMAND_CAPABILITY_CONTRACTS)}function renderPmCommandVisibilityMarkdownFromContracts(contracts){const rows=contracts.map(({command,tier,family})=>`| \`${command}\` | ${tier} | ${family} |`);return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...rows,""].join("\n")}function renderPmCapabilityRoutingMarkdown(contracts=PM_COMMAND_CAPABILITY_CONTRACTS){const rows=listPmCommandCapabilityGroups(contracts).map(({family,commands})=>`| ${family} | ${commands.map(command=>`\`${command}\``).join(", ")} |`);return["# Generated agent capability routing","","Tracker: `pm-kxci8x`.","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Capability family | Commands |","| --- | --- |",...rows,""].join("\n")}export{PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_CORE_HELP_BUDGET,PM_CORE_HELP_OPTION_FLAGS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,listPmCommandCapabilityGroups,listPmCommandsForFamily,listPmCommandsForFamilyFromContracts,listPmCommandsForTier,listPmCommandsForTierFromContracts,listPmMcpToolsForProfile,listPmMcpToolsForProfileFromContracts,measurePmCoreHelp,renderPmCapabilityRoutingMarkdown,renderPmCommandVisibilityMarkdown,renderPmCommandVisibilityMarkdownFromContracts,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier};
|
|
2
2
|
//# sourceMappingURL=agent-capability-contracts.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="17b52e35-0115-5736-adf5-5adaa8c40cad")}catch(e2){}})();import{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias}from"./cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand}from"./cli-contracts/flag-contracts.js";import{levenshteinDistanceWithinLimit}from"../core/shared/levenshtein.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{findPmNamespacedCommand}from"./cli-contracts/command-aliases.js";import{normalizeItemAddressInvocation}from"./agent/item-addressing.js";import{BOOTSTRAP_BOOLEAN_FLAGS,GLOBAL_VALUE_CONSUMING_FLAGS,consumesBootstrapValue,findBootstrapCommandTokenIndex as findContractBootstrapCommandTokenIndex,isInlineGlobalValueToken,parseBootstrapCommandName as parseContractBootstrapCommandName}from"./cli-contracts/bootstrap-command-scanner.js";const OUTPUT_VALUE_FLAGS=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]);function consumeBootstrapGlobalToken(argv,index,state){const token=argv[index];if(BOOTSTRAP_BOOLEAN_FLAGS.has(token)){state.booleanFlags.add(token);return 1}const equalsIndex=token.indexOf("=");const canonicalFlag=equalsIndex>0?token.slice(0,equalsIndex):token;if(!GLOBAL_VALUE_CONSUMING_FLAGS.has(canonicalFlag))return 1;const inlineValue=equalsIndex>0?token.slice(equalsIndex+1):void 0;const consumesValue=inlineValue===void 0&&consumesBootstrapValue(canonicalFlag,argv[index+1]);const value=inlineValue??(consumesValue?argv[index+1]:void 0);if(canonicalFlag==="--author"){state.author=value??""}else if(typeof value==="string"&&value.length>0){const target=OUTPUT_VALUE_FLAGS.has(canonicalFlag)?state.outputValues:state.pathValues;target.set(canonicalFlag,value)}return consumesValue?2:1}function parseBootstrapGlobalOptions(argv){const state={booleanFlags:new Set,outputValues:new Map,pathValues:new Map};let index=0;while(index<argv.length){if(argv[index]==="--")break;index+=consumeBootstrapGlobalToken(argv,index,state)}return{path:state.pathValues.get("--pm-path")??state.pathValues.get("--path"),noExtensions:state.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(parseBootstrapCommandPathName(argv)??""),noPager:state.booleanFlags.has("--no-pager"),json:state.booleanFlags.has("--json"),quiet:state.booleanFlags.has("--quiet"),lean:state.booleanFlags.has("--lean"),tokenAccounting:state.booleanFlags.has("--token-accounting"),...state.booleanFlags.has("--output-row-contract")?{outputRowContract:true}:{},...state.outputValues.get("--output-include")===void 0?{}:{outputInclude:state.outputValues.get("--output-include")},...state.outputValues.get("--output-limit")===void 0?{}:{outputLimit:state.outputValues.get("--output-limit")},...state.outputValues.get("--output-budget")===void 0?{}:{outputBudget:state.outputValues.get("--output-budget")},...state.outputValues.get("--output-format")==="toon"||state.outputValues.get("--output-format")==="json"?{outputFormat:state.outputValues.get("--output-format")}:{},...state.outputValues.get("--output-session")===void 0?{}:{outputSession:state.outputValues.get("--output-session")},...state.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:state.outputValues.get("--output-cursor")},...state.author===""?{authorMissingValue:true}:state.author!==void 0?{author:state.author}:{}}}function stripGlobalBootstrapTokens(argv){const remaining=[];let index=0;while(index<argv.length){const token=argv[index];if(token==="--"){break}if(BOOTSTRAP_BOOLEAN_FLAGS.has(token)||token==="--profile"||token==="--id-only"||token==="--full-changed-fields"||token==="--explain"){index+=1;continue}if(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)){index+=consumesBootstrapValue(token,argv[index+1])?2:1;continue}if(isInlineGlobalValueToken(token)){index+=1;continue}remaining.push(token);index+=1}return remaining}function parseBootstrapHelpRequest(argv){const stripped=stripGlobalBootstrapTokens(argv);const first=stripped[0]?.trim().toLowerCase();if(first==="help"){const commandPathTokens2=[];for(let index=1;index<stripped.length;index+=1){const token=stripped[index];if(token.startsWith("-")){break}commandPathTokens2.push(token.trim().toLowerCase())}return{requested:true,commandPathTokens:commandPathTokens2}}const helpFlagIndex=stripped.findIndex(token=>token==="--help"||token==="-h");if(helpFlagIndex<0){return{requested:false,commandPathTokens:[]}}const commandPathTokens=[];for(const token of stripped){if(token.startsWith("-")){break}commandPathTokens.push(token.trim().toLowerCase())}return{requested:true,commandPathTokens}}function findBootstrapCommandTokenIndex(argv){return findContractBootstrapCommandTokenIndex(argv)}function parseBootstrapCommandName(argv){return parseContractBootstrapCommandName(argv)}function shouldDisablePagerForInvocation(argv,bootstrapGlobal){if(bootstrapGlobal.noPager){return true}if(process.stdout.isTTY===true){return false}const helpRequest=parseBootstrapHelpRequest(argv);return helpRequest.requested}function applyBootstrapPagerPolicy(argv){const pagerEnvironmentKeys=["PAGER","MANPAGER","GIT_PAGER","LESS"];const previousValues=pagerEnvironmentKeys.map(key=>process.env[key]);const restore=()=>{for(const[index,key]of pagerEnvironmentKeys.entries()){const value=previousValues[index];if(value===void 0){delete process.env[key]}else{process.env[key]=value}}};const bootstrapGlobal=parseBootstrapGlobalOptions(argv);if(!shouldDisablePagerForInvocation(argv,bootstrapGlobal)){return restore}process.env.PAGER="cat";process.env.MANPAGER="cat";process.env.GIT_PAGER="cat";if(typeof process.env.LESS!=="string"||process.env.LESS.trim().length===0){process.env.LESS="FRX"}return restore}const EXTENSION_ACTION_SYNTAX_TOKENS=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function normalizeLegacyExtensionActionSyntax(argv){const extensionIndex=findBootstrapCommandTokenIndex(argv);if(extensionIndex===void 0||argv[extensionIndex]!=="extension"){return[...argv]}const actionToken=argv[extensionIndex+1];if(!actionToken||actionToken.startsWith("-")){return[...argv]}if(!EXTENSION_ACTION_SYNTAX_TOKENS.has(actionToken)){return[...argv]}if(argv.includes("--help")||argv.includes("-h")){return[...argv]}const forcedActionFlag=`--${actionToken}`;if(argv.includes(forcedActionFlag)){return[...argv]}return[...argv.slice(0,extensionIndex+1),forcedActionFlag,...argv.slice(extensionIndex+2)]}const CLI_EXECUTABLE_ALIASES=new Set(["pm","pm-cli"]);function stripLeadingExecutableAlias(argv,trace){const index=findBootstrapCommandTokenIndex(argv);if(index===void 0){return argv}const token=argv[index];if(!CLI_EXECUTABLE_ALIASES.has(token.trim().toLowerCase())){return argv}trace.push({from:token,to:[],reason:"executable_alias",confidence:"high"});return[...argv.slice(0,index),...argv.slice(index+1)]}function rewriteCommandAlias(argv,trace){let index=findBootstrapCommandTokenIndex(argv);if(index!==void 0&&argv[index]==="help"){const offset=findBootstrapCommandTokenIndex(argv.slice(index+1));index=offset===void 0?void 0:index+1+offset}if(index===void 0){return argv}const token=argv[index];const canonical=EXECUTABLE_COMMAND_ALIASES[token.trim().toLowerCase()];if(!canonical){return argv}const canonicalTokens=canonical.split(" ");const rewritten=[...argv.slice(0,index),...canonicalTokens,...argv.slice(index+1)];trace.push({from:token,to:canonicalTokens,reason:"command_alias",confidence:"high"});return rewritten}function normalizeFlagKeyToken(raw){const withoutPrefix=raw.replace(/^--?/,"");return withoutPrefix.replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function toComparableFlagKey(raw){return normalizeFlagKeyToken(raw).replace(/-/g,"")}function markUnambiguousFlag(map,key,canonicalFlag){const existing=map.get(key);if(existing===void 0){map.set(key,canonicalFlag);return}if(existing!==canonicalFlag){map.set(key,null)}}function collectLongFlagCandidates(contract){const candidates=[];const pushLongFlag=value=>{if(typeof value!=="string"){return}if(!value.startsWith("--")){return}candidates.push(value)};pushLongFlag(contract.flag);for(const alias of contract.aliases??[]){pushLongFlag(alias)}return candidates}function buildFlagLookup(commandName,contractsOverride){const contracts=contractsOverride??resolveSubcommandFlagContractsForCommand(commandName);const canonicalByNormalized=new Map;const canonicalByCompact=new Map;const canonicalComparablesMap=new Map;const listCanonicalFlags=new Set;for(const contract of contracts){const longCandidates=collectLongFlagCandidates(contract);if(longCandidates.length===0){continue}const canonicalFlag=`--${normalizeFlagKeyToken(longCandidates[0])}`;for(const candidate of longCandidates){markUnambiguousFlag(canonicalByNormalized,normalizeFlagKeyToken(candidate),canonicalFlag);markUnambiguousFlag(canonicalByCompact,toComparableFlagKey(candidate),canonicalFlag)}const comparable=toComparableFlagKey(canonicalFlag);if(!canonicalComparablesMap.has(canonicalFlag)){canonicalComparablesMap.set(canonicalFlag,comparable)}if(contract.list===true){listCanonicalFlags.add(canonicalFlag)}}return{canonicalByNormalized,canonicalByCompact,canonicalComparables:[...canonicalComparablesMap.entries()].map(([canonicalFlag,comparable])=>({canonicalFlag,comparable})),listCanonicalFlags}}function resolveCanonicalFlag(rawKey,lookup){const normalizedKey=normalizeFlagKeyToken(rawKey);const direct=lookup.canonicalByNormalized.get(normalizedKey);if(typeof direct==="string"){return{flag:direct,reason:"flag_alias",confidence:"high"}}const comparableKey=normalizedKey.replace(/-/g,"");const compactMatch=lookup.canonicalByCompact.get(comparableKey);if(typeof compactMatch==="string"){return{flag:compactMatch,reason:"flag_alias",confidence:"high"}}const maxDistance=comparableKey.length>=8?2:1;let bestDistance=Number.POSITIVE_INFINITY;let bestFlag;let tied=false;for(const candidate of lookup.canonicalComparables){const distance=levenshteinDistanceWithinLimit(comparableKey,candidate.comparable,maxDistance);if(distance===null){continue}if(distance<bestDistance){bestDistance=distance;bestFlag=candidate.canonicalFlag;tied=false;continue}if(distance===bestDistance&&bestFlag!==candidate.canonicalFlag){tied=true}}if(!bestFlag||tied||!Number.isFinite(bestDistance)||bestDistance<=0){return null}return{flag:bestFlag,reason:"flag_typo",confidence:bestDistance>=2?"medium":"high"}}function listAliasPluralKeys(normalizedKey){const candidates=[`${normalizedKey}s`];if(normalizedKey.endsWith("y")&&normalizedKey.length>1){candidates.push(`${normalizedKey.slice(0,-1)}ies`)}return candidates}function parseBareKeyValueToken(token,preserve=false){if(preserve||token.includes("://")){return null}const match=token.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!match){return null}const key=match[1];const value=match[3];if(value.length===0){return null}return{key,value}}function normalizeLongOptionToken(token,lookup,preserve=false){if(preserve||!token.startsWith("--")){return{tokens:[token]}}const equalsIndex=token.indexOf("=");const key=equalsIndex>=0?token.slice(0,equalsIndex):token;const inlineValue=equalsIndex>=0?token.slice(equalsIndex+1):void 0;const resolution=resolveCanonicalFlag(key,lookup);if(!resolution){return{tokens:[token]}}const normalizedToken=inlineValue===void 0?resolution.flag:`${resolution.flag}=${inlineValue}`;if(normalizedToken===token){return{tokens:[token]}}return{tokens:[normalizedToken],event:{from:token,to:[normalizedToken],reason:resolution.reason,confidence:resolution.confidence}}}function collectBootstrapPathValueIndices(argv){const indices=new Set;let expectsValue=false;for(let index=0;index<argv.length;index+=1){if(expectsValue){indices.add(index);expectsValue=false;continue}const token=argv[index];expectsValue=token==="--path"||token==="--pm-path"}return indices}function splitCanonicalListToken(token){if(!token.startsWith("--")){return null}const equalsIndex=token.indexOf("=");if(equalsIndex<0){return{flag:token}}return{flag:token.slice(0,equalsIndex),inlineValue:token.slice(equalsIndex+1)}}function copyValueConsumingFlag(argv,index,result){result.push(argv[index]);const next=argv[index+1];if(typeof next==="string"&&next!=="--"){result.push(next);return index+2}return index+1}function readListFlagOccurrence(argv,index,parsed,multiValueListFlags){if(parsed.inlineValue!==void 0){return{originalTokens:[argv[index]],value:parsed.inlineValue,consumed:1}}const values=[];let valueIndex=index+1;while(valueIndex<argv.length&&argv[valueIndex]!=="--"&&!argv[valueIndex].startsWith("-")&&(values.length===0||multiValueListFlags.has(parsed.flag))){values.push(argv[valueIndex]);valueIndex+=1}const consumed=values.length===0?1:1+values.length;return{originalTokens:argv.slice(index,index+consumed),value:values.length===0?void 0:values.join(","),consumed}}function recordListFlagOccurrence(slots,result,flag,occurrence){const existing=slots.get(flag);if(existing){existing.values.push(occurrence.value);existing.occurrences+=1;return}slots.set(flag,{outputIndex:result.length,originalTokens:occurrence.originalTokens,values:[occurrence.value],occurrences:1});result.push(null)}function buildListFlagCoalescingSplices(slots,multiValueListFlags){const events=[];const splices=[];for(const[flag,slot]of slots){const shouldMerge=slot.occurrences>=2||multiValueListFlags.has(flag)&&slot.originalTokens.length>2;if(!shouldMerge){splices.push({outputIndex:slot.outputIndex,tokens:slot.originalTokens});continue}const mergedToken=`${flag}=${slot.values.join(",")}`;splices.push({outputIndex:slot.outputIndex,tokens:[mergedToken]});events.push({from:`${flag} (x${slot.occurrences})`,to:[mergedToken],reason:"list_merge",confidence:"high"})}return{events,splices}}function applyListFlagSplices(result,splices){splices.sort((a,b)=>b.outputIndex-a.outputIndex);for(const splice of splices){result.splice(splice.outputIndex,1,...splice.tokens)}}function coalesceRepeatedListFlags(argv,listFlags,valueConsumingFlags=new Set,multiValueListFlags=new Set){if(listFlags.size===0){return{argv:[...argv],events:[]}}const result=[];const slots=new Map;let index=0;while(index<argv.length){const token=argv[index];if(token==="--"){result.push(...argv.slice(index));break}if(valueConsumingFlags.has(token)){index=copyValueConsumingFlag(argv,index,result);continue}const parsed=splitCanonicalListToken(token);if(!parsed||!listFlags.has(parsed.flag)){result.push(token);index+=1;continue}const occurrence=readListFlagOccurrence(argv,index,parsed,multiValueListFlags);if(occurrence.value===void 0){result.push(token);index+=occurrence.consumed;continue}recordListFlagOccurrence(slots,result,parsed.flag,{originalTokens:occurrence.originalTokens,value:occurrence.value});index+=occurrence.consumed}const{events,splices}=buildListFlagCoalescingSplices(slots,multiValueListFlags);applyListFlagSplices(result,splices);return{argv:result,events}}const LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function isLinkedTestTwoTokenValuePosition(commandName,emittedTokens){if(commandName!=="test"||emittedTokens.length<2){return false}const key=emittedTokens[emittedTokens.length-1];const flag=emittedTokens[emittedTokens.length-2];const keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(flag);return keys!==void 0&&keys.has(key)}function shouldPreserveBareKeyValueToken(commandName,emittedTokens){return commandName==="search"||isLinkedTestTwoTokenValuePosition(commandName,emittedTokens)}function mergeLinkedTestTwoTokenEntries(argv,commandName,trace){if(commandName!=="test"){return argv}const result=[];let index=0;while(index<argv.length){const token=argv[index];if(token==="--"){result.push(...argv.slice(index));return result}const keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(token);const key=keys?argv[index+1]:void 0;if(!keys||typeof key!=="string"||!keys.has(key)){result.push(token);index+=1;continue}let runEnd=index+2;while(runEnd<argv.length&&!argv[runEnd].startsWith("-")){runEnd+=1}if(runEnd-(index+2)!==1){result.push(token);index+=1;continue}const value=argv[index+2];const mergedValue=`${key}=${value}`;result.push(token,mergedValue);trace.push({from:`${token} ${key} ${value}`,to:[token,mergedValue],reason:"bare_key_value",confidence:"high"});index+=3}return result}function normalizeBootstrapTokens(argv,lookup,commandName,trace){const normalizedArgv=[];const pathValueIndices=collectBootstrapPathValueIndices(argv);for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--"){normalizedArgv.push(...argv.slice(index));break}const preserveCurrentToken=pathValueIndices.has(index);const previous=normalizedArgv[normalizedArgv.length-1];if(token.startsWith("--")){const normalizedToken=normalizeLongOptionToken(token,lookup,preserveCurrentToken);normalizedArgv.push(...normalizedToken.tokens);if(normalizedToken.event)trace.push(normalizedToken.event);continue}const bareKeyValue=parseBareKeyValueToken(token,preserveCurrentToken);if(bareKeyValue&&!(typeof previous==="string"&&previous.startsWith("-"))&&!shouldPreserveBareKeyValueToken(commandName,normalizedArgv)){const resolution=resolveCanonicalFlag(bareKeyValue.key,lookup);if(resolution){const replacement=[resolution.flag,bareKeyValue.value];normalizedArgv.push(...replacement);trace.push({from:token,to:replacement,reason:"bare_key_value",confidence:resolution.confidence});continue}}normalizedArgv.push(token)}return normalizedArgv}function bindAttestationVerification(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--verify"){const value=argv[index+1];if(value===void 0||value==="--")throw new PmCliError("history attest --verify requires a bundle file.",EXIT_CODE.USAGE);argv.splice(index,2,`--verify=${value}`)}else if(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)||token==="--output"||token==="--hash-algorithm"){index+=1}}}function normalizeBootstrapInvocation(argv){const trace=[];const executableNormalized=stripLeadingExecutableAlias(argv,trace);const legacyNormalized=normalizeLegacyExtensionActionSyntax(executableNormalized);if(legacyNormalized.length!==executableNormalized.length||legacyNormalized.some((token,index)=>token!==executableNormalized[index])){trace.push({from:executableNormalized.join(" "),to:[...legacyNormalized],reason:"legacy_extension_action",confidence:"high"})}const aliasNormalized=rewriteCommandAlias(legacyNormalized,trace);const itemAddress=normalizeItemAddressInvocation(aliasNormalized);if(itemAddress.conflict){throw new PmCliError("Provide the item id either positionally or with --id, not both.",EXIT_CODE.USAGE)}if(itemAddress.changed){trace.push({from:`--id ${itemAddress.itemId}`,to:[itemAddress.itemId],reason:"item_id_alias",confidence:"high"})}const commandName=parseBootstrapCommandName(itemAddress.argv);const commandPathName=parseBootstrapCommandPathName(itemAddress.argv);const lookup=buildFlagLookup(commandPathName??commandName);const normalizedArgv=normalizeBootstrapTokens(itemAddress.argv,lookup,commandName,trace);const linkedTestNormalized=mergeLinkedTestTwoTokenEntries(normalizedArgv,commandName,trace);const coalesced=coalesceRepeatedListFlags(linkedTestNormalized,lookup.listCanonicalFlags,GLOBAL_VALUE_CONSUMING_FLAGS,commandName==="create"?new Set(["--tags"]):new Set);for(const event of coalesced.events){trace.push(event)}if(commandPathName==="history attest")bindAttestationVerification(coalesced.argv);return{argv:coalesced.argv,commandName,trace}}function parseBootstrapCommandPathName(argv){const stripped=stripGlobalBootstrapTokens(argv);const first=stripped[0]?.trim().toLowerCase();const second=stripped[1]?.trim().toLowerCase();const namespaced=findPmNamespacedCommand(stripped);if(namespaced)return namespaced.canonical;if((first==="extension"||first==="package"||first==="packages")&&typeof second==="string"&&second.length>0&&!second.startsWith("-")){return`${first} ${second}`}return first}function parseBootstrapTypeValue(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--"){break}if(token==="--type"){const candidate=argv[index+1];if(typeof candidate==="string"&&candidate.trim().length>0){return candidate.trim()}continue}if(token.startsWith("--type=")){const candidate=token.slice("--type=".length).trim();if(candidate.length>0){return candidate}}}return void 0}const _testOnly={buildFlagLookup,collectBootstrapPathValueIndices,collectLongFlagCandidates,markUnambiguousFlag,normalizeLongOptionToken,resolveCanonicalFlag};export{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,_testOnly,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,findBootstrapCommandTokenIndex,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,stripGlobalBootstrapTokens};
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8ef3b254-0494-57bc-8bbf-8ee58eb7d152")}catch(e2){}})();import{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias}from"./cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand}from"./cli-contracts/flag-contracts.js";import{levenshteinDistanceWithinLimit}from"../core/shared/levenshtein.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{findPmNamespacedCommand,resolvePmCommandOperation}from"./cli-contracts/command-aliases.js";import{normalizeItemAddressInvocation}from"./agent/item-addressing.js";import{BOOTSTRAP_BOOLEAN_FLAGS,GLOBAL_VALUE_CONSUMING_FLAGS,consumesBootstrapValue,findBootstrapCommandTokenIndex as findContractBootstrapCommandTokenIndex,isInlineGlobalValueToken,parseBootstrapCommandName as parseContractBootstrapCommandName}from"./cli-contracts/bootstrap-command-scanner.js";const OUTPUT_VALUE_FLAGS=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]);function consumeBootstrapGlobalToken(argv,index,state){const token=argv[index];if(BOOTSTRAP_BOOLEAN_FLAGS.has(token)){state.booleanFlags.add(token);return 1}const equalsIndex=token.indexOf("=");const canonicalFlag=equalsIndex>0?token.slice(0,equalsIndex):token;if(!GLOBAL_VALUE_CONSUMING_FLAGS.has(canonicalFlag))return 1;const inlineValue=equalsIndex>0?token.slice(equalsIndex+1):void 0;const consumesValue=inlineValue===void 0&&consumesBootstrapValue(canonicalFlag,argv[index+1]);const value=inlineValue??(consumesValue?argv[index+1]:void 0);if(canonicalFlag==="--author"){state.author=value??""}else if(typeof value==="string"&&value.length>0){const target=OUTPUT_VALUE_FLAGS.has(canonicalFlag)?state.outputValues:state.pathValues;target.set(canonicalFlag,value)}return consumesValue?2:1}function parseBootstrapGlobalOptions(argv){const state={booleanFlags:new Set,outputValues:new Map,pathValues:new Map};let index=0;while(index<argv.length){if(argv[index]==="--")break;index+=consumeBootstrapGlobalToken(argv,index,state)}return{path:state.pathValues.get("--pm-path")??state.pathValues.get("--path"),noExtensions:state.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(parseBootstrapCommandPathName(argv)??""),noPager:state.booleanFlags.has("--no-pager"),json:state.booleanFlags.has("--json"),quiet:state.booleanFlags.has("--quiet"),lean:state.booleanFlags.has("--lean"),tokenAccounting:state.booleanFlags.has("--token-accounting"),...state.booleanFlags.has("--output-row-contract")?{outputRowContract:true}:{},...state.outputValues.get("--output-include")===void 0?{}:{outputInclude:state.outputValues.get("--output-include")},...state.outputValues.get("--output-limit")===void 0?{}:{outputLimit:state.outputValues.get("--output-limit")},...state.outputValues.get("--output-budget")===void 0?{}:{outputBudget:state.outputValues.get("--output-budget")},...state.outputValues.get("--output-format")==="toon"||state.outputValues.get("--output-format")==="json"?{outputFormat:state.outputValues.get("--output-format")}:{},...state.outputValues.get("--output-session")===void 0?{}:{outputSession:state.outputValues.get("--output-session")},...state.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:state.outputValues.get("--output-cursor")},...state.author===""?{authorMissingValue:true}:state.author!==void 0?{author:state.author}:{}}}function stripGlobalBootstrapTokens(argv){const remaining=[];let index=0;while(index<argv.length){const token=argv[index];if(token==="--"){break}if(BOOTSTRAP_BOOLEAN_FLAGS.has(token)||token==="--profile"||token==="--id-only"||token==="--full-changed-fields"||token==="--explain"){index+=1;continue}if(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)){index+=consumesBootstrapValue(token,argv[index+1])?2:1;continue}if(isInlineGlobalValueToken(token)){index+=1;continue}remaining.push(token);index+=1}return remaining}function parseBootstrapHelpRequest(argv){const stripped=stripGlobalBootstrapTokens(argv);const first=stripped[0]?.trim().toLowerCase();if(first==="help"){const commandPathTokens2=[];for(let index=1;index<stripped.length;index+=1){const token=stripped[index];if(token.startsWith("-")){break}commandPathTokens2.push(token.trim().toLowerCase())}return{requested:true,commandPathTokens:commandPathTokens2}}const helpFlagIndex=stripped.findIndex(token=>token==="--help"||token==="-h");if(helpFlagIndex<0){return{requested:false,commandPathTokens:[]}}const commandPathTokens=[];for(const token of stripped){if(token.startsWith("-")){break}commandPathTokens.push(token.trim().toLowerCase())}return{requested:true,commandPathTokens}}function findBootstrapCommandTokenIndex(argv){return findContractBootstrapCommandTokenIndex(argv)}function parseBootstrapCommandName(argv){return parseContractBootstrapCommandName(argv)}function shouldDisablePagerForInvocation(argv,bootstrapGlobal){if(bootstrapGlobal.noPager){return true}if(process.stdout.isTTY===true){return false}const helpRequest=parseBootstrapHelpRequest(argv);return helpRequest.requested}function applyBootstrapPagerPolicy(argv){const pagerEnvironmentKeys=["PAGER","MANPAGER","GIT_PAGER","LESS"];const previousValues=pagerEnvironmentKeys.map(key=>process.env[key]);const restore=()=>{for(const[index,key]of pagerEnvironmentKeys.entries()){const value=previousValues[index];if(value===void 0){delete process.env[key]}else{process.env[key]=value}}};const bootstrapGlobal=parseBootstrapGlobalOptions(argv);if(!shouldDisablePagerForInvocation(argv,bootstrapGlobal)){return restore}process.env.PAGER="cat";process.env.MANPAGER="cat";process.env.GIT_PAGER="cat";if(typeof process.env.LESS!=="string"||process.env.LESS.trim().length===0){process.env.LESS="FRX"}return restore}const EXTENSION_ACTION_SYNTAX_TOKENS=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function normalizeLegacyExtensionActionSyntax(argv){const extensionIndex=findBootstrapCommandTokenIndex(argv);if(extensionIndex===void 0||argv[extensionIndex]!=="extension"){return[...argv]}const actionToken=argv[extensionIndex+1];if(!actionToken||actionToken.startsWith("-")){return[...argv]}if(!EXTENSION_ACTION_SYNTAX_TOKENS.has(actionToken)){return[...argv]}if(argv.includes("--help")||argv.includes("-h")){return[...argv]}const forcedActionFlag=`--${actionToken}`;if(argv.includes(forcedActionFlag)){return[...argv]}return[...argv.slice(0,extensionIndex+1),forcedActionFlag,...argv.slice(extensionIndex+2)]}const CLI_EXECUTABLE_ALIASES=new Set(["pm","pm-cli"]);function stripLeadingExecutableAlias(argv,trace){const index=findBootstrapCommandTokenIndex(argv);if(index===void 0){return argv}const token=argv[index];if(!CLI_EXECUTABLE_ALIASES.has(token.trim().toLowerCase())){return argv}trace.push({from:token,to:[],reason:"executable_alias",confidence:"high"});return[...argv.slice(0,index),...argv.slice(index+1)]}function rewriteCommandAlias(argv,trace){let index=findBootstrapCommandTokenIndex(argv);if(index!==void 0&&argv[index]==="help"){const offset=findBootstrapCommandTokenIndex(argv.slice(index+1));index=offset===void 0?void 0:index+1+offset}if(index===void 0){return argv}const token=argv[index];const canonical=EXECUTABLE_COMMAND_ALIASES[token.trim().toLowerCase()];if(!canonical){return argv}const canonicalTokens=canonical.split(" ");const rewritten=[...argv.slice(0,index),...canonicalTokens,...argv.slice(index+1)];trace.push({from:token,to:canonicalTokens,reason:"command_alias",confidence:"high"});return rewritten}function normalizeFlagKeyToken(raw){const withoutPrefix=raw.replace(/^--?/,"");return withoutPrefix.replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function toComparableFlagKey(raw){return normalizeFlagKeyToken(raw).replace(/-/g,"")}function markUnambiguousFlag(map,key,canonicalFlag){const existing=map.get(key);if(existing===void 0){map.set(key,canonicalFlag);return}if(existing!==canonicalFlag){map.set(key,null)}}function collectLongFlagCandidates(contract){const candidates=[];const pushLongFlag=value=>{if(typeof value!=="string"){return}if(!value.startsWith("--")){return}candidates.push(value)};pushLongFlag(contract.flag);for(const alias of contract.aliases??[]){pushLongFlag(alias)}return candidates}function buildFlagLookup(commandName,contractsOverride){const contracts=contractsOverride??resolveSubcommandFlagContractsForCommand(commandName);const canonicalByNormalized=new Map;const canonicalByCompact=new Map;const canonicalComparablesMap=new Map;const listCanonicalFlags=new Set;for(const contract of contracts){const longCandidates=collectLongFlagCandidates(contract);if(longCandidates.length===0){continue}const canonicalFlag=`--${normalizeFlagKeyToken(longCandidates[0])}`;for(const candidate of longCandidates){markUnambiguousFlag(canonicalByNormalized,normalizeFlagKeyToken(candidate),canonicalFlag);markUnambiguousFlag(canonicalByCompact,toComparableFlagKey(candidate),canonicalFlag)}const comparable=toComparableFlagKey(canonicalFlag);if(!canonicalComparablesMap.has(canonicalFlag)){canonicalComparablesMap.set(canonicalFlag,comparable)}if(contract.list===true){listCanonicalFlags.add(canonicalFlag)}}return{canonicalByNormalized,canonicalByCompact,canonicalComparables:[...canonicalComparablesMap.entries()].map(([canonicalFlag,comparable])=>({canonicalFlag,comparable})),listCanonicalFlags}}function resolveCanonicalFlag(rawKey,lookup){const normalizedKey=normalizeFlagKeyToken(rawKey);const direct=lookup.canonicalByNormalized.get(normalizedKey);if(typeof direct==="string"){return{flag:direct,reason:"flag_alias",confidence:"high"}}const comparableKey=normalizedKey.replace(/-/g,"");const compactMatch=lookup.canonicalByCompact.get(comparableKey);if(typeof compactMatch==="string"){return{flag:compactMatch,reason:"flag_alias",confidence:"high"}}const maxDistance=comparableKey.length>=8?2:1;let bestDistance=Number.POSITIVE_INFINITY;let bestFlag;let tied=false;for(const candidate of lookup.canonicalComparables){const distance=levenshteinDistanceWithinLimit(comparableKey,candidate.comparable,maxDistance);if(distance===null){continue}if(distance<bestDistance){bestDistance=distance;bestFlag=candidate.canonicalFlag;tied=false;continue}if(distance===bestDistance&&bestFlag!==candidate.canonicalFlag){tied=true}}if(!bestFlag||tied||!Number.isFinite(bestDistance)||bestDistance<=0){return null}return{flag:bestFlag,reason:"flag_typo",confidence:bestDistance>=2?"medium":"high"}}function listAliasPluralKeys(normalizedKey){const candidates=[`${normalizedKey}s`];if(normalizedKey.endsWith("y")&&normalizedKey.length>1){candidates.push(`${normalizedKey.slice(0,-1)}ies`)}return candidates}function parseBareKeyValueToken(token,preserve=false){if(preserve||token.includes("://")){return null}const match=token.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!match){return null}const key=match[1];const value=match[3];if(value.length===0){return null}return{key,value}}function normalizeLongOptionToken(token,lookup,preserve=false){if(preserve||!token.startsWith("--")){return{tokens:[token]}}const equalsIndex=token.indexOf("=");const key=equalsIndex>=0?token.slice(0,equalsIndex):token;const inlineValue=equalsIndex>=0?token.slice(equalsIndex+1):void 0;const resolution=resolveCanonicalFlag(key,lookup);if(!resolution){return{tokens:[token]}}const normalizedToken=inlineValue===void 0?resolution.flag:`${resolution.flag}=${inlineValue}`;if(normalizedToken===token){return{tokens:[token]}}return{tokens:[normalizedToken],event:{from:token,to:[normalizedToken],reason:resolution.reason,confidence:resolution.confidence}}}function collectBootstrapPathValueIndices(argv){const indices=new Set;let expectsValue=false;for(let index=0;index<argv.length;index+=1){if(expectsValue){indices.add(index);expectsValue=false;continue}const token=argv[index];expectsValue=token==="--path"||token==="--pm-path"}return indices}function splitCanonicalListToken(token){if(!token.startsWith("--")){return null}const equalsIndex=token.indexOf("=");if(equalsIndex<0){return{flag:token}}return{flag:token.slice(0,equalsIndex),inlineValue:token.slice(equalsIndex+1)}}function copyValueConsumingFlag(argv,index,result){result.push(argv[index]);const next=argv[index+1];if(typeof next==="string"&&next!=="--"){result.push(next);return index+2}return index+1}function readListFlagOccurrence(argv,index,parsed,multiValueListFlags){if(parsed.inlineValue!==void 0){return{originalTokens:[argv[index]],value:parsed.inlineValue,consumed:1}}const values=[];let valueIndex=index+1;while(valueIndex<argv.length&&argv[valueIndex]!=="--"&&!argv[valueIndex].startsWith("-")&&(values.length===0||multiValueListFlags.has(parsed.flag))){values.push(argv[valueIndex]);valueIndex+=1}const consumed=values.length===0?1:1+values.length;return{originalTokens:argv.slice(index,index+consumed),value:values.length===0?void 0:values.join(","),consumed}}function recordListFlagOccurrence(slots,result,flag,occurrence){const existing=slots.get(flag);if(existing){existing.values.push(occurrence.value);existing.occurrences+=1;return}slots.set(flag,{outputIndex:result.length,originalTokens:occurrence.originalTokens,values:[occurrence.value],occurrences:1});result.push(null)}function buildListFlagCoalescingSplices(slots,multiValueListFlags){const events=[];const splices=[];for(const[flag,slot]of slots){const shouldMerge=slot.occurrences>=2||multiValueListFlags.has(flag)&&slot.originalTokens.length>2;if(!shouldMerge){splices.push({outputIndex:slot.outputIndex,tokens:slot.originalTokens});continue}const mergedToken=`${flag}=${slot.values.join(",")}`;splices.push({outputIndex:slot.outputIndex,tokens:[mergedToken]});events.push({from:`${flag} (x${slot.occurrences})`,to:[mergedToken],reason:"list_merge",confidence:"high"})}return{events,splices}}function applyListFlagSplices(result,splices){splices.sort((a,b)=>b.outputIndex-a.outputIndex);for(const splice of splices){result.splice(splice.outputIndex,1,...splice.tokens)}}function coalesceRepeatedListFlags(argv,listFlags,valueConsumingFlags=new Set,multiValueListFlags=new Set){if(listFlags.size===0){return{argv:[...argv],events:[]}}const result=[];const slots=new Map;let index=0;while(index<argv.length){const token=argv[index];if(token==="--"){result.push(...argv.slice(index));break}if(valueConsumingFlags.has(token)){index=copyValueConsumingFlag(argv,index,result);continue}const parsed=splitCanonicalListToken(token);if(!parsed||!listFlags.has(parsed.flag)){result.push(token);index+=1;continue}const occurrence=readListFlagOccurrence(argv,index,parsed,multiValueListFlags);if(occurrence.value===void 0){result.push(token);index+=occurrence.consumed;continue}recordListFlagOccurrence(slots,result,parsed.flag,{originalTokens:occurrence.originalTokens,value:occurrence.value});index+=occurrence.consumed}const{events,splices}=buildListFlagCoalescingSplices(slots,multiValueListFlags);applyListFlagSplices(result,splices);return{argv:result,events}}const LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function isLinkedTestTwoTokenValuePosition(commandName,emittedTokens){if(commandName!=="test"||emittedTokens.length<2){return false}const key=emittedTokens[emittedTokens.length-1];const flag=emittedTokens[emittedTokens.length-2];const keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(flag);return keys!==void 0&&keys.has(key)}function shouldPreserveBareKeyValueToken(commandName,emittedTokens){return commandName==="search"||isLinkedTestTwoTokenValuePosition(commandName,emittedTokens)}function mergeLinkedTestTwoTokenEntries(argv,commandName,trace){if(commandName!=="test"){return argv}const result=[];let index=0;while(index<argv.length){const token=argv[index];if(token==="--"){result.push(...argv.slice(index));return result}const keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(token);const key=keys?argv[index+1]:void 0;if(!keys||typeof key!=="string"||!keys.has(key)){result.push(token);index+=1;continue}let runEnd=index+2;while(runEnd<argv.length&&!argv[runEnd].startsWith("-")){runEnd+=1}if(runEnd-(index+2)!==1){result.push(token);index+=1;continue}const value=argv[index+2];const mergedValue=`${key}=${value}`;result.push(token,mergedValue);trace.push({from:`${token} ${key} ${value}`,to:[token,mergedValue],reason:"bare_key_value",confidence:"high"});index+=3}return result}function normalizeBootstrapTokens(argv,lookup,commandName,trace){const normalizedArgv=[];const pathValueIndices=collectBootstrapPathValueIndices(argv);for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--"){normalizedArgv.push(...argv.slice(index));break}const preserveCurrentToken=pathValueIndices.has(index);const previous=normalizedArgv[normalizedArgv.length-1];if(token.startsWith("--")){const normalizedToken=normalizeLongOptionToken(token,lookup,preserveCurrentToken);normalizedArgv.push(...normalizedToken.tokens);if(normalizedToken.event)trace.push(normalizedToken.event);continue}const bareKeyValue=parseBareKeyValueToken(token,preserveCurrentToken);if(bareKeyValue&&!(typeof previous==="string"&&previous.startsWith("-"))&&!shouldPreserveBareKeyValueToken(commandName,normalizedArgv)){const resolution=resolveCanonicalFlag(bareKeyValue.key,lookup);if(resolution){const replacement=[resolution.flag,bareKeyValue.value];normalizedArgv.push(...replacement);trace.push({from:token,to:replacement,reason:"bare_key_value",confidence:resolution.confidence});continue}}normalizedArgv.push(token)}return normalizedArgv}function bindAttestationVerification(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--verify"){const value=argv[index+1];if(value===void 0||value==="--")throw new PmCliError("history attest --verify requires a bundle file.",EXIT_CODE.USAGE);argv.splice(index,2,`--verify=${value}`)}else if(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)||token==="--output"||token==="--hash-algorithm"){index+=1}}}function normalizeBootstrapInvocation(argv){const trace=[];const executableNormalized=stripLeadingExecutableAlias(argv,trace);const legacyNormalized=normalizeLegacyExtensionActionSyntax(executableNormalized);if(legacyNormalized.length!==executableNormalized.length||legacyNormalized.some((token,index)=>token!==executableNormalized[index])){trace.push({from:executableNormalized.join(" "),to:[...legacyNormalized],reason:"legacy_extension_action",confidence:"high"})}const aliasNormalized=rewriteCommandAlias(legacyNormalized,trace);const itemAddress=normalizeItemAddressInvocation(aliasNormalized);if(itemAddress.conflict){throw new PmCliError("Provide the item id either positionally or with --id, not both.",EXIT_CODE.USAGE)}if(itemAddress.changed){trace.push({from:`--id ${itemAddress.itemId}`,to:[itemAddress.itemId],reason:"item_id_alias",confidence:"high"})}const commandName=parseBootstrapCommandName(itemAddress.argv);const commandPathName=parseBootstrapCommandPathName(itemAddress.argv);const operationName=resolvePmCommandOperation(commandPathName??commandName??"");const lookup=buildFlagLookup(commandPathName??commandName);const normalizedArgv=normalizeBootstrapTokens(itemAddress.argv,lookup,operationName,trace);const linkedTestNormalized=mergeLinkedTestTwoTokenEntries(normalizedArgv,operationName,trace);const coalesced=coalesceRepeatedListFlags(linkedTestNormalized,lookup.listCanonicalFlags,GLOBAL_VALUE_CONSUMING_FLAGS,commandName==="create"?new Set(["--tags"]):new Set);for(const event of coalesced.events){trace.push(event)}if(commandPathName==="history attest")bindAttestationVerification(coalesced.argv);return{argv:coalesced.argv,commandName,trace}}function parseBootstrapCommandPathName(argv){const stripped=stripGlobalBootstrapTokens(argv);const first=stripped[0]?.trim().toLowerCase();const second=stripped[1]?.trim().toLowerCase();const namespaced=findPmNamespacedCommand(stripped);if(namespaced)return namespaced.canonical;if((first==="extension"||first==="package"||first==="packages")&&typeof second==="string"&&second.length>0&&!second.startsWith("-")){return`${first} ${second}`}return first}function parseBootstrapTypeValue(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--"){break}if(token==="--type"){const candidate=argv[index+1];if(typeof candidate==="string"&&candidate.trim().length>0){return candidate.trim()}continue}if(token.startsWith("--type=")){const candidate=token.slice("--type=".length).trim();if(candidate.length>0){return candidate}}}return void 0}const _testOnly={buildFlagLookup,collectBootstrapPathValueIndices,collectLongFlagCandidates,markUnambiguousFlag,normalizeLongOptionToken,resolveCanonicalFlag};export{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,_testOnly,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,findBootstrapCommandTokenIndex,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,stripGlobalBootstrapTokens};
|
|
2
2
|
//# sourceMappingURL=cli-bootstrap.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4f0a2e76-6e07-579b-9d9b-1abbe7e5019b")}catch(e2){}})();const PM_HISTORY_COMMAND_ALIASES=[["history-redact","history redact"],["history-repair","history repair"],["history-compact","history compact"],["activity","history activity"],["restore","history restore"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"permanent",hidden:true,registration:"commander",owner:"pm-tqel"}));const PM_CONTEXT_OPS_COMMAND_ALIASES=[...["next","focus"].map(alias=>({alias,canonical:`context ${alias}`,owner:"pm-kcs4"})),...["stats","health","validate","gc","telemetry","eval","test-all"].map(alias=>({alias,canonical:`ops ${alias}`,owner:"pm-6apl"})),...["normalize","reindex"].map(alias=>({alias,canonical:`ops ${alias}`,owner:"pm-3i9q8g"})),{alias:"events",canonical:"history events",owner:"pm-3i9q8g"}].map(entry=>({...entry,canonical_argv:entry.canonical.split(" "),lifecycle:"permanent",hidden:true,registration:"bootstrap"}));const PM_BULK_LIFECYCLE_COMMAND_ALIASES=[["update-many","update many"],["close-many","close many"],["delete","close delete"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"permanent",hidden:true,registration:"bootstrap",owner:"pm-ik19"}));const PM_RELOCATED_COMMAND_ALIASES=[...PM_CONTEXT_OPS_COMMAND_ALIASES,...PM_BULK_LIFECYCLE_COMMAND_ALIASES,...[...["comments","notes","learnings","files","docs","deps","append","test"].map(facet=>[facet,`item ${facet}`,"pm-yql1"]),["test-runs-worker","item test worker","pm-lp4j"],...["statuses","tags","types"].map(facet=>[`completion-${facet}`,`completion ${facet}`,"pm-szdc"]),["history-author-acknowledge","history acknowledge","pm-djyvbk"],["copy","item copy","pm-m6g87m"],["merge","workspace merge","pm-m6g87m"],["duplicates","item duplicates","pm-fmy9ih"],["dedupe-audit","item duplicates audit","pm-fmy9ih"],["dedupe-merge","item duplicates merge","pm-fmy9ih"],["comments-audit","item audit-comments","pm-fmy9ih"],["search-advanced","search advanced","pm-wfskfn"]].map(([alias,canonical,owner])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"permanent",hidden:true,registration:"bootstrap",owner}))];const PM_NAMESPACED_COMMAND_ALIASES=[{alias:"history-attest",canonical:"history attest",canonical_argv:["history","attest"],lifecycle:"permanent",hidden:true,registration:"commander",owner:"pm-3z0k"},...PM_HISTORY_COMMAND_ALIASES,...PM_RELOCATED_COMMAND_ALIASES,...["discover","lookup"].map(action=>({alias:`files ${action}`,canonical:`item files ${action}`,canonical_argv:["item","files",action],lifecycle:"permanent",hidden:true,registration:"bootstrap",owner:"pm-yql1"}))];function findPmNamespacedCommand(tokens){let matched;for(const alias of PM_NAMESPACED_COMMAND_ALIASES){if(alias.canonical_argv.length<=(matched?.canonical_argv.length??0))continue;if(alias.canonical_argv.every((token,index)=>token===(index===0&&tokens[index]==="ctx"?"context":tokens[index])))matched=alias}return matched}function resolvePmCommandOperation(command){const normalized=command.trim().replace(/\s+/gu," ");return PM_NAMESPACED_COMMAND_ALIASES.find(alias=>alias.canonical===normalized.replace(/^ctx /u,"context "))?.alias??normalized}function resolvePmHistoryOperation(command){return resolvePmCommandOperation(command)}const PM_COMMAND_ALIAS_CONTRACTS=[...PM_NAMESPACED_COMMAND_ALIASES,...[["ctx","context"],["packages","package"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:[canonical],lifecycle:"permanent",hidden:false,registration:"commander",owner:"pm-pbyu"})),...[["start-task","claim","--start"],["pause-task","release","--pause"],["close-task","close","--release-assignment"]].map(([alias,canonical,flag])=>({alias,canonical,canonical_argv:[canonical,flag],lifecycle:"deprecated",hidden:true,registration:"commander",owner:"pm-eq4x"})),{alias:"tests",canonical:"item test",canonical_argv:["item","test"],lifecycle:"permanent",hidden:false,registration:"bootstrap",owner:"pm-u4t9gp"},...[["fetch","get"],["read","get"],["show","get"],["view","get"],["comment","comments"],["note","notes"],["learning","learnings"]].map(([alias,canonical])=>({alias,canonical:["comments","notes","learnings"].includes(canonical)?`item ${canonical}`:canonical,canonical_argv:["comments","notes","learnings"].includes(canonical)?["item",canonical]:[canonical],lifecycle:"permanent",hidden:false,registration:"bootstrap",owner:"pm-pbyu"})),...[["extension list","extension catalog"],["extension scaffold","extension init"],["package list","package catalog"],["package scaffold","package init"],["packages list","packages catalog"],["packages scaffold","packages init"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"permanent",hidden:false,registration:"commander",owner:"pm-ya7x55"})),{alias:"list-all",canonical:"list",canonical_argv:["list","--all"],lifecycle:"deprecated",hidden:true,registration:"commander",owner:"pm-pfqi"},...[["list-draft","draft"],["list-open","open"],["list-in-progress","in_progress"],["list-blocked","blocked"],["list-closed","closed"],["list-canceled","canceled"]].map(([alias,status])=>({alias,canonical:"list",canonical_argv:["list","--status",status],lifecycle:"deprecated",hidden:true,registration:"commander",owner:"pm-pfqi"})),...[["extension","package"],["install","package install"],["upgrade","package upgrade"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"deprecated",hidden:true,registration:"commander",owner:"pm-tnud"}))];const EXECUTABLE_COMMAND_ALIASES=Object.fromEntries(PM_COMMAND_ALIAS_CONTRACTS.filter(contract=>contract.registration==="bootstrap").map(contract=>[contract.alias,contract.canonical]));function resolvePmCommandAlias(alias){const normalized=alias.trim().toLowerCase();return PM_COMMAND_ALIAS_CONTRACTS.find(contract=>contract.alias===normalized)}function renderPmCommandAliasMigrationHint(contract){return`Deprecated command \`${contract.alias}\`; use \`pm ${contract.canonical_argv.join(" ")}\`.`}export{EXECUTABLE_COMMAND_ALIASES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_HISTORY_COMMAND_ALIASES,PM_NAMESPACED_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,findPmNamespacedCommand,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,resolvePmCommandOperation,resolvePmHistoryOperation};
|
|
2
2
|
//# sourceMappingURL=command-aliases.js.map
|