@unbrained/pm-cli 2026.11.25 → 2026.11.27

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.
Files changed (172) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/commander-usage.js +9 -9
  3. package/dist/cli/error-guidance.js +5 -5
  4. package/dist/cli/help-content.js +4 -4
  5. package/dist/cli/register-setup.js +1 -1
  6. package/dist/cli/runtime/selection.js +1 -1
  7. package/dist/cli-bundle/bundle-manifest.json +1 -1
  8. package/dist/cli-bundle/chunks/{chunk-CZEMEPPQ.js → chunk-5CMR4R5V.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-YIGBEY7K.js → chunk-5M7UTO2G.js} +2 -2
  10. package/dist/cli-bundle/chunks/chunk-63AVXDZS.js +2 -0
  11. package/dist/cli-bundle/chunks/{chunk-CONBVY2O.js → chunk-66TNCHHG.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-LPW7S5KA.js → chunk-6NJ3BONB.js} +2 -2
  13. package/dist/cli-bundle/chunks/chunk-AVHRMUXJ.js +3 -0
  14. package/dist/cli-bundle/chunks/{chunk-FVY7U3SU.js → chunk-HTT52JL3.js} +37 -37
  15. package/dist/cli-bundle/chunks/{chunk-OS5W4ZG2.js → chunk-J25DZRYJ.js} +31 -31
  16. package/dist/cli-bundle/chunks/chunk-J6TFG34A.js +4 -0
  17. package/dist/cli-bundle/chunks/{chunk-K34FR5CO.js → chunk-JX475QVU.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-KP75JTTO.js +35 -0
  19. package/dist/cli-bundle/chunks/chunk-KS47NGMQ.js +69 -0
  20. package/dist/cli-bundle/chunks/{chunk-BVJMVU4Z.js → chunk-O23KTJL6.js} +6 -6
  21. package/dist/cli-bundle/chunks/{chunk-DF6A7C32.js → chunk-OFX2VA5Z.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-FHLOGAGA.js → chunk-QVDEZBSV.js} +2 -2
  23. package/dist/cli-bundle/chunks/chunk-SIRZ4VMT.js +2 -0
  24. package/dist/cli-bundle/chunks/{chunk-C4KIZQHW.js → chunk-VC4BJIA7.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-GBVF2ZB3.js → chunk-W7SPEGSP.js} +2 -2
  26. package/dist/cli-bundle/chunks/chunk-WY7467RY.js +3 -0
  27. package/dist/cli-bundle/chunks/{chunk-7EPYCU7U.js → chunk-X6TE47CS.js} +5 -5
  28. package/dist/cli-bundle/chunks/chunk-XB6QEVUK.js +2 -0
  29. package/dist/cli-bundle/chunks/chunk-XYX4CXFR.js +2 -0
  30. package/dist/cli-bundle/chunks/{chunk-SCIPT7WF.js → chunk-Y5U7QCNX.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-L6VS7F3R.js → chunk-YGK6SA7P.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-OWK2JL4I.js → chunk-ZGV4ZXDS.js} +2 -2
  33. package/dist/cli-bundle/chunks/{chunk-CNUFU454.js → chunk-ZILIHDDY.js} +41 -41
  34. package/dist/cli-bundle/chunks/{field-option-collisions-QE65APSD.js → field-option-collisions-UL6BIPAK.js} +2 -2
  35. package/dist/cli-bundle/chunks/{item-revision-INDHJV6X.js → item-revision-WNUDY5DM.js} +2 -2
  36. package/dist/cli-bundle/chunks/item-transaction-ER3OWOPV.js +2 -0
  37. package/dist/cli-bundle/chunks/{mutation-actor-KU7BMLUN.js → mutation-actor-SFYTD2ZB.js} +2 -2
  38. package/dist/cli-bundle/chunks/{mutation-admission-3OMCTQD4.js → mutation-admission-AVOOT3KH.js} +2 -2
  39. package/dist/cli-bundle/chunks/{register-list-query-3GV3LBOT.js → register-list-query-Q7UW2EPV.js} +2 -2
  40. package/dist/cli-bundle/chunks/{register-mutation-GZLF47SX.js → register-mutation-YNW7E3T4.js} +2 -2
  41. package/dist/cli-bundle/chunks/{register-operations-PBJZGCAL.js → register-operations-DAUTQCIO.js} +2 -2
  42. package/dist/cli-bundle/chunks/register-setup-VSURGF7V.js +2 -0
  43. package/dist/cli-bundle/chunks/{stage-3WIZBD4N.js → stage-N5GDBS5A.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-X4EWD6TL.js → chunk-24W63UPP.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-C3FEDTSD.js → chunk-2XGHBYDA.js} +26 -26
  46. package/dist/cli-bundle/focused-chunks/{chunk-ZLRRII55.js → chunk-3QRMY6KF.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-PKX2EHE3.js → chunk-4HLZOOZI.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/chunk-52PHSTGP.js +27 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-YYEWIKNI.js → chunk-7FKGIJEB.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/chunk-7GZMOLQY.js +15 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-AL47ODFZ.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-AN4NFFLL.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-BYQK5DGH.js → chunk-B2HJI6KA.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-JOKRDFMQ.js → chunk-C2HW7BSE.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-TQIKDFOD.js → chunk-GISZWMBS.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-BOIMP2AR.js → chunk-GUAT4OAC.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-VU2PH4PF.js → chunk-H4JBS477.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-XKLBTDJ7.js → chunk-HGJ4MILN.js} +37 -37
  59. package/dist/cli-bundle/focused-chunks/{chunk-TRL4JDWX.js → chunk-HSWL6L2O.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-SXC2EO3E.js → chunk-I4GY7HAP.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/chunk-KMG4O2IU.js +4 -0
  62. package/dist/cli-bundle/focused-chunks/{chunk-4LQL4EO6.js → chunk-N7ZAMULP.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{chunk-UWWAVXG4.js → chunk-REORRDPH.js} +3 -3
  64. package/dist/cli-bundle/focused-chunks/{chunk-MB56Y4M6.js → chunk-SXWUKNTY.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-5RBC4WSE.js → chunk-UGQ2EXTU.js} +58 -59
  66. package/dist/cli-bundle/focused-chunks/chunk-YPOATPTX.js +3 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-7SSGTGZO.js → chunk-ZZYJS74B.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{field-option-collisions-5ROXGUME.js → field-option-collisions-BP7ILGQK.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/{item-revision-KYMSQVZE.js → item-revision-NOHVIOQQ.js} +2 -2
  70. package/dist/cli-bundle/focused-chunks/{item-transaction-I4HLVHEJ.js → item-transaction-O26COBOJ.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/{mutation-actor-GGOQKAE6.js → mutation-actor-HVJV5S76.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/{mutation-admission-OS36ZCMH.js → mutation-admission-JRICEVYN.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/{stage-4ZFWJUKO.js → stage-NSX6ASBZ.js} +2 -2
  74. package/dist/cli-bundle/main.js +26 -26
  75. package/dist/cli-bundle/sdk-authoring.js +1 -1
  76. package/dist/cli-bundle/sdk-contracts.js +4 -4
  77. package/dist/cli-bundle/sdk-core.js +1 -1
  78. package/dist/cli-bundle/sdk-governance.js +1 -1
  79. package/dist/cli-bundle/sdk-graph.js +1 -1
  80. package/dist/cli-bundle/sdk-merge.js +63 -63
  81. package/dist/cli-bundle/sdk-query.js +1 -1
  82. package/dist/cli-bundle/sdk-runtime.js +1 -1
  83. package/dist/cli-bundle/sdk-testing.js +1 -1
  84. package/dist/cli-bundle/sdk.js +11 -11
  85. package/dist/core/extensions/index.js +1 -1
  86. package/dist/core/reproducibility/context.d.ts +2 -0
  87. package/dist/core/reproducibility/context.js +1 -1
  88. package/dist/core/shared/command-line.d.ts +2 -2
  89. package/dist/core/shared/command-line.js +1 -1
  90. package/dist/core/shared/secret-rules.js +5 -5
  91. package/dist/sdk/cli-bootstrap.d.ts +17 -0
  92. package/dist/sdk/cli-bootstrap.js +1 -1
  93. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  94. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  95. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  96. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  97. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  98. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  99. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  100. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  101. package/dist/sdk/cli-contracts.d.ts +1 -1
  102. package/dist/sdk/cli-contracts.js +1 -1
  103. package/dist/sdk/completion/shared.d.ts +1 -1
  104. package/dist/sdk/completion/shared.js +1 -1
  105. package/dist/sdk/extension/bundled-catalog.js +1 -1
  106. package/dist/sdk/extension/install-sources.js +5 -5
  107. package/dist/sdk/extension/listing-fields.d.ts +15 -0
  108. package/dist/sdk/extension/listing-fields.js +2 -0
  109. package/dist/sdk/extension/managed-update-status.js +1 -1
  110. package/dist/sdk/extension/npm-spec.d.ts +18 -0
  111. package/dist/sdk/extension/npm-spec.js +2 -0
  112. package/dist/sdk/extension/static-inventory.d.ts +53 -1
  113. package/dist/sdk/extension/static-inventory.js +1 -1
  114. package/dist/sdk/extension/update-check.js +1 -1
  115. package/dist/sdk/extension/update-observations.js +3 -0
  116. package/dist/sdk/extension/upgrade-hints.js +2 -0
  117. package/dist/sdk/extension.d.ts +2 -0
  118. package/dist/sdk/extension.js +1 -1
  119. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  120. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  121. package/dist/sdk/governance/upgrade.d.ts +7 -2
  122. package/dist/sdk/governance/upgrade.js +2 -2
  123. package/dist/sdk/index.d.ts +1 -1
  124. package/dist/sdk/public-surface.json +1 -1
  125. package/dist/sdk/query/context.d.ts +20 -7
  126. package/dist/sdk/query/context.js +4 -2
  127. package/dist/sdk/runtime-input.js +1 -1
  128. package/dist/sdk/testing.d.ts +20 -2
  129. package/docs/COMMANDS.md +19 -1
  130. package/docs/CONFIGURATION.md +1 -1
  131. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +6 -0
  132. package/docs/EXTENSION_LIFECYCLE.md +72 -2
  133. package/docs/MUTATION_INTEGRITY.md +47 -0
  134. package/docs/SDK.md +24 -3
  135. package/marketplace.json +1 -1
  136. package/package.json +1 -1
  137. package/packages/pm-beads/package.json +1 -1
  138. package/packages/pm-calendar/package.json +1 -1
  139. package/packages/pm-command-kit/package.json +1 -1
  140. package/packages/pm-digital-twin/package.json +1 -1
  141. package/packages/pm-governance-audit/package.json +1 -1
  142. package/packages/pm-guide-shell/package.json +1 -1
  143. package/packages/pm-kanban/package.json +1 -1
  144. package/packages/pm-lifecycle-hooks/package.json +1 -1
  145. package/packages/pm-linked-test-adapters/package.json +1 -1
  146. package/packages/pm-search-advanced/package.json +1 -1
  147. package/packages/pm-templates/package.json +1 -1
  148. package/packages/pm-todos/package.json +1 -1
  149. package/packages/pm-vcs/package.json +1 -1
  150. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  151. package/plugins/pm-claude/package.json +1 -1
  152. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  153. package/plugins/pm-codex/package.json +1 -1
  154. package/plugins/pm-codex/plugin.json +1 -1
  155. package/runtime-dependencies.json +1 -1
  156. package/dist/cli-bundle/chunks/chunk-4FZH5BTV.js +0 -2
  157. package/dist/cli-bundle/chunks/chunk-GZI7ZAB7.js +0 -2
  158. package/dist/cli-bundle/chunks/chunk-LOX3VY4T.js +0 -2
  159. package/dist/cli-bundle/chunks/chunk-VA4T37Q4.js +0 -70
  160. package/dist/cli-bundle/chunks/chunk-WQOEVGLQ.js +0 -2
  161. package/dist/cli-bundle/chunks/chunk-XHCIOLJP.js +0 -3
  162. package/dist/cli-bundle/chunks/chunk-XKWJONAO.js +0 -2
  163. package/dist/cli-bundle/chunks/chunk-ZBOQEZ2H.js +0 -33
  164. package/dist/cli-bundle/chunks/chunk-ZLICQPRG.js +0 -3
  165. package/dist/cli-bundle/chunks/item-transaction-LCKK4XXB.js +0 -2
  166. package/dist/cli-bundle/chunks/register-setup-ZLJEF6NZ.js +0 -2
  167. package/dist/cli-bundle/focused-chunks/chunk-3Y5PTQ2F.js +0 -27
  168. package/dist/cli-bundle/focused-chunks/chunk-A4R57E4K.js +0 -2
  169. package/dist/cli-bundle/focused-chunks/chunk-IAOKVKWW.js +0 -2
  170. package/dist/cli-bundle/focused-chunks/chunk-VMYVN36N.js +0 -13
  171. package/dist/cli-bundle/focused-chunks/chunk-WL2R7T5G.js +0 -2
  172. package/dist/cli-bundle/focused-chunks/chunk-WVA5KOXF.js +0 -3
@@ -0,0 +1,15 @@
1
+ /** Split `--fields` into distinct keys; undefined when the option is absent. `example` replaces the generated refusal example. */
2
+ export declare function parseListingFields(raw:unknown,allowed:readonly string[],listing:string,example?:string):string[]|undefined;
3
+ /** Keep only the requested keys of each row, in the requested order; a key a row lacks reads as null. */
4
+ export declare function projectListingRows(rows:ReadonlyArray<object>,fields:readonly string[]):Record<string,unknown>[];
5
+ /** Row keys an explore or manage row can carry, in their emitted order. */
6
+ export declare const EXPLORE_MANAGE_ROW_FIELDS:readonly["name","directory","version","entry","scope","active","enabled","runtime_active","activation_status","managed","source","update_available","last_update_check_at","last_update_remote_version","last_update_remote_commit","update_error","update_check_timeout_ms","update_check_status","update_check_reason","command_paths","action_paths","contributions"];
7
+ /** Validate an explore or manage `--fields` selection; called at admission, before any check or adoption runs. */
8
+ export declare function parseExploreManageFields(rawFields:unknown,listing:string):string[]|undefined;
9
+ /**
10
+ * Shape explore and manage rows from an admitted selection: `--fields` selects
11
+ * any subset; without it the embedded `contributions` map stays out, because
12
+ * `pm package describe` maps every registered surface and the map dominated each
13
+ * row (pm-gh1777).
14
+ */
15
+ export declare function projectExploreManageRows(rows:ReadonlyArray<object>,fields:readonly string[]|undefined):object[];
@@ -0,0 +1,2 @@
1
+ import{EXIT_CODE as s}from"../../core/shared/constants.js";import{PmCliError as c}from"../../core/shared/errors.js";function u(e,t,n,r){if(e==null||e===!1)return;const i=[...new Set(String(e).split(",").map(a=>a.trim()).filter(a=>a.length>0))];if(i.length===0)throw new c(`Package ${n} --fields requires a comma-separated list of field names`,s.USAGE);const o=i.filter(a=>!t.includes(a));if(o.length>0)throw new c(`Package ${n} --fields has unknown field(s): ${o.join(", ")}`,s.USAGE,{code:"invalid_argument_value",examples:[r??`pm package ${n} --fields ${t.slice(0,3).join(",")}`],recovery:{allowed_values:[...t],provided_fields:["--fields"]}});return i}function p(e,t){return e.map(n=>Object.fromEntries(t.map(r=>[r,n[r]??null])))}const d=["name","directory","version","entry","scope","active","enabled","runtime_active","activation_status","managed","source","update_available","last_update_check_at","last_update_remote_version","last_update_remote_commit","update_error","update_check_timeout_ms","update_check_status","update_check_reason","command_paths","action_paths","contributions"];function m(e,t){return u(e,d,t)}function f(e,t){return t!==void 0?p(e,t):e.map(n=>{const{contributions:r,...i}=n;return i})}export{d as EXPLORE_MANAGE_ROW_FIELDS,m as parseExploreManageFields,u as parseListingFields,f as projectExploreManageRows,p as projectListingRows};
2
+ //# sourceMappingURL=listing-fields.js.map
@@ -1,2 +1,2 @@
1
- import{mapWithFixedConcurrency as c}from"./concurrency.js";import{sortManagedEntries as _}from"./managed-state.js";import{checkGithubUpdate as m,checkNpmUpdate as p,resolveExtensionUpdateCheckTimeoutMs as f,updateCheckTeardown as l}from"./update-check.js";const u=4;function h(n){let r=n;const a=[];return{acquire:()=>r>0?(r-=1,Promise.resolve()):new Promise(e=>a.push(e)),release:()=>{const e=a.shift();e?e():r+=1}}}function s(n,r){const{update_check_timeout_ms:a,...e}=n;return r===void 0?e:{...e,update_check_timeout_ms:r}}async function w(n,r=!1,a=f(),e=!0){const o=h(u),d=await c(n.entries,u,async i=>{if(!["github","npm"].includes(i.source.kind))return i;if(r)return s({...i,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0},void 0);await o.acquire();const t=i.source.kind==="github"?await m(i.source,void 0,a):await p(i.source,void 0,a);return e?l(t).then(o.release):o.release(),s({...i,last_update_check_at:t.checked_at,last_update_remote_commit:"remote_commit"in t?t.remote_commit:void 0,last_update_remote_version:"remote_version"in t?t.remote_version:void 0,update_available:t.available,update_error:t.error},t.timeout_ms)});return{...n,entries:_(d)}}export{w as refreshManagedExtensionUpdates};
1
+ import{mapWithFixedConcurrency as c}from"./concurrency.js";import{isRegistryNpmSource as m}from"./npm-spec.js";import{sortManagedEntries as _}from"./managed-state.js";import{checkGithubUpdate as p,checkNpmUpdate as f,resolveExtensionUpdateCheckTimeoutMs as l,updateCheckTeardown as h}from"./update-check.js";const u=4;function k(n){let i=n;const a=[];return{acquire:()=>i>0?(i-=1,Promise.resolve()):new Promise(e=>a.push(e)),release:()=>{const e=a.shift();e?e():i+=1}}}function s(n,i){const{update_check_timeout_ms:a,...e}=n;return i===void 0?e:{...e,update_check_timeout_ms:i}}async function U(n,i=!1,a=l(),e=!0){const o=k(u),d=await c(n.entries,u,async t=>{if(!["github","npm"].includes(t.source.kind))return t;if(i||t.source.kind==="npm"&&!m(t.source))return s({...t,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0},void 0);await o.acquire();const r=t.source.kind==="github"?await p(t.source,void 0,a):await f(t.source,void 0,a);return e?h(r).then(o.release):o.release(),s({...t,last_update_check_at:r.checked_at,last_update_remote_commit:"remote_commit"in r?r.remote_commit:void 0,last_update_remote_version:"remote_version"in r?r.remote_version:void 0,update_available:r.available,update_error:r.error},r.timeout_ms)});return{...n,entries:_(d)}}export{U as refreshManagedExtensionUpdates};
2
2
  //# sourceMappingURL=managed-update-status.js.map
@@ -0,0 +1,18 @@
1
+ import type{ManagedExtensionSource}from "./managed-state.js";
2
+ /** Whether a raw npm spec names a local path, tarball or `file:` artifact rather than a registry package. */
3
+ export declare function isLocalNpmSpec(spec:string):boolean;
4
+ /** Whether a managed source installs from the npm registry, so a newer registry release can replace it. */
5
+ export declare function isRegistryNpmSource(source:ManagedExtensionSource):boolean;
6
+ /**
7
+ * Whether a string is an exact npm version, by the rule the live freshness check applies to the registry's
8
+ * answer (npm-package-arg resolves it as a `version` spec), so the offline cache reader accepts exactly what
9
+ * the writer can produce, build metadata included (Codex review round 14).
10
+ */
11
+ export declare function isExactNpmVersion(value:string):boolean;
12
+ /**
13
+ * Whether a registry `latest` is an update for an installed version: newer under
14
+ * SemVer precedence (a release is newer than its own prerelease; an older
15
+ * `latest` is no update, because installing it would downgrade). Versions that
16
+ * are not valid SemVer count as an update whenever they differ.
17
+ */
18
+ export declare function isNewerRegistryVersion(latest:string,installed:string):boolean;
@@ -0,0 +1,2 @@
1
+ import a from"node:path";import s from"npm-package-arg";import n from"semver";const o=new Set(["tag","version","range"]);function p(t){try{const e=s(t),r=e.subSpec;return e.type==="alias"?r?.type:e.type}catch{return}}function l(t){if(a.isAbsolute(t)||t.startsWith(".")||t.startsWith("file:"))return!0;const e=p(t);return e!==void 0&&o.has(e)?!1:e==="file"||e==="directory"||/\.(?:tgz|tar\.gz|tar)$/iu.test(t)}function m(t){if(t.kind!=="npm")return!1;const e=t.input.startsWith("npm:")?t.input.slice(4).trim():t.input.trim(),r=p(e);return r!==void 0&&o.has(r)}function d(t){try{return s.resolve("pm-version-probe",t).type==="version"}catch{return!1}}function y(t,e){const r=n.parse(t,{loose:!0}),i=n.parse(e,{loose:!0});return r===null||i===null?t!==e:n.gt(r,i)}export{d as isExactNpmVersion,l as isLocalNpmSpec,y as isNewerRegistryVersion,m as isRegistryNpmSource};
2
+ //# sourceMappingURL=npm-spec.js.map
@@ -23,7 +23,57 @@ managed:boolean|null;
23
23
  /** Runtime state is never inferred from configuration. */
24
24
  runtime_active:null;
25
25
  /** Manifest version when available. */
26
- version?:string;}
26
+ version?:string;
27
+ /**
28
+ * Newer version the last `pm package manage` check observed for this installed
29
+ * version, or null when none is known (pm-gh1777); absent on a row for a
30
+ * requested package that is not installed.
31
+ */
32
+ update?:string|null;}
33
+ /** The `--fields` contract every package listing shares (pm-gh1777), published with the listing it serves. */
34
+ export{parseListingFields,projectListingRows}from "./listing-fields.js";
35
+ /**
36
+ * Refuse a lifecycle option another package action owns. Commander accepts these on the parent command, so
37
+ * without this check `pm package list --fix-managed-state` would succeed without adopting anything, and a
38
+ * caller could mistake the listing for the operation it asked for (Codex review round 13).
39
+ */
40
+ export declare function refuseStaticInventoryForeignOptions(options:Record<string,unknown>):void;
41
+ /** The read-output controls a caller passed, by their global-option keys. */
42
+ export interface StaticInventoryReadOutputControls{
43
+ /** Row cap a read would apply; the inventory cannot page, so any value is refused. */
44
+ outputLimit?:string;
45
+ /** Projection mode a read would apply; the inventory projects with `--fields` instead, so any value is refused. */
46
+ outputInclude?:string;
47
+ /** Read session that would suppress repeated rows across calls; refused because the inventory keeps no session. */
48
+ outputSession?:string;
49
+ /** Continuation token of an earlier page; refused because the inventory returns every row at once. */
50
+ outputCursor?:string;
51
+ /** Request for the per-row identity contract; refused when true because inventory rows carry none. */
52
+ outputRowContract?:boolean;
53
+ /** Byte budget for the rendered result; only `unbounded` is accepted, since the inventory cannot trim rows to fit. */
54
+ outputBudget?:string;
55
+ /** Raw `--output-format` value as typed; only `toon` and `json` are formats, anything else is refused. */
56
+ outputFormat?:unknown;}
57
+ /**
58
+ * The static inventory returns every installed package and applies no read-output
59
+ * row controls, so those controls are refused instead of silently ignored; the
60
+ * output format and an unbounded budget still apply (Codex review round 2).
61
+ */
62
+ export declare function refuseStaticInventoryReadOutputControls(controls:StaticInventoryReadOutputControls):void;
63
+ /**
64
+ * The tracker's configured default output format (`output.default_format`), so the static
65
+ * listing renders as every other command does (Codex review round 9). Absent, unreadable or
66
+ * unknown values yield undefined.
67
+ */
68
+ export declare function readStaticDefaultOutputFormat(pmRoot:string):Promise<"json"|"toon"|undefined>;
69
+ /**
70
+ * Whether the tracker shows deprecation hints (`ux.deprecation_hints`, on by default), read
71
+ * statically so the deprecated `pm extension list` spelling keeps its migration hint without
72
+ * leaving the no-activation path (Codex review round 11).
73
+ */
74
+ export declare function readStaticDeprecationHints(pmRoot:string):Promise<boolean>;
75
+ /** Row keys `pm package list --fields` selects from, in their emitted order. */
76
+ export declare const INVENTORY_ROW_FIELDS:readonly["name","directory","scope","installed","status","configured_enabled","managed","runtime_active","version","update"];
27
77
  /** A read-only inventory with explicit completeness and source receipts. */
28
78
  export interface StaticExtensionInventoryResult{
29
79
  /** Selected storage scope. */
@@ -34,6 +84,8 @@ complete:boolean;
34
84
  settings_status:"ok"|"absent"|"invalid"|"unreadable";
35
85
  /** Status of the managed install metadata. */
36
86
  managed_state_status:"ok"|"absent"|"invalid"|"unreadable";
87
+ /** Installed entries whose last observed check found a newer release; always set by {@link inspectStaticExtensionInventory}. */
88
+ updates_available?:number;
37
89
  /** Installed entries, or one absent entry for a missing requested name. */
38
90
  extensions:StaticExtensionInventoryEntry[];
39
91
  /** Every failure that affected completeness. */
@@ -1,2 +1,2 @@
1
- import c from"node:fs/promises";import u from"node:path";import{resolveGlobalPmRoot as _}from"../../core/store/paths.js";import{normalizeManagedState as x}from"./managed-state.js";import{normalizeExtensionNameForMatch as o,normalizeStringList as h,parseExtensionManifest as E}from"./shared.js";function f(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function b(e){return e!=="invalid"&&e!=="unreadable"}function j(e){const r=JSON.parse(e);if(typeof r!="object"||r===null||Array.isArray(r))throw new SyntaxError("Invalid settings object");const t=r.extensions;if(t===void 0)return{enabled:[],disabled:[]};if(typeof t!="object"||t===null||Array.isArray(t))throw new SyntaxError("Invalid extensions settings");const n=t;if(n.enabled!==void 0&&(!Array.isArray(n.enabled)||!n.enabled.every(a=>typeof a=="string"))||n.disabled!==void 0&&(!Array.isArray(n.disabled)||!n.disabled.every(a=>typeof a=="string")))throw new SyntaxError("Invalid extension enablement lists");return{enabled:n.enabled??[],disabled:n.disabled??[]}}async function S(e){let r;try{r=await c.readFile(e,"utf8")}catch(t){return f(t)?{status:"absent",enabled:[],disabled:[]}:{status:"unreadable",enabled:[],disabled:[],error:{code:"settings_unreadable",path:e}}}try{return{status:"ok",...j(r)}}catch{return{status:"invalid",enabled:[],disabled:[],error:{code:"settings_invalid",path:e}}}}async function A(e){let r;try{r=await c.readFile(e,"utf8")}catch(t){if(f(t))try{if((await c.stat(u.dirname(e))).isDirectory())return{status:"absent",entries:[]}}catch(n){if(f(n))return{status:"absent",entries:[]}}return{status:"unreadable",entries:[],error:{code:"managed_state_unreadable",path:e}}}try{const t=JSON.parse(r),n=x(t);if(!n||typeof t!="object"||t===null||!Array.isArray(t.entries)||n.entries.length!==t.entries.length)throw new SyntaxError("Invalid managed extension state");return{status:"ok",entries:n.entries}}catch{return{status:"invalid",entries:[],error:{code:"managed_state_invalid",path:e}}}}async function M(e){try{return{directories:(await c.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>t.localeCompare(n))}}catch(r){return f(r)?{directories:[]}:{directories:[],error:{code:"extensions_unreadable",path:e}}}}async function N(e){let r;try{r=await c.readFile(e,"utf8")}catch(t){return f(t)?{manifest:null,error:{code:"manifest_invalid",path:e}}:{manifest:null,error:{code:"manifest_unreadable",path:e}}}try{const t=E(JSON.parse(r));return t?{manifest:t}:{manifest:null,error:{code:"manifest_invalid",path:e}}}catch{return{manifest:null,error:{code:"manifest_invalid",path:e}}}}function z(e){const r=e.manifest?.name??e.directory,t=new Set(h(e.settings.enabled)),n=new Set(h(e.settings.disabled)),a=!b(e.settings.status)||!e.manifest?null:!n.has(r)&&(t.size===0||t.has(r)),i=b(e.managed.status)?e.managed.entries.some(d=>o(d.name)===o(r)||o(d.directory)===o(e.directory)):null;return{name:r,directory:e.directory,scope:e.scope,installed:!0,status:e.manifest?a===!1?"inactive":"installed":"malformed_manifest",configured_enabled:a,managed:i,runtime_active:null,...e.manifest?{version:e.manifest.version}:{}}}async function J(e){const r=e.scope??"project",t=r==="global"?_(e.cwd??process.cwd()):e.pmRoot,n=u.join(t,"extensions"),a=await S(u.join(t,"settings.json")),i=await A(u.join(n,".managed-extensions.json")),d=await M(n),l=[];for(const s of[a,i,d])s.error&&l.push(s.error);const m=e.name?.trim(),y=[];for(const s of d.directories){const w=u.join(n,s,"manifest.json"),p=await N(w);p.error&&l.push(p.error);const g=z({directory:s,scope:r,manifest:p.manifest,settings:a,managed:i});m&&![g.name,s].some(v=>o(v)===o(m))||y.push(g)}return m&&y.length===0&&l.every(s=>s.code!=="extensions_unreadable")&&y.push({name:m,directory:null,scope:r,installed:!1,status:"absent",configured_enabled:b(a.status)?!1:null,managed:b(i.status)?!1:null,runtime_active:null}),{scope:r,complete:l.length===0,settings_status:a.status,managed_state_status:i.status,extensions:y,errors:l}}export{J as inspectStaticExtensionInventory};
1
+ import h from"node:fs/promises";import s from"node:path";import{resolveGlobalPmRoot as I}from"../../core/store/paths.js";import{EXIT_CODE as y}from"../../core/shared/constants.js";import{PmCliError as _}from"../../core/shared/errors.js";import{normalizeManagedState as O}from"./managed-state.js";import{normalizeExtensionNameForMatch as d,normalizeStringList as v,parseExtensionManifest as N}from"./shared.js";import{findApplicableUpdateObservation as R,readBoundedRegularFile as m,readExtensionUpdateObservations as M,resolveObservedUpdateVersion as F}from"./update-observations.js";import{parseListingFields as de,projectListingRows as ue}from"./listing-fields.js";const C=[["install","--install"],["uninstall","--uninstall"],["explore","--explore"],["list","--list"],["manage","--manage"],["describe","--describe"],["markdown","--markdown"],["output","--output"],["reload","--reload"],["doctor","--doctor"],["catalog","--catalog"],["adopt","--adopt"],["adoptAll","--adopt-all"],["activate","--activate"],["deactivate","--deactivate"],["migrate","--migrate"],["init","--init"],["scaffold","--scaffold"],["capability","--capability"],["declarative","--declarative"],["gh","--gh"],["github","--github"],["ref","--ref"],["fixManagedState","--fix-managed-state"],["runtimeProbe","--runtime-probe"],["trace","--trace"],["watch","--watch"],["strictExit","--strict-exit"],["failOnWarn","--fail-on-warn"],["isolated","--isolated"],["ignoreGlobal","--ignore-global"],["detail","--detail"],["dryRun","--dry-run"]];function ee(e){const n=C.filter(([t])=>e[t]!==void 0&&e[t]!==!1).map(([,t])=>t);if(n.length!==0)throw new _(`${n.join(", ")} ${n.length===1?"does":"do"} not apply to pm package list, a read that changes nothing.`,y.USAGE,{code:"invalid_argument_value",required:"Drop the option, or run the package action that owns it (pm package manage, pm package doctor, pm package reload).",examples:["pm package manage --fix-managed-state","pm package list --fields name,version,update"]})}function te(e){if(e.outputFormat!==void 0&&e.outputFormat!=="json"&&e.outputFormat!=="toon")throw new _("--output-format must be toon or json.",y.USAGE,{code:"invalid_argument_value"});const n=[["--output-limit",e.outputLimit],["--output-include",e.outputInclude],["--output-session",e.outputSession],["--output-cursor",e.outputCursor],["--output-row-contract",e.outputRowContract===!0?"true":void 0],["--output-budget",e.outputBudget==="unbounded"?void 0:e.outputBudget]].filter(t=>typeof t[1]=="string").map(([t])=>t);if(n.length!==0)throw new _(`pm package list does not apply ${n.join(", ")}: it returns every installed package. Narrow rows with --fields, or use pm package manage or pm package catalog for read-output controls.`,y.USAGE,{code:"read_output_surface_unsupported",flag:n[0],details:{command:"package list",output_option_keys:n},required:"Drop the row-shaping output controls; pm package list keeps --output-format and an unbounded --output-budget.",examples:["pm package list --fields name,version,update"]})}const D=16*1024*1024,L=1024*1024,S=4*1024*1024;async function x(e){try{const n=await m(s.join(e,"settings.json"),S,{followLinks:!0}),t=n===void 0?void 0:JSON.parse(n);return typeof t=="object"&&t!==null?t:void 0}catch{return}}async function ne(e){const n=(await x(e))?.output?.default_format;return n==="json"||n==="toon"?n:void 0}async function ae(e){return(await x(e))?.ux?.deprecation_hints!==!1}const re=["name","directory","scope","installed","status","configured_enabled","managed","runtime_active","version","update"];function c(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function g(e){return e!=="invalid"&&e!=="unreadable"}function G(e){const n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))throw new SyntaxError("Invalid settings object");const t=n.extensions;if(t===void 0)return{enabled:[],disabled:[]};if(typeof t!="object"||t===null||Array.isArray(t))throw new SyntaxError("Invalid extensions settings");const a=t;if(a.enabled!==void 0&&(!Array.isArray(a.enabled)||!a.enabled.every(r=>typeof r=="string"))||a.disabled!==void 0&&(!Array.isArray(a.disabled)||!a.disabled.every(r=>typeof r=="string")))throw new SyntaxError("Invalid extension enablement lists");return{enabled:a.enabled??[],disabled:a.disabled??[]}}async function U(e){let n;try{n=await m(e,S,{followLinks:!0})}catch(t){return c(t)?{status:"absent",enabled:[],disabled:[]}:{status:"unreadable",enabled:[],disabled:[],error:{code:"settings_unreadable",path:e}}}if(n===void 0)return{status:"unreadable",enabled:[],disabled:[],error:{code:"settings_unreadable",path:e}};try{return{status:"ok",...G(n)}}catch{return{status:"invalid",enabled:[],disabled:[],error:{code:"settings_invalid",path:e}}}}async function B(e){let n;try{n=await m(e,D,{followLinks:!0})}catch(t){if(c(t))try{if((await h.stat(s.dirname(e))).isDirectory())return{status:"absent",entries:[]}}catch(a){if(c(a))return{status:"absent",entries:[]}}return{status:"unreadable",entries:[],error:{code:"managed_state_unreadable",path:e}}}if(n===void 0)return{status:"unreadable",entries:[],error:{code:"managed_state_unreadable",path:e}};try{const t=JSON.parse(n),a=O(t);if(!a||typeof t!="object"||t===null||!Array.isArray(t.entries)||a.entries.length!==t.entries.length)throw new SyntaxError("Invalid managed extension state");return{status:"ok",entries:a.entries}}catch{return{status:"invalid",entries:[],error:{code:"managed_state_invalid",path:e}}}}async function z(e){try{return{directories:(await h.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,a)=>t.localeCompare(a))}}catch(n){return c(n)?{directories:[]}:{directories:[],error:{code:"extensions_unreadable",path:e}}}}async function Y(e){let n;try{n=await m(e,L,{followLinks:!0})}catch(t){return c(t)?{manifest:null,error:{code:"manifest_invalid",path:e}}:{manifest:null,error:{code:"manifest_unreadable",path:e}}}if(n===void 0)return{manifest:null,error:{code:"manifest_unreadable",path:e}};try{const t=N(JSON.parse(n));return t?{manifest:t}:{manifest:null,error:{code:"manifest_invalid",path:e}}}catch{return{manifest:null,error:{code:"manifest_invalid",path:e}}}}function J(e,n,t){return e.find(a=>d(a.name)===d(n)||d(a.directory)===d(t))}function X(e){const n=e.manifest?.name??e.directory,t=new Set(v(e.settings.enabled)),a=new Set(v(e.settings.disabled)),r=!g(e.settings.status)||!e.manifest?null:!a.has(n)&&(t.size===0||t.has(n)),i=g(e.managed.status)?J(e.managed.entries,n,e.directory)!==void 0:null;return{name:n,directory:e.directory,scope:e.scope,installed:!0,status:e.manifest?r===!1?"inactive":"installed":"malformed_manifest",configured_enabled:r,managed:i,runtime_active:null,...e.manifest?{version:e.manifest.version}:{}}}function q(e,n,t,a){const r=t.find(p=>p.directory===n),i={name:e.name,version:e.version,updated_at:r?.updated_at,source:r?.source};return{...e,update:F(R(a,i))}}async function oe(e){const n=e.scope??"project",t=n==="global"?I(e.cwd??process.cwd()):e.pmRoot,a=s.join(t,"extensions"),r=await U(s.join(t,"settings.json")),i=await B(s.join(a,".managed-extensions.json")),p=await z(a),u=[];for(const o of[r,i,p])o.error&&u.push(o.error);const f=e.name?.trim(),E=await M(t),A=i.entries,l=[];for(const o of p.directories){const k=s.join(a,o,"manifest.json"),b=await Y(k);b.error&&u.push(b.error);const w=X({directory:o,scope:n,manifest:b.manifest,settings:r,managed:i});f&&![w.name,o].some(T=>d(T)===d(f))||l.push(q(w,o,A,E))}f&&l.length===0&&u.every(o=>o.code!=="extensions_unreadable")&&l.push({name:f,directory:null,scope:n,installed:!1,status:"absent",configured_enabled:g(r.status)?!1:null,managed:g(i.status)?!1:null,runtime_active:null});const j=l.filter(o=>typeof o.update=="string").length;return{scope:n,complete:u.length===0,settings_status:r.status,managed_state_status:i.status,updates_available:j,extensions:l,errors:u}}export{re as INVENTORY_ROW_FIELDS,oe as inspectStaticExtensionInventory,de as parseListingFields,ue as projectListingRows,ne as readStaticDefaultOutputFormat,ae as readStaticDeprecationHints,ee as refuseStaticInventoryForeignOptions,te as refuseStaticInventoryReadOutputControls};
2
2
  //# sourceMappingURL=static-inventory.js.map
@@ -1,2 +1,2 @@
1
- import{nowIso as v}from"../../core/shared/time.js";import{spawn as S}from"node:child_process";import{AsyncLocalStorage as C}from"node:async_hooks";import{isMainThread as A}from"node:worker_threads";import b from"npm-package-arg";import{killProcessTree as D}from"../../core/shared/process-tree.js";import{resolveNpmCommandName as R,shouldRunNpmCommandInShell as K}from"./install-sources.js";const L="PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS",B=1e4,G=1e3,H=25e3,X=2e3,V="npm_registry_lookup_failed",Q="npm_registry_lookup_timed_out",z="github_remote_lookup_failed",F="github_remote_lookup_timed_out";function y(e=process.env){const t=e[L]?.trim(),r=t?Number(t):Number.NaN;return Number.isFinite(r)?Math.min(H,Math.max(G,Math.trunc(r))):B}class c extends Error{timeout_ms;teardown;constructor(t,r,n){super(t),this.name="UpdateQueryError",this.timeout_ms=r,this.teardown=n}}const O=new WeakMap;function oe(e){return O.get(e)??Promise.resolve()}function I(e,t){const r={checked_at:e,available:null,error:t instanceof Error?t.message:String(t)};return t instanceof c&&t.timeout_ms!==void 0&&(r.timeout_ms=t.timeout_ms),t instanceof c&&t.teardown!==void 0&&O.set(r,t.teardown),r}const _=new Set;function M(){for(const e of _)e()}const N=new C;async function se(e){const t=new Set;try{return await N.run(t,e)}finally{A||await Promise.all(t)}}function W(e){return _.size===0&&process.on("exit",M),_.add(e),()=>{_.delete(e),_.size===0&&process.off("exit",M)}}function Y(e){const t=()=>e.exitCode!==null||e.signalCode!==null,r=()=>{t()||e.kill("SIGKILL")},n=()=>t()||e.pid===void 0?Promise.resolve():new Promise(s=>{const o=setTimeout(()=>{e.unref(),s()},X);e.once("exit",()=>{clearTimeout(o),s()})}),i=()=>(r(),e.stdout?.destroy(),n());return{stop:()=>t()||e.pid===void 0?Promise.resolve().then(i):D(e.pid,{kill:r,alive:()=>!t()}).then(i,i),killNow:r}}function P(e,t,r,n){return new Promise((i,s)=>{let o;try{o=S(e,t,{env:n.env,shell:n.shell,stdio:["ignore","pipe","ignore"]})}catch{s(new c(n.failed));return}const a=o,u=performance.now()+r;let f=!1,E="",T=0;const h=Y(a),k=N.getStore();let w;const p=()=>{const d=W(h.killNow),l=new Promise(g=>{setTimeout(()=>{h.stop().then(g,g)},0)}).finally(d);return k?.add(l),w=l,l},x=setTimeout(()=>{m(new c(n.timedOut,r,p()))},r);function m(d){f||(f=!0,clearTimeout(x),performance.now()>=u?s(new c(n.timedOut,r,w)):d?s(d):i(E.trim()))}if(a.on("error",()=>m(new c(n.failed))),!a.stdout){m(new c(n.failed,void 0,p()));return}a.stdout.setEncoding("utf8"),a.stdout.on("data",d=>{if(!f){if(T+=Buffer.byteLength(d),T>n.maxBuffer){m(new c(n.failed,void 0,p()));return}E+=d}}),a.on("exit",(d,l)=>{d===0&&l===null||(m(new c(n.failed)),a.stdout.destroy())}),a.on("close",(d,l)=>m(d===0&&l===null?void 0:new c(n.failed)))})}function U(e,t,r){if(typeof t=="string")try{const n=b.resolve(e,t);if(n.type==="version")return n.fetchSpec}catch{}throw new Error(r)}const Z=(e,t)=>P(R(),e,t,{env:{...process.env,npm_config_ignore_scripts:"true"},shell:K(),maxBuffer:64*1024,timedOut:Q,failed:V}),$=(e,t)=>P("git",e,t,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never"},maxBuffer:1024*1024,timedOut:F,failed:z});async function ae(e,t=Z,r=y()){const n=v();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");const i=U(e.package,e.version,"missing_or_invalid_installed_npm_version"),s=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],r);let o;try{o=JSON.parse(s)}catch{throw new Error("invalid_npm_registry_metadata")}const a=Array.isArray(o)&&o.length===1?o[0]:o,u=U(e.package,a,"invalid_npm_registry_version");return{checked_at:n,available:u!==i,remote_version:u}}catch(i){return I(n,i)}}const J=(e,t,r)=>{const n=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{const[a,u=""]=o.split(/\s+/);return{commit:a,ref:u}}),i=n.find(o=>o.ref.endsWith("^{}"))??n[0];if(!i)return{checked_at:r,available:null,error:"no_remote_reference_found"};const s=t?.trim();return s?{checked_at:r,remote_commit:i.commit,available:i.commit!==s}:{checked_at:r,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},de=async(e,t=$,r=y())=>{const n=v();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{const i=[e.ref?.trim(),"HEAD"].find(Boolean),s=await t(["ls-remote",e.repository,i,`${i}^{}`],r);return J(s,e.commit,n)}catch(i){return I(n,i)}};export{B as EXTENSION_UPDATE_CHECK_TIMEOUT_DEFAULT_MS,z as GITHUB_REMOTE_LOOKUP_FAILED,F as GITHUB_REMOTE_LOOKUP_TIMED_OUT,V as NPM_REGISTRY_LOOKUP_FAILED,Q as NPM_REGISTRY_LOOKUP_TIMED_OUT,L as PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS_ENV,de as checkGithubUpdate,ae as checkNpmUpdate,y as resolveExtensionUpdateCheckTimeoutMs,oe as updateCheckTeardown,se as withUpdateCheckTeardownScope};
1
+ import{nowIso as m}from"../../core/shared/time.js";import{spawn as k}from"node:child_process";import{AsyncLocalStorage as C}from"node:async_hooks";import{isMainThread as b}from"node:worker_threads";import A from"npm-package-arg";import{killProcessTree as R}from"../../core/shared/process-tree.js";import{isNewerRegistryVersion as D}from"./npm-spec.js";import{resolveNpmCommandName as K,shouldRunNpmCommandInShell as L}from"./install-sources.js";const B="PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS",G=1e4,H=1e3,V=25e3,X=2e3,Q="npm_registry_lookup_failed",z="npm_registry_lookup_timed_out",F="github_remote_lookup_failed",W="github_remote_lookup_timed_out";function y(e=process.env){const t=e[B]?.trim(),r=t?Number(t):Number.NaN;return Number.isFinite(r)?Math.min(V,Math.max(H,Math.trunc(r))):G}class l extends Error{timeout_ms;teardown;constructor(t,r,n){super(t),this.name="UpdateQueryError",this.timeout_ms=r,this.teardown=n}}const N=new WeakMap;function ae(e){return N.get(e)??Promise.resolve()}function O(e,t){const r={checked_at:e,available:null,error:t instanceof Error?t.message:String(t)};return t instanceof l&&t.timeout_ms!==void 0&&(r.timeout_ms=t.timeout_ms),t instanceof l&&t.teardown!==void 0&&N.set(r,t.teardown),r}const _=new Set;function I(){for(const e of _)e()}const M=new C;async function de(e){const t=new Set;try{return await M.run(t,e)}finally{b||await Promise.all(t)}}function Y(e){return _.size===0&&process.on("exit",I),_.add(e),()=>{_.delete(e),_.size===0&&process.off("exit",I)}}function Z(e){const t=()=>e.exitCode!==null||e.signalCode!==null,r=()=>{t()||e.kill("SIGKILL")},n=()=>t()||e.pid===void 0?Promise.resolve():new Promise(i=>{const a=setTimeout(()=>{e.unref(),i()},X);e.once("exit",()=>{clearTimeout(a),i()})}),o=()=>(r(),e.stdout?.destroy(),n());return{stop:()=>t()||e.pid===void 0?Promise.resolve().then(o):R(e.pid,{kill:r,alive:()=>!t()}).then(o,o),killNow:r}}function P(e,t,r,n){return new Promise((o,i)=>{let a;try{a=k(e,t,{env:n.env,shell:n.shell,stdio:["ignore","pipe","ignore"]})}catch{i(new l(n.failed));return}const s=a,f=performance.now()+r;let p=!1,T="",w=0;const h=Z(s),x=M.getStore();let g;const E=()=>{const d=Y(h.killNow),c=new Promise(v=>{setTimeout(()=>{h.stop().then(v,v)},0)}).finally(d);return x?.add(c),g=c,c},S=setTimeout(()=>{u(new l(n.timedOut,r,E()))},r);function u(d){p||(p=!0,clearTimeout(S),performance.now()>=f?i(new l(n.timedOut,r,g)):d?i(d):o(T.trim()))}if(s.on("error",()=>u(new l(n.failed))),!s.stdout){u(new l(n.failed,void 0,E()));return}s.stdout.setEncoding("utf8"),s.stdout.on("data",d=>{if(!p){if(w+=Buffer.byteLength(d),w>n.maxBuffer){u(new l(n.failed,void 0,E()));return}T+=d}}),s.on("exit",(d,c)=>{d===0&&c===null||(u(new l(n.failed)),s.stdout.destroy())}),s.on("close",(d,c)=>u(d===0&&c===null?void 0:new l(n.failed)))})}function U(e,t,r){if(typeof t=="string")try{const n=A.resolve(e,t);if(n.type==="version")return n.fetchSpec}catch{}throw new Error(r)}const $=(e,t)=>P(K(),e,t,{env:{...process.env,npm_config_ignore_scripts:"true"},shell:L(),maxBuffer:64*1024,timedOut:z,failed:Q}),J=(e,t)=>P("git",e,t,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never"},maxBuffer:1024*1024,timedOut:W,failed:F});async function le(e,t=$,r=y()){try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");const n=U(e.package,e.version,"missing_or_invalid_installed_npm_version"),o=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],r);let i;try{i=JSON.parse(o)}catch{throw new Error("invalid_npm_registry_metadata")}const a=Array.isArray(i)&&i.length===1?i[0]:i,s=U(e.package,a,"invalid_npm_registry_version");return{checked_at:m(),available:D(s,n),remote_version:s}}catch(n){return O(m(),n)}}const q=(e,t,r)=>{const n=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{const[s,f=""]=a.split(/\s+/);return{commit:s,ref:f}}),o=n.find(a=>a.ref.endsWith("^{}"))??n[0];if(!o)return{checked_at:r,available:null,error:"no_remote_reference_found"};const i=t?.trim();return i?{checked_at:r,remote_commit:o.commit,available:o.commit!==i}:{checked_at:r,remote_commit:o.commit,available:null,error:"missing_installed_commit"}},ce=async(e,t=J,r=y())=>{if(e.kind!=="github"||!e.repository)return{checked_at:m(),available:null,error:"not_a_github_managed_source"};try{const n=[e.ref?.trim(),"HEAD"].find(Boolean),o=await t(["ls-remote",e.repository,n,`${n}^{}`],r);return q(o,e.commit,m())}catch(n){return O(m(),n)}};export{G as EXTENSION_UPDATE_CHECK_TIMEOUT_DEFAULT_MS,F as GITHUB_REMOTE_LOOKUP_FAILED,W as GITHUB_REMOTE_LOOKUP_TIMED_OUT,Q as NPM_REGISTRY_LOOKUP_FAILED,z as NPM_REGISTRY_LOOKUP_TIMED_OUT,B as PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS_ENV,ce as checkGithubUpdate,le as checkNpmUpdate,y as resolveExtensionUpdateCheckTimeoutMs,ae as updateCheckTeardown,de as withUpdateCheckTeardownScope};
2
2
  //# sourceMappingURL=update-check.js.map
@@ -0,0 +1,3 @@
1
+ import{constants as h}from"node:fs";import _ from"node:fs/promises";import d from"node:path";import{isReproducibleExecutionActive as M}from"../../core/reproducibility/context.js";import{acquireLockLease as T}from"../../core/lock/lock.js";import{writeFileAtomic as L}from"../../core/fs/fs-utils.js";import{normalizeManagedState as R,resolveManagedExtensionStatePath as C}from"./managed-state.js";import{isFileMissingError as U}from"../../core/fs/fs-utils.js";import{isExactNpmVersion as w,isNewerRegistryVersion as B,isRegistryNpmSource as E}from"./npm-spec.js";import{normalizeExtensionNameForMatch as u}from"./shared.js";const F="extension-update-observations.json",b=1,D=64*1024,I=16*1024*1024,O=1024*1024,V=300*1e3,A=2e3;function g(t){return d.join(t,"runtime",F)}const S=256;function l(t,e){const n=t[e];return typeof n=="string"&&n.length>0&&n.length<=S?n:void 0}function $(t){const e=Date.parse(t);return Number.isFinite(e)&&e<=Date.now()+V}function j(t){return t.remote_version===void 0||t.remote_version===null?null:l(t,"remote_version")}function X(t){if(typeof t!="object"||t===null||Array.isArray(t))return;const e=t,n=l(e,"name"),a=l(e,"installed_version"),r=l(e,"installed_updated_at"),i=l(e,"checked_at"),o=j(e);if(!(n===void 0||a===void 0||r===void 0||o===void 0)&&!(i===void 0||!$(i)||typeof e.update_available!="boolean"))return{name:n,installed_version:a,installed_updated_at:r,remote_version:o,update_available:e.update_available,checked_at:i}}const z=".stale-cleanup",K=64*1024;async function P(t){try{const e=await _.lstat(t);return!e.isFile()||e.size>K}catch{return!1}}async function x(t){try{return!(await _.lstat(t)).isDirectory()}catch{return!1}}async function W(t){const e=g(t);try{if(await x(d.dirname(e)))return[];const n=await k(e,O);if(n===void 0)return[];const a=JSON.parse(n),r=typeof a=="object"&&a!==null?a:{};return(r.version===b&&Array.isArray(r.observations)?r.observations:[]).flatMap(o=>X(o)??[])}catch{return[]}}function G(t=h,e=!1){return t.O_RDONLY|(e?0:t.O_NOFOLLOW??0)|(t.O_NONBLOCK??0)}async function k(t,e,n={}){if(n.followLinks!==!0&&!(await _.lstat(t)).isFile())return;const a=await _.open(t,G(h,n.followLinks===!0));try{if(!(await a.stat()).isFile())return;const r=Buffer.alloc(Math.min(D,e+1)),i=[];let o=0;for(;o<=e;){const{bytesRead:s}=await a.read(r,0,Math.min(r.length,e+1-o),o);if(s===0)break;i.push(Buffer.from(r.subarray(0,s))),o+=s}return o>e?void 0:Buffer.concat(i,o).toString("utf8")}finally{await a.close()}}function Y(t){return t.flatMap(e=>typeof e.last_update_check_at=="string"&&e.update_error===void 0&&typeof e.update_available=="boolean"&&(e.source.kind==="github"||E(e.source))&&[e.name,e.manifest_version,e.updated_at,e.last_update_remote_version??""].every(n=>n.length<=S)?[{name:e.name,installed_version:e.manifest_version,installed_updated_at:e.updated_at,remote_version:e.last_update_remote_version??e.last_update_remote_commit?.slice(0,12)??null,update_available:e.update_available,checked_at:e.last_update_check_at}]:[]).sort((e,n)=>e.name.localeCompare(n.name))}async function H(t){let e;try{e=await k(C(t),I,{followLinks:!0})}catch(n){return U(n)?[]:void 0}if(e!==void 0)try{const n=JSON.parse(e),a=R(n),r=n.entries;return a!==null&&Array.isArray(r)&&r.length===a.entries.length?a.entries:void 0}catch{return}}function p(t){const e=new Map;for(const n of t){const a=`${u(n.name)}\0${n.installed_version}\0${n.installed_updated_at}`,r=e.get(a);(r===void 0||Date.parse(r.checked_at)<=Date.parse(n.checked_at))&&e.set(a,n)}return[...e.values()]}function J(t,e){return u(t.name)===u(e.name)&&t.installed_version===e.manifest_version&&t.installed_updated_at===e.updated_at}async function q(t,e,n){if(n.length===0)return;const a=g(t),r=async()=>{if(await x(d.dirname(a)))throw new Error(`${d.dirname(a)} is not a directory`)};await r();const i=d.join(t,"locks","extension-update-observations.lock");for(const s of[i,d.join(`${i}${z}`,"owner.json")])if(await P(s))throw new Error("update observation lock metadata is not a small regular file");const o=await T(t,"extension-update-observations",30,"pm package manage",!1,!1,A,{maxWaitMs:A});try{await r();const s=[...await W(t),...n],m=await H(e),N=(m===void 0?p(s):m.flatMap(c=>p(s.filter(f=>J(f,c)&&y(f,c.source))))).sort((c,f)=>c.name.localeCompare(f.name)),v=`${JSON.stringify({version:b,observations:N},null,2)}
2
+ `;if(Buffer.byteLength(v,"utf8")>O)throw new Error("update observation record exceeds its size limit");await o.fence(()=>L(a,v))}finally{await o.release()}}async function ue(t,e,n,a){if(!(a||M()))try{await q(t,e,Y(n));return}catch(r){const i=r?.context?.code;return typeof i=="string"&&i.length>0?`extension_update_observation_write_failed:${i}`:"extension_update_observation_write_failed"}}function le(t,e){if(typeof e.version!="string"||e.updated_at===void 0)return;const n=u(e.name);return p(t.filter(a=>u(a.name)===n&&a.installed_version===e.version&&a.installed_updated_at===e.updated_at&&y(a,e.source)))[0]}function Q(t,e){const n=e?.trim().toLowerCase(),a=t.remote_version?.toLowerCase();return!n||a===void 0||!/^[0-9a-f]{7,40}$/u.test(a)?!1:n.startsWith(a)!==t.update_available}function y(t,e){return e===void 0?!0:e.kind==="github"?Q(t,e.commit):E(e)?typeof e.version=="string"&&w(e.version)&&t.remote_version!==null&&w(t.remote_version)&&B(t.remote_version,e.version)===t.update_available:t.update_available===!1}function ce(t){return t?.update_available===!0?t.remote_version??"available":null}export{F as EXTENSION_UPDATE_OBSERVATIONS_FILE,Y as collectExtensionUpdateObservations,le as findApplicableUpdateObservation,k as readBoundedRegularFile,W as readExtensionUpdateObservations,H as readStrictManagedRecords,ue as recordCheckedUpdateObservations,q as recordExtensionUpdateObservations,g as resolveExtensionUpdateObservationsPath,G as resolveGuardedReadFlags,ce as resolveObservedUpdateVersion};
3
+ //# sourceMappingURL=update-observations.js.map
@@ -0,0 +1,2 @@
1
+ import o from"node:path";import{renderPmCommand as p}from"../command-line.js";function c(r,e,n=!1){return["project","global"].filter(t=>r.some(a=>a.scope===t)).map(t=>p(["--pm-path",s(e),...n?["--no-extensions"]:[],"package","manage",`--${t}`]))}function s(r){const e=o.resolve(r);return/\s$/u.test(e)?`${e}${o.sep}.`:e}export{c as buildExtensionUpgradeHints,s as renderTrimSafeTrackerPath};
2
+ //# sourceMappingURL=upgrade-hints.js.map
@@ -12,6 +12,8 @@ export type ExtensionScope="project"|"global";
12
12
  export type ExtensionActivationStatus="ok"|"failed"|"not_loaded"|"unknown";
13
13
  /** Documents the extension command options payload exchanged by command, SDK, and package integrations. */
14
14
  export interface ExtensionCommandOptions{
15
+ /** Declared lifecycle scope from MCP and SDK callers; selects the same scope as the `project`/`local`/`global` switches. */
16
+ scope?:"project"|"local"|"global";
15
17
  /** Value that configures or reports install for this contract. */
16
18
  install?:boolean;
17
19
  /** Value that configures or reports uninstall for this contract. */
@@ -1,2 +1,2 @@
1
- import O from"node:fs/promises";import A from"node:path";import{activateExtensions as M,createSerialQueue as ze,loadExtensions as P,nextExtensionReloadToken as se}from"../core/extensions/index.js";import{describeExtensionActivation as qe}from"../core/extensions/activation-summary.js";import{createExtensionContributionInventory as Be}from"../core/extensions/contribution-inventory.js";import{resolveExtensionRoots as We}from"../core/extensions/loader.js";import{pathExists as W}from"../core/fs/fs-utils.js";import{resolvePmPackageRootFromModule as Xe}from"../core/packages/root.js";import{EXIT_CODE as y}from"../core/shared/constants.js";import{PmCliError as x}from"../core/shared/errors.js";import{levenshteinDistanceWithinLimit as He}from"../core/shared/levenshtein.js";import{nowIso as F}from"../core/shared/time.js";import{resolveGlobalPmRoot as Ke,resolvePmRoot as Ve}from"../core/store/paths.js";import{readSettings as $,writeSettings as X}from"../core/store/settings.js";import{quoteCommandArg as Ye,renderPmCommand as Je}from"./command-line.js";import{createUnknownSubcommandError as Qe}from"./agent/subcommand-recovery.js";import{ensureTypeFolderScaffold as Ze}from"./schema.js";import{normalizeStringList as C,normalizeExtensionNameForMatch as h,normalizeManagedDirectoryName as et,parseExtensionManifest as re,validateExtensionDirectory as G}from"./extension/shared.js";import{managedExtensionSourcesEquivalent as tt,readManagedExtensionState as T,writeManagedExtensionState as j,upsertManagedEntry as H,persistManagedContributionInventory as nt,resolveManagedExtensionStatePath as at}from"./extension/managed-state.js";import{parseExtensionInstallSource as le,resolveInstallSource as ot,areDirectoriesEquivalent as it}from"./extension/install-sources.js";import{resolveBundledExtensionAliasSource as st,isBundledPackageInstallAllTarget as rt,listBundledPackageAliases as lt,resolveBundledAliasManifestName as ct,buildBundledPackageCatalog as dt}from"./extension/bundled-catalog.js";import{scaffoldExtensionProject as ut}from"./extension/scaffold.js";import{buildExtensionDescribeResult as mt}from"./extension/describe.js";import{applyDoctorRuntimeActivationState as K,classifyDoctorLoadFailureWarnings as pt,classifyDoctorActivationFailureWarnings as _t,classifyUnusedCapabilityWarnings as gt,buildExtensionTriageSummary as V,parseDoctorDetailMode as ft,collectUnknownCapabilityGuidance as ht,buildCapabilityContractMetadata as wt,buildDoctorConsistencySummary as bt,summarizeExtensionFailures as ce}from"./extension/doctor.js";import{copyExtensionDirectoryForInstall as de,copyExtensionDirectoryWithoutSelfNesting as vt,ensureExtensionModuleTypeMarker as yt,ensureInstalledExtensionSdkLink as xt,isErrnoCode as kt,isRetriableExtensionInstallCopyError as Et,resolveCanonicalExtensionInstallDestination as St,withExtensionInstallLock as Y}from"./extension/install-runtime.js";import{mapWithFixedConcurrency as Rt}from"./extension/concurrency.js";import{summarizeRuntimeCommandPathsForExtension as At}from"./extension/runtime-summary.js";import{collectGlobalOutputOverrideDoctorWarnings as ue}from"./extension/output-ownership.js";import{collectMcpCustomFieldCollisionDoctorWarnings as me}from"./extension/custom-field-collisions.js";import{checkGithubUpdate as It,EXTENSION_UPDATE_CHECK_TIMEOUT_DEFAULT_MS as Ct,resolveExtensionUpdateCheckTimeoutMs as $t,withUpdateCheckTeardownScope as Tt}from"./extension/update-check.js";import{refreshManagedExtensionUpdates as Dt}from"./extension/managed-update-status.js";import{runExtensionMigrateAction as Ot}from"./extension/migrations.js";import{buildBundledInstallReceipt as Mt}from"./extension/install-receipts.js";import{buildExtensionInstallPlan as Pt}from"./extension/install-plan.js";import{inspectExtensionAuthorManifestAtPmRoot as jt}from"./extension/author-manifest.js";import{resolveExtensionInstallSourceIdentity as Lt}from"./extension/source-resolution.js";import{readOptionalMetadataFile as Nt,withVerifiedExtensionInstall as Ft}from"./extension/install-snapshot.js";const pe=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],Gt=pe.map(([,,e])=>e).filter((e,t,a)=>a.indexOf(e)===t).join(", "),Ut={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},zt="__pm_native_output",qt=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],_e=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Bt=["disabled","require_trusted","require_provenance"],ge={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},Wt=e=>{const t=e??ge,a={};for(const n of qt)a[n]=C(t[n]??[]);return a},Xt=(e,t)=>{for(const a of _e)t[a].length>0&&(e[a]=t[a]);return e},Ht=(e,t)=>{for(const a of Bt)t[a]===!0&&(e[a]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Kt=e=>{const t={};for(const a of _e)t[a]=C(e[a]??[]);return t},Vt=e=>{const t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Xt(Ht({name:t},e),Kt(e))},Yt=e=>(e??[]).map(t=>Vt(t)).filter(t=>t!==null).sort((t,a)=>t.name.localeCompare(a.name)),fe=e=>{const t=Object.assign({},ge,e??{}),a=Wt(e),n=Yt(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:a.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:a.allowed_extensions,blocked_extensions:a.blocked_extensions,allowed_capabilities:a.allowed_capabilities,blocked_capabilities:a.blocked_capabilities,allowed_surfaces:a.allowed_surfaces,blocked_surfaces:a.blocked_surfaces,allowed_commands:a.allowed_commands,blocked_commands:a.blocked_commands,allowed_actions:a.allowed_actions,blocked_actions:a.blocked_actions,allowed_services:a.allowed_services,blocked_services:a.blocked_services,extension_overrides:n}},J=async(e,t)=>{const a=[t],n=await ct(t);n&&a.push(n);const o=[...new Set(a.map(i=>h(i)).filter(i=>i.length>0))];for(const i of o){const d=e.find(r=>h(r.name)===i);if(d)return d;const s=e.find(r=>h(r.directory)===i);if(s)return s}},he=(e,t)=>{const a=t.trim(),n=new Set(C(e.extensions.enabled));return new Set(C(e.extensions.disabled)).has(a)?!1:n.size===0?!0:n.has(a)},we=(e,t)=>{const a=t.trim(),n=new Set(C(e.extensions.enabled)),o=new Set(C(e.extensions.disabled)),i=[...n],d=[...o];return o.delete(a),n.size>0&&n.add(a),e.extensions.enabled=[...n].sort((s,r)=>s.localeCompare(r)),e.extensions.disabled=[...o].sort((s,r)=>s.localeCompare(r)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==d.join("\0")},Jt=(e,t)=>{const a=t.trim(),n=new Set(C(e.extensions.enabled)),o=new Set(C(e.extensions.disabled)),i=[...n],d=[...o];return n.delete(a),o.add(a),e.extensions.enabled=[...n].sort((s,r)=>s.localeCompare(r)),e.extensions.disabled=[...o].sort((s,r)=>s.localeCompare(r)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==d.join("\0")},be=(e,t)=>{const a=t.trim(),n=new Set(C(e.extensions.enabled)),o=new Set(C(e.extensions.disabled)),i=[...n],d=[...o];return n.delete(a),o.delete(a),e.extensions.enabled=[...n].sort((s,r)=>s.localeCompare(r)),e.extensions.disabled=[...o].sort((s,r)=>s.localeCompare(r)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==d.join("\0")},Qt=e=>{const t=e.trim().toLowerCase(),a=Math.min(2,Math.max(1,Math.ceil(t.length/4))),n=pe.map(([o,i,d])=>({action:i,flag:d,distance:He(t,o,a)})).filter(o=>o.distance!==null).sort((o,i)=>o.distance-i.distance)[0];return n?{action:n.action,flag:n.flag}:null},Zt=(e,t)=>{const a=t.vocabulary==="package"?"package":"extension",n=Qt(e);if(!n)return new x(`One action flag is required. Use one of: ${Gt}. Bare \`pm package\` and \`pm extension\` default to --explore.`,y.USAGE);const o=`pm ${a} ${n.flag}`;return Qe({command_path:a,display_name:`${a} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(ve),retry_command:o,message_suffix:`. Did you mean "${n.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:o,reason:`nearest lifecycle action for "${e}"`}]})},en=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],ve={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},tn=e=>ve[e]??null,ye=(e,t)=>{const a=[...new Set(en.filter(([n])=>t[n]===!0).map(([,n])=>n))];if(a.length===0){if(e===void 0)return"explore";const n=tn(e.trim().toLowerCase());if(n)return n;throw Zt(e,t)}if(a.length>1)throw new x("Extension action flags are mutually exclusive.",y.USAGE);return a[0]},xe=e=>{const t=e.project===!0||e.local===!0,a=e.global===!0;if(t&&a)throw new x('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return a?"global":"project"},nn=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{const t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{const t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],Q=e=>{for(const t of nn){const a=t(e);if(a)return a}return{status:"not_checked",reason:"no_update_check_recorded"}},ke=(e,t,a,n)=>{const o=a??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:o.contributions,managed:!!a,source:o.source,update_available:o.update_available,last_update_check_at:o.last_update_check_at,last_update_remote_commit:o.last_update_remote_commit,last_update_remote_version:o.last_update_remote_version,update_error:o.update_error,...n.status==="failed"&&o.update_check_timeout_ms!==void 0?{update_check_timeout_ms:o.update_check_timeout_ms}:{},update_check_status:n.status,update_check_reason:n.reason}},an=(e,t,a,n)=>{const o=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},n),i=n?he(a,n.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:ke({name:o.name,directory:e,version:o.manifest_version,entry:o.manifest_entry,enabled:i},t,n,Q(n))}},on=async(e,t,a,n,o,i)=>{const d=A.join(e,t),s=A.join(d,"manifest.json"),r=i.get(h(t));if(!await W(s))return an(t,a,n,r);const l=Symbol("invalid-extension-manifest-json"),c=await O.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>l);if(c===l)return{warning:`extension_manifest_invalid_json:${a}:${t}`};const u=re(c);if(!u)return{warning:`extension_manifest_invalid:${a}:${t}`};const p=o.get(h(u.name))??i.get(h(t));return{summary:ke({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:he(n,u.name)},a,p,Q(p))}},I=async(e,t,a,n)=>{if(!await W(e))return{extensions:[],warnings:[]};const i=(await O.readdir(e,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name).sort((c,u)=>c.localeCompare(u)),d=new Map(n.entries.map(c=>[h(c.name),c])),s=new Map(n.entries.map(c=>[h(c.directory),c])),r=[],l=[];for(const c of i){const u=await on(e,c,t,a,d,s);u.warning&&r.push(u.warning),u.summary&&l.push(u.summary)}return{extensions:l.sort((c,u)=>c.name.localeCompare(u.name)),warnings:r.sort((c,u)=>c.localeCompare(u))}},sn=ze(),Ee=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(a=>a?.trim())?.trim()??e,Se=(e,t,a,n)=>{const o=a.command_paths.map(s=>`pm ${s} --help`),i=n?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,d=a.command_paths.length>0?[...o]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return i&&d.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Ee(e,t),extension_name:e,command_paths:a.command_paths,action_paths:a.action_paths,help_commands:o,next_steps:d,...i?{sdk_dependency_status:"missing"}:{}}},rn=e=>{const t=e.trace,a={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(a.trace=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)),t.missing_capability&&(a.missing_capability=t.missing_capability),t.hint&&(a.hint=t.hint)),a},Z=e=>e.map(t=>rn(t)).sort((t,a)=>`${t.layer}:${t.name}`.localeCompare(`${a.layer}:${a.name}`)),ee=(e,t,a)=>{const n=h(e);return t.find(o=>(a===void 0||o.layer===a)&&h(o.name)===n)},Re=(e,t,a,n)=>a.find(i=>i.scope===t&&h(i.name)===h(e))?.activation_status??(n?"failed":"unknown"),Ae=(e,t,a,n,o)=>sn.enqueue(async()=>{const i=process.env.PM_CLI_PACKAGE_ROOT,d=await O.mkdtemp(A.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Xe(import.meta.url,["../.."]);try{const s=await P({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:o.noExtensions===!0,reload_token:se(),cache_bust:!0,module_graph_snapshot_root:d}),r=await M({...s}),l=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...Z(r.failed)],c=Object.fromEntries(s.loaded.map(u=>[h(u.name),Be(qe(r,{extensionName:u.name}))]));return{installed:K(n,s,r),warnings:[...s.warnings,...r.warnings],activation_failures:l,extensions_disabled:s.disabled_by_flag,item_type_registrations:r.registrations.item_types,contribution_inventories:c}}finally{await O.rm(d,{recursive:!0,force:!0}),i===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=i}}),U=async(e,t,a,n)=>{const o=a.filter(r=>!r.managed),i=[...o].sort((r,l)=>{const c=r.name.localeCompare(l.name);return c!==0?c:r.directory.localeCompare(l.directory)});let d=n;const s=[];for(const r of i){const l=A.join(e,r.directory),c=await G(l),u=F(),p={kind:"local",input:r.name,location:l};d=H(d,{name:c.manifest.name,directory:r.directory,scope:t,manifest_version:c.manifest.version,manifest_entry:c.manifest.entry,capabilities:[...c.manifest.capabilities],contributions:c.manifest.contributions,installed_at:u,updated_at:u,source:p}),s.push({name:c.manifest.name,directory:r.directory,version:c.manifest.version,entry:c.manifest.entry,source:p})}return s.length>0&&await j(e,d),{state:d,adopted_entries:s,unmanaged_candidates:i,already_managed_count:a.length-o.length}},ln=(e,t)=>{const a=Ve(process.cwd(),t.path),n=We(a,process.cwd()),o=e==="global"?Ke(process.cwd()):a,i=e==="global"?n.global:n.project;return{pm_root:a,scope:e,settings_root:o,selected_root:i,roots:n}},L=e=>{const t=[e.gh,e.github].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean),a=[...new Set(t)];if(a.length>1)throw new x('Options "--gh" and "--github" must match when both are provided.',y.USAGE);return a[0]},cn=e=>Ut[e],dn=(e,t)=>{const a=t.vocabulary==="package"?"package":"extension",n=e==="install"?"source":"name",o=`${a} ${n}`,i=cn(e),d=`<${n}>`,s=`pm ${a} ${i} ${d}`;throw new x(`Action "${e}" requires ${o} input.`,y.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${n} target for ${e}.`,examples:[`pm ${a} ${e} ${d}`,s,`pm ${a} --help`],recovery:{attempted_command:`pm ${a} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${n} target`}]}})},N=(e,t,a={})=>{const n=e?.trim();if(n)return n;if(t==="init")throw new x('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',y.USAGE);return dn(t,a)},Ie=(e,t)=>{const a=new Set([...t.registrations.item_types.map(n=>({entry:n,count:n.types.length})),...t.registrations.item_fields.map(n=>({entry:n,count:n.fields.length}))].filter(({count:n})=>n>0).map(({entry:n})=>`${n.layer}:${h(n.name)}`));return e.loaded.filter(n=>(n.activation?.commands??[]).length>0).filter(n=>a.has(`${n.layer}:${h(n.name)}`)).map(n=>`extension_schema_narrow_activation:${n.layer}:${n.name}`).filter((n,o,i)=>i.indexOf(n)===o).sort((n,o)=>n.localeCompare(o))},un=(e,t)=>{const n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(o=>o.triggered&&!o.allowed);if(n)throw new x(n.message,y.USAGE)},mn=(e,t,a)=>{const n=String(e??"").trim().toLowerCase(),o=[a.init,a.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:o?[]:["init","scaffold"]}[t]??[]).includes(n)?void 0:e},pn=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},_n=(e,t,a)=>{const n={ok:a,action:e.action,scope:e.scope,roots:pn(e),warnings:[...new Set(e.warnings)].sort((o,i)=>o.localeCompare(i)),details:t};return e.action==="doctor"&&Object.defineProperty(n,zt,{value:!0,enumerable:!1,configurable:!1}),n},gn=async(e,t,a)=>{const n=ye(e,t);un(n,t);const o=mn(e,n,t),i=xe(t),d=ln(i,a),r={action:n,normalizedTarget:o,scope:i,resolvedRoots:d,warnings:[],options:t,global:a},c={...r,withResult:(u,p=!0)=>_n(r,u,p)};return await Tt(()=>Xn(c))},fn=(e,t)=>{const a=t.vocabulary??"extension",n=e.target_path.replace(/\\/g,"/"),o=Ye(n),i={package:`Install dependencies: cd ${o}, then run "npm install"`,extension:`Install type-check dependencies: cd ${o}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},d={package:`Validate the package: cd ${o}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${o}, then run "npx tsc --noEmit"`},s=[];return[a==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[i[a],...s,`Install the scaffold: ${Je(a==="package"?["install","--project",n]:["extension","--install","--project",n])}`,`Smoke-test command path: pm ${e.command_name}`,d[a],`Run diagnostics: ${a==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},hn=async e=>{const{action:t,normalizedTarget:a,options:n,withResult:o}=e;if([L(n),n.ref].filter(l=>typeof l=="string").map(l=>l.trim()).filter(Boolean).length>0)throw new x('Action "init" does not accept --gh/--github/--ref options.',y.USAGE);const s=N(a,t,n),r=await ut(s,n.vocabulary??"extension",n.capability,n.declarative===!0);return o({scaffolded:r.created_directory||r.files.some(l=>l.status==="created"),extension:{name:r.extension_name,command:r.command_name},capability:r.capability,style:r.style,target_path:r.target_path,created_directory:r.created_directory,files:r.files,next_steps:fn(r,n)})},wn=async e=>{const{normalizedTarget:t,resolvedRoots:a,warnings:n,options:o,global:i,withResult:d}=e;if(t!==void 0)throw new x('Action "reload" does not accept a target argument.',y.USAGE);const s=await $(a.settings_root),r=se(),l=await P({pmRoot:a.settings_root,settings:s,cwd:process.cwd(),noExtensions:i.noExtensions,reload_token:r,cache_bust:!0});n.push(...l.warnings);const c=await M(l);n.push(...c.warnings);const u={reload:{token:r,cache_bust:!0,watch:o.watch===!0},loaded_count:l.loaded.length,failed_count:l.failed.length,activated_count:Math.max(0,l.loaded.length-c.failed.length),activation_failed_count:c.failed.length,loaded_extensions:l.loaded.map(p=>({name:p.name,layer:p.layer,version:p.version})),failed_extensions:l.failed.map(p=>({name:p.name,layer:p.layer,error:p.error})),activation_failures:c.failed.map(p=>({name:p.name,layer:p.layer,error:p.error}))};return o.watch===!0&&n.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),d(u)},bn=async e=>{const{normalizedTarget:t,scope:a,options:n,global:o,withResult:i}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new x('Action "catalog" does not accept a package target.',y.USAGE);return i(await dt(a,o,n))},vn=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),yn=e=>({kind:"local",input:e.input,location:e.absolute_path}),xn=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),kn=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),En=(e,t,a,n)=>e?vn(e,t):a.kind==="local"?yn(a):a.kind==="npm"?xn(a,n):kn(a,n),Ce=(e,t,a,n)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:n}:tt(e.source,a)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:n}:{installed_at:n,updated_at:n},Sn=async(e,t)=>{const{scope:a,resolvedRoots:n,warnings:o}=e,{validated:i,destinationDirectoryName:d}=t,s=await $(n.settings_root),r=await T(n.selected_root);o.push(...r.warnings);const l=A.join(n.selected_root,d),c=await W(l),u=await it(i.directory,l);await O.mkdir(n.selected_root,{recursive:!0});const p=En(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),f=r.state.entries.find(m=>h(m.name)===h(i.manifest.name)),b=Ce(f,i.manifest.version,p,F()),_=H(r.state,{name:i.manifest.name,directory:d,scope:a,manifest_version:i.manifest.version,manifest_entry:i.manifest.entry,capabilities:[...i.manifest.capabilities],contributions:i.manifest.contributions,...b,source:p}),k=we(s,i.manifest.name);return u||await de(i.directory,l),await yt(l),await xt(l),await j(n.selected_root,_),k&&await X(n.settings_root,s,"settings:write"),{settings:s,managedState:_,sourceRecord:p,destinationDirectory:l,destinationExists:c,installInPlace:u,activationChanged:k}},Rn=async(e,t,a)=>{const n=a.filter(o=>h(o.name)===h(t)).flatMap(o=>o.types.map(i=>({name:i.name,folder:i.folder})));return e.scope==="project"&&n.length>0&&await Ze(e.resolvedRoots.pm_root,n,e.warnings,"install:type-folder"),n},An=(e,t,a,n,o)=>{const i=ee(t,a.activation_failures,e.scope),d=Re(t,e.scope,a.installed,i),s=[!a.extensions_disabled,d==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${d}`);const r={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:d,failure:i,verification:{status:r[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:d,activated:s,registered_commands:n.command_paths,registered_actions:n.action_paths,registered_item_types:o,module_graph_verification:"fresh_in_topology_snapshot",health:r[String(s)]}}},In=async(e,t)=>{const{scope:a,resolvedRoots:n,warnings:o,global:i,withResult:d}=e,{validated:s,destinationDirectoryName:r}=t;return Ft({selectedRoot:n.selected_root,settingsRoot:n.settings_root,destinationDirectory:A.join(n.selected_root,r),sourceDirectory:s.directory,scope:a},async()=>{const l=await Sn(e,t),c=await I(n.selected_root,a,l.settings,l.managedState);o.push(...c.warnings);const u=await Ae(n.pm_root,A.dirname(n.selected_root),l.settings,c.extensions,i);o.push(...u.warnings);const p=await Rn(e,s.manifest.name,u.item_type_registrations),f=At(s.manifest.name,u.installed),b=An(e,s.manifest.name,u,f,p),_=u.contribution_inventories[h(s.manifest.name)];return _&&(l.managedState=await nt(n.selected_root,l.managedState,s.manifest.name,_)),d({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:r},source:l.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:l.destinationDirectory,overwritten:[l.destinationExists,!l.installInPlace].every(Boolean),installed_in_place:l.installInPlace,activated:b.activated,settings_changed:l.activationChanged,runtime_activation_status:b.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:_,command_discovery:Se(s.manifest.name,l.sourceRecord,f,b.failure),verification:b.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:b.failure??null}},b.activated)})},Cn=async e=>{const{options:t,global:a,warnings:n,withResult:o}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new x('Action "install all" does not accept --ref.',y.USAGE);const i=[],d=new Map;for(const s of await lt()){const r=await st(s),l=A.resolve(r);let c=d.get(l);c===void 0&&(c=await gn(s,{...t,install:!0},a),d.set(l,c)),i.push({alias:s,result:c})}return n.push(...i.flatMap(s=>s.result.warnings)),o(Mt(i,t.dryRun===!0),i.every(s=>s.result.ok))},$n=async(e,t,a)=>{const{resolvedRoots:n}=e,{bundledAliasName:o,bundledPackageName:i,installSource:d,sourceResolution:s}=await Lt(t,a,e.options.ref,(await T(n.selected_root)).state.entries);if(s.ambiguous){const l=s.candidates.find(c=>c.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${o}:npm:${l.package}`)}const r=await ot(d);try{const l=await G(r.directory,{source_kind:d.kind,source_input:d.input,source_root:r.source_root}),c=et(l.manifest.name),u=e.options.dryRun===!0||d.kind==="local"&&o===null?await Pt(r,A.join(n.selected_root,c),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:l.manifest.name,version:l.manifest.version},source_resolution:s,install_plan:u}):await Y(n.settings_root,c,()=>In(e,{validated:l,destinationDirectoryName:c,bundledAliasName:o,bundledPackageName:i,sourceResolution:s,installSource:d,resolvedSource:r,installPlan:u}))}finally{r.cleanup&&await r.cleanup()}},Tn=async e=>{const t=L(e.options),a=t??N(e.normalizedTarget,e.action,e.options);return[t===void 0,rt(a)].every(Boolean)?Cn(e):$n(e,a,t)},Dn=async e=>{const{normalizedTarget:t,scope:a,resolvedRoots:n,warnings:o,options:i,withResult:d}=e;if(t!==void 0)throw new x('Action "adopt-all" does not accept a target argument.',y.USAGE);if(L(i)!==void 0||typeof i.ref=="string"&&i.ref.trim().length>0)throw new x('Action "adopt-all" does not accept --gh/--github/--ref options.',y.USAGE);const r=await $(n.settings_root),l=await T(n.selected_root);o.push(...l.warnings);const c=await I(n.selected_root,a,r,l.state);o.push(...c.warnings);const u=await U(n.selected_root,a,c.extensions,l.state),p=await I(n.selected_root,a,r,u.state);o.push(...p.warnings);const f=V(a,o,p.extensions,i);o.push(...f.warnings);const b=new Map(p.extensions.map(m=>[`${h(m.name)}:${h(m.directory)}`,m])),_=new Map(p.extensions.map(m=>[h(m.directory),m])),k=u.adopted_entries.map(m=>{const g=h(m.directory),R=b.get(`${h(m.name)}:${g}`)??_.get(g);return{...m,...te(R)}});return d({adopted_all:k.length>0,adopted_count:k.length,already_managed_count:u.already_managed_count,extensions:k,triage:f,warning_codes:f.warning_codes,update_health_partial:f.update_health_partial,update_health_coverage:f.update_health_coverage})},te=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),$e=(e,t,a,n)=>{if(e===void 0)return{kind:"local",input:t,location:a};const o=le(e,{forceGithub:!0,ref:n});if(o.kind!=="github")throw new x(`Invalid GitHub shorthand "${e}".`,y.USAGE);return{kind:"github",input:o.input,location:o.subpath??".",repository:o.repository,owner:o.owner,repo:o.repo,ref:o.ref,subpath:o.subpath}},On=async e=>{const{action:t,normalizedTarget:a,scope:n,resolvedRoots:o,warnings:i,options:d,withResult:s}=e,r=N(a,t,d),l=L(d),c=await $(o.settings_root),u=await T(o.selected_root);i.push(...u.warnings);const p=await I(o.selected_root,n,c,u.state);i.push(...p.warnings);const f=await J(p.extensions,r);if(!f)throw new x(`Installed extension "${r}" was not found in ${n} scope.`,y.NOT_FOUND);if(f.managed)return s({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});const b=A.join(o.selected_root,f.directory),_=await G(b),k=F(),m=$e(l,r,b,d.ref),g=H(u.state,{name:_.manifest.name,directory:f.directory,scope:n,manifest_version:_.manifest.version,manifest_entry:_.manifest.entry,capabilities:[..._.manifest.capabilities],contributions:_.manifest.contributions,installed_at:k,updated_at:k,source:m});await j(o.selected_root,g);const R=await I(o.selected_root,n,c,g);i.push(...R.warnings);const E=R.extensions.find(D=>h(D.name)===h(_.manifest.name))??R.extensions.find(D=>h(D.directory)===h(f.directory));return s({adopted:!0,extension:{name:_.manifest.name,directory:f.directory,version:_.manifest.version,entry:_.manifest.entry},source:m,...te(E)})},Te=async e=>{const{action:t,normalizedTarget:a,scope:n,resolvedRoots:o,warnings:i,options:d}=e,s=N(a,t,d),r=await $(o.settings_root),l=await T(o.selected_root);i.push(...l.warnings);const c=await I(o.selected_root,n,r,l.state);i.push(...c.warnings);const u=await J(c.extensions,s);if(!u)throw new x(`Installed extension "${s}" was not found in ${n} scope.`,y.NOT_FOUND);return{settings:r,managedStateRead:l,candidate:u}},Mn=async e=>{const{resolvedRoots:t,withResult:a}=e,{settings:n,managedStateRead:o,candidate:i}=await Te(e),d=A.join(t.selected_root,i.directory);await O.rm(d,{recursive:!0,force:!0});const s={...o.state,updated_at:F(),entries:o.state.entries.filter(l=>h(l.name)!==h(i.name)&&h(l.directory)!==h(i.directory))};await j(t.selected_root,s);const r=be(n,i.name);return r&&await X(t.settings_root,n,"settings:write"),a({removed:!0,extension:{name:i.name,directory:i.directory},destination_path:d,settings_changed:r})},De=async e=>{const{action:t,resolvedRoots:a,warnings:n,global:o,withResult:i}=e,{settings:d,candidate:s}=await Te(e),r=t==="activate"?we(d,s.name):Jt(d,s.name);r&&await X(a.settings_root,d,"settings:write");const l=t==="activate"?await Ae(a.pm_root,A.dirname(a.selected_root),d,[s],o).then(c=>(n.push(...c.warnings),ee(s.name,c.activation_failures,e.scope))):void 0;return l&&n.push(`extension_activate_failed:${e.scope}:${s.name}`),i({extension:{name:s.name,directory:s.directory},active:t==="activate"&&l===void 0,runtime_active:t==="activate"&&l===void 0,activation_failure:l??null,settings_changed:r,settings:{enabled:[...d.extensions.enabled],disabled:[...d.extensions.disabled]}},l===void 0)},Pn=(e,t,a,n,o,i)=>{const d=n==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[d],r=o?.adopted_entries.length??0,l=[[i!==null,i??""],[t>0,`Run pm ${d} explore --project and pm ${d} explore --global to inspect load failures.`],[a>0,`Review activation failures in pm ${d} ${s} --detail deep output.`],[r>0,`Managed-state fix adopted ${r} extension(s).`]];return[...new Set([...e,...l.filter(([c])=>c).map(([,c])=>c)].map(c=>c.trim()).filter(c=>c.length>0))]},ne=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),jn=(e,t,a,n)=>{if(e!=="project"||t||!ne(n))return null;const o=a==="package"?"package":"extension";return`Global ${o} registrations are included in project diagnostics. For hermetic ${o} smoke tests, rerun pm ${o} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Ln=(e,t,a)=>{if(String(e??"").trim().length>0)throw new x('Action "doctor" does not accept a target argument.',y.USAGE);const n=[a.isolated,a.ignoreGlobal].includes(!0);if([n,t==="global"].every(Boolean))throw new x("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",y.USAGE);const o=ft(a.detail),i=a.trace===!0;if([i,o!=="deep"].every(Boolean))throw new x("--trace requires --detail deep with --doctor.",y.USAGE);return{isolated:n,detailMode:o,includeTrace:i}},Nn=async(e,t,a)=>{if(e.options.fixManagedState!==!0)return{state:a,fix:null};const n=await U(e.resolvedRoots.selected_root,e.scope,t,a);return{state:n.state,fix:n}},Fn=(e,t,a,n)=>{const o=a==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:ne(n),rerun_command:null,pm_global_path_recipe:null};const i=`pm ${o} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:ne(n),rerun_command:t?null:i,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${o} doctor --project --detail deep --trace`}},Gn=async e=>{const{normalizedTarget:t,scope:a,resolvedRoots:n,warnings:o,options:i,global:d,withResult:s}=e,{isolated:r,detailMode:l,includeTrace:c}=Ln(t,a,i),u=await $(n.settings_root),p=await T(n.selected_root);o.push(...p.warnings);const f=await I(n.selected_root,a,u,p.state);o.push(...f.warnings);const{state:b,fix:_}=await Nn(e,f.extensions,p.state),k=await I(n.selected_root,a,u,b);o.push(...k.warnings);const m=await P({pmRoot:n.pm_root,settings:u,cwd:process.cwd(),noExtensions:d.noExtensions===!0,ignoreGlobalExtensions:r}),g=await M({...m,loaded:m.loaded}),R=await jt(n.pm_root);o.push(...R.warnings,...m.warnings),o.push(...pt(m.failed)),o.push(...g.warnings),o.push(..._t(g.failed)),o.push(...gt(m,g)),o.push(...ue(g,m)),o.push(...Ie(m,g)),o.push(...me(g));const E=K(k.extensions,m,g),D=bt(a,E,m.loaded.map(w=>({layer:w.layer,name:w.name})),m.failed.map(w=>({name:w.name})),m.disabled_by_flag);o.push(...D.warnings);const Pe=E.filter(w=>w.update_check_status==="failed").map(w=>`extension_update_check_failed:${w.name}`);o.push(...Pe);const S=V(a,o,E,i);o.push(...S.warnings);const ae=[...S.warnings],je={mode:m.policy.mode,trust_mode:m.policy.trust_mode,require_provenance:m.policy.require_provenance,default_sandbox_profile:m.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:m.policy.trusted_extensions.length,allowed_extensions_count:m.policy.allowed_extensions.length,blocked_extensions_count:m.policy.blocked_extensions.length,allowed_capabilities_count:m.policy.allowed_capabilities.length,blocked_capabilities_count:m.policy.blocked_capabilities.length,allowed_surfaces_count:m.policy.allowed_surfaces.length,blocked_surfaces_count:m.policy.blocked_surfaces.length,allowed_commands_count:m.policy.allowed_commands.length,blocked_commands_count:m.policy.blocked_commands.length,allowed_actions_count:m.policy.allowed_actions.length,blocked_actions_count:m.policy.blocked_actions.length,allowed_services_count:m.policy.allowed_services.length,blocked_services_count:m.policy.blocked_services.length,extension_override_count:m.policy.extension_overrides.length},z=ht(ae),q=wt(),oe=S.warning_codes,Le=jn(a,r,i.vocabulary,m),Ne=Pn(S.remediation,m.failed.length,g.failed.length,i.vocabulary,_,Le),ie=Fn(a,r,i.vocabulary,m),Fe={status:S.status,scope:a,warning_count:S.warning_count,warning_codes:oe,total_extensions:E.length,managed_total:E.filter(w=>w.managed).length,enabled_total:E.filter(w=>w.enabled).length,active_total:E.filter(w=>w.active).length,unmanaged_loaded_extension_count:S.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:S.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:S.unmanaged_expected_extension_count,runtime_active_total:E.filter(w=>w.runtime_active===!0).length,activation_status_totals:{ok:E.filter(w=>w.activation_status==="ok").length,failed:E.filter(w=>w.activation_status==="failed").length,not_loaded:E.filter(w=>w.activation_status==="not_loaded").length,unknown:E.filter(w=>w.activation_status==="unknown").length},unknown_capability_count:z.length,capability_contract_version:q.version,update_available_total:S.update_available_total,update_check_status_totals:S.update_check_status_totals,update_health_coverage:S.update_health_coverage,update_health_partial:S.update_health_partial,update_check_failed_total:E.filter(w=>w.update_check_status==="failed").length,load_failure_count:m.failed.length,activation_failure_count:g.failed.length,load_failures:ce(m.failed),activation_failures:ce(g.failed),blocking_failure_count:m.failed.length+g.failed.length,has_blocking_failures:m.failed.length+g.failed.length>0,consistency_warning_count:D.warnings.length,trace_enabled:c,isolation:ie,policy:je,remediation:Ne},Ge=_?{requested:!0,applied:_.adopted_entries.length>0,adopted_count:_.adopted_entries.length,already_managed_count:_.already_managed_count,adopted_extensions:_.adopted_entries.map(w=>w.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:k.extensions.filter(w=>w.managed).length,adopted_extensions:[]},B={mode:l,summary:Fe,triage:S,trace_enabled:c,capability_contract:q,capability_guidance:z,managed_state_fix:Ge,author_manifest:R,isolation:ie,policy:m.policy};if(l==="deep"){const w=c?g.failed:g.failed.map(v=>{const{trace:Hn,...Ue}=v;return Ue});B.deep={warnings:ae,warning_codes:oe,capability_contract:q,capability_guidance:z,trace_enabled:c,managed_state:{path:p.path,count:b.entries.length,entries:b.entries},installed_extensions:E,load:{roots:m.roots,policy:m.policy,warnings:m.warnings,failed:m.failed,loaded:m.loaded.map(v=>({layer:v.layer,directory:v.directory,name:v.name,version:v.version,entry:v.entry,priority:v.priority}))},activation:{failed:w,warnings:g.warnings,hook_counts:g.hook_counts,registration_counts:g.registration_counts,parser_override_count:g.parser_override_count,preflight_override_count:g.preflight_override_count,service_override_count:g.service_override_count,renderer_override_count:g.renderer_override_count},consistency:D.summary},c&&(B.deep.trace={activation_failures:g.failed.filter(v=>v.trace!==void 0).map(v=>({layer:v.layer,name:v.name,entry_path:v.entry_path,error:v.error,method:v.trace.method,command:v.trace.command,capability:v.trace.capability,missing_capability:v.trace.missing_capability,registration_index:v.trace.registration_index,expected_schema:v.trace.expected_schema,hint:v.trace.hint,received:v.trace.received}))})}return s(B)},Un=async e=>{const{normalizedTarget:t,scope:a,resolvedRoots:n,warnings:o,options:i,global:d,withResult:s}=e,r=await $(n.settings_root),l=await P({pmRoot:n.pm_root,settings:r,cwd:process.cwd(),noExtensions:d.noExtensions===!0}),c=await M(l);o.push(...l.warnings),o.push(...c.warnings);const u=mt(t,l,c);if(t!==void 0&&u.extensions.length===0){const p=i.vocabulary==="package"?"package":"extension",f=[...new Set(l.loaded.map(_=>i.vocabulary==="package"&&typeof _.source_package=="string"&&_.source_package.trim().length>0?_.source_package.trim():_.name))].sort((_,k)=>_.localeCompare(k)),b=f.length>0?` Loaded ${p} names: ${f.join(", ")}.`:"";throw new x(`No loaded ${p} named "${t}" was found in ${a} scope.${b} Run pm ${p} explore to list discovered ${p}s.`,y.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},zn=async(e,t,a)=>{let n=a,o=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(o=await U(e.resolvedRoots.selected_root,e.scope,t,a),n=o.state),e.action==="manage"){const i=e.options.fixManagedState===!0;n=await Dt(n,e.options.offline,i?Ct:$t(),!i)}return{state:n,fix:o}},qn=async(e,t,a)=>{const n=await P({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),o=await M({...n,loaded:n.loaded});return e.warnings.push(...n.warnings,...o.warnings),{installed:K(a,n,o),failures:Z(o.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:n.failed.length,activation_failure_count:o.failed.length,warning_count:[...new Set([...n.warnings,...o.warnings])].length,policy:n.policy}}},Bn=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(a=>a.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(a=>a.managed).length},Oe=async e=>{const{action:t,scope:a,resolvedRoots:n,warnings:o,options:i,withResult:d}=e,s=await $(n.settings_root),r=fe(s.extensions.policy),l=await T(n.selected_root);o.push(...l.warnings);const c=await I(n.selected_root,a,s,l.state);o.push(...c.warnings);const{state:u,fix:p}=await zn(e,c.extensions,l.state),f=await I(n.selected_root,a,s,u);if(o.push(...f.warnings),t==="manage"&&i.offline===!0)for(const g of f.extensions)g.managed&&["npm","github"].includes(g.source.kind)&&(g.update_check_reason="offline_requested");if(t==="manage"){const g=f.extensions.filter(R=>R.update_check_status==="failed").map(R=>`extension_update_check_failed:${R.name}`);o.push(...g)}const b=await qn(e,s,f.extensions),_=b.installed,k=V(a,o,_,i);o.push(...k.warnings);const m={total:_.length,managed_total:_.filter(g=>g.managed).length,enabled_total:_.filter(g=>g.enabled).length,active_total:_.filter(g=>g.active).length,extensions:_,triage:k,policy:r};return b.failures!==void 0&&(m.activation_diagnostics={failed_count:b.failures.length,failed:b.failures}),t==="explore"&&(m.runtime_probe=b.summary),t==="manage"&&(m.runtime_probe=b.summary,m.managed_state_fix=Bn(p,_)),d(m)},Me={init:hn,install:Tn,uninstall:Mn,explore:Oe,manage:Oe,describe:Un,reload:wn,doctor:Gn,catalog:bn,adopt:On,"adopt-all":Dn,activate:De,deactivate:De,migrate:Ot},Wn=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),Xn=e=>Wn(e)?Y(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Me[e.action](e)):Me[e.action](e),Ta={adoptUnmanagedExtensions:U,buildAdoptedExtensionSource:$e,buildExtensionPolicyDetails:fe,buildInstallCommandDiscovery:Se,checkGithubUpdate:It,clearExtensionState:be,collectActivationFailureDiagnostics:Z,findActivationFailureByName:ee,resolveInstallRuntimeActivationStatus:Re,collectGlobalOutputOverrideDoctorWarnings:ue,collectMcpCustomFieldCollisionDoctorWarnings:me,collectSchemaNarrowActivationDoctorWarnings:Ie,copyExtensionDirectoryWithoutSelfNesting:vt,isErrnoCode:kt,isRetriableExtensionInstallCopyError:Et,listInstalledExtensions:I,mapWithFixedConcurrency:Rt,projectExtensionUpdateCheck:te,readOptionalMetadataFile:Nt,requireTarget:N,resolveAction:ye,resolveCommandDiscoveryPackageName:Ee,resolveGithubOption:L,resolveInstalledExtensionCandidate:J,resolveManagedInstallTimestamps:Ce,resolveScope:xe,resolveUpdateCheckResolution:Q,withExtensionInstallLock:Y};export{Ta as _testOnly,de as copyExtensionDirectoryForInstall,le as parseExtensionInstallSource,re as parseExtensionManifest,T as readManagedExtensionState,St as resolveCanonicalExtensionInstallDestination,at as resolveManagedExtensionStatePath,gn as runExtension,G as validateExtensionDirectory,j as writeManagedExtensionState};
1
+ import D from"node:fs/promises";import A from"node:path";import{activateExtensions as M,createSerialQueue as qe,loadExtensions as P,nextExtensionReloadToken as se}from"../core/extensions/index.js";import{describeExtensionActivation as Be}from"../core/extensions/activation-summary.js";import{createExtensionContributionInventory as We}from"../core/extensions/contribution-inventory.js";import{resolveExtensionRoots as Xe}from"../core/extensions/loader.js";import{pathExists as W}from"../core/fs/fs-utils.js";import{resolvePmPackageRootFromModule as He}from"../core/packages/root.js";import{EXIT_CODE as E}from"../core/shared/constants.js";import{PmCliError as S}from"../core/shared/errors.js";import{levenshteinDistanceWithinLimit as Ke}from"../core/shared/levenshtein.js";import{nowIso as F}from"../core/shared/time.js";import{resolveGlobalPmRoot as Ve,resolvePmRoot as Ye}from"../core/store/paths.js";import{readSettings as $,writeSettings as X}from"../core/store/settings.js";import{quoteCommandArg as Je,renderPmCommand as Qe}from"./command-line.js";import{createUnknownSubcommandError as Ze}from"./agent/subcommand-recovery.js";import{ensureTypeFolderScaffold as et}from"./schema.js";import{normalizeStringList as C,normalizeExtensionNameForMatch as f,normalizeManagedDirectoryName as tt,parseExtensionManifest as re,validateExtensionDirectory as G}from"./extension/shared.js";import{managedExtensionSourcesEquivalent as nt,readManagedExtensionState as T,writeManagedExtensionState as j,upsertManagedEntry as H,persistManagedContributionInventory as at,resolveManagedExtensionStatePath as ot}from"./extension/managed-state.js";import{parseExtensionInstallSource as le,resolveInstallSource as it,areDirectoriesEquivalent as st}from"./extension/install-sources.js";import{resolveBundledExtensionAliasSource as rt,isBundledPackageInstallAllTarget as lt,listBundledPackageAliases as ct,resolveBundledAliasManifestName as dt,buildBundledPackageCatalog as ut}from"./extension/bundled-catalog.js";import{scaffoldExtensionProject as pt}from"./extension/scaffold.js";import{buildExtensionDescribeResult as mt}from"./extension/describe.js";import{applyDoctorRuntimeActivationState as K,classifyDoctorLoadFailureWarnings as _t,classifyDoctorActivationFailureWarnings as gt,classifyUnusedCapabilityWarnings as ft,buildExtensionTriageSummary as V,parseDoctorDetailMode as ht,collectUnknownCapabilityGuidance as wt,buildCapabilityContractMetadata as bt,buildDoctorConsistencySummary as vt,summarizeExtensionFailures as ce}from"./extension/doctor.js";import{copyExtensionDirectoryForInstall as de,copyExtensionDirectoryWithoutSelfNesting as yt,ensureExtensionModuleTypeMarker as xt,ensureInstalledExtensionSdkLink as kt,isErrnoCode as Et,isRetriableExtensionInstallCopyError as St,resolveCanonicalExtensionInstallDestination as Rt,withExtensionInstallLock as Y}from"./extension/install-runtime.js";import{mapWithFixedConcurrency as At}from"./extension/concurrency.js";import{summarizeRuntimeCommandPathsForExtension as It}from"./extension/runtime-summary.js";import{collectGlobalOutputOverrideDoctorWarnings as ue}from"./extension/output-ownership.js";import{collectMcpCustomFieldCollisionDoctorWarnings as pe}from"./extension/custom-field-collisions.js";import{checkGithubUpdate as Ct,EXTENSION_UPDATE_CHECK_TIMEOUT_DEFAULT_MS as $t,resolveExtensionUpdateCheckTimeoutMs as Tt,withUpdateCheckTeardownScope as Ot}from"./extension/update-check.js";import{refreshManagedExtensionUpdates as Dt}from"./extension/managed-update-status.js";import{recordCheckedUpdateObservations as Mt}from"./extension/update-observations.js";import{parseExploreManageFields as me,projectExploreManageRows as Pt}from"./extension/listing-fields.js";import{isRegistryNpmSource as jt}from"./extension/npm-spec.js";import{runExtensionMigrateAction as Lt}from"./extension/migrations.js";import{buildBundledInstallReceipt as Nt}from"./extension/install-receipts.js";import{buildExtensionInstallPlan as Ft}from"./extension/install-plan.js";import{inspectExtensionAuthorManifestAtPmRoot as Gt}from"./extension/author-manifest.js";import{resolveExtensionInstallSourceIdentity as Ut}from"./extension/source-resolution.js";import{readOptionalMetadataFile as zt,withVerifiedExtensionInstall as qt}from"./extension/install-snapshot.js";const _e=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],Bt=_e.map(([,,e])=>e).filter((e,t,a)=>a.indexOf(e)===t).join(", "),Wt={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},Xt="__pm_native_output",Ht=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],ge=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Kt=["disabled","require_trusted","require_provenance"],fe={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},Vt=e=>{const t=e??fe,a={};for(const n of Ht)a[n]=C(t[n]??[]);return a},Yt=(e,t)=>{for(const a of ge)t[a].length>0&&(e[a]=t[a]);return e},Jt=(e,t)=>{for(const a of Kt)t[a]===!0&&(e[a]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Qt=e=>{const t={};for(const a of ge)t[a]=C(e[a]??[]);return t},Zt=e=>{const t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Yt(Jt({name:t},e),Qt(e))},en=e=>(e??[]).map(t=>Zt(t)).filter(t=>t!==null).sort((t,a)=>t.name.localeCompare(a.name)),he=e=>{const t=Object.assign({},fe,e??{}),a=Vt(e),n=en(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:a.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:a.allowed_extensions,blocked_extensions:a.blocked_extensions,allowed_capabilities:a.allowed_capabilities,blocked_capabilities:a.blocked_capabilities,allowed_surfaces:a.allowed_surfaces,blocked_surfaces:a.blocked_surfaces,allowed_commands:a.allowed_commands,blocked_commands:a.blocked_commands,allowed_actions:a.allowed_actions,blocked_actions:a.blocked_actions,allowed_services:a.allowed_services,blocked_services:a.blocked_services,extension_overrides:n}},J=async(e,t)=>{const a=[t],n=await dt(t);n&&a.push(n);const o=[...new Set(a.map(i=>f(i)).filter(i=>i.length>0))];for(const i of o){const d=e.find(r=>f(r.name)===i);if(d)return d;const s=e.find(r=>f(r.directory)===i);if(s)return s}},we=(e,t)=>{const a=t.trim(),n=new Set(C(e.extensions.enabled));return new Set(C(e.extensions.disabled)).has(a)?!1:n.size===0?!0:n.has(a)},be=(e,t)=>{const a=t.trim(),n=new Set(C(e.extensions.enabled)),o=new Set(C(e.extensions.disabled)),i=[...n],d=[...o];return o.delete(a),n.size>0&&n.add(a),e.extensions.enabled=[...n].sort((s,r)=>s.localeCompare(r)),e.extensions.disabled=[...o].sort((s,r)=>s.localeCompare(r)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==d.join("\0")},tn=(e,t)=>{const a=t.trim(),n=new Set(C(e.extensions.enabled)),o=new Set(C(e.extensions.disabled)),i=[...n],d=[...o];return n.delete(a),o.add(a),e.extensions.enabled=[...n].sort((s,r)=>s.localeCompare(r)),e.extensions.disabled=[...o].sort((s,r)=>s.localeCompare(r)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==d.join("\0")},ve=(e,t)=>{const a=t.trim(),n=new Set(C(e.extensions.enabled)),o=new Set(C(e.extensions.disabled)),i=[...n],d=[...o];return n.delete(a),o.delete(a),e.extensions.enabled=[...n].sort((s,r)=>s.localeCompare(r)),e.extensions.disabled=[...o].sort((s,r)=>s.localeCompare(r)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==d.join("\0")},nn=e=>{const t=e.trim().toLowerCase(),a=Math.min(2,Math.max(1,Math.ceil(t.length/4))),n=_e.map(([o,i,d])=>({action:i,flag:d,distance:Ke(t,o,a)})).filter(o=>o.distance!==null).sort((o,i)=>o.distance-i.distance)[0];return n?{action:n.action,flag:n.flag}:null},an=(e,t)=>{const a=t.vocabulary==="package"?"package":"extension",n=nn(e);if(!n)return new S(`One action flag is required. Use one of: ${Bt}. Bare \`pm package\` and \`pm extension\` default to --explore.`,E.USAGE);const o=`pm ${a} ${n.flag}`;return Ze({command_path:a,display_name:`${a} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(ye),retry_command:o,message_suffix:`. Did you mean "${n.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:o,reason:`nearest lifecycle action for "${e}"`}]})},on=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],ye={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},sn=e=>ye[e]??null,xe=(e,t)=>{const a=[...new Set(on.filter(([n])=>t[n]===!0).map(([,n])=>n))];if(a.length===0){if(e===void 0)return"explore";const n=sn(e.trim().toLowerCase());if(n)return n;throw an(e,t)}if(a.length>1)throw new S("Extension action flags are mutually exclusive.",E.USAGE);return a[0]},ke=e=>{const t=e.scope,a=e.project===!0||e.local===!0||t==="project"||t==="local",n=e.global===!0||t==="global";if(a&&n)throw new S('Options "--project/--local" and "--global" are mutually exclusive.',E.USAGE);return n?"global":"project"},rn=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>e?.source.kind==="npm"&&!jt(e.source)?{status:"skipped_non_github",reason:"managed_npm_source_not_registry"}:null,e=>{const t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{const t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],Q=e=>{for(const t of rn){const a=t(e);if(a)return a}return{status:"not_checked",reason:"no_update_check_recorded"}},Ee=(e,t,a,n)=>{const o=a??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:o.contributions,managed:!!a,source:o.source,update_available:o.update_available,last_update_check_at:o.last_update_check_at,last_update_remote_commit:o.last_update_remote_commit,last_update_remote_version:o.last_update_remote_version,update_error:o.update_error,...n.status==="failed"&&o.update_check_timeout_ms!==void 0?{update_check_timeout_ms:o.update_check_timeout_ms}:{},update_check_status:n.status,update_check_reason:n.reason}},ln=(e,t,a,n)=>{const o=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},n),i=n?we(a,n.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Ee({name:o.name,directory:e,version:o.manifest_version,entry:o.manifest_entry,enabled:i},t,n,Q(n))}},cn=async(e,t,a,n,o,i)=>{const d=A.join(e,t),s=A.join(d,"manifest.json"),r=i.get(f(t));if(!await W(s))return ln(t,a,n,r);const c=Symbol("invalid-extension-manifest-json"),l=await D.readFile(s,"utf8").then(w=>JSON.parse(w)).catch(()=>c);if(l===c)return{warning:`extension_manifest_invalid_json:${a}:${t}`};const u=re(l);if(!u)return{warning:`extension_manifest_invalid:${a}:${t}`};const m=o.get(f(u.name))??i.get(f(t));return{summary:Ee({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:we(n,u.name)},a,m,Q(m))}},I=async(e,t,a,n)=>{if(!await W(e))return{extensions:[],warnings:[]};const i=(await D.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,u)=>l.localeCompare(u)),d=new Map(n.entries.map(l=>[f(l.name),l])),s=new Map(n.entries.map(l=>[f(l.directory),l])),r=[],c=[];for(const l of i){const u=await cn(e,l,t,a,d,s);u.warning&&r.push(u.warning),u.summary&&c.push(u.summary)}return{extensions:c.sort((l,u)=>l.name.localeCompare(u.name)),warnings:r.sort((l,u)=>l.localeCompare(u))}},dn=qe(),Se=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(a=>a?.trim())?.trim()??e,Re=(e,t,a,n)=>{const o=a.command_paths.map(s=>`pm ${s} --help`),i=n?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,d=a.command_paths.length>0?[...o]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return i&&d.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Se(e,t),extension_name:e,command_paths:a.command_paths,action_paths:a.action_paths,help_commands:o,next_steps:d,...i?{sdk_dependency_status:"missing"}:{}}},un=e=>{const t=e.trace,a={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(a.trace=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)),t.missing_capability&&(a.missing_capability=t.missing_capability),t.hint&&(a.hint=t.hint)),a},Z=e=>e.map(t=>un(t)).sort((t,a)=>`${t.layer}:${t.name}`.localeCompare(`${a.layer}:${a.name}`)),ee=(e,t,a)=>{const n=f(e);return t.find(o=>(a===void 0||o.layer===a)&&f(o.name)===n)},Ae=(e,t,a,n)=>a.find(i=>i.scope===t&&f(i.name)===f(e))?.activation_status??(n?"failed":"unknown"),Ie=(e,t,a,n,o)=>dn.enqueue(async()=>{const i=process.env.PM_CLI_PACKAGE_ROOT,d=await D.mkdtemp(A.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=He(import.meta.url,["../.."]);try{const s=await P({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:o.noExtensions===!0,reload_token:se(),cache_bust:!0,module_graph_snapshot_root:d}),r=await M({...s}),c=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...Z(r.failed)],l=Object.fromEntries(s.loaded.map(u=>[f(u.name),We(Be(r,{extensionName:u.name}))]));return{installed:K(n,s,r),warnings:[...s.warnings,...r.warnings],activation_failures:c,extensions_disabled:s.disabled_by_flag,item_type_registrations:r.registrations.item_types,contribution_inventories:l}}finally{await D.rm(d,{recursive:!0,force:!0}),i===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=i}}),U=async(e,t,a,n)=>{const o=a.filter(r=>!r.managed),i=[...o].sort((r,c)=>{const l=r.name.localeCompare(c.name);return l!==0?l:r.directory.localeCompare(c.directory)});let d=n;const s=[];for(const r of i){const c=A.join(e,r.directory),l=await G(c),u=F(),m={kind:"local",input:r.name,location:c};d=H(d,{name:l.manifest.name,directory:r.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:u,updated_at:u,source:m}),s.push({name:l.manifest.name,directory:r.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return s.length>0&&await j(e,d),{state:d,adopted_entries:s,unmanaged_candidates:i,already_managed_count:a.length-o.length}},pn=(e,t)=>{const a=Ye(process.cwd(),t.path),n=Xe(a,process.cwd()),o=e==="global"?Ve(process.cwd()):a,i=e==="global"?n.global:n.project;return{pm_root:a,scope:e,settings_root:o,selected_root:i,roots:n}},L=e=>{const t=[e.gh,e.github].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean),a=[...new Set(t)];if(a.length>1)throw new S('Options "--gh" and "--github" must match when both are provided.',E.USAGE);return a[0]},mn=e=>Wt[e],_n=(e,t)=>{const a=t.vocabulary==="package"?"package":"extension",n=e==="install"?"source":"name",o=`${a} ${n}`,i=mn(e),d=`<${n}>`,s=`pm ${a} ${i} ${d}`;throw new S(`Action "${e}" requires ${o} input.`,E.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${n} target for ${e}.`,examples:[`pm ${a} ${e} ${d}`,s,`pm ${a} --help`],recovery:{attempted_command:`pm ${a} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${n} target`}]}})},N=(e,t,a={})=>{const n=e?.trim();if(n)return n;if(t==="init")throw new S('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',E.USAGE);return _n(t,a)},Ce=(e,t)=>{const a=new Set([...t.registrations.item_types.map(n=>({entry:n,count:n.types.length})),...t.registrations.item_fields.map(n=>({entry:n,count:n.fields.length}))].filter(({count:n})=>n>0).map(({entry:n})=>`${n.layer}:${f(n.name)}`));return e.loaded.filter(n=>(n.activation?.commands??[]).length>0).filter(n=>a.has(`${n.layer}:${f(n.name)}`)).map(n=>`extension_schema_narrow_activation:${n.layer}:${n.name}`).filter((n,o,i)=>i.indexOf(n)===o).sort((n,o)=>n.localeCompare(o))},gn=(e,t)=>{const n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."},{triggered:t.fields!==void 0,allowed:e==="explore"||e==="manage"||e==="catalog",message:"--fields is only valid on the package listings: pm package list, pm package explore, pm package manage and pm package catalog."}].find(o=>o.triggered&&!o.allowed);if(n)throw new S(n.message,E.USAGE)},fn=(e,t,a)=>{const n=String(e??"").trim().toLowerCase(),o=[a.init,a.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:o?[]:["init","scaffold"]}[t]??[]).includes(n)?void 0:e},hn=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},wn=(e,t,a)=>{const n={ok:a,action:e.action,scope:e.scope,roots:hn(e),warnings:[...new Set(e.warnings)].sort((o,i)=>o.localeCompare(i)),details:t};return e.action==="doctor"&&Object.defineProperty(n,Xt,{value:!0,enumerable:!1,configurable:!1}),n},bn=async(e,t,a)=>{const n=xe(e,t);gn(n,t),(n==="explore"||n==="manage")&&me(t.fields,n);const o=fn(e,n,t),i=ke(t),d=pn(i,a),r={action:n,normalizedTarget:o,scope:i,resolvedRoots:d,warnings:[],options:t,global:a},l={...r,withResult:(u,m=!0)=>wn(r,u,m)};return await Ot(()=>Yn(l))},vn=(e,t)=>{const a=t.vocabulary??"extension",n=e.target_path.replace(/\\/g,"/"),o=Je(n),i={package:`Install dependencies: cd ${o}, then run "npm install"`,extension:`Install type-check dependencies: cd ${o}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},d={package:`Validate the package: cd ${o}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${o}, then run "npx tsc --noEmit"`},s=[];return[a==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[i[a],...s,`Install the scaffold: ${Qe(a==="package"?["install","--project",n]:["extension","--install","--project",n])}`,`Smoke-test command path: pm ${e.command_name}`,d[a],`Run diagnostics: ${a==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},yn=async e=>{const{action:t,normalizedTarget:a,options:n,withResult:o}=e;if([L(n),n.ref].filter(c=>typeof c=="string").map(c=>c.trim()).filter(Boolean).length>0)throw new S('Action "init" does not accept --gh/--github/--ref options.',E.USAGE);const s=N(a,t,n),r=await pt(s,n.vocabulary??"extension",n.capability,n.declarative===!0);return o({scaffolded:r.created_directory||r.files.some(c=>c.status==="created"),extension:{name:r.extension_name,command:r.command_name},capability:r.capability,style:r.style,target_path:r.target_path,created_directory:r.created_directory,files:r.files,next_steps:vn(r,n)})},xn=async e=>{const{normalizedTarget:t,resolvedRoots:a,warnings:n,options:o,global:i,withResult:d}=e;if(t!==void 0)throw new S('Action "reload" does not accept a target argument.',E.USAGE);const s=await $(a.settings_root),r=se(),c=await P({pmRoot:a.settings_root,settings:s,cwd:process.cwd(),noExtensions:i.noExtensions,reload_token:r,cache_bust:!0});n.push(...c.warnings);const l=await M(c);n.push(...l.warnings);const u={reload:{token:r,cache_bust:!0,watch:o.watch===!0},loaded_count:c.loaded.length,failed_count:c.failed.length,activated_count:Math.max(0,c.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:c.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:c.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return o.watch===!0&&n.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),d(u)},kn=async e=>{const{normalizedTarget:t,scope:a,options:n,global:o,withResult:i}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new S('Action "catalog" does not accept a package target.',E.USAGE);return i(await ut(a,o,n))},En=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Sn=e=>({kind:"local",input:e.input,location:e.absolute_path}),Rn=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),An=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),In=(e,t,a,n)=>e?En(e,t):a.kind==="local"?Sn(a):a.kind==="npm"?Rn(a,n):An(a,n),$e=(e,t,a,n)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:n}:nt(e.source,a)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:n}:{installed_at:n,updated_at:n},Cn=async(e,t)=>{const{scope:a,resolvedRoots:n,warnings:o}=e,{validated:i,destinationDirectoryName:d}=t,s=await $(n.settings_root),r=await T(n.selected_root);o.push(...r.warnings);const c=A.join(n.selected_root,d),l=await W(c),u=await st(i.directory,c);await D.mkdir(n.selected_root,{recursive:!0});const m=In(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),w=r.state.entries.find(p=>f(p.name)===f(i.manifest.name)),b=$e(w,i.manifest.version,m,F()),_=H(r.state,{name:i.manifest.name,directory:d,scope:a,manifest_version:i.manifest.version,manifest_entry:i.manifest.entry,capabilities:[...i.manifest.capabilities],contributions:i.manifest.contributions,...b,source:m}),v=be(s,i.manifest.name);return u||await de(i.directory,c),await xt(c),await kt(c),await j(n.selected_root,_),v&&await X(n.settings_root,s,"settings:write"),{settings:s,managedState:_,sourceRecord:m,destinationDirectory:c,destinationExists:l,installInPlace:u,activationChanged:v}},$n=async(e,t,a)=>{const n=a.filter(o=>f(o.name)===f(t)).flatMap(o=>o.types.map(i=>({name:i.name,folder:i.folder})));return e.scope==="project"&&n.length>0&&await et(e.resolvedRoots.pm_root,n,e.warnings,"install:type-folder"),n},Tn=(e,t,a,n,o)=>{const i=ee(t,a.activation_failures,e.scope),d=Ae(t,e.scope,a.installed,i),s=[!a.extensions_disabled,d==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${d}`);const r={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:d,failure:i,verification:{status:r[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:d,activated:s,registered_commands:n.command_paths,registered_actions:n.action_paths,registered_item_types:o,module_graph_verification:"fresh_in_topology_snapshot",health:r[String(s)]}}},On=async(e,t)=>{const{scope:a,resolvedRoots:n,warnings:o,global:i,withResult:d}=e,{validated:s,destinationDirectoryName:r}=t;return qt({selectedRoot:n.selected_root,settingsRoot:n.settings_root,destinationDirectory:A.join(n.selected_root,r),sourceDirectory:s.directory,scope:a},async()=>{const c=await Cn(e,t),l=await I(n.selected_root,a,c.settings,c.managedState);o.push(...l.warnings);const u=await Ie(n.pm_root,A.dirname(n.selected_root),c.settings,l.extensions,i);o.push(...u.warnings);const m=await $n(e,s.manifest.name,u.item_type_registrations),w=It(s.manifest.name,u.installed),b=Tn(e,s.manifest.name,u,w,m),_=u.contribution_inventories[f(s.manifest.name)];return _&&(c.managedState=await at(n.selected_root,c.managedState,s.manifest.name,_)),d({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:r},source:c.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:c.destinationDirectory,overwritten:[c.destinationExists,!c.installInPlace].every(Boolean),installed_in_place:c.installInPlace,activated:b.activated,settings_changed:c.activationChanged,runtime_activation_status:b.status,command_paths:w.command_paths,action_paths:w.action_paths,contributions:_,command_discovery:Re(s.manifest.name,c.sourceRecord,w,b.failure),verification:b.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:b.failure??null}},b.activated)})},Dn=async e=>{const{options:t,global:a,warnings:n,withResult:o}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new S('Action "install all" does not accept --ref.',E.USAGE);const i=[],d=new Map;for(const s of await ct()){const r=await rt(s),c=A.resolve(r);let l=d.get(c);l===void 0&&(l=await bn(s,{...t,install:!0},a),d.set(c,l)),i.push({alias:s,result:l})}return n.push(...i.flatMap(s=>s.result.warnings)),o(Nt(i,t.dryRun===!0),i.every(s=>s.result.ok))},Mn=async(e,t,a)=>{const{resolvedRoots:n}=e,{bundledAliasName:o,bundledPackageName:i,installSource:d,sourceResolution:s}=await Ut(t,a,e.options.ref,(await T(n.selected_root)).state.entries);if(s.ambiguous){const c=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${o}:npm:${c.package}`)}const r=await it(d);try{const c=await G(r.directory,{source_kind:d.kind,source_input:d.input,source_root:r.source_root}),l=tt(c.manifest.name),u=e.options.dryRun===!0||d.kind==="local"&&o===null?await Ft(r,A.join(n.selected_root,l),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:c.manifest.name,version:c.manifest.version},source_resolution:s,install_plan:u}):await Y(n.settings_root,l,()=>On(e,{validated:c,destinationDirectoryName:l,bundledAliasName:o,bundledPackageName:i,sourceResolution:s,installSource:d,resolvedSource:r,installPlan:u}))}finally{r.cleanup&&await r.cleanup()}},Pn=async e=>{const t=L(e.options),a=t??N(e.normalizedTarget,e.action,e.options);return[t===void 0,lt(a)].every(Boolean)?Dn(e):Mn(e,a,t)},jn=async e=>{const{normalizedTarget:t,scope:a,resolvedRoots:n,warnings:o,options:i,withResult:d}=e;if(t!==void 0)throw new S('Action "adopt-all" does not accept a target argument.',E.USAGE);if(L(i)!==void 0||typeof i.ref=="string"&&i.ref.trim().length>0)throw new S('Action "adopt-all" does not accept --gh/--github/--ref options.',E.USAGE);const r=await $(n.settings_root),c=await T(n.selected_root);o.push(...c.warnings);const l=await I(n.selected_root,a,r,c.state);o.push(...l.warnings);const u=await U(n.selected_root,a,l.extensions,c.state),m=await I(n.selected_root,a,r,u.state);o.push(...m.warnings);const w=V(a,o,m.extensions,i);o.push(...w.warnings);const b=new Map(m.extensions.map(p=>[`${f(p.name)}:${f(p.directory)}`,p])),_=new Map(m.extensions.map(p=>[f(p.directory),p])),v=u.adopted_entries.map(p=>{const g=f(p.directory),x=b.get(`${f(p.name)}:${g}`)??_.get(g);return{...p,...te(x)}});return d({adopted_all:v.length>0,adopted_count:v.length,already_managed_count:u.already_managed_count,extensions:v,triage:w,warning_codes:w.warning_codes,update_health_partial:w.update_health_partial,update_health_coverage:w.update_health_coverage})},te=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Te=(e,t,a,n)=>{if(e===void 0)return{kind:"local",input:t,location:a};const o=le(e,{forceGithub:!0,ref:n});if(o.kind!=="github")throw new S(`Invalid GitHub shorthand "${e}".`,E.USAGE);return{kind:"github",input:o.input,location:o.subpath??".",repository:o.repository,owner:o.owner,repo:o.repo,ref:o.ref,subpath:o.subpath}},Ln=async e=>{const{action:t,normalizedTarget:a,scope:n,resolvedRoots:o,warnings:i,options:d,withResult:s}=e,r=N(a,t,d),c=L(d),l=await $(o.settings_root),u=await T(o.selected_root);i.push(...u.warnings);const m=await I(o.selected_root,n,l,u.state);i.push(...m.warnings);const w=await J(m.extensions,r);if(!w)throw new S(`Installed extension "${r}" was not found in ${n} scope.`,E.NOT_FOUND);if(w.managed)return s({adopted:!1,already_managed:!0,extension:{name:w.name,directory:w.directory}});const b=A.join(o.selected_root,w.directory),_=await G(b),v=F(),p=Te(c,r,b,d.ref),g=H(u.state,{name:_.manifest.name,directory:w.directory,scope:n,manifest_version:_.manifest.version,manifest_entry:_.manifest.entry,capabilities:[..._.manifest.capabilities],contributions:_.manifest.contributions,installed_at:v,updated_at:v,source:p});await j(o.selected_root,g);const x=await I(o.selected_root,n,l,g);i.push(...x.warnings);const k=x.extensions.find(O=>f(O.name)===f(_.manifest.name))??x.extensions.find(O=>f(O.directory)===f(w.directory));return s({adopted:!0,extension:{name:_.manifest.name,directory:w.directory,version:_.manifest.version,entry:_.manifest.entry},source:p,...te(k)})},Oe=async e=>{const{action:t,normalizedTarget:a,scope:n,resolvedRoots:o,warnings:i,options:d}=e,s=N(a,t,d),r=await $(o.settings_root),c=await T(o.selected_root);i.push(...c.warnings);const l=await I(o.selected_root,n,r,c.state);i.push(...l.warnings);const u=await J(l.extensions,s);if(!u)throw new S(`Installed extension "${s}" was not found in ${n} scope.`,E.NOT_FOUND);return{settings:r,managedStateRead:c,candidate:u}},Nn=async e=>{const{resolvedRoots:t,withResult:a}=e,{settings:n,managedStateRead:o,candidate:i}=await Oe(e),d=A.join(t.selected_root,i.directory);await D.rm(d,{recursive:!0,force:!0});const s={...o.state,updated_at:F(),entries:o.state.entries.filter(c=>f(c.name)!==f(i.name)&&f(c.directory)!==f(i.directory))};await j(t.selected_root,s);const r=ve(n,i.name);return r&&await X(t.settings_root,n,"settings:write"),a({removed:!0,extension:{name:i.name,directory:i.directory},destination_path:d,settings_changed:r})},De=async e=>{const{action:t,resolvedRoots:a,warnings:n,global:o,withResult:i}=e,{settings:d,candidate:s}=await Oe(e),r=t==="activate"?be(d,s.name):tn(d,s.name);r&&await X(a.settings_root,d,"settings:write");const c=t==="activate"?await Ie(a.pm_root,A.dirname(a.selected_root),d,[s],o).then(l=>(n.push(...l.warnings),ee(s.name,l.activation_failures,e.scope))):void 0;return c&&n.push(`extension_activate_failed:${e.scope}:${s.name}`),i({extension:{name:s.name,directory:s.directory},active:t==="activate"&&c===void 0,runtime_active:t==="activate"&&c===void 0,activation_failure:c??null,settings_changed:r,settings:{enabled:[...d.extensions.enabled],disabled:[...d.extensions.disabled]}},c===void 0)},Fn=(e,t,a,n,o,i)=>{const d=n==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[d],r=o?.adopted_entries.length??0,c=[[i!==null,i??""],[t>0,`Run pm ${d} explore --project and pm ${d} explore --global to inspect load failures.`],[a>0,`Review activation failures in pm ${d} ${s} --detail deep output.`],[r>0,`Managed-state fix adopted ${r} extension(s).`]];return[...new Set([...e,...c.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},ne=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Gn=(e,t,a,n)=>{if(e!=="project"||t||!ne(n))return null;const o=a==="package"?"package":"extension";return`Global ${o} registrations are included in project diagnostics. For hermetic ${o} smoke tests, rerun pm ${o} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Un=(e,t,a)=>{if(String(e??"").trim().length>0)throw new S('Action "doctor" does not accept a target argument.',E.USAGE);const n=[a.isolated,a.ignoreGlobal].includes(!0);if([n,t==="global"].every(Boolean))throw new S("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",E.USAGE);const o=ht(a.detail),i=a.trace===!0;if([i,o!=="deep"].every(Boolean))throw new S("--trace requires --detail deep with --doctor.",E.USAGE);return{isolated:n,detailMode:o,includeTrace:i}},zn=async(e,t,a)=>{if(e.options.fixManagedState!==!0)return{state:a,fix:null};const n=await U(e.resolvedRoots.selected_root,e.scope,t,a);return{state:n.state,fix:n}},qn=(e,t,a,n)=>{const o=a==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:ne(n),rerun_command:null,pm_global_path_recipe:null};const i=`pm ${o} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:ne(n),rerun_command:t?null:i,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${o} doctor --project --detail deep --trace`}},Bn=async e=>{const{normalizedTarget:t,scope:a,resolvedRoots:n,warnings:o,options:i,global:d,withResult:s}=e,{isolated:r,detailMode:c,includeTrace:l}=Un(t,a,i),u=await $(n.settings_root),m=await T(n.selected_root);o.push(...m.warnings);const w=await I(n.selected_root,a,u,m.state);o.push(...w.warnings);const{state:b,fix:_}=await zn(e,w.extensions,m.state),v=await I(n.selected_root,a,u,b);o.push(...v.warnings);const p=await P({pmRoot:n.pm_root,settings:u,cwd:process.cwd(),noExtensions:d.noExtensions===!0,ignoreGlobalExtensions:r}),g=await M({...p,loaded:p.loaded}),x=await Gt(n.pm_root);o.push(...x.warnings,...p.warnings),o.push(..._t(p.failed)),o.push(...g.warnings),o.push(...gt(g.failed)),o.push(...ft(p,g)),o.push(...ue(g,p)),o.push(...Ce(p,g)),o.push(...pe(g));const k=K(v.extensions,p,g),O=vt(a,k,p.loaded.map(h=>({layer:h.layer,name:h.name})),p.failed.map(h=>({name:h.name})),p.disabled_by_flag);o.push(...O.warnings);const je=k.filter(h=>h.update_check_status==="failed").map(h=>`extension_update_check_failed:${h.name}`);o.push(...je);const R=V(a,o,k,i);o.push(...R.warnings);const ae=[...R.warnings],Le={mode:p.policy.mode,trust_mode:p.policy.trust_mode,require_provenance:p.policy.require_provenance,default_sandbox_profile:p.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:p.policy.trusted_extensions.length,allowed_extensions_count:p.policy.allowed_extensions.length,blocked_extensions_count:p.policy.blocked_extensions.length,allowed_capabilities_count:p.policy.allowed_capabilities.length,blocked_capabilities_count:p.policy.blocked_capabilities.length,allowed_surfaces_count:p.policy.allowed_surfaces.length,blocked_surfaces_count:p.policy.blocked_surfaces.length,allowed_commands_count:p.policy.allowed_commands.length,blocked_commands_count:p.policy.blocked_commands.length,allowed_actions_count:p.policy.allowed_actions.length,blocked_actions_count:p.policy.blocked_actions.length,allowed_services_count:p.policy.allowed_services.length,blocked_services_count:p.policy.blocked_services.length,extension_override_count:p.policy.extension_overrides.length},z=wt(ae),q=bt(),oe=R.warning_codes,Ne=Gn(a,r,i.vocabulary,p),Fe=Fn(R.remediation,p.failed.length,g.failed.length,i.vocabulary,_,Ne),ie=qn(a,r,i.vocabulary,p),Ge={status:R.status,scope:a,warning_count:R.warning_count,warning_codes:oe,total_extensions:k.length,managed_total:k.filter(h=>h.managed).length,enabled_total:k.filter(h=>h.enabled).length,active_total:k.filter(h=>h.active).length,unmanaged_loaded_extension_count:R.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:R.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:R.unmanaged_expected_extension_count,runtime_active_total:k.filter(h=>h.runtime_active===!0).length,activation_status_totals:{ok:k.filter(h=>h.activation_status==="ok").length,failed:k.filter(h=>h.activation_status==="failed").length,not_loaded:k.filter(h=>h.activation_status==="not_loaded").length,unknown:k.filter(h=>h.activation_status==="unknown").length},unknown_capability_count:z.length,capability_contract_version:q.version,update_available_total:R.update_available_total,update_check_status_totals:R.update_check_status_totals,update_health_coverage:R.update_health_coverage,update_health_partial:R.update_health_partial,update_check_failed_total:k.filter(h=>h.update_check_status==="failed").length,load_failure_count:p.failed.length,activation_failure_count:g.failed.length,load_failures:ce(p.failed),activation_failures:ce(g.failed),blocking_failure_count:p.failed.length+g.failed.length,has_blocking_failures:p.failed.length+g.failed.length>0,consistency_warning_count:O.warnings.length,trace_enabled:l,isolation:ie,policy:Le,remediation:Fe},Ue=_?{requested:!0,applied:_.adopted_entries.length>0,adopted_count:_.adopted_entries.length,already_managed_count:_.already_managed_count,adopted_extensions:_.adopted_entries.map(h=>h.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:v.extensions.filter(h=>h.managed).length,adopted_extensions:[]},B={mode:c,summary:Ge,triage:R,trace_enabled:l,capability_contract:q,capability_guidance:z,managed_state_fix:Ue,author_manifest:x,isolation:ie,policy:p.policy};if(c==="deep"){const h=l?g.failed:g.failed.map(y=>{const{trace:Jn,...ze}=y;return ze});B.deep={warnings:ae,warning_codes:oe,capability_contract:q,capability_guidance:z,trace_enabled:l,managed_state:{path:m.path,count:b.entries.length,entries:b.entries},installed_extensions:k,load:{roots:p.roots,policy:p.policy,warnings:p.warnings,failed:p.failed,loaded:p.loaded.map(y=>({layer:y.layer,directory:y.directory,name:y.name,version:y.version,entry:y.entry,priority:y.priority}))},activation:{failed:h,warnings:g.warnings,hook_counts:g.hook_counts,registration_counts:g.registration_counts,parser_override_count:g.parser_override_count,preflight_override_count:g.preflight_override_count,service_override_count:g.service_override_count,renderer_override_count:g.renderer_override_count},consistency:O.summary},l&&(B.deep.trace={activation_failures:g.failed.filter(y=>y.trace!==void 0).map(y=>({layer:y.layer,name:y.name,entry_path:y.entry_path,error:y.error,method:y.trace.method,command:y.trace.command,capability:y.trace.capability,missing_capability:y.trace.missing_capability,registration_index:y.trace.registration_index,expected_schema:y.trace.expected_schema,hint:y.trace.hint,received:y.trace.received}))})}return s(B)},Wn=async e=>{const{normalizedTarget:t,scope:a,resolvedRoots:n,warnings:o,options:i,global:d,withResult:s}=e,r=await $(n.settings_root),c=await P({pmRoot:n.pm_root,settings:r,cwd:process.cwd(),noExtensions:d.noExtensions===!0}),l=await M(c);o.push(...c.warnings),o.push(...l.warnings);const u=mt(t,c,l);if(t!==void 0&&u.extensions.length===0){const m=i.vocabulary==="package"?"package":"extension",w=[...new Set(c.loaded.map(_=>i.vocabulary==="package"&&typeof _.source_package=="string"&&_.source_package.trim().length>0?_.source_package.trim():_.name))].sort((_,v)=>_.localeCompare(v)),b=w.length>0?` Loaded ${m} names: ${w.join(", ")}.`:"";throw new S(`No loaded ${m} named "${t}" was found in ${a} scope.${b} Run pm ${m} explore to list discovered ${m}s.`,E.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},Xn=async(e,t,a)=>{let n=a,o=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(o=await U(e.resolvedRoots.selected_root,e.scope,t,a),n=o.state),e.action==="manage"){const i=e.options.fixManagedState===!0;n=await Dt(n,e.options.offline,i?$t:Tt(),!i);const d=await Mt(e.resolvedRoots.settings_root,e.resolvedRoots.selected_root,n.entries,e.options.offline===!0);d&&e.warnings.push(d)}return{state:n,fix:o}},Hn=async(e,t,a)=>{const n=await P({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),o=await M({...n,loaded:n.loaded});return e.warnings.push(...n.warnings,...o.warnings),{installed:K(a,n,o),failures:Z(o.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:n.failed.length,activation_failure_count:o.failed.length,warning_count:[...new Set([...n.warnings,...o.warnings])].length,policy:n.policy}}},Kn=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(a=>a.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(a=>a.managed).length},Me=async e=>{const{action:t,scope:a,resolvedRoots:n,warnings:o,options:i,withResult:d}=e,s=me(i.fields,t),r=await $(n.settings_root),c=he(r.extensions.policy),l=await T(n.selected_root);o.push(...l.warnings);const u=await I(n.selected_root,a,r,l.state);o.push(...u.warnings);const{state:m,fix:w}=await Xn(e,u.extensions,l.state),b=await I(n.selected_root,a,r,m);if(o.push(...b.warnings),t==="manage"&&i.offline===!0)for(const x of b.extensions)x.managed&&["npm","github"].includes(x.source.kind)&&(x.update_check_reason="offline_requested");if(t==="manage"){const x=b.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);o.push(...x)}const _=await Hn(e,r,b.extensions),v=_.installed,p=V(a,o,v,i);o.push(...p.warnings);const g={total:v.length,managed_total:v.filter(x=>x.managed).length,enabled_total:v.filter(x=>x.enabled).length,active_total:v.filter(x=>x.active).length,extensions:Pt(v,s),triage:p,policy:c};return _.failures!==void 0&&(g.activation_diagnostics={failed_count:_.failures.length,failed:_.failures}),t==="explore"&&(g.runtime_probe=_.summary),t==="manage"&&(g.runtime_probe=_.summary,g.managed_state_fix=Kn(w,v)),d(g)},Pe={init:yn,install:Pn,uninstall:Nn,explore:Me,manage:Me,describe:Wn,reload:xn,doctor:Bn,catalog:kn,adopt:Ln,"adopt-all":jn,activate:De,deactivate:De,migrate:Lt},Vn=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),Yn=e=>Vn(e)?Y(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Pe[e.action](e)):Pe[e.action](e),Na={adoptUnmanagedExtensions:U,buildAdoptedExtensionSource:Te,buildExtensionPolicyDetails:he,buildInstallCommandDiscovery:Re,checkGithubUpdate:Ct,clearExtensionState:ve,collectActivationFailureDiagnostics:Z,findActivationFailureByName:ee,resolveInstallRuntimeActivationStatus:Ae,collectGlobalOutputOverrideDoctorWarnings:ue,collectMcpCustomFieldCollisionDoctorWarnings:pe,collectSchemaNarrowActivationDoctorWarnings:Ce,copyExtensionDirectoryWithoutSelfNesting:yt,isErrnoCode:Et,isRetriableExtensionInstallCopyError:St,listInstalledExtensions:I,mapWithFixedConcurrency:At,projectExtensionUpdateCheck:te,readOptionalMetadataFile:zt,requireTarget:N,resolveAction:xe,resolveCommandDiscoveryPackageName:Se,resolveGithubOption:L,resolveInstalledExtensionCandidate:J,resolveManagedInstallTimestamps:$e,resolveScope:ke,resolveUpdateCheckResolution:Q,withExtensionInstallLock:Y};export{Na as _testOnly,de as copyExtensionDirectoryForInstall,le as parseExtensionInstallSource,re as parseExtensionManifest,T as readManagedExtensionState,Rt as resolveCanonicalExtensionInstallDestination,ot as resolveManagedExtensionStatePath,bn as runExtension,G as validateExtensionDirectory,j as writeManagedExtensionState};
2
2
  //# sourceMappingURL=extension.js.map