@unbrained/pm-cli 2026.9.14 → 2026.9.16
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 +64 -0
- package/dist/cli/error-guidance.d.ts +1 -1
- package/dist/cli/error-guidance.js +1 -1
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +147 -147
- package/dist/cli-bundle/chunks/{chunk-B6W5LIXK.js → chunk-3UXLVJIM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XEV7BHH3.js → chunk-A5EKLGOU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D5AJQU7F.js → chunk-C3MFMGCR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-A2Q64TGR.js → chunk-CPFBDM53.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DBHQIS6Z.js → chunk-DLVCGXO6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5JIJAWIF.js → chunk-GA73HHQG.js} +19 -19
- package/dist/cli-bundle/chunks/{chunk-ZYRN2OG3.js → chunk-GX5XSANL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-O7SRS7Y3.js → chunk-LD2FH2YE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NYE6EREL.js → chunk-PTMZALZM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GQMILIC5.js → chunk-Q6KPZGMP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BY3ID7QI.js → chunk-T526C5DX.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-UJSB6NO6.js +237 -0
- package/dist/cli-bundle/chunks/{register-list-query-B2U36YWL.js → register-list-query-ISM35VIX.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-GX42CQYR.js → register-mutation-PA5M3X77.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-ZV34KX5E.js → register-operations-MBSG5D22.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-W4OS7IZW.js → register-setup-S6MMYN4D.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZFNRD7EN.js → chunk-267N774W.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-O4EROPO3.js → chunk-5FSGN4MP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-6WZBO4VQ.js → chunk-5KYHDFDN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UFSMYVZF.js → chunk-7S7XWMXC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FHQLQOUZ.js → chunk-BFUXTNZU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-CPQQIVDL.js → chunk-G4TKJZ4A.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GKSAMNBG.js +20 -0
- package/dist/cli-bundle/focused-chunks/{chunk-N23WTRCC.js → chunk-JZSLDLR4.js} +20 -20
- package/dist/cli-bundle/focused-chunks/{chunk-LFGTCEHX.js → chunk-LNM3BS45.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FNLAQJES.js → chunk-NOK652OP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-7BUJABHB.js → chunk-OCTTDZOU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-D4FQV6TY.js → chunk-OWDDVMAP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ENJH7CBZ.js → chunk-SSG62L7U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KWP3QTN7.js → chunk-WHL5CQG3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-C5NQVXKE.js → chunk-WUMGGQYN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GGDO6VBT.js → chunk-Z4PWEIMX.js} +21 -21
- package/dist/cli-bundle/main.js +11 -10
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +2 -2
- 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 +40 -40
- 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 +2 -2
- package/dist/core/extensions/index.d.ts +7 -0
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/lock/lock.js +2 -2
- package/dist/core/store/tracker-preflight.js +1 -1
- package/dist/core/telemetry/policy.d.ts +2 -0
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/read-sampling.d.ts +8 -0
- package/dist/core/telemetry/read-sampling.js +3 -0
- package/dist/core/telemetry/runtime.js +2 -2
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/init.d.ts +22 -1
- package/dist/sdk/init.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/read-output-budget.d.ts +2 -0
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.d.ts +4 -0
- package/dist/sdk/read-output-contracts.js +1 -1
- package/docs/CONFIGURATION.md +6 -2
- package/docs/QUICKSTART.md +16 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +14 -0
- package/marketplace.json +2 -2
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/dist/cli-bundle/chunks/chunk-33PER336.js +0 -236
- package/dist/cli-bundle/focused-chunks/chunk-CMCSUANO.js +0 -20
|
@@ -38,6 +38,13 @@ export declare function resetActiveExtensionRuntimeState(): void;
|
|
|
38
38
|
export declare function setActiveCommandContext(context: Omit<CommandOverrideContext, "result"> | null): void;
|
|
39
39
|
/** Return a defensive snapshot of the current invocation's command context. */
|
|
40
40
|
export declare function getActiveCommandContext(): Omit<CommandOverrideContext, "result"> | null;
|
|
41
|
+
/**
|
|
42
|
+
* Prove that the active command has no extension execution surface. Unrelated
|
|
43
|
+
* command registrations are harmless; hooks, services, renderers, migrations,
|
|
44
|
+
* and matching handlers/parsers make ownership uncertain and fail closed.
|
|
45
|
+
* Snapshot this predicate before entering an isolated infrastructure context.
|
|
46
|
+
*/
|
|
47
|
+
export declare function isActiveCommandUnextended(command: string): boolean;
|
|
41
48
|
/** Implements set active command result for the public runtime surface of this module. */
|
|
42
49
|
export declare function setActiveCommandResult(result: unknown): void;
|
|
43
50
|
/** Implements get active command result for the public runtime surface of this module. */
|
|
@@ -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]="0989270e-6969-5059-b3df-06411211f701")}catch(e2){}})();import{existsSync}from"node:fs";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";import{runCommandHandler,runBeforeMutationHooks,runCommandOverride,runOnIndexHooks,runParserOverride,runPreflightOverride,runOnReadHooks,runRendererOverride,runServiceOverride,runServiceOverrideSync,runOnWriteHooks}from"./loader.js";let activeExtensionHooks=null;let activeExtensionCommands=null;let activeExtensionParsers=null;let activeExtensionPreflight=null;let activeExtensionServices=null;let activeExtensionRenderers=null;let activeExtensionRegistrations=null;let activeCommandContext=null;let activeCommandResult=void 0;let activeAfterCommandAffectedItems=[];const isolatedExtensionRuntime=new AsyncLocalStorage;function runtimeState(){return isolatedExtensionRuntime.getStore()}function runWithIsolatedExtensionRuntime(run){return isolatedExtensionRuntime.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},run)}const AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function findSourceRepositoryRoot(candidate){let cursor=path.resolve(candidate);while(true){if(existsSync(path.join(cursor,".git"))){return cursor}const parent=path.dirname(cursor);if(parent===cursor){return void 0}cursor=parent}}function resolvePortableWorkspaceContext(pmRoot){const sourceCandidate=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd();const sourceWorkspaceRoot=findSourceRepositoryRoot(sourceCandidate)??path.resolve(sourceCandidate);const repoRoot=findSourceRepositoryRoot(sourceWorkspaceRoot);if(!pmRoot){return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{}}}const relativePmRoot=path.relative(sourceWorkspaceRoot,path.resolve(pmRoot));const contained=relativePmRoot.length>0&&!relativePmRoot.startsWith(`..${path.sep}`)&&relativePmRoot!==".."&&!path.isAbsolute(relativePmRoot);return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{},...contained?{pm_root_rel:relativePmRoot.split(path.sep).join("/")}:{}}}function setActiveExtensionHooks(hooks){const state=runtimeState();if(state){state.hooks=hooks;return}activeExtensionHooks=hooks}function setActiveExtensionCommands(commands){const state=runtimeState();if(state){state.commands=commands;return}activeExtensionCommands=commands}function setActiveExtensionParsers(parsers){const state=runtimeState();if(state){state.parsers=parsers;return}activeExtensionParsers=parsers}function setActiveExtensionPreflight(preflight){const state=runtimeState();if(state){state.preflight=preflight;return}activeExtensionPreflight=preflight}function setActiveExtensionServices(services){const state=runtimeState();if(state){state.services=services;return}activeExtensionServices=services}function setActiveExtensionRenderers(renderers){const state=runtimeState();if(state){state.renderers=renderers;return}activeExtensionRenderers=renderers}function setActiveExtensionRegistrations(registrations){const state=runtimeState();if(state){state.registrations=registrations;return}activeExtensionRegistrations=registrations}function getActiveExtensionRegistrations(){const state=runtimeState();return state?state.registrations:activeExtensionRegistrations}function resetActiveExtensionRuntimeState(){const state=runtimeState();if(state){state.hooks=null;state.commands=null;state.parsers=null;state.preflight=null;state.services=null;state.renderers=null;state.registrations=null;state.commandContext=null;state.commandResult=null;state.affectedItems=[];return}activeExtensionHooks=null;activeExtensionCommands=null;activeExtensionParsers=null;activeExtensionPreflight=null;activeExtensionServices=null;activeExtensionRenderers=null;activeExtensionRegistrations=null;activeCommandContext=null;activeCommandResult=null}function setActiveCommandContext(context){const resolved=context?{...context,...resolvePortableWorkspaceContext(context.pm_root)}:null;const state=runtimeState();if(state){state.commandContext=resolved;return}activeCommandContext=resolved}function getActiveCommandContext(){const state=runtimeState();const context=state?state.commandContext:activeCommandContext;return context?{...context,args:[...context.args],options:context.options?{...context.options}:{},global:context.global?{...context.global}:void 0}:null}function setActiveCommandResult(result){const state=runtimeState();if(state){state.commandResult=result;return}activeCommandResult=result}function getActiveCommandResult(){const state=runtimeState();return state?state.commandResult:activeCommandResult}function recordAfterCommandAffectedItem(item){if(!item){return}const state=runtimeState();if(state){state.affectedItems.push(item)}else{activeAfterCommandAffectedItems.push(item)}}function projectAfterCommandItemSnapshot(metadata,changedFields){if(!metadata||!metadata.id){return{}}const snapshot={id:metadata.id,type:metadata.type,status:metadata.status};if(!Array.isArray(changedFields)){return snapshot}const source=metadata;for(const field of changedFields){if(typeof field!=="string"){continue}const actualField=field.startsWith("unset:")?field.slice("unset:".length):field;if(actualField==="id"||actualField==="type"||actualField==="status"||AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS.has(actualField)){continue}if(Object.hasOwn(source,actualField)&&source[actualField]!==void 0){snapshot[actualField]=source[actualField]}}return snapshot}function consumeAfterCommandAffectedItems(){const state=runtimeState();const affectedItems=state?.affectedItems??activeAfterCommandAffectedItems;if(affectedItems.length===0){return void 0}const affected=affectedItems;if(state){state.affectedItems=[]}else{activeAfterCommandAffectedItems=[]}return affected}function clearActiveExtensionHooks(){const state=runtimeState();if(state){state.hooks=null;state.commands=null;state.parsers=null;state.preflight=null;state.services=null;state.renderers=null;state.registrations=null;state.commandContext=null;state.commandResult=void 0;state.affectedItems=[];return}activeExtensionHooks=null;activeExtensionCommands=null;activeExtensionParsers=null;activeExtensionPreflight=null;activeExtensionServices=null;activeExtensionRenderers=null;activeExtensionRegistrations=null;activeCommandContext=null;activeCommandResult=void 0;activeAfterCommandAffectedItems=[]}async function runActiveOnWriteHooks(context){const state=runtimeState();const hooks=state?state.hooks:activeExtensionHooks;if(!hooks){return[]}return runOnWriteHooks(hooks,context)}async function runActiveBeforeMutationHooks(context){const state=runtimeState();const hooks=state?state.hooks:activeExtensionHooks;if(!hooks)return;await runBeforeMutationHooks(hooks,context)}async function runActiveOnReadHooks(context){const state=runtimeState();const hooks=state?state.hooks:activeExtensionHooks;if(!hooks){return[]}return runOnReadHooks(hooks,context)}function hasActiveOnReadHooks(){const state=runtimeState();const hooks=state?state.hooks:activeExtensionHooks;return(hooks?.onRead?.length??0)>0}async function runActiveOnIndexHooks(context){const state=runtimeState();const hooks=state?state.hooks:activeExtensionHooks;if(!hooks){return[]}return runOnIndexHooks(hooks,context)}function runActiveCommandOverride(result){const state=runtimeState();const commands=state?state.commands:activeExtensionCommands;const commandContext=state?state.commandContext:activeCommandContext;if(!commands||!commandContext){return{overridden:false,result,warnings:[]}}return runCommandOverride(commands,{command:commandContext.command,args:[...commandContext.args],options:commandContext.options?{...commandContext.options}:{},global:commandContext.global?{...commandContext.global}:void 0,pm_root:commandContext.pm_root,source_workspace_root:commandContext.source_workspace_root,repo_root:commandContext.repo_root,pm_root_rel:commandContext.pm_root_rel,result})}async function runActiveCommandHandler(context){const state=runtimeState();const commands=state?state.commands:activeExtensionCommands;if(!commands){return{handled:false,result:null,warnings:[]}}return runCommandHandler(commands,{...context,...resolvePortableWorkspaceContext(context.pm_root)})}async function runActiveParserOverride(context){const state=runtimeState();const parsers=state?state.parsers:activeExtensionParsers;if(!parsers){return{overridden:false,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},warnings:[]}}return runParserOverride(parsers,{...context,...resolvePortableWorkspaceContext(context.pm_root)})}async function runActivePreflightOverride(context){const state=runtimeState();const preflight=state?state.preflight:activeExtensionPreflight;if(!preflight){return{overridden:false,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},decision:{...context.decision},warnings:[]}}return runPreflightOverride(preflight,{...context,...resolvePortableWorkspaceContext(context.pm_root)})}function runActiveRendererOverride(format,result){const state=runtimeState();const renderers=state?state.renderers:activeExtensionRenderers;const commandContext=state?state.commandContext:activeCommandContext;if(!renderers){return{overridden:false,rendered:null,warnings:[]}}return runRendererOverride(renderers,{format,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,result})}function buildServiceContext(service,payload){const state=runtimeState();const commandContext=state?state.commandContext:activeCommandContext;return{service,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,payload}}async function runActiveServiceOverride(service,payload){const state=runtimeState();const services=state?state.services:activeExtensionServices;if(!services){return{handled:false,result:payload,warnings:[]}}return runServiceOverride(services,buildServiceContext(service,payload))}function runActiveServiceOverrideSync(service,payload){const state=runtimeState();const services=state?state.services:activeExtensionServices;if(!services){return{handled:false,result:payload,warnings:[]}}return runServiceOverrideSync(services,buildServiceContext(service,payload))}export*from"./loader.js";export*from"./command-hook-context.js";import{createSerialQueue}from"../shared/serial-queue.js";import{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,collectUsedExtensionCapabilities,reconcileExtensionCapabilityUsage}from"./capability-usage.js";export{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,clearActiveExtensionHooks,collectUsedExtensionCapabilities,consumeAfterCommandAffectedItems,createSerialQueue,getActiveCommandContext,getActiveCommandResult,getActiveExtensionRegistrations,hasActiveOnReadHooks,projectAfterCommandItemSnapshot,reconcileExtensionCapabilityUsage,recordAfterCommandAffectedItem,resetActiveExtensionRuntimeState,resolvePortableWorkspaceContext,runActiveBeforeMutationHooks,runActiveCommandHandler,runActiveCommandOverride,runActiveOnIndexHooks,runActiveOnReadHooks,runActiveOnWriteHooks,runActiveParserOverride,runActivePreflightOverride,runActiveRendererOverride,runActiveServiceOverride,runActiveServiceOverrideSync,runWithIsolatedExtensionRuntime,setActiveCommandContext,setActiveCommandResult,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices};
|
|
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]="40b169fc-3c5f-5b2a-8fed-a9388b07d9f7")}catch(e2){}})();import{existsSync}from"node:fs";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";import{runCommandHandler,runBeforeMutationHooks,runCommandOverride,runOnIndexHooks,runParserOverride,runPreflightOverride,runOnReadHooks,runRendererOverride,runServiceOverride,runServiceOverrideSync,runOnWriteHooks}from"./loader.js";let activeExtensionHooks=null;let activeExtensionCommands=null;let activeExtensionParsers=null;let activeExtensionPreflight=null;let activeExtensionServices=null;let activeExtensionRenderers=null;let activeExtensionRegistrations=null;let activeCommandContext=null;let activeCommandResult=void 0;let activeAfterCommandAffectedItems=[];const isolatedExtensionRuntime=new AsyncLocalStorage;function runtimeState(){return isolatedExtensionRuntime.getStore()}function runWithIsolatedExtensionRuntime(run){return isolatedExtensionRuntime.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},run)}const AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function findSourceRepositoryRoot(candidate){let cursor=path.resolve(candidate);while(true){if(existsSync(path.join(cursor,".git"))){return cursor}const parent=path.dirname(cursor);if(parent===cursor){return void 0}cursor=parent}}function resolvePortableWorkspaceContext(pmRoot){const sourceCandidate=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd();const sourceWorkspaceRoot=findSourceRepositoryRoot(sourceCandidate)??path.resolve(sourceCandidate);const repoRoot=findSourceRepositoryRoot(sourceWorkspaceRoot);if(!pmRoot){return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{}}}const relativePmRoot=path.relative(sourceWorkspaceRoot,path.resolve(pmRoot));const contained=relativePmRoot.length>0&&!relativePmRoot.startsWith(`..${path.sep}`)&&relativePmRoot!==".."&&!path.isAbsolute(relativePmRoot);return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{},...contained?{pm_root_rel:relativePmRoot.split(path.sep).join("/")}:{}}}function setActiveExtensionHooks(hooks){const state=runtimeState();if(state){state.hooks=hooks;return}activeExtensionHooks=hooks}function setActiveExtensionCommands(commands){const state=runtimeState();if(state){state.commands=commands;return}activeExtensionCommands=commands}function setActiveExtensionParsers(parsers){const state=runtimeState();if(state){state.parsers=parsers;return}activeExtensionParsers=parsers}function setActiveExtensionPreflight(preflight){const state=runtimeState();if(state){state.preflight=preflight;return}activeExtensionPreflight=preflight}function setActiveExtensionServices(services){const state=runtimeState();if(state){state.services=services;return}activeExtensionServices=services}function setActiveExtensionRenderers(renderers){const state=runtimeState();if(state){state.renderers=renderers;return}activeExtensionRenderers=renderers}function setActiveExtensionRegistrations(registrations){const state=runtimeState();if(state){state.registrations=registrations;return}activeExtensionRegistrations=registrations}function getActiveExtensionRegistrations(){const state=runtimeState();return state?state.registrations:activeExtensionRegistrations}function resetActiveExtensionRuntimeState(){const state=runtimeState();if(state){state.hooks=null;state.commands=null;state.parsers=null;state.preflight=null;state.services=null;state.renderers=null;state.registrations=null;state.commandContext=null;state.commandResult=null;state.affectedItems=[];return}activeExtensionHooks=null;activeExtensionCommands=null;activeExtensionParsers=null;activeExtensionPreflight=null;activeExtensionServices=null;activeExtensionRenderers=null;activeExtensionRegistrations=null;activeCommandContext=null;activeCommandResult=null}function setActiveCommandContext(context){const resolved=context?{...context,...resolvePortableWorkspaceContext(context.pm_root)}:null;const state=runtimeState();if(state){state.commandContext=resolved;return}activeCommandContext=resolved}function getActiveCommandContext(){const state=runtimeState();const context=state?state.commandContext:activeCommandContext;return context?{...context,args:[...context.args],options:context.options?{...context.options}:{},global:context.global?{...context.global}:void 0}:null}function isActiveCommandUnextended(command){const state=runtimeState()??{commandContext:activeCommandContext,hooks:activeExtensionHooks,commands:activeExtensionCommands,parsers:activeExtensionParsers,preflight:activeExtensionPreflight,services:activeExtensionServices,renderers:activeExtensionRenderers,registrations:activeExtensionRegistrations};if(state.commandContext?.command!==command)return false;const broadInterceptors=[state.hooks,state.preflight,state.services,state.renderers];if(broadInterceptors.some(registry=>Object.values(registry??{}).some(entries=>entries.length>0)))return false;const commandInterceptors=[state.commands,state.parsers];if(commandInterceptors.some(registry=>Object.values(registry??{}).some(entries=>entries.some(entry=>entry.command===command))))return false;return!Object.entries(state.registrations??{}).some(([key,entries])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(key)&&entries.length>0)}function setActiveCommandResult(result){const state=runtimeState();if(state){state.commandResult=result;return}activeCommandResult=result}function getActiveCommandResult(){const state=runtimeState();return state?state.commandResult:activeCommandResult}function recordAfterCommandAffectedItem(item){if(!item){return}const state=runtimeState();if(state){state.affectedItems.push(item)}else{activeAfterCommandAffectedItems.push(item)}}function projectAfterCommandItemSnapshot(metadata,changedFields){if(!metadata||!metadata.id){return{}}const snapshot={id:metadata.id,type:metadata.type,status:metadata.status};if(!Array.isArray(changedFields)){return snapshot}const source=metadata;for(const field of changedFields){if(typeof field!=="string"){continue}const actualField=field.startsWith("unset:")?field.slice("unset:".length):field;if(actualField==="id"||actualField==="type"||actualField==="status"||AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS.has(actualField)){continue}if(Object.hasOwn(source,actualField)&&source[actualField]!==void 0){snapshot[actualField]=source[actualField]}}return snapshot}function consumeAfterCommandAffectedItems(){const state=runtimeState();const affectedItems=state?.affectedItems??activeAfterCommandAffectedItems;if(affectedItems.length===0){return void 0}const affected=affectedItems;if(state){state.affectedItems=[]}else{activeAfterCommandAffectedItems=[]}return affected}function clearActiveExtensionHooks(){const state=runtimeState();if(state){state.hooks=null;state.commands=null;state.parsers=null;state.preflight=null;state.services=null;state.renderers=null;state.registrations=null;state.commandContext=null;state.commandResult=void 0;state.affectedItems=[];return}activeExtensionHooks=null;activeExtensionCommands=null;activeExtensionParsers=null;activeExtensionPreflight=null;activeExtensionServices=null;activeExtensionRenderers=null;activeExtensionRegistrations=null;activeCommandContext=null;activeCommandResult=void 0;activeAfterCommandAffectedItems=[]}async function runActiveOnWriteHooks(context){const state=runtimeState();const hooks=state?state.hooks:activeExtensionHooks;if(!hooks){return[]}return runOnWriteHooks(hooks,context)}async function runActiveBeforeMutationHooks(context){const state=runtimeState();const hooks=state?state.hooks:activeExtensionHooks;if(!hooks)return;await runBeforeMutationHooks(hooks,context)}async function runActiveOnReadHooks(context){const state=runtimeState();const hooks=state?state.hooks:activeExtensionHooks;if(!hooks){return[]}return runOnReadHooks(hooks,context)}function hasActiveOnReadHooks(){const state=runtimeState();const hooks=state?state.hooks:activeExtensionHooks;return(hooks?.onRead?.length??0)>0}async function runActiveOnIndexHooks(context){const state=runtimeState();const hooks=state?state.hooks:activeExtensionHooks;if(!hooks){return[]}return runOnIndexHooks(hooks,context)}function runActiveCommandOverride(result){const state=runtimeState();const commands=state?state.commands:activeExtensionCommands;const commandContext=state?state.commandContext:activeCommandContext;if(!commands||!commandContext){return{overridden:false,result,warnings:[]}}return runCommandOverride(commands,{command:commandContext.command,args:[...commandContext.args],options:commandContext.options?{...commandContext.options}:{},global:commandContext.global?{...commandContext.global}:void 0,pm_root:commandContext.pm_root,source_workspace_root:commandContext.source_workspace_root,repo_root:commandContext.repo_root,pm_root_rel:commandContext.pm_root_rel,result})}async function runActiveCommandHandler(context){const state=runtimeState();const commands=state?state.commands:activeExtensionCommands;if(!commands){return{handled:false,result:null,warnings:[]}}return runCommandHandler(commands,{...context,...resolvePortableWorkspaceContext(context.pm_root)})}async function runActiveParserOverride(context){const state=runtimeState();const parsers=state?state.parsers:activeExtensionParsers;if(!parsers){return{overridden:false,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},warnings:[]}}return runParserOverride(parsers,{...context,...resolvePortableWorkspaceContext(context.pm_root)})}async function runActivePreflightOverride(context){const state=runtimeState();const preflight=state?state.preflight:activeExtensionPreflight;if(!preflight){return{overridden:false,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},decision:{...context.decision},warnings:[]}}return runPreflightOverride(preflight,{...context,...resolvePortableWorkspaceContext(context.pm_root)})}function runActiveRendererOverride(format,result){const state=runtimeState();const renderers=state?state.renderers:activeExtensionRenderers;const commandContext=state?state.commandContext:activeCommandContext;if(!renderers){return{overridden:false,rendered:null,warnings:[]}}return runRendererOverride(renderers,{format,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,result})}function buildServiceContext(service,payload){const state=runtimeState();const commandContext=state?state.commandContext:activeCommandContext;return{service,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,payload}}async function runActiveServiceOverride(service,payload){const state=runtimeState();const services=state?state.services:activeExtensionServices;if(!services){return{handled:false,result:payload,warnings:[]}}return runServiceOverride(services,buildServiceContext(service,payload))}function runActiveServiceOverrideSync(service,payload){const state=runtimeState();const services=state?state.services:activeExtensionServices;if(!services){return{handled:false,result:payload,warnings:[]}}return runServiceOverrideSync(services,buildServiceContext(service,payload))}export*from"./loader.js";export*from"./command-hook-context.js";import{createSerialQueue}from"../shared/serial-queue.js";import{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,collectUsedExtensionCapabilities,reconcileExtensionCapabilityUsage}from"./capability-usage.js";export{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,clearActiveExtensionHooks,collectUsedExtensionCapabilities,consumeAfterCommandAffectedItems,createSerialQueue,getActiveCommandContext,getActiveCommandResult,getActiveExtensionRegistrations,hasActiveOnReadHooks,isActiveCommandUnextended,projectAfterCommandItemSnapshot,reconcileExtensionCapabilityUsage,recordAfterCommandAffectedItem,resetActiveExtensionRuntimeState,resolvePortableWorkspaceContext,runActiveBeforeMutationHooks,runActiveCommandHandler,runActiveCommandOverride,runActiveOnIndexHooks,runActiveOnReadHooks,runActiveOnWriteHooks,runActiveParserOverride,runActivePreflightOverride,runActiveRendererOverride,runActiveServiceOverride,runActiveServiceOverrideSync,runWithIsolatedExtensionRuntime,setActiveCommandContext,setActiveCommandResult,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/core/lock/lock.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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
|
-
`,"utf8")}finally{await handle.close()}await emitLockWriteHook(lockPath,"lock:create")}async function unlinkLockWithHook(lockPath,op){try{await fs.unlink(lockPath);await emitLockWriteHook(lockPath,op);return true}catch{return false}}async function releaseOwnedLock(lockPath,id,owner,token){const startedAtMs=Date.now();let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;for(;;){const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate!==null){try{const current2=await readLockInfo(lockPath,false);if(isOwnedLock(current2.info,id,owner,token)){await unlinkLockWithHook(lockPath,"lock:release")}}finally{await releaseCleanupGate()}return}const current=await readLockInfo(lockPath,false);if(!isOwnedLock(current.info,id,owner,token)){return}const elapsedMs=Date.now()-startedAtMs;if(elapsedMs>=LOCK_RELEASE_GATE_WAIT_MS){return}await sleepWithJitter(Math.min(backoffMs,LOCK_RELEASE_GATE_WAIT_MS-elapsedMs));backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}function isOwnedLock(info,id,owner,token){return info?.id===id&&info.pid===process.pid&&info.owner===owner&&info.token===token}function isStaleLock(info,ttlSeconds){const createdAtMs=info?.created_at?Date.parse(info.created_at):Number.NaN;const ageMs=Number.isFinite(createdAtMs)?Date.now()-createdAtMs:Number.POSITIVE_INFINITY;return ageMs>ttlSeconds*1e3}function lockOwnerSuffix(info){return info?.owner?` (owner ${info.owner})`:""}const LOCK_WAIT_INITIAL_DELAY_MS=25;const LOCK_WAIT_MAX_DELAY_MS=200;const LOCK_CONFLICT_RETRY_HINT_MS=250;const MAX_STALE_LOCK_REMOVALS=3;const STALE_CLEANUP_GATE_SUFFIX=".stale-cleanup";const STALE_CLEANUP_GATE_OWNER_FILE="owner.json";const STALE_CLEANUP_GATE_STALE_MS=1e4;const LOCK_RELEASE_GATE_WAIT_MS=STALE_CLEANUP_GATE_STALE_MS+LOCK_WAIT_MAX_DELAY_MS;const STALE_CLEANUP_GATE_MAX_UNVERIFIED_MS=60*6e4;function parseNonNegativeIntegerWaitMs(value){if(typeof value==="string"){const trimmed=value.trim();if(!/^\d+$/.test(trimmed)){return void 0}const parsed=Number(trimmed);return Number.isSafeInteger(parsed)?parsed:void 0}if(typeof value==="number"&&Number.isFinite(value)&&value>=0){return Math.trunc(value)}return void 0}function resolveLockWaitMs(waitMs){const envRaw=process.env.PM_LOCK_WAIT_MS;const envParsed=parseNonNegativeIntegerWaitMs(envRaw);if(envParsed!==void 0){return envParsed}const callerParsed=parseNonNegativeIntegerWaitMs(waitMs);if(callerParsed!==void 0){return callerParsed}return 0}function sleepWithJitter(baseDelayMs){const jitteredMs=Math.max(1,Math.round(baseDelayMs*(.5+Math.random())));return new Promise(resolve=>setTimeout(resolve,jitteredMs))}function buildLockConflictError(id,info,waitedMs){const waitedSuffix=waitedMs>0?` after waiting ${waitedMs}ms`:"";return new PmCliError(`Item ${id} is locked${lockOwnerSuffix(info)}${waitedSuffix}`,EXIT_CODE.CONFLICT,{code:"lock_conflict",recovery:{retry_after_ms:LOCK_CONFLICT_RETRY_HINT_MS}})}function resolveLockOverrideRelease(result){if(typeof result==="function"){return result}if(typeof result==="object"&&result!==null&&"release"in result){const release=result.release;return typeof release==="function"?release:null}return null}function throwIfStaleLockNeedsForce(id,lockInfo,force,forceRequired){if(!force&&forceRequired){const warningSuffix=lockInfo.warnings.length>0?` (${lockInfo.warnings.join(",")})`:"";throw new PmCliError(`Item ${id} lock is stale${warningSuffix}; rerun with --force when supported for this command`,EXIT_CODE.CONFLICT)}}function parseStaleCleanupGateOwner(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){return null}const candidate=parsed;const pid=candidate.pid;const token=candidate.token;const processStartIdentity=candidate.process_start_identity;if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0||typeof token!=="string"||token.length===0||processStartIdentity!==void 0&&(typeof processStartIdentity!=="string"||!/^\d+$/u.test(processStartIdentity))){return null}return{pid,token,...typeof processStartIdentity==="string"?{process_start_identity:processStartIdentity}:{}}}async function readStaleCleanupGateOwner(gatePath){try{return parseStaleCleanupGateOwner(await fs.readFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),"utf8"))}catch{return null}}function isProcessAlive(pid){if(!Number.isSafeInteger(pid)||pid<=0)return false;try{process.kill(pid,0);return true}catch(error){if(isErrno(error,"ESRCH")){return false}return true}}function parseLinuxProcessStartIdentity(raw){const closeParenIndex=raw.lastIndexOf(")");if(closeParenIndex<0)return null;const startTime=raw.slice(closeParenIndex+2).trim().split(/\s+/u)[19];return startTime!==void 0&&/^\d+$/u.test(startTime)?startTime:null}async function readProcessStartIdentity(pid){try{return parseLinuxProcessStartIdentity(await fs.readFile(`/proc/${pid}/stat`,"utf8"))}catch{return null}}async function captureProcessIdentity(pid=process.pid){const processStartIdentity=await readProcessStartIdentity(pid);return{pid,...processStartIdentity===null?{}:{process_start_identity:processStartIdentity}}}async function isProcessIdentityAlive(identity,unverifiedAgeMs,maxUnverifiedAgeMs){if(!isProcessAlive(identity.pid))return false;const currentStartIdentity=await readProcessStartIdentity(identity.pid);if(identity.process_start_identity!==void 0&¤tStartIdentity!==null){return currentStartIdentity===identity.process_start_identity}return unverifiedAgeMs<=maxUnverifiedAgeMs}async function removeStaleCleanupGateDirectory(gatePath){try{await fs.rm(gatePath,{recursive:true,force:true});return true}catch{return false}}async function releaseStaleCleanupGate(gatePath,token){const owner=await readStaleCleanupGateOwner(gatePath);if(owner===null||owner.token!==token){return}await removeStaleCleanupGateDirectory(gatePath)}async function tryCreateStaleCleanupGate(gatePath){try{await fs.mkdir(gatePath)}catch(error){if(isErrno(error,"EEXIST")){return null}return null}const owner={...await captureProcessIdentity(),token:randomUUID()};try{await fs.writeFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),`${JSON.stringify(owner)}
|
|
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]="f0484213-41f9-583e-bd0f-f85e507682b2")}catch(e2){}})();import{isFileMissingError}from"../fs/fs-utils.js";import{constants as fsConstants}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{randomUUID}from"node:crypto";import{runActiveOnReadHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{toErrorMessage}from"../shared/primitives.js";import{getLockPath}from"../store/paths.js";import{nowIso}from"../shared/time.js";function parseLockInfo(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){return{info:null,warnings:["lock_info_invalid_shape"]}}const candidate=parsed;const id=candidate.id;const pid=candidate.pid;const owner=candidate.owner;const token=candidate.token;const createdAt=candidate.created_at;const ttlSeconds=candidate.ttl_seconds;if(typeof id!=="string"||typeof pid!=="number"||!Number.isFinite(pid)||typeof owner!=="string"||token!==void 0&&(typeof token!=="string"||token.trim().length===0)||typeof createdAt!=="string"||typeof ttlSeconds!=="number"||!Number.isFinite(ttlSeconds)){return{info:null,warnings:["lock_info_invalid_shape"]}}return{info:{id,pid,owner,...typeof token==="string"?{token}:{},created_at:createdAt,ttl_seconds:ttlSeconds},warnings:[]}}async function readLockInfo(lockPath,emitReadHook=true){try{const raw=await fs.readFile(lockPath,"utf8");if(emitReadHook){await runActiveOnReadHooks({path:lockPath,scope:"project"})}return parseLockInfo(raw)}catch(error){if(isFileMissingError(error)){return{info:null,warnings:[]}}return{info:null,warnings:["lock_info_read_failed"]}}}function isErrno(error,code){return typeof error==="object"&&error!==null&&"code"in error&&error.code===code}async function isLockCreateContention(error,lockPath,platform=process.platform){if(isErrno(error,"EEXIST"))return true;if(!isErrno(error,"EPERM")&&!isErrno(error,"EACCES")&&!isErrno(error,"EBUSY")){return false}try{await fs.lstat(lockPath);return true}catch(probeError){if(platform!=="win32"||!isFileMissingError(probeError)&&!isErrno(probeError,"EPERM")&&!isErrno(probeError,"EACCES")&&!isErrno(probeError,"EBUSY")){return false}}try{await fs.access(path.dirname(lockPath),fsConstants.W_OK);return true}catch{return false}}async function emitLockWriteHook(lockPath,op){await runActiveOnWriteHooks({path:lockPath,scope:"project",op})}function buildLockPayload(id,owner,ttlSeconds,token=randomUUID()){return{id,pid:process.pid,owner,token,created_at:nowIso(),ttl_seconds:ttlSeconds}}async function createLockFile(lockPath,id,owner,ttlSeconds,token){await fs.mkdir(path.dirname(lockPath),{recursive:true});const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate===null){throw Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"})}try{const handle=await fs.open(lockPath,"wx");try{try{await handle.writeFile(`${JSON.stringify(buildLockPayload(id,owner,ttlSeconds,token),null,2)}
|
|
2
|
+
`,"utf8")}finally{await handle.close()}}catch(error){await unlinkLockWithHook(lockPath,"lock:release");throw error}}finally{await releaseCleanupGate()}await emitLockWriteHook(lockPath,"lock:create")}async function unlinkLockWithHook(lockPath,op){try{await fs.unlink(lockPath);await emitLockWriteHook(lockPath,op);return true}catch{return false}}async function releaseOwnedLock(lockPath,id,owner,token){const startedAtMs=Date.now();let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;for(;;){const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate!==null){try{const current2=await readLockInfo(lockPath,false);if(isOwnedLock(current2.info,id,owner,token)){await unlinkLockWithHook(lockPath,"lock:release")}}finally{await releaseCleanupGate()}return}const current=await readLockInfo(lockPath,false);if(!isOwnedLock(current.info,id,owner,token)){return}const elapsedMs=Date.now()-startedAtMs;if(elapsedMs>=LOCK_RELEASE_GATE_WAIT_MS){return}await sleepWithJitter(Math.min(backoffMs,LOCK_RELEASE_GATE_WAIT_MS-elapsedMs));backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}function isOwnedLock(info,id,owner,token){return info?.id===id&&info.pid===process.pid&&info.owner===owner&&info.token===token}function isStaleLock(info,ttlSeconds){const createdAtMs=info?.created_at?Date.parse(info.created_at):Number.NaN;const ageMs=Number.isFinite(createdAtMs)?Date.now()-createdAtMs:Number.POSITIVE_INFINITY;return ageMs>ttlSeconds*1e3}function lockOwnerSuffix(info){return info?.owner?` (owner ${info.owner})`:""}const LOCK_WAIT_INITIAL_DELAY_MS=25;const LOCK_WAIT_MAX_DELAY_MS=200;const LOCK_CONFLICT_RETRY_HINT_MS=250;const MAX_STALE_LOCK_REMOVALS=3;const STALE_CLEANUP_GATE_SUFFIX=".stale-cleanup";const STALE_CLEANUP_GATE_OWNER_FILE="owner.json";const STALE_CLEANUP_GATE_STALE_MS=1e4;const LOCK_RELEASE_GATE_WAIT_MS=STALE_CLEANUP_GATE_STALE_MS+LOCK_WAIT_MAX_DELAY_MS;const STALE_CLEANUP_GATE_MAX_UNVERIFIED_MS=60*6e4;function parseNonNegativeIntegerWaitMs(value){if(typeof value==="string"){const trimmed=value.trim();if(!/^\d+$/.test(trimmed)){return void 0}const parsed=Number(trimmed);return Number.isSafeInteger(parsed)?parsed:void 0}if(typeof value==="number"&&Number.isFinite(value)&&value>=0){return Math.trunc(value)}return void 0}function resolveLockWaitMs(waitMs){const envRaw=process.env.PM_LOCK_WAIT_MS;const envParsed=parseNonNegativeIntegerWaitMs(envRaw);if(envParsed!==void 0){return envParsed}const callerParsed=parseNonNegativeIntegerWaitMs(waitMs);if(callerParsed!==void 0){return callerParsed}return 0}function sleepWithJitter(baseDelayMs){const jitteredMs=Math.max(1,Math.round(baseDelayMs*(.5+Math.random())));return new Promise(resolve=>setTimeout(resolve,jitteredMs))}function buildLockConflictError(id,info,waitedMs){const waitedSuffix=waitedMs>0?` after waiting ${waitedMs}ms`:"";return new PmCliError(`Item ${id} is locked${lockOwnerSuffix(info)}${waitedSuffix}`,EXIT_CODE.CONFLICT,{code:"lock_conflict",recovery:{retry_after_ms:LOCK_CONFLICT_RETRY_HINT_MS}})}function resolveLockOverrideRelease(result){if(typeof result==="function"){return result}if(typeof result==="object"&&result!==null&&"release"in result){const release=result.release;return typeof release==="function"?release:null}return null}function throwIfStaleLockNeedsForce(id,lockInfo,force,forceRequired){if(!force&&forceRequired){const warningSuffix=lockInfo.warnings.length>0?` (${lockInfo.warnings.join(",")})`:"";throw new PmCliError(`Item ${id} lock is stale${warningSuffix}; rerun with --force when supported for this command`,EXIT_CODE.CONFLICT)}}function parseStaleCleanupGateOwner(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){return null}const candidate=parsed;const pid=candidate.pid;const token=candidate.token;const processStartIdentity=candidate.process_start_identity;if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0||typeof token!=="string"||token.length===0||processStartIdentity!==void 0&&(typeof processStartIdentity!=="string"||!/^\d+$/u.test(processStartIdentity))){return null}return{pid,token,...typeof processStartIdentity==="string"?{process_start_identity:processStartIdentity}:{}}}async function readStaleCleanupGateOwner(gatePath){try{return parseStaleCleanupGateOwner(await fs.readFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),"utf8"))}catch{return null}}function isProcessAlive(pid){if(!Number.isSafeInteger(pid)||pid<=0)return false;try{process.kill(pid,0);return true}catch(error){if(isErrno(error,"ESRCH")){return false}return true}}function parseLinuxProcessStartIdentity(raw){const closeParenIndex=raw.lastIndexOf(")");if(closeParenIndex<0)return null;const startTime=raw.slice(closeParenIndex+2).trim().split(/\s+/u)[19];return startTime!==void 0&&/^\d+$/u.test(startTime)?startTime:null}async function readProcessStartIdentity(pid){try{return parseLinuxProcessStartIdentity(await fs.readFile(`/proc/${pid}/stat`,"utf8"))}catch{return null}}async function captureProcessIdentity(pid=process.pid){const processStartIdentity=await readProcessStartIdentity(pid);return{pid,...processStartIdentity===null?{}:{process_start_identity:processStartIdentity}}}async function isProcessIdentityAlive(identity,unverifiedAgeMs,maxUnverifiedAgeMs){if(!isProcessAlive(identity.pid))return false;const currentStartIdentity=await readProcessStartIdentity(identity.pid);if(identity.process_start_identity!==void 0&¤tStartIdentity!==null){return currentStartIdentity===identity.process_start_identity}return unverifiedAgeMs<=maxUnverifiedAgeMs}async function removeStaleCleanupGateDirectory(gatePath){try{await fs.rm(gatePath,{recursive:true,force:true});return true}catch{return false}}async function releaseStaleCleanupGate(gatePath,token){const owner=await readStaleCleanupGateOwner(gatePath);if(owner===null||owner.token!==token){return}await removeStaleCleanupGateDirectory(gatePath)}async function tryCreateStaleCleanupGate(gatePath){try{await fs.mkdir(gatePath)}catch(error){if(isErrno(error,"EEXIST")){return null}return null}const owner={...await captureProcessIdentity(),token:randomUUID()};try{await fs.writeFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),`${JSON.stringify(owner)}
|
|
3
3
|
`,"utf8")}catch{await removeStaleCleanupGateDirectory(gatePath);return null}return owner}async function removeExpiredStaleCleanupGate(gatePath){let gateAgeMs;try{const stats=await fs.stat(gatePath);gateAgeMs=Date.now()-stats.mtimeMs;if(gateAgeMs<=STALE_CLEANUP_GATE_STALE_MS){return false}}catch(error){return isFileMissingError(error)}const owner=await readStaleCleanupGateOwner(gatePath);if(owner!==null&&await isProcessIdentityAlive(owner,gateAgeMs,STALE_CLEANUP_GATE_MAX_UNVERIFIED_MS)){return false}return removeStaleCleanupGateDirectory(gatePath)}async function acquireStaleCleanupGate(lockPath,_id){const gatePath=`${lockPath}${STALE_CLEANUP_GATE_SUFFIX}`;const owner=await tryCreateStaleCleanupGate(gatePath);if(owner!==null){return async()=>releaseStaleCleanupGate(gatePath,owner.token)}if(!await removeExpiredStaleCleanupGate(gatePath)){return null}const recoveredOwner=await tryCreateStaleCleanupGate(gatePath);if(recoveredOwner===null){return null}return async()=>releaseStaleCleanupGate(gatePath,recoveredOwner.token)}async function removeConfirmedStaleLock(params){const releaseCleanupGate=await acquireStaleCleanupGate(params.lockPath,params.id);if(releaseCleanupGate===null){return{lockInfo:params.fallbackLockInfo,shouldRetryCreate:false,staleRemovalCounted:false}}try{const currentLockInfo=await readLockInfo(params.lockPath);if(currentLockInfo.info===null&¤tLockInfo.warnings.length===0){return{lockInfo:currentLockInfo,shouldRetryCreate:true,staleRemovalCounted:false}}if(!isStaleLock(currentLockInfo.info,params.ttlSeconds)){return{lockInfo:currentLockInfo,shouldRetryCreate:false,staleRemovalCounted:false}}throwIfStaleLockNeedsForce(params.id,currentLockInfo,params.force,params.forceRequiredForStaleLock);if(params.staleRemovals>=MAX_STALE_LOCK_REMOVALS){throw buildLockConflictError(params.id,currentLockInfo.info,Date.now()-params.startedAtMs)}return{lockInfo:currentLockInfo,shouldRetryCreate:await unlinkLockWithHook(params.lockPath,"lock:stale_remove"),staleRemovalCounted:true}}finally{await releaseCleanupGate()}}const _testOnly={parseLockInfo,readLockInfo,isErrno,isLockCreateContention,buildLockPayload,isStaleLock,lockOwnerSuffix,resolveLockWaitMs,parseLinuxProcessStartIdentity,readProcessStartIdentity,acquireStaleCleanupGate,removeConfirmedStaleLock};async function acquireLock(pmRoot,id,ttlSeconds,owner,force=false,forceRequiredForStaleLock=true,waitMs){const lockOverride=await runActiveServiceOverride("lock_acquire",{pm_root:pmRoot,id,ttl_seconds:ttlSeconds,owner,force,force_required_for_stale_lock:forceRequiredForStaleLock});if(lockOverride.handled){const release=resolveLockOverrideRelease(lockOverride.result);if(release){return async()=>{await Promise.resolve(release());await runActiveServiceOverride("lock_release",{pm_root:pmRoot,id,owner})}}}const lockPath=getLockPath(pmRoot,id);const waitBudgetMs=resolveLockWaitMs(waitMs);const startedAtMs=Date.now();let staleRemovals=0;let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;const token=randomUUID();for(;;){try{await createLockFile(lockPath,id,owner,ttlSeconds,token);return async()=>{await releaseOwnedLock(lockPath,id,owner,token);await runActiveServiceOverride("lock_release",{pm_root:pmRoot,id,owner})}}catch(error){if(!await isLockCreateContention(error,lockPath)){throw new PmCliError(`Failed to acquire lock for ${id}: ${toErrorMessage(error)}`,EXIT_CODE.GENERIC_FAILURE)}let lockInfo=await readLockInfo(lockPath);if(isStaleLock(lockInfo.info,ttlSeconds)){const staleRemoval=await removeConfirmedStaleLock({lockPath,id,ttlSeconds,force,forceRequiredForStaleLock,staleRemovals,waitBudgetMs,startedAtMs,fallbackLockInfo:lockInfo});lockInfo=staleRemoval.lockInfo;if(staleRemoval.staleRemovalCounted){staleRemovals+=1}if(staleRemoval.shouldRetryCreate){continue}}const elapsedMs=Date.now()-startedAtMs;if(waitBudgetMs===0||elapsedMs>=waitBudgetMs){throw buildLockConflictError(id,lockInfo.info,waitBudgetMs===0?0:elapsedMs)}await sleepWithJitter(Math.min(backoffMs,waitBudgetMs-elapsedMs));backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}}export{_testOnly,acquireLock,captureProcessIdentity,isProcessIdentityAlive,readProcessStartIdentity};
|
|
4
4
|
//# sourceMappingURL=lock.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]="b6e08d70-4e3f-5ad3-83ad-9cb49edb526e")}catch(e2){}})();import fs from"node:fs/promises";import path from"node:path";import{renderPmCommand}from"../shared/command-line.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{pathExists}from"../fs/fs-utils.js";import{getSettingsPath}from"./paths.js";function isErrno(error,code){return typeof error==="object"&&error!==null&&"code"in error&&error.code===code}function buildTrackerInitializationRecovery(pmRoot){const suggestedRetryArguments=["--pm-path",pmRoot,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}}function trackerRootNotDirectoryError(pmRoot){return new PmCliError(`Tracker root is not a directory at ${pmRoot}.`,EXIT_CODE.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",resolved_path:pmRoot,nextSteps:["Pass a tracker directory, usually <workspace>/.agents/pm, rather than a file path."]})}function trackerRootUnreadableError(pmRoot){return new PmCliError(`Tracker root is not readable at ${pmRoot}.`,EXIT_CODE.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",resolved_path:pmRoot,nextSteps:["Grant read and directory-search permission to the tracker root, then retry."]})}async function assertMissingRootAncestors(pmRoot){const resolvedRoot=path.resolve(pmRoot);const filesystemRoot=path.parse(resolvedRoot).root;let ancestor=path.dirname(resolvedRoot);while(ancestor!==filesystemRoot){let ancestorStats;try{ancestorStats=await fs.stat(ancestor)}catch(error){if(isErrno(error,"ENOTDIR")){throw trackerRootNotDirectoryError(pmRoot)}if(!isErrno(error,"ENOENT")){throw error}ancestor=path.dirname(ancestor);continue}if(!ancestorStats.isDirectory()){throw trackerRootNotDirectoryError(pmRoot)}return}}async function assertReadableTrackerRoot(pmRoot){let stats;try{stats=await fs.stat(pmRoot)}catch(error){if(isErrno(error,"ENOENT")){await assertMissingRootAncestors(pmRoot);throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Tracker root does not exist. Run pm init first.`,EXIT_CODE.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",resolved_path:pmRoot,nextSteps:["Confirm the tracker root path or initialize it with the emitted retry."],recovery:buildTrackerInitializationRecovery(pmRoot)})}if(isErrno(error,"ENOTDIR")){throw trackerRootNotDirectoryError(pmRoot)}if(isErrno(error,"EACCES")||isErrno(error,"EPERM")){throw trackerRootUnreadableError(pmRoot)}throw error}if(!stats.isDirectory()){throw trackerRootNotDirectoryError(pmRoot)}if(process.platform!=="win32"&&((stats.mode&292)===0||(stats.mode&73)===0)){throw trackerRootUnreadableError(pmRoot)}try{const directory=await fs.opendir(pmRoot);await directory.close()}catch(error){if(isErrno(error,"EACCES")||isErrno(error,"EPERM")){throw trackerRootUnreadableError(pmRoot)}throw error}}async function assertInitializedTracker(pmRoot){await assertReadableTrackerRoot(pmRoot);if(await pathExists(getSettingsPath(pmRoot))){return}throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`,EXIT_CODE.NOT_FOUND,{code:"tracker_not_initialized",reason:"settings_missing",resolved_path:pmRoot,nextSteps:["Initialize the selected tracker root with the emitted retry."],recovery:buildTrackerInitializationRecovery(pmRoot)})}export{assertInitializedTracker,assertReadableTrackerRoot,buildTrackerInitializationRecovery};
|
|
2
2
|
//# sourceMappingURL=tracker-preflight.js.map
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
/** Supported explicit classifications for intentional telemetry delivery. */
|
|
2
2
|
export declare const PM_TELEMETRY_SOURCE_CONTEXT_VALUES: readonly ["user", "automation", "test", "dogfood"];
|
|
3
|
+
/** Fixed core reads eligible only after runtime ownership has been established. */
|
|
4
|
+
export declare const TELEMETRY_SAMPLEABLE_READS: ReadonlySet<string>;
|
|
3
5
|
/** Resolve explicit read sampling only for core-only invocations with no write-capable extensions. */
|
|
4
6
|
export declare function resolveTelemetryReadSampleRate(command: string, noExtensions: boolean, env?: Readonly<Record<string, string | undefined>>): number;
|
|
5
7
|
/** Explain process opt-outs without reading settings or creating installation identity. */
|
|
@@ -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]="c4fba032-7cda-53a2-b518-fa13a60a76d5")}catch(e2){}})();const TRUE_VALUES=new Set(["1","true","yes","on"]);const PM_TELEMETRY_SOURCE_CONTEXT_VALUES=["user","automation","test","dogfood"];const SOURCE_CONTEXTS=new Set(PM_TELEMETRY_SOURCE_CONTEXT_VALUES);const TELEMETRY_SAMPLEABLE_READS=new Set(["stats","ops stats","list","get","next","context","activity","aggregate"]);function resolveTelemetryReadSampleRate(command,noExtensions,env=process.env){const raw=env.PM_TELEMETRY_READ_SAMPLE_RATE?.trim();if(!raw||!noExtensions||!TELEMETRY_SAMPLEABLE_READS.has(command))return 1;const rate=Number(raw);return Number.isFinite(rate)&&rate>0&&rate<=1?rate:1}function telemetryEnvironmentFlag(key,env){return TRUE_VALUES.has((env[key]??"").trim().toLowerCase())}function resolveTelemetryEnvironmentPolicy(env=process.env){const doNotTrack=telemetryEnvironmentFlag("DO_NOT_TRACK",env);const override=(env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();const inferredTest=typeof env.VITEST==="string"||typeof env.VITEST_WORKER_ID==="string"||(env.NODE_ENV??"").trim().toLowerCase()==="test";const testSuppressed=inferredTest&&!SOURCE_CONTEXTS.has(override)&&!telemetryEnvironmentFlag("PM_TELEMETRY_SEND_TEST_EVENTS",env);return{telemetry_disabled:doNotTrack||testSuppressed||telemetryEnvironmentFlag("PM_TELEMETRY_DISABLED",env)||telemetryEnvironmentFlag("PM_NO_TELEMETRY",env),do_not_track:doNotTrack,test_suppressed:testSuppressed}}export{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,TELEMETRY_SAMPLEABLE_READS,resolveTelemetryEnvironmentPolicy,resolveTelemetryReadSampleRate};
|
|
2
2
|
//# sourceMappingURL=policy.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Retain the first ten reads of each command per UTC minute, then sample the
|
|
3
|
+
* nth read at (10/n)^2. Expected retained successes stay below twenty per
|
|
4
|
+
* command per minute; this is a statistical bound, not a hard delivery cap.
|
|
5
|
+
* Explicit rates bypass automatic state. Corrupt or inaccessible state retains
|
|
6
|
+
* the invocation. Failures must override the returned probability at finish.
|
|
7
|
+
*/
|
|
8
|
+
export declare function resolveAutomaticReadSampleRate(globalPmRoot: string, command: string, coreReadOwned: boolean, env?: Readonly<Record<string, string | undefined>>, now?: number): Promise<number>;
|
|
@@ -0,0 +1,3 @@
|
|
|
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]="9d949852-abfe-5fbd-88c5-5da0cfbaf7de")}catch(e2){}})();import path from"node:path";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{resolveTelemetryReadSampleRate,TELEMETRY_SAMPLEABLE_READS}from"./policy.js";async function resolveAutomaticReadSampleRate(globalPmRoot,command,coreReadOwned,env=process.env,now=Date.now()){if(!coreReadOwned||!TELEMETRY_SAMPLEABLE_READS.has(command))return 1;if(env.PM_TELEMETRY_READ_SAMPLE_RATE!==void 0){return resolveTelemetryReadSampleRate(command,true,env)}try{const statePath=path.join(globalPmRoot,"runtime","telemetry","read-sampling.json");const minute=Math.floor(now/6e4);const counts=parseReadCounts(await readFileIfExists(statePath),minute);const ordinal=Math.min(Number.MAX_SAFE_INTEGER,(counts[command]??0)+1);counts[command]=ordinal;await writeFileAtomic(statePath,`${JSON.stringify({minute,counts})}
|
|
2
|
+
`);return Math.min(1,(10/ordinal)**2)}catch{return 1}}function parseReadCounts(raw,minute){const counts={};let previous;try{previous=JSON.parse(raw??"null")}catch{return counts}if(typeof previous!=="object"||previous===null||!("minute"in previous)||previous.minute!==minute||!("counts"in previous)||typeof previous.counts!=="object"||previous.counts===null)return counts;for(const[key,value]of Object.entries(previous.counts)){if(TELEMETRY_SAMPLEABLE_READS.has(key)&&typeof value==="number"&&Number.isSafeInteger(value)&&value>=0)counts[key]=value}return counts}export{resolveAutomaticReadSampleRate};
|
|
3
|
+
//# sourceMappingURL=read-sampling.js.map
|
|
@@ -1,6 +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]="
|
|
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]="9d073708-29b1-56b5-bcff-b964bfdcb43d")}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{isActiveCommandUnextended,runWithIsolatedExtensionRuntime}from"../extensions/index.js";import{resolveAutomaticReadSampleRate}from"./read-sampling.js";import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,resolveTelemetryEnvironmentPolicy}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{clearSettingsReadCache}from"../store/settings-read-cache.js";import{deriveTelemetryCommandResolution,deriveTelemetryCommandTaxonomy,inferTelemetryErrorCode}from"./observability.js";const TELEMETRY_QUEUE_RELATIVE_PATH=path.join("runtime","telemetry","events.jsonl");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
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
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
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
|
+
`:"";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{clearSettingsReadCache(globalPmRoot);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 coreReadOwned=context.global.noExtensions===true||isActiveCommandUnextended(context.command);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=await resolveAutomaticReadSampleRate(globalPmRoot,context.command,coreReadOwned);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};
|
|
6
6
|
//# sourceMappingURL=runtime.js.map
|
package/dist/sdk/index.d.ts
CHANGED
|
@@ -63,7 +63,7 @@ export { _testOnly as _testOnlyTemplates, type TemplateSource, } from "./templat
|
|
|
63
63
|
export { runConfig, _testOnlyConfigCommand, type NestedSettingResultValue, } from "./config.js";
|
|
64
64
|
export * from "./agent/identity-config.js";
|
|
65
65
|
export { INIT_AGENT_GUIDANCE_MODE_VALUES, runInitAgentGuidance, _testOnly as _testOnlyInitAgentGuidance, type InitAgentGuidanceMode, type InitAgentGuidanceSummary, type RunInitAgentGuidanceOptions, type RunInitAgentGuidanceResult, } from "./init-agent-guidance.js";
|
|
66
|
-
export { runInit, summarizeInitResult, _testOnly as _testOnlyInit, type InitAgentGuidanceResult, type InitConciseResult, type InitInstalledPackagesSummary, type InitRegisteredTypePresetSummary, type InitTargetResolution, type InitTypePresetName, } from "./init.js";
|
|
66
|
+
export { runInit, summarizeInitResult, _testOnly as _testOnlyInit, type InitAgentGuidanceResult, type InitConciseResult, type InitDisplayResult, type InitInstalledPackagesSummary, type InitRegisteredTypePresetSummary, type InitTargetResolution, type InitTypePresetName, } from "./init.js";
|
|
67
67
|
export { PROFILE_SUBCOMMANDS, formatProfileApplyHuman, formatProfileLintHuman, formatProfileListHuman, formatProfileShowHuman, runProfileApply, runProfileLint, runProfileList, runProfileShow, type ProfileApplyDimension, type ProfileComposition, type ProfileListEntry, } from "./profile.js";
|
|
68
68
|
export * from "./extension-contracts.js";
|
|
69
69
|
export { RESERVED_ITEM_FIELD_NAMES } from "../core/extensions/item-fields.js";
|