@unbrained/pm-cli 2026.5.29 → 2026.5.31

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 (274) hide show
  1. package/CHANGELOG.md +54 -12
  2. package/dist/cli/bootstrap-args.d.ts +1 -1
  3. package/dist/cli/bootstrap-args.js +59 -9
  4. package/dist/cli/bootstrap-args.js.map +1 -1
  5. package/dist/cli/commands/activity.js +4 -4
  6. package/dist/cli/commands/activity.js.map +1 -1
  7. package/dist/cli/commands/calendar.js +83 -11
  8. package/dist/cli/commands/calendar.js.map +1 -1
  9. package/dist/cli/commands/close.js +4 -4
  10. package/dist/cli/commands/close.js.map +1 -1
  11. package/dist/cli/commands/completion.js +4 -4
  12. package/dist/cli/commands/completion.js.map +1 -1
  13. package/dist/cli/commands/create.js +50 -7
  14. package/dist/cli/commands/create.js.map +1 -1
  15. package/dist/cli/commands/deps.js +4 -4
  16. package/dist/cli/commands/deps.js.map +1 -1
  17. package/dist/cli/commands/extension/install-sources.d.ts +3 -0
  18. package/dist/cli/commands/extension/install-sources.js +29 -4
  19. package/dist/cli/commands/extension/install-sources.js.map +1 -1
  20. package/dist/cli/commands/extension.js +26 -5
  21. package/dist/cli/commands/extension.js.map +1 -1
  22. package/dist/cli/commands/get.js +6 -3
  23. package/dist/cli/commands/get.js.map +1 -1
  24. package/dist/cli/commands/list.js +25 -6
  25. package/dist/cli/commands/list.js.map +1 -1
  26. package/dist/cli/commands/reindex.js +3 -3
  27. package/dist/cli/commands/reindex.js.map +1 -1
  28. package/dist/cli/commands/search.d.ts +17 -0
  29. package/dist/cli/commands/search.js +40 -10
  30. package/dist/cli/commands/search.js.map +1 -1
  31. package/dist/cli/commands/stats.js +4 -4
  32. package/dist/cli/commands/stats.js.map +1 -1
  33. package/dist/cli/commands/test-all.js +4 -4
  34. package/dist/cli/commands/test-all.js.map +1 -1
  35. package/dist/cli/main.d.ts +2 -0
  36. package/dist/cli/main.js +39 -11
  37. package/dist/cli/main.js.map +1 -1
  38. package/dist/cli/register-list-query.js +10 -12
  39. package/dist/cli/register-list-query.js.map +1 -1
  40. package/dist/cli/register-mutation.js +20 -22
  41. package/dist/cli/register-mutation.js.map +1 -1
  42. package/dist/cli/register-operations.js +32 -25
  43. package/dist/cli/register-operations.js.map +1 -1
  44. package/dist/cli/register-setup.js +7 -9
  45. package/dist/cli/register-setup.js.map +1 -1
  46. package/dist/cli/registration-helpers.js +6 -3
  47. package/dist/cli/registration-helpers.js.map +1 -1
  48. package/dist/cli/search-refresh.d.ts +2 -0
  49. package/dist/cli/search-refresh.js +13 -0
  50. package/dist/cli/search-refresh.js.map +1 -0
  51. package/dist/cli-bundle/chunks/activity-OWYSUZOY.js +17 -0
  52. package/dist/cli-bundle/chunks/activity-OWYSUZOY.js.map +7 -0
  53. package/dist/cli-bundle/chunks/aggregate-ADUOSFRO.js +209 -0
  54. package/dist/cli-bundle/chunks/aggregate-ADUOSFRO.js.map +7 -0
  55. package/dist/cli-bundle/chunks/append-JD2DETU7.js +73 -0
  56. package/dist/cli-bundle/chunks/append-JD2DETU7.js.map +7 -0
  57. package/dist/cli-bundle/chunks/chunk-3HUE7XOF.js +27 -0
  58. package/dist/cli-bundle/chunks/chunk-3HUE7XOF.js.map +7 -0
  59. package/dist/cli-bundle/chunks/chunk-3M73P3G6.js +1636 -0
  60. package/dist/cli-bundle/chunks/chunk-3M73P3G6.js.map +7 -0
  61. package/dist/cli-bundle/chunks/chunk-4AEZR5EJ.js +189 -0
  62. package/dist/cli-bundle/chunks/chunk-4AEZR5EJ.js.map +7 -0
  63. package/dist/cli-bundle/chunks/chunk-5HSEP75M.js +330 -0
  64. package/dist/cli-bundle/chunks/chunk-5HSEP75M.js.map +7 -0
  65. package/dist/cli-bundle/chunks/chunk-6HT2F4TK.js +1770 -0
  66. package/dist/cli-bundle/chunks/chunk-6HT2F4TK.js.map +7 -0
  67. package/dist/cli-bundle/chunks/chunk-6YCV7WSL.js +552 -0
  68. package/dist/cli-bundle/chunks/chunk-6YCV7WSL.js.map +7 -0
  69. package/dist/cli-bundle/chunks/chunk-7Y53ZJIQ.js +202 -0
  70. package/dist/cli-bundle/chunks/chunk-7Y53ZJIQ.js.map +7 -0
  71. package/dist/cli-bundle/chunks/chunk-A7E7PUVX.js +157 -0
  72. package/dist/cli-bundle/chunks/chunk-A7E7PUVX.js.map +7 -0
  73. package/dist/cli-bundle/chunks/chunk-AKOOMO3T.js +90 -0
  74. package/dist/cli-bundle/chunks/chunk-AKOOMO3T.js.map +7 -0
  75. package/dist/cli-bundle/chunks/chunk-BUPWJ3IJ.js +950 -0
  76. package/dist/cli-bundle/chunks/chunk-BUPWJ3IJ.js.map +7 -0
  77. package/dist/cli-bundle/chunks/chunk-CEFIVZPG.js +79 -0
  78. package/dist/cli-bundle/chunks/chunk-CEFIVZPG.js.map +7 -0
  79. package/dist/cli-bundle/chunks/chunk-D7AOMPRH.js +349 -0
  80. package/dist/cli-bundle/chunks/chunk-D7AOMPRH.js.map +7 -0
  81. package/dist/cli-bundle/chunks/chunk-EAOG77HM.js +56 -0
  82. package/dist/cli-bundle/chunks/chunk-EAOG77HM.js.map +7 -0
  83. package/dist/cli-bundle/chunks/chunk-EGUGFSNX.js +47 -0
  84. package/dist/cli-bundle/chunks/chunk-EGUGFSNX.js.map +7 -0
  85. package/dist/cli-bundle/chunks/chunk-FM26RGSU.js +56 -0
  86. package/dist/cli-bundle/chunks/chunk-FM26RGSU.js.map +7 -0
  87. package/dist/cli-bundle/chunks/chunk-FQE6XZDB.js +435 -0
  88. package/dist/cli-bundle/chunks/chunk-FQE6XZDB.js.map +7 -0
  89. package/dist/cli-bundle/chunks/chunk-G57E5D7T.js +185 -0
  90. package/dist/cli-bundle/chunks/chunk-G57E5D7T.js.map +7 -0
  91. package/dist/cli-bundle/chunks/chunk-GN7IJPCD.js +3621 -0
  92. package/dist/cli-bundle/chunks/chunk-GN7IJPCD.js.map +7 -0
  93. package/dist/cli-bundle/chunks/chunk-JFWUHHS2.js +233 -0
  94. package/dist/cli-bundle/chunks/chunk-JFWUHHS2.js.map +7 -0
  95. package/dist/cli-bundle/chunks/chunk-JTWRXG4B.js +1861 -0
  96. package/dist/cli-bundle/chunks/chunk-JTWRXG4B.js.map +7 -0
  97. package/dist/cli-bundle/chunks/chunk-JULRTHJQ.js +648 -0
  98. package/dist/cli-bundle/chunks/chunk-JULRTHJQ.js.map +7 -0
  99. package/dist/cli-bundle/chunks/chunk-KBQY3YG5.js +122 -0
  100. package/dist/cli-bundle/chunks/chunk-KBQY3YG5.js.map +7 -0
  101. package/dist/cli-bundle/chunks/chunk-L2FXEKDB.js +185 -0
  102. package/dist/cli-bundle/chunks/chunk-L2FXEKDB.js.map +7 -0
  103. package/dist/cli-bundle/chunks/chunk-LRBOHPUE.js +189 -0
  104. package/dist/cli-bundle/chunks/chunk-LRBOHPUE.js.map +7 -0
  105. package/dist/cli-bundle/chunks/chunk-LSXGH6NE.js +5153 -0
  106. package/dist/cli-bundle/chunks/chunk-LSXGH6NE.js.map +7 -0
  107. package/dist/cli-bundle/chunks/chunk-MD7K4JYF.js +1345 -0
  108. package/dist/cli-bundle/chunks/chunk-MD7K4JYF.js.map +7 -0
  109. package/dist/cli-bundle/chunks/chunk-NGN7UV5K.js +341 -0
  110. package/dist/cli-bundle/chunks/chunk-NGN7UV5K.js.map +7 -0
  111. package/dist/cli-bundle/chunks/chunk-O7IWB35H.js +18 -0
  112. package/dist/cli-bundle/chunks/chunk-O7IWB35H.js.map +7 -0
  113. package/dist/cli-bundle/chunks/chunk-OGZEG5TT.js +2929 -0
  114. package/dist/cli-bundle/chunks/chunk-OGZEG5TT.js.map +7 -0
  115. package/dist/cli-bundle/chunks/chunk-P53TN6IA.js +674 -0
  116. package/dist/cli-bundle/chunks/chunk-P53TN6IA.js.map +7 -0
  117. package/dist/cli-bundle/chunks/chunk-PVNQLCIS.js +176 -0
  118. package/dist/cli-bundle/chunks/chunk-PVNQLCIS.js.map +7 -0
  119. package/dist/cli-bundle/chunks/chunk-PXUAZUUY.js +1680 -0
  120. package/dist/cli-bundle/chunks/chunk-PXUAZUUY.js.map +7 -0
  121. package/dist/cli-bundle/chunks/chunk-QAJBIGRA.js +20 -0
  122. package/dist/cli-bundle/chunks/chunk-QAJBIGRA.js.map +7 -0
  123. package/dist/cli-bundle/chunks/chunk-SEXQN4KL.js +60 -0
  124. package/dist/cli-bundle/chunks/chunk-SEXQN4KL.js.map +7 -0
  125. package/dist/cli-bundle/chunks/chunk-U7FMKRXH.js +362 -0
  126. package/dist/cli-bundle/chunks/chunk-U7FMKRXH.js.map +7 -0
  127. package/dist/cli-bundle/chunks/chunk-VGICHR7D.js +141 -0
  128. package/dist/cli-bundle/chunks/chunk-VGICHR7D.js.map +7 -0
  129. package/dist/cli-bundle/chunks/chunk-WDPXDQFG.js +632 -0
  130. package/dist/cli-bundle/chunks/chunk-WDPXDQFG.js.map +7 -0
  131. package/dist/cli-bundle/chunks/chunk-WJ2NAC37.js +252 -0
  132. package/dist/cli-bundle/chunks/chunk-WJ2NAC37.js.map +7 -0
  133. package/dist/cli-bundle/chunks/claim-EE4TKKCV.js +133 -0
  134. package/dist/cli-bundle/chunks/claim-EE4TKKCV.js.map +7 -0
  135. package/dist/cli-bundle/chunks/close-XY4CSAYF.js +14 -0
  136. package/dist/cli-bundle/chunks/close-XY4CSAYF.js.map +7 -0
  137. package/dist/cli-bundle/chunks/comments-AAKJQ6LW.js +104 -0
  138. package/dist/cli-bundle/chunks/comments-AAKJQ6LW.js.map +7 -0
  139. package/dist/cli-bundle/chunks/config-V3FZOKLI.js +1577 -0
  140. package/dist/cli-bundle/chunks/config-V3FZOKLI.js.map +7 -0
  141. package/dist/cli-bundle/chunks/context-RZ5QPNJB.js +1458 -0
  142. package/dist/cli-bundle/chunks/context-RZ5QPNJB.js.map +7 -0
  143. package/dist/cli-bundle/chunks/contracts-YLMH33VU.js +1245 -0
  144. package/dist/cli-bundle/chunks/contracts-YLMH33VU.js.map +7 -0
  145. package/dist/cli-bundle/chunks/create-PZVHRIZQ.js +28 -0
  146. package/dist/cli-bundle/chunks/create-PZVHRIZQ.js.map +7 -0
  147. package/dist/cli-bundle/chunks/delete-RHCTEORS.js +59 -0
  148. package/dist/cli-bundle/chunks/delete-RHCTEORS.js.map +7 -0
  149. package/dist/cli-bundle/chunks/deps-MZYCMLAO.js +229 -0
  150. package/dist/cli-bundle/chunks/deps-MZYCMLAO.js.map +7 -0
  151. package/dist/cli-bundle/chunks/docs-FXXUCZYU.js +35 -0
  152. package/dist/cli-bundle/chunks/docs-FXXUCZYU.js.map +7 -0
  153. package/dist/cli-bundle/chunks/extension-B4WL7BQU.js +25 -0
  154. package/dist/cli-bundle/chunks/extension-B4WL7BQU.js.map +7 -0
  155. package/dist/cli-bundle/chunks/files-WVOX67PE.js +286 -0
  156. package/dist/cli-bundle/chunks/files-WVOX67PE.js.map +7 -0
  157. package/dist/cli-bundle/chunks/gc-JWNF66EC.js +181 -0
  158. package/dist/cli-bundle/chunks/gc-JWNF66EC.js.map +7 -0
  159. package/dist/cli-bundle/chunks/get-LTK3HOCQ.js +198 -0
  160. package/dist/cli-bundle/chunks/get-LTK3HOCQ.js.map +7 -0
  161. package/dist/cli-bundle/chunks/health-TCWL55KM.js +1233 -0
  162. package/dist/cli-bundle/chunks/health-TCWL55KM.js.map +7 -0
  163. package/dist/cli-bundle/chunks/history-A2JUDXUE.js +21 -0
  164. package/dist/cli-bundle/chunks/history-A2JUDXUE.js.map +7 -0
  165. package/dist/cli-bundle/chunks/history-redact-ED6RFCPL.js +20 -0
  166. package/dist/cli-bundle/chunks/history-redact-ED6RFCPL.js.map +7 -0
  167. package/dist/cli-bundle/chunks/history-repair-ZWSTDRH2.js +198 -0
  168. package/dist/cli-bundle/chunks/history-repair-ZWSTDRH2.js.map +7 -0
  169. package/dist/cli-bundle/chunks/init-M2WUB4YH.js +16 -0
  170. package/dist/cli-bundle/chunks/init-M2WUB4YH.js.map +7 -0
  171. package/dist/cli-bundle/chunks/learnings-NXTWE3FR.js +48 -0
  172. package/dist/cli-bundle/chunks/learnings-NXTWE3FR.js.map +7 -0
  173. package/dist/cli-bundle/chunks/list-OGWQPC26.js +20 -0
  174. package/dist/cli-bundle/chunks/list-OGWQPC26.js.map +7 -0
  175. package/dist/cli-bundle/chunks/notes-DFS5ZGOO.js +48 -0
  176. package/dist/cli-bundle/chunks/notes-DFS5ZGOO.js.map +7 -0
  177. package/dist/cli-bundle/chunks/plan-67AB2PLM.js +1175 -0
  178. package/dist/cli-bundle/chunks/plan-67AB2PLM.js.map +7 -0
  179. package/dist/cli-bundle/chunks/register-list-query-UP3VRUFS.js +232 -0
  180. package/dist/cli-bundle/chunks/register-list-query-UP3VRUFS.js.map +7 -0
  181. package/dist/cli-bundle/chunks/register-mutation-YWSBF545.js +712 -0
  182. package/dist/cli-bundle/chunks/register-mutation-YWSBF545.js.map +7 -0
  183. package/dist/cli-bundle/chunks/register-operations-3BDTGSDH.js +374 -0
  184. package/dist/cli-bundle/chunks/register-operations-3BDTGSDH.js.map +7 -0
  185. package/dist/cli-bundle/chunks/register-setup-V56GDRUS.js +246 -0
  186. package/dist/cli-bundle/chunks/register-setup-V56GDRUS.js.map +7 -0
  187. package/dist/cli-bundle/chunks/restore-MB2ISME7.js +18 -0
  188. package/dist/cli-bundle/chunks/restore-MB2ISME7.js.map +7 -0
  189. package/dist/cli-bundle/chunks/schema-Q622KC46.js +119 -0
  190. package/dist/cli-bundle/chunks/schema-Q622KC46.js.map +7 -0
  191. package/dist/cli-bundle/chunks/search-HENBL456.js +1135 -0
  192. package/dist/cli-bundle/chunks/search-HENBL456.js.map +7 -0
  193. package/dist/cli-bundle/chunks/stats-N6H3YP2F.js +124 -0
  194. package/dist/cli-bundle/chunks/stats-N6H3YP2F.js.map +7 -0
  195. package/dist/cli-bundle/chunks/test-VNBDRJ4Z.js +32 -0
  196. package/dist/cli-bundle/chunks/test-VNBDRJ4Z.js.map +7 -0
  197. package/dist/cli-bundle/chunks/test-all-G2AZOHXI.js +332 -0
  198. package/dist/cli-bundle/chunks/test-all-G2AZOHXI.js.map +7 -0
  199. package/dist/cli-bundle/chunks/test-runs-GX5HTPSF.js +939 -0
  200. package/dist/cli-bundle/chunks/test-runs-GX5HTPSF.js.map +7 -0
  201. package/dist/cli-bundle/chunks/update-H6SCWNMA.js +22 -0
  202. package/dist/cli-bundle/chunks/update-H6SCWNMA.js.map +7 -0
  203. package/dist/cli-bundle/chunks/update-many-46HRSP2Q.js +676 -0
  204. package/dist/cli-bundle/chunks/update-many-46HRSP2Q.js.map +7 -0
  205. package/dist/cli-bundle/chunks/upgrade-H5HHM5UV.js +271 -0
  206. package/dist/cli-bundle/chunks/upgrade-H5HHM5UV.js.map +7 -0
  207. package/dist/cli-bundle/chunks/validate-TMCVKIGZ.js +1110 -0
  208. package/dist/cli-bundle/chunks/validate-TMCVKIGZ.js.map +7 -0
  209. package/dist/cli-bundle/main.js +6952 -0
  210. package/dist/cli-bundle/main.js.map +7 -0
  211. package/dist/cli.js +1 -1
  212. package/dist/core/config/nested-settings.d.ts +2 -0
  213. package/dist/core/config/nested-settings.js +17 -2
  214. package/dist/core/config/nested-settings.js.map +1 -1
  215. package/dist/core/item/item-type-definition.js +6 -2
  216. package/dist/core/item/item-type-definition.js.map +1 -1
  217. package/dist/core/item/type-registry.d.ts +4 -0
  218. package/dist/core/item/type-registry.js +10 -2
  219. package/dist/core/item/type-registry.js.map +1 -1
  220. package/dist/core/item/type-synonyms.d.ts +20 -0
  221. package/dist/core/item/type-synonyms.js +42 -0
  222. package/dist/core/item/type-synonyms.js.map +1 -0
  223. package/dist/core/search/background-refresh.d.ts +53 -0
  224. package/dist/core/search/background-refresh.js +286 -0
  225. package/dist/core/search/background-refresh.js.map +1 -0
  226. package/dist/core/search/cache.d.ts +20 -1
  227. package/dist/core/search/cache.js +76 -5
  228. package/dist/core/search/cache.js.map +1 -1
  229. package/dist/core/search/semantic-defaults.js +73 -32
  230. package/dist/core/search/semantic-defaults.js.map +1 -1
  231. package/dist/core/search/vector-stores.js +7 -3
  232. package/dist/core/search/vector-stores.js.map +1 -1
  233. package/dist/core/sentry/helpers.d.ts +1 -1
  234. package/dist/core/sentry/helpers.js +4 -4
  235. package/dist/core/sentry/helpers.js.map +1 -1
  236. package/dist/core/shared/constants.d.ts +2 -2
  237. package/dist/core/shared/constants.js +3 -3
  238. package/dist/core/shared/constants.js.map +1 -1
  239. package/dist/core/shared/html-entity-decode.d.ts +2 -1
  240. package/dist/core/shared/html-entity-decode.js +14 -9
  241. package/dist/core/shared/html-entity-decode.js.map +1 -1
  242. package/dist/core/shared/time.js +52 -2
  243. package/dist/core/shared/time.js.map +1 -1
  244. package/dist/core/store/front-matter-cache.d.ts +24 -0
  245. package/dist/core/store/front-matter-cache.js +119 -8
  246. package/dist/core/store/front-matter-cache.js.map +1 -1
  247. package/dist/core/store/item-format-migration.js +25 -15
  248. package/dist/core/store/item-format-migration.js.map +1 -1
  249. package/dist/core/store/item-store.d.ts +7 -0
  250. package/dist/core/store/item-store.js +13 -3
  251. package/dist/core/store/item-store.js.map +1 -1
  252. package/dist/core/store/settings-validator.d.ts +1 -0
  253. package/dist/core/store/settings-validator.js +7 -2
  254. package/dist/core/store/settings-validator.js.map +1 -1
  255. package/dist/core/store/settings.js +19 -3
  256. package/dist/core/store/settings.js.map +1 -1
  257. package/dist/core/telemetry/runtime.d.ts +10 -0
  258. package/dist/core/telemetry/runtime.js +86 -2
  259. package/dist/core/telemetry/runtime.js.map +1 -1
  260. package/dist/mcp/server.js +3 -3
  261. package/dist/mcp/server.js.map +1 -1
  262. package/dist/sdk/cli-contracts/tool-parameter-tables.js +4 -4
  263. package/dist/sdk/cli-contracts/tool-parameter-tables.js.map +1 -1
  264. package/dist/sdk/cli-contracts.js +29 -8
  265. package/dist/sdk/cli-contracts.js.map +1 -1
  266. package/dist/types.d.ts +9 -1
  267. package/dist/types.js +2 -2
  268. package/dist/types.js.map +1 -1
  269. package/docs/CONFIGURATION.md +11 -0
  270. package/docs/RELEASING.md +1 -1
  271. package/package.json +7 -5
  272. package/packages/pm-calendar/extensions/calendar/index.js +27 -2
  273. package/packages/pm-calendar/extensions/calendar/index.ts +28 -2
  274. package/scripts/bundle-cli.mjs +39 -0
@@ -0,0 +1,2929 @@
1
+ import {
2
+ resolvePmPackageRootFromModule
3
+ } from "./chunk-EGUGFSNX.js";
4
+ import {
5
+ splitCommaList
6
+ } from "./chunk-3HUE7XOF.js";
7
+ import {
8
+ nowIso
9
+ } from "./chunk-PVNQLCIS.js";
10
+ import {
11
+ EXIT_CODE,
12
+ EXTENSION_CAPABILITY_CONTRACT,
13
+ KNOWN_EXTENSION_CAPABILITIES,
14
+ PmCliError,
15
+ activateExtensions,
16
+ isPathWithinDirectory,
17
+ loadExtensions,
18
+ nextExtensionReloadToken,
19
+ parseLegacyExtensionCapabilityAliasWarning,
20
+ parseUnknownExtensionCapabilityWarning,
21
+ pathExists,
22
+ readSettings,
23
+ resolveExtensionRoots,
24
+ resolveGlobalPmRoot,
25
+ resolvePmRoot,
26
+ writeSettings
27
+ } from "./chunk-LSXGH6NE.js";
28
+
29
+ // dist/cli/commands/extension.js
30
+ import { execFile as execFile2 } from "node:child_process";
31
+ import fs7 from "node:fs/promises";
32
+ import os2 from "node:os";
33
+ import path7 from "node:path";
34
+ import { promisify as promisify2 } from "node:util";
35
+
36
+ // dist/cli/commands/extension/shared.js
37
+ import fs from "node:fs/promises";
38
+ import path from "node:path";
39
+ !(function() {
40
+ try {
41
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
42
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "cb831def-7a8a-55f8-85e2-7749a5591bfe");
43
+ } catch (e2) {
44
+ }
45
+ })();
46
+ var DEFAULT_EXTENSION_PRIORITY = 100;
47
+ function normalizeStringList(values) {
48
+ return [...new Set(values.map((value) => value.trim()).filter((value) => value.length > 0))].sort((left, right) => left.localeCompare(right));
49
+ }
50
+ function normalizeExtensionNameForMatch(value) {
51
+ return value.trim().toLowerCase();
52
+ }
53
+ function normalizeManagedDirectoryName(name) {
54
+ const normalized = name.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
55
+ if (normalized.length === 0) {
56
+ throw new PmCliError("Extension manifest name must resolve to a non-empty directory name.", EXIT_CODE.USAGE);
57
+ }
58
+ if (normalized === "." || normalized === "..") {
59
+ throw new PmCliError('Extension manifest name must not resolve to "." or "..".', EXIT_CODE.USAGE);
60
+ }
61
+ return normalized;
62
+ }
63
+ function parseExtensionManifest(raw) {
64
+ if (typeof raw !== "object" || raw === null) {
65
+ return null;
66
+ }
67
+ const candidate = raw;
68
+ if (typeof candidate.name !== "string" || candidate.name.trim().length === 0) {
69
+ return null;
70
+ }
71
+ if (typeof candidate.version !== "string" || candidate.version.trim().length === 0) {
72
+ return null;
73
+ }
74
+ if (typeof candidate.entry !== "string" || candidate.entry.trim().length === 0) {
75
+ return null;
76
+ }
77
+ let priority = DEFAULT_EXTENSION_PRIORITY;
78
+ if (candidate.priority !== void 0 && candidate.priority !== null) {
79
+ if (typeof candidate.priority !== "number" || !Number.isInteger(candidate.priority)) {
80
+ return null;
81
+ }
82
+ priority = candidate.priority;
83
+ }
84
+ let capabilities = [];
85
+ if (candidate.capabilities !== void 0 && candidate.capabilities !== null) {
86
+ if (!Array.isArray(candidate.capabilities) || candidate.capabilities.some((value) => typeof value !== "string")) {
87
+ return null;
88
+ }
89
+ capabilities = normalizeStringList(candidate.capabilities.map((value) => String(value).toLowerCase()));
90
+ }
91
+ return {
92
+ name: candidate.name.trim(),
93
+ version: candidate.version.trim(),
94
+ entry: candidate.entry.trim(),
95
+ priority,
96
+ capabilities
97
+ };
98
+ }
99
+ async function isCanonicalPathWithinDirectory(directory, targetPath) {
100
+ const [resolvedDirectory, resolvedTargetPath] = await Promise.all([fs.realpath(directory), fs.realpath(targetPath)]);
101
+ return isPathWithinDirectory(resolvedDirectory, resolvedTargetPath);
102
+ }
103
+ async function validateExtensionDirectory(directory) {
104
+ const manifestPath = path.join(directory, "manifest.json");
105
+ if (!await pathExists(manifestPath)) {
106
+ throw new PmCliError(`Extension manifest is missing at "${manifestPath}".`, EXIT_CODE.USAGE);
107
+ }
108
+ let parsedManifest;
109
+ try {
110
+ parsedManifest = JSON.parse(await fs.readFile(manifestPath, "utf8"));
111
+ } catch (error) {
112
+ throw new PmCliError(`Failed to parse extension manifest at "${manifestPath}": ${error instanceof Error ? error.message : String(error)}`, EXIT_CODE.USAGE);
113
+ }
114
+ const manifest = parseExtensionManifest(parsedManifest);
115
+ if (!manifest) {
116
+ throw new PmCliError(`Extension manifest at "${manifestPath}" is invalid.`, EXIT_CODE.USAGE);
117
+ }
118
+ const entryPath = path.resolve(directory, manifest.entry);
119
+ if (!isPathWithinDirectory(directory, entryPath)) {
120
+ throw new PmCliError(`Extension entry "${manifest.entry}" resolves outside extension directory "${directory}".`, EXIT_CODE.USAGE);
121
+ }
122
+ if (!await pathExists(entryPath)) {
123
+ throw new PmCliError(`Extension entry file is missing at "${entryPath}".`, EXIT_CODE.USAGE);
124
+ }
125
+ if (!await isCanonicalPathWithinDirectory(directory, entryPath)) {
126
+ throw new PmCliError(`Extension entry "${manifest.entry}" resolves outside extension directory after symlink resolution.`, EXIT_CODE.USAGE);
127
+ }
128
+ return {
129
+ directory,
130
+ manifest_path: manifestPath,
131
+ entry_path: entryPath,
132
+ manifest
133
+ };
134
+ }
135
+
136
+ // dist/cli/commands/extension/managed-state.js
137
+ import fs2 from "node:fs/promises";
138
+ import path2 from "node:path";
139
+ !(function() {
140
+ try {
141
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
142
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "f7dc1712-641e-52f3-bbd9-7f20eafddd5f");
143
+ } catch (e2) {
144
+ }
145
+ })();
146
+ var MANAGED_EXTENSION_STATE_FILENAME = ".managed-extensions.json";
147
+ var MANAGED_EXTENSION_STATE_VERSION = 1;
148
+ function resolveManagedExtensionStatePath(extensionsRoot) {
149
+ return path2.join(extensionsRoot, MANAGED_EXTENSION_STATE_FILENAME);
150
+ }
151
+ function createEmptyManagedExtensionState() {
152
+ return {
153
+ version: MANAGED_EXTENSION_STATE_VERSION,
154
+ updated_at: nowIso(),
155
+ entries: []
156
+ };
157
+ }
158
+ function sortManagedEntries(entries) {
159
+ return [...entries].sort((left, right) => {
160
+ const byScope = left.scope.localeCompare(right.scope);
161
+ if (byScope !== 0) {
162
+ return byScope;
163
+ }
164
+ const byName = left.name.localeCompare(right.name);
165
+ if (byName !== 0) {
166
+ return byName;
167
+ }
168
+ return left.directory.localeCompare(right.directory);
169
+ });
170
+ }
171
+ function managedExtensionSourcesEquivalent(left, right) {
172
+ if (left.kind !== right.kind || left.input !== right.input || left.location !== right.location) {
173
+ return false;
174
+ }
175
+ if (left.kind === "npm" && right.kind === "npm") {
176
+ return left.package === right.package && left.version === right.version;
177
+ }
178
+ if (left.kind === "github" && right.kind === "github") {
179
+ return left.repository === right.repository && left.ref === right.ref && left.subpath === right.subpath && left.commit === right.commit;
180
+ }
181
+ if (left.kind === "builtin" && right.kind === "builtin") {
182
+ return left.name === right.name;
183
+ }
184
+ return true;
185
+ }
186
+ function normalizeManagedState(raw) {
187
+ if (typeof raw !== "object" || raw === null) {
188
+ return null;
189
+ }
190
+ const candidate = raw;
191
+ if (candidate.version !== MANAGED_EXTENSION_STATE_VERSION || !Array.isArray(candidate.entries)) {
192
+ return null;
193
+ }
194
+ const entries = [];
195
+ for (const rawEntry of candidate.entries) {
196
+ if (typeof rawEntry !== "object" || rawEntry === null) {
197
+ continue;
198
+ }
199
+ const entry = rawEntry;
200
+ if (typeof entry.name !== "string" || entry.name.trim().length === 0 || typeof entry.directory !== "string" || entry.directory.trim().length === 0 || entry.scope !== "project" && entry.scope !== "global" || typeof entry.manifest_version !== "string" || typeof entry.manifest_entry !== "string" || !Array.isArray(entry.capabilities) || entry.capabilities.some((value) => typeof value !== "string") || typeof entry.installed_at !== "string" || typeof entry.updated_at !== "string" || typeof entry.source !== "object" || entry.source === null) {
201
+ continue;
202
+ }
203
+ const source = entry.source;
204
+ if (source.kind !== "local" && source.kind !== "github" && source.kind !== "npm" && source.kind !== "builtin" || typeof source.input !== "string" || typeof source.location !== "string") {
205
+ continue;
206
+ }
207
+ entries.push({
208
+ name: entry.name.trim(),
209
+ directory: entry.directory.trim(),
210
+ scope: entry.scope,
211
+ manifest_version: entry.manifest_version,
212
+ manifest_entry: entry.manifest_entry,
213
+ capabilities: normalizeStringList(entry.capabilities),
214
+ installed_at: entry.installed_at,
215
+ updated_at: entry.updated_at,
216
+ source: {
217
+ kind: source.kind,
218
+ input: source.input,
219
+ location: source.location,
220
+ name: typeof source.name === "string" ? source.name : void 0,
221
+ package: typeof source.package === "string" ? source.package : void 0,
222
+ version: typeof source.version === "string" ? source.version : void 0,
223
+ repository: typeof source.repository === "string" ? source.repository : void 0,
224
+ owner: typeof source.owner === "string" ? source.owner : void 0,
225
+ repo: typeof source.repo === "string" ? source.repo : void 0,
226
+ ref: typeof source.ref === "string" ? source.ref : void 0,
227
+ subpath: typeof source.subpath === "string" ? source.subpath : void 0,
228
+ commit: typeof source.commit === "string" ? source.commit : void 0
229
+ },
230
+ last_update_check_at: typeof entry.last_update_check_at === "string" ? entry.last_update_check_at : void 0,
231
+ last_update_remote_commit: typeof entry.last_update_remote_commit === "string" ? entry.last_update_remote_commit : void 0,
232
+ update_available: typeof entry.update_available === "boolean" || entry.update_available === null ? entry.update_available : void 0,
233
+ update_error: typeof entry.update_error === "string" ? entry.update_error : void 0
234
+ });
235
+ }
236
+ return {
237
+ version: MANAGED_EXTENSION_STATE_VERSION,
238
+ updated_at: typeof candidate.updated_at === "string" ? candidate.updated_at : nowIso(),
239
+ entries: sortManagedEntries(entries)
240
+ };
241
+ }
242
+ async function readManagedExtensionState(extensionsRoot) {
243
+ const statePath = resolveManagedExtensionStatePath(extensionsRoot);
244
+ const fallback = createEmptyManagedExtensionState();
245
+ try {
246
+ const raw = await fs2.readFile(statePath, "utf8");
247
+ const parsed = JSON.parse(raw);
248
+ const normalized = normalizeManagedState(parsed);
249
+ if (!normalized) {
250
+ throw new PmCliError(`Managed extension state file "${statePath}" has an invalid schema. Repair or remove it before mutating extension state.`, EXIT_CODE.GENERIC_FAILURE);
251
+ }
252
+ return {
253
+ path: statePath,
254
+ state: normalized,
255
+ warnings: []
256
+ };
257
+ } catch (error) {
258
+ if (error instanceof PmCliError) {
259
+ throw error;
260
+ }
261
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
262
+ return {
263
+ path: statePath,
264
+ state: fallback,
265
+ warnings: []
266
+ };
267
+ }
268
+ throw new PmCliError(`Managed extension state file "${statePath}" could not be read. Repair or remove it before mutating extension state.`, EXIT_CODE.GENERIC_FAILURE);
269
+ }
270
+ }
271
+ async function writeManagedExtensionState(extensionsRoot, state) {
272
+ const statePath = resolveManagedExtensionStatePath(extensionsRoot);
273
+ const normalized = {
274
+ version: MANAGED_EXTENSION_STATE_VERSION,
275
+ updated_at: nowIso(),
276
+ entries: sortManagedEntries(state.entries)
277
+ };
278
+ await fs2.mkdir(extensionsRoot, { recursive: true });
279
+ await fs2.writeFile(statePath, `${JSON.stringify(normalized, null, 2)}
280
+ `, "utf8");
281
+ }
282
+ function upsertManagedEntry(state, entry) {
283
+ const updatedEntries = state.entries.filter((candidate) => normalizeExtensionNameForMatch(candidate.name) !== normalizeExtensionNameForMatch(entry.name) && normalizeExtensionNameForMatch(candidate.directory) !== normalizeExtensionNameForMatch(entry.directory));
284
+ updatedEntries.push(entry);
285
+ return {
286
+ ...state,
287
+ updated_at: nowIso(),
288
+ entries: sortManagedEntries(updatedEntries)
289
+ };
290
+ }
291
+
292
+ // dist/cli/commands/extension/install-sources.js
293
+ import { execFile } from "node:child_process";
294
+ import fs4 from "node:fs/promises";
295
+ import os from "node:os";
296
+ import path4 from "node:path";
297
+ import { fileURLToPath, pathToFileURL } from "node:url";
298
+ import { promisify } from "node:util";
299
+
300
+ // dist/core/packages/manifest.js
301
+ import fs3 from "node:fs/promises";
302
+ import path3 from "node:path";
303
+ !(function() {
304
+ try {
305
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
306
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "84dfbdeb-902c-58a1-a6c4-9411f5c2293e");
307
+ } catch (e2) {
308
+ }
309
+ })();
310
+ var PM_PACKAGE_RESOURCE_KINDS = [
311
+ "extensions",
312
+ "docs",
313
+ "examples"
314
+ ];
315
+ var PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS = Object.freeze({
316
+ extensions: Object.freeze([
317
+ ".agents/pm/extensions",
318
+ "extensions",
319
+ ".custom/pm-extensions",
320
+ ".custom/pm-extension"
321
+ ]),
322
+ docs: Object.freeze([
323
+ "docs",
324
+ "documentation"
325
+ ]),
326
+ examples: Object.freeze([
327
+ "examples",
328
+ "docs/examples"
329
+ ])
330
+ });
331
+ function isKnownPackageResourceKind(value) {
332
+ return PM_PACKAGE_RESOURCE_KINDS.includes(value);
333
+ }
334
+ function normalizePackageResourceEntries(kind, raw) {
335
+ if (raw === void 0 || raw === null) {
336
+ return [];
337
+ }
338
+ const entries = Array.isArray(raw) ? raw : [raw];
339
+ const normalized = [];
340
+ for (const entry of entries) {
341
+ if (typeof entry !== "string" || entry.trim().length === 0) {
342
+ throw new PmCliError(`Package manifest field pm.${kind} must contain string paths.`, EXIT_CODE.USAGE);
343
+ }
344
+ normalized.push(entry.trim());
345
+ }
346
+ return [...new Set(normalized)].sort((left, right) => left.localeCompare(right));
347
+ }
348
+ function normalizePackageResourceMap(raw) {
349
+ if (raw === void 0 || raw === null) {
350
+ return {};
351
+ }
352
+ if (typeof raw !== "object" || Array.isArray(raw)) {
353
+ throw new PmCliError("Package manifest field pm must be an object.", EXIT_CODE.USAGE);
354
+ }
355
+ const resources = {};
356
+ const candidate = raw;
357
+ for (const [key, value] of Object.entries(candidate)) {
358
+ if (!isKnownPackageResourceKind(key)) {
359
+ continue;
360
+ }
361
+ const entries = normalizePackageResourceEntries(key, value);
362
+ if (entries.length > 0) {
363
+ resources[key] = entries;
364
+ }
365
+ }
366
+ return resources;
367
+ }
368
+ function readStringField(source, key) {
369
+ const value = source[key];
370
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
371
+ }
372
+ function normalizeStringArray(raw) {
373
+ if (!Array.isArray(raw)) {
374
+ return void 0;
375
+ }
376
+ const values = raw.map((value) => typeof value === "string" ? value.trim() : "").filter((value) => value.length > 0);
377
+ return values.length > 0 ? [...new Set(values)].sort((left, right) => left.localeCompare(right)) : void 0;
378
+ }
379
+ function readUrlLikeField(raw) {
380
+ if (typeof raw === "string" && raw.trim().length > 0) {
381
+ return raw.trim();
382
+ }
383
+ if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
384
+ const value = raw.url;
385
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
386
+ }
387
+ return void 0;
388
+ }
389
+ function normalizeCatalogLinks(raw) {
390
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
391
+ return void 0;
392
+ }
393
+ const source = raw;
394
+ const links = {
395
+ docs: readStringField(source, "docs"),
396
+ npm: readStringField(source, "npm"),
397
+ repository: readStringField(source, "repository"),
398
+ report: readStringField(source, "report")
399
+ };
400
+ return Object.values(links).some((value) => typeof value === "string") ? links : void 0;
401
+ }
402
+ function normalizeCatalogMedia(raw) {
403
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
404
+ return void 0;
405
+ }
406
+ const source = raw;
407
+ const media = {
408
+ image: readStringField(source, "image"),
409
+ video: readStringField(source, "video")
410
+ };
411
+ return Object.values(media).some((value) => typeof value === "string") ? media : void 0;
412
+ }
413
+ function normalizePackageCatalogMetadata(raw) {
414
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
415
+ return void 0;
416
+ }
417
+ const source = raw;
418
+ const catalog = {
419
+ display_name: readStringField(source, "display_name") ?? readStringField(source, "displayName"),
420
+ category: readStringField(source, "category"),
421
+ summary: readStringField(source, "summary"),
422
+ links: normalizeCatalogLinks(source.links),
423
+ media: normalizeCatalogMedia(source.media),
424
+ tags: normalizeStringArray(source.tags)
425
+ };
426
+ return Object.values(catalog).some((value) => value !== void 0) ? catalog : void 0;
427
+ }
428
+ async function readPmPackageManifest(packageRoot) {
429
+ const packageJsonPath = path3.join(packageRoot, "package.json");
430
+ if (!await pathExists(packageJsonPath)) {
431
+ return {
432
+ source: "convention",
433
+ resources: {}
434
+ };
435
+ }
436
+ let parsed;
437
+ try {
438
+ parsed = JSON.parse(await fs3.readFile(packageJsonPath, "utf8"));
439
+ } catch (error) {
440
+ throw new PmCliError(`Failed to parse package manifest at "${packageJsonPath}": ${String(error)}`, EXIT_CODE.USAGE);
441
+ }
442
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
443
+ throw new PmCliError(`Package manifest at "${packageJsonPath}" must be a JSON object.`, EXIT_CODE.USAGE);
444
+ }
445
+ const packageJson = parsed;
446
+ const pmManifest = packageJson.pm;
447
+ const hasPmManifest = pmManifest !== void 0 && pmManifest !== null;
448
+ const pmManifestRecord = typeof pmManifest === "object" && pmManifest !== null && !Array.isArray(pmManifest) ? pmManifest : {};
449
+ return {
450
+ source: hasPmManifest ? "pm" : "convention",
451
+ package_json_path: packageJsonPath,
452
+ package_name: typeof packageJson.name === "string" ? packageJson.name : void 0,
453
+ package_version: typeof packageJson.version === "string" ? packageJson.version : void 0,
454
+ package_private: packageJson.private === true,
455
+ package_description: typeof packageJson.description === "string" ? packageJson.description : void 0,
456
+ package_keywords: normalizeStringArray(packageJson.keywords),
457
+ package_homepage: typeof packageJson.homepage === "string" ? packageJson.homepage : void 0,
458
+ package_repository_url: readUrlLikeField(packageJson.repository),
459
+ package_bugs_url: readUrlLikeField(packageJson.bugs),
460
+ aliases: normalizeStringArray(pmManifestRecord.aliases),
461
+ resources: normalizePackageResourceMap(pmManifest),
462
+ catalog: normalizePackageCatalogMetadata(pmManifestRecord.catalog)
463
+ };
464
+ }
465
+ async function listExtensionManifestDirectories(parentDirectory) {
466
+ if (!await pathExists(parentDirectory)) {
467
+ return [];
468
+ }
469
+ const entries = await fs3.readdir(parentDirectory, { withFileTypes: true });
470
+ const candidates = [];
471
+ for (const entry of entries) {
472
+ if (!entry.isDirectory()) {
473
+ continue;
474
+ }
475
+ const directory = path3.join(parentDirectory, entry.name);
476
+ if (await pathExists(path3.join(directory, "manifest.json"))) {
477
+ candidates.push(directory);
478
+ }
479
+ }
480
+ return candidates.sort((left, right) => left.localeCompare(right));
481
+ }
482
+ async function collectPackageExtensionDirectories(packageRoot) {
483
+ if (await pathExists(path3.join(packageRoot, "manifest.json"))) {
484
+ return [packageRoot];
485
+ }
486
+ const manifest = await readPmPackageManifest(packageRoot);
487
+ const manifestEntries = manifest.resources.extensions ?? [];
488
+ const discovered = /* @__PURE__ */ new Set();
489
+ for (const entry of manifestEntries) {
490
+ if (entry.includes("*") || entry.startsWith("!")) {
491
+ throw new PmCliError(`Package extension entry "${entry}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`, EXIT_CODE.USAGE);
492
+ }
493
+ const absolute = path3.resolve(packageRoot, entry);
494
+ if (!isPathWithinDirectory(packageRoot, absolute)) {
495
+ throw new PmCliError(`Package extension entry "${entry}" resolves outside package root.`, EXIT_CODE.USAGE);
496
+ }
497
+ if (await pathExists(path3.join(absolute, "manifest.json"))) {
498
+ discovered.add(absolute);
499
+ continue;
500
+ }
501
+ for (const child of await listExtensionManifestDirectories(absolute)) {
502
+ discovered.add(child);
503
+ }
504
+ }
505
+ if (manifestEntries.length === 0) {
506
+ for (const root of PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS.extensions) {
507
+ for (const child of await listExtensionManifestDirectories(path3.join(packageRoot, root))) {
508
+ discovered.add(child);
509
+ }
510
+ }
511
+ }
512
+ return [...discovered].sort((left, right) => left.localeCompare(right));
513
+ }
514
+
515
+ // dist/cli/commands/extension/install-sources.js
516
+ !(function() {
517
+ try {
518
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
519
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "eaa543ef-b644-5b26-9eb4-dcb40aaa8a53");
520
+ } catch (e2) {
521
+ }
522
+ })();
523
+ var execFileAsync = promisify(execFile);
524
+ function parseGithubPathSpec(pathSpec, input, refOverride) {
525
+ const segments = pathSpec.split("/").map((segment) => segment.trim()).filter((segment) => segment.length > 0);
526
+ if (segments.length < 2) {
527
+ return null;
528
+ }
529
+ const owner = segments[0];
530
+ const repo = segments[1].replace(/\.git$/i, "");
531
+ if (owner.length === 0 || repo.length === 0) {
532
+ return null;
533
+ }
534
+ const tail = segments.slice(2);
535
+ let ref;
536
+ let subpath;
537
+ if (tail[0] === "tree" && tail.length >= 2) {
538
+ ref = tail[1];
539
+ subpath = tail.slice(2).join("/");
540
+ } else if (tail.length > 0) {
541
+ subpath = tail.join("/");
542
+ }
543
+ if (typeof refOverride === "string" && refOverride.trim().length > 0) {
544
+ ref = refOverride.trim();
545
+ }
546
+ return {
547
+ kind: "github",
548
+ input,
549
+ owner,
550
+ repo,
551
+ repository: `https://github.com/${owner}/${repo}.git`,
552
+ ref,
553
+ subpath: subpath && subpath.length > 0 ? subpath : void 0
554
+ };
555
+ }
556
+ function parseExtensionInstallSource(input, options = {}) {
557
+ const normalizedInput = input.trim();
558
+ if (normalizedInput.length === 0) {
559
+ throw new PmCliError("Extension source is required for --install.", EXIT_CODE.USAGE);
560
+ }
561
+ const refOverride = typeof options.ref === "string" && options.ref.trim().length > 0 ? options.ref.trim() : void 0;
562
+ if (normalizedInput.startsWith("npm:")) {
563
+ const spec = normalizedInput.slice("npm:".length).trim();
564
+ if (spec.length === 0) {
565
+ throw new PmCliError('npm package source must include a package spec after "npm:".', EXIT_CODE.USAGE);
566
+ }
567
+ if (options.forceGithub) {
568
+ throw new PmCliError('Options "--gh/--github" cannot be combined with npm: package sources.', EXIT_CODE.USAGE);
569
+ }
570
+ if (refOverride) {
571
+ throw new PmCliError('Option "--ref" cannot be combined with npm: package sources.', EXIT_CODE.USAGE);
572
+ }
573
+ return {
574
+ kind: "npm",
575
+ input: normalizedInput,
576
+ spec
577
+ };
578
+ }
579
+ const maybeGithubByUrl = (() => {
580
+ try {
581
+ const parsed = new URL(normalizedInput);
582
+ if (parsed.hostname !== "github.com") {
583
+ return null;
584
+ }
585
+ const pathSpec = parsed.pathname.replace(/^\/+/, "");
586
+ return parseGithubPathSpec(pathSpec, normalizedInput, refOverride);
587
+ } catch {
588
+ return null;
589
+ }
590
+ })();
591
+ if (maybeGithubByUrl) {
592
+ return maybeGithubByUrl;
593
+ }
594
+ const strippedDomainInput = normalizedInput.startsWith("github.com/") ? normalizedInput.slice("github.com/".length) : null;
595
+ if (strippedDomainInput) {
596
+ const parsed = parseGithubPathSpec(strippedDomainInput, normalizedInput, refOverride);
597
+ if (!parsed) {
598
+ throw new PmCliError(`Invalid GitHub source "${normalizedInput}".`, EXIT_CODE.USAGE);
599
+ }
600
+ return parsed;
601
+ }
602
+ if (options.forceGithub) {
603
+ const parsed = parseGithubPathSpec(normalizedInput, normalizedInput, refOverride);
604
+ if (!parsed) {
605
+ throw new PmCliError(`Invalid GitHub shorthand "${normalizedInput}".`, EXIT_CODE.USAGE);
606
+ }
607
+ return parsed;
608
+ }
609
+ if (/^https?:\/\//i.test(normalizedInput)) {
610
+ throw new PmCliError(`Unsupported extension source URL "${normalizedInput}". Supported remote source host: github.com.`, EXIT_CODE.USAGE);
611
+ }
612
+ return {
613
+ kind: "local",
614
+ input: normalizedInput,
615
+ absolute_path: path4.resolve(process.cwd(), normalizedInput)
616
+ };
617
+ }
618
+ async function runGitCommand(args) {
619
+ try {
620
+ const result = await execFileAsync("git", args, { encoding: "utf8" });
621
+ return (result.stdout ?? "").trim();
622
+ } catch (error) {
623
+ const stderr = typeof error === "object" && error !== null && "stderr" in error ? String(error.stderr) : "";
624
+ const message = stderr.trim().length > 0 ? stderr.trim() : error instanceof Error ? error.message : String(error);
625
+ throw new PmCliError(`Git command failed: git ${args.join(" ")}
626
+ ${message}`, EXIT_CODE.GENERIC_FAILURE);
627
+ }
628
+ }
629
+ function resolveNpmCommandName(platform = process.platform) {
630
+ return platform === "win32" ? "npm.cmd" : "npm";
631
+ }
632
+ function shouldRunNpmCommandInShell(platform = process.platform) {
633
+ return platform === "win32";
634
+ }
635
+ async function runNpmCommand(args, cwd) {
636
+ const npmCommand = resolveNpmCommandName();
637
+ try {
638
+ const result = await execFileAsync(npmCommand, args, { cwd, encoding: "utf8", shell: shouldRunNpmCommandInShell() });
639
+ return (result.stdout ?? "").trim();
640
+ } catch (error) {
641
+ const stderr = typeof error === "object" && error !== null && "stderr" in error ? String(error.stderr) : "";
642
+ const message = stderr.trim().length > 0 ? stderr.trim() : error instanceof Error ? error.message : String(error);
643
+ throw new PmCliError(`npm command failed: ${npmCommand} ${args.join(" ")}
644
+ ${message}`, EXIT_CODE.GENERIC_FAILURE);
645
+ }
646
+ }
647
+ async function resolveLocalNpmPackagePath(spec) {
648
+ if (path4.isAbsolute(spec) || spec.startsWith(".") || spec.startsWith("..")) {
649
+ const absolutePath = path4.resolve(process.cwd(), spec);
650
+ return await pathExists(absolutePath) ? absolutePath : null;
651
+ }
652
+ try {
653
+ const parsed = new URL(spec);
654
+ if (parsed.protocol === "file:") {
655
+ const absolutePath = fileURLToPath(parsed);
656
+ return await pathExists(absolutePath) ? absolutePath : null;
657
+ }
658
+ } catch {
659
+ }
660
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(spec)) {
661
+ const absolutePath = path4.resolve(process.cwd(), spec);
662
+ if (await pathExists(absolutePath)) {
663
+ return absolutePath;
664
+ }
665
+ }
666
+ return null;
667
+ }
668
+ async function resolveNpmPackSpec(spec) {
669
+ const localPath = await resolveLocalNpmPackagePath(spec);
670
+ if (localPath) {
671
+ return pathToFileURL(localPath).href;
672
+ }
673
+ const localFileAlias = normalizeNpmLocalFileAliasSpec(spec);
674
+ if (localFileAlias !== spec) {
675
+ return localFileAlias;
676
+ }
677
+ if (/^[a-z][a-z0-9+.-]*:/i.test(spec)) {
678
+ return spec;
679
+ }
680
+ return spec;
681
+ }
682
+ function normalizeNpmLocalFileAliasSpec(spec, cwd = process.cwd()) {
683
+ const marker = "@file:";
684
+ const markerIndex = spec.lastIndexOf(marker);
685
+ if (markerIndex <= 0) {
686
+ return spec;
687
+ }
688
+ const packageName = spec.slice(0, markerIndex);
689
+ const target = spec.slice(markerIndex + marker.length);
690
+ if (packageName.trim().length === 0 || target.trim().length === 0 || target.startsWith("//")) {
691
+ return spec;
692
+ }
693
+ const absolutePath = path4.isAbsolute(target) || path4.win32.isAbsolute(target) ? target : path4.resolve(cwd, target);
694
+ return `${packageName}@${pathToFileURL(absolutePath).href}`;
695
+ }
696
+ function parsePackedNpmPackage(stdout, packDirectory) {
697
+ try {
698
+ const parsed = JSON.parse(stdout);
699
+ const first = Array.isArray(parsed) ? parsed[0] : void 0;
700
+ if (first && typeof first.filename === "string" && first.filename.trim().length > 0) {
701
+ return {
702
+ tarball: path4.resolve(packDirectory, first.filename),
703
+ package: typeof first.name === "string" ? first.name : void 0,
704
+ version: typeof first.version === "string" ? first.version : void 0
705
+ };
706
+ }
707
+ } catch {
708
+ }
709
+ const lastLine = stdout.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0).at(-1);
710
+ if (!lastLine) {
711
+ throw new PmCliError("npm pack did not report a tarball filename.", EXIT_CODE.GENERIC_FAILURE);
712
+ }
713
+ return {
714
+ tarball: path4.resolve(packDirectory, lastLine)
715
+ };
716
+ }
717
+ async function resolveNpmSourceDirectory(source) {
718
+ const localPackageRoot = await resolveLocalNpmPackagePath(source.spec);
719
+ if (localPackageRoot) {
720
+ const packageJsonPath = path4.join(localPackageRoot, "package.json");
721
+ const packageJson = await pathExists(packageJsonPath) ? JSON.parse(await fs4.readFile(packageJsonPath, "utf8")) : {};
722
+ return {
723
+ directory: await resolvePackageExtensionDirectory(localPackageRoot, source.input),
724
+ package: typeof packageJson.name === "string" ? packageJson.name : void 0,
725
+ version: typeof packageJson.version === "string" ? packageJson.version : void 0,
726
+ cleanup: async () => {
727
+ }
728
+ };
729
+ }
730
+ const tempRoot = await fs4.mkdtemp(path4.join(os.tmpdir(), "pm-npm-package-source-"));
731
+ const packDirectory = path4.join(tempRoot, "pack");
732
+ const extractDirectory = path4.join(tempRoot, "extract");
733
+ await fs4.mkdir(packDirectory, { recursive: true });
734
+ await fs4.mkdir(extractDirectory, { recursive: true });
735
+ try {
736
+ const packSpec = await resolveNpmPackSpec(source.spec);
737
+ const packStdout = await runNpmCommand(["pack", packSpec, "--json", "--pack-destination", packDirectory]);
738
+ const packed = parsePackedNpmPackage(packStdout, packDirectory);
739
+ await execFileAsync("tar", ["-xzf", packed.tarball, "-C", extractDirectory], { encoding: "utf8" });
740
+ const packageRoot = path4.join(extractDirectory, "package");
741
+ await installNpmPackageRuntimeDependencies(packageRoot);
742
+ const directory = await resolvePackageExtensionDirectory(packageRoot, source.input);
743
+ return {
744
+ directory,
745
+ package: packed.package,
746
+ version: packed.version,
747
+ cleanup: async () => {
748
+ await fs4.rm(tempRoot, { recursive: true, force: true });
749
+ }
750
+ };
751
+ } catch (error) {
752
+ await fs4.rm(tempRoot, { recursive: true, force: true });
753
+ throw error;
754
+ }
755
+ }
756
+ async function installNpmPackageRuntimeDependencies(packageRoot) {
757
+ const packageJsonPath = path4.join(packageRoot, "package.json");
758
+ if (!await pathExists(packageJsonPath)) {
759
+ return;
760
+ }
761
+ let parsed;
762
+ try {
763
+ parsed = JSON.parse(await fs4.readFile(packageJsonPath, "utf8"));
764
+ } catch {
765
+ return;
766
+ }
767
+ if (typeof parsed !== "object" || parsed === null) {
768
+ return;
769
+ }
770
+ const manifest = parsed;
771
+ const dependencySpecs = runtimeDependencyInstallSpecs(manifest);
772
+ if (dependencySpecs.length === 0) {
773
+ return;
774
+ }
775
+ const runtimeOnlyManifest = { ...parsed };
776
+ delete runtimeOnlyManifest.devDependencies;
777
+ await fs4.writeFile(packageJsonPath, `${JSON.stringify(runtimeOnlyManifest, null, 2)}
778
+ `, "utf8");
779
+ await Promise.all([
780
+ fs4.rm(path4.join(packageRoot, "package-lock.json"), { force: true }),
781
+ fs4.rm(path4.join(packageRoot, "npm-shrinkwrap.json"), { force: true })
782
+ ]);
783
+ await runNpmCommand(["install", "--ignore-scripts", "--no-audit", "--fund=false", "--package-lock=false", "--no-save", ...dependencySpecs], packageRoot);
784
+ }
785
+ function runtimeDependencyInstallSpecs(manifest) {
786
+ const specs = /* @__PURE__ */ new Map();
787
+ for (const dependencyMap of [manifest.dependencies, manifest.optionalDependencies, manifest.peerDependencies]) {
788
+ if (typeof dependencyMap !== "object" || dependencyMap === null) {
789
+ continue;
790
+ }
791
+ for (const [name, version] of Object.entries(dependencyMap)) {
792
+ if (typeof version !== "string" || version.trim().length === 0 || specs.has(name)) {
793
+ continue;
794
+ }
795
+ specs.set(name, `${name}@${version.trim()}`);
796
+ }
797
+ }
798
+ return [...specs.values()];
799
+ }
800
+ async function resolvePackageExtensionDirectory(packageRoot, sourceLabel) {
801
+ const discovered = await collectPackageExtensionDirectories(packageRoot);
802
+ if (discovered.length === 1) {
803
+ return discovered[0];
804
+ }
805
+ if (discovered.length > 1) {
806
+ const choices = discovered.map((entry) => path4.relative(packageRoot, entry).replaceAll(path4.sep, "/")).sort((left, right) => left.localeCompare(right));
807
+ throw new PmCliError(`Package source "${sourceLabel}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${choices.join(", ")}`, EXIT_CODE.USAGE);
808
+ }
809
+ throw new PmCliError(`Unable to locate a pm extension manifest in package source "${sourceLabel}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`, EXIT_CODE.USAGE);
810
+ }
811
+ async function resolveGithubSourceDirectory(cloneDirectory, source) {
812
+ const candidatePaths = [];
813
+ if (source.subpath) {
814
+ candidatePaths.push(source.subpath);
815
+ candidatePaths.push(path4.posix.join(".agents/pm/extensions", source.subpath));
816
+ candidatePaths.push(path4.posix.join(".custom/pm-extensions", source.subpath));
817
+ candidatePaths.push(path4.posix.join(".custom/pm-extension", source.subpath));
818
+ }
819
+ for (const candidate of candidatePaths) {
820
+ const absolute = path4.resolve(cloneDirectory, candidate);
821
+ if (!isPathWithinDirectory(cloneDirectory, absolute)) {
822
+ continue;
823
+ }
824
+ if (await pathExists(path4.join(absolute, "manifest.json"))) {
825
+ return { directory: absolute, resolved_subpath: candidate };
826
+ }
827
+ }
828
+ if (await pathExists(path4.join(cloneDirectory, "manifest.json"))) {
829
+ return { directory: cloneDirectory, resolved_subpath: "." };
830
+ }
831
+ const discoveredDirectory = await resolvePackageExtensionDirectory(cloneDirectory, source.input);
832
+ return {
833
+ directory: discoveredDirectory,
834
+ resolved_subpath: path4.relative(cloneDirectory, discoveredDirectory).replaceAll(path4.sep, "/")
835
+ };
836
+ }
837
+ async function resolveInstallSource(source) {
838
+ if (source.kind === "local") {
839
+ let localStats;
840
+ try {
841
+ localStats = await fs4.stat(source.absolute_path);
842
+ } catch {
843
+ throw new PmCliError(`Local extension source does not exist: "${source.absolute_path}".`, EXIT_CODE.NOT_FOUND);
844
+ }
845
+ if (!localStats.isDirectory()) {
846
+ throw new PmCliError(`Local extension source must be a directory: "${source.absolute_path}".`, EXIT_CODE.USAGE);
847
+ }
848
+ const directory = await resolvePackageExtensionDirectory(source.absolute_path, source.input);
849
+ return {
850
+ source,
851
+ directory
852
+ };
853
+ }
854
+ if (source.kind === "npm") {
855
+ const resolved = await resolveNpmSourceDirectory(source);
856
+ return {
857
+ source,
858
+ directory: resolved.directory,
859
+ cleanup: resolved.cleanup,
860
+ resolved_subpath: path4.relative(path4.dirname(resolved.directory), resolved.directory).replaceAll(path4.sep, "/"),
861
+ npm_package: resolved.package,
862
+ npm_version: resolved.version
863
+ };
864
+ }
865
+ const cloneDirectory = await fs4.mkdtemp(path4.join(os.tmpdir(), "pm-extension-source-"));
866
+ const cloneArgs = ["clone", "--depth", "1"];
867
+ if (source.ref) {
868
+ cloneArgs.push("--branch", source.ref);
869
+ }
870
+ cloneArgs.push(source.repository, cloneDirectory);
871
+ try {
872
+ await runGitCommand(cloneArgs);
873
+ const commit = await runGitCommand(["-C", cloneDirectory, "rev-parse", "HEAD"]);
874
+ const resolved = await resolveGithubSourceDirectory(cloneDirectory, source);
875
+ return {
876
+ source,
877
+ directory: resolved.directory,
878
+ resolved_subpath: resolved.resolved_subpath,
879
+ commit,
880
+ cleanup: async () => {
881
+ await fs4.rm(cloneDirectory, { recursive: true, force: true });
882
+ }
883
+ };
884
+ } catch (error) {
885
+ await fs4.rm(cloneDirectory, { recursive: true, force: true });
886
+ throw error;
887
+ }
888
+ }
889
+ async function areDirectoriesEquivalent(left, right) {
890
+ if (!await pathExists(left) || !await pathExists(right)) {
891
+ return false;
892
+ }
893
+ const [leftRealPath, rightRealPath] = await Promise.all([fs4.realpath(left), fs4.realpath(right)]);
894
+ return leftRealPath === rightRealPath;
895
+ }
896
+
897
+ // dist/cli/commands/extension/bundled-catalog.js
898
+ import fs5 from "node:fs/promises";
899
+ import path5 from "node:path";
900
+ !(function() {
901
+ try {
902
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
903
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "778dfce2-07e1-50c3-8e47-2c43f61a9a0f");
904
+ } catch (e2) {
905
+ }
906
+ })();
907
+ var PM_PACKAGE_ROOT_ENV = "PM_CLI_PACKAGE_ROOT";
908
+ var LEGACY_BUNDLED_PACKAGE_ALIASES = {
909
+ beads: {
910
+ package_directory: "pm-beads",
911
+ legacy_extension_directory: "beads"
912
+ },
913
+ todos: {
914
+ package_directory: "pm-todos",
915
+ legacy_extension_directory: "todos"
916
+ }
917
+ };
918
+ var BUNDLED_PACKAGE_INSTALL_ALL_TARGETS = /* @__PURE__ */ new Set(["*", "all"]);
919
+ function resolvePackageRootCandidates() {
920
+ const candidates = [];
921
+ const envRoot = process.env[PM_PACKAGE_ROOT_ENV];
922
+ if (typeof envRoot === "string" && envRoot.trim().length > 0) {
923
+ candidates.push(path5.resolve(envRoot.trim()));
924
+ }
925
+ candidates.push(resolvePmPackageRootFromModule(import.meta.url, ["../../../.."]));
926
+ return [...new Set(candidates)];
927
+ }
928
+ async function resolveBundledExtensionAliasSource(input) {
929
+ const normalized = input.trim().toLowerCase();
930
+ const packageRoot = await resolveBundledPackageRoot(normalized);
931
+ if (packageRoot) {
932
+ return packageRoot;
933
+ }
934
+ const alias = LEGACY_BUNDLED_PACKAGE_ALIASES[normalized];
935
+ if (!alias) {
936
+ return null;
937
+ }
938
+ for (const packageRoot2 of resolvePackageRootCandidates()) {
939
+ const legacyExtensionPath = path5.join(packageRoot2, ".agents", "pm", "extensions", alias.legacy_extension_directory);
940
+ if (await pathExists(path5.join(legacyExtensionPath, "manifest.json"))) {
941
+ return legacyExtensionPath;
942
+ }
943
+ }
944
+ return null;
945
+ }
946
+ function isBundledPackageInstallAllTarget(input) {
947
+ return BUNDLED_PACKAGE_INSTALL_ALL_TARGETS.has(input.trim().toLowerCase());
948
+ }
949
+ function derivePackageAlias(packageDirectory) {
950
+ return packageDirectory.replace(/^pm-/i, "").trim().toLowerCase();
951
+ }
952
+ async function collectBundledPackageEntries() {
953
+ const entriesByAlias = /* @__PURE__ */ new Map();
954
+ for (const packageRoot of resolvePackageRootCandidates()) {
955
+ const packagesRoot = path5.join(packageRoot, "packages");
956
+ if (!await pathExists(packagesRoot)) {
957
+ continue;
958
+ }
959
+ const entries = await fs5.readdir(packagesRoot, { withFileTypes: true });
960
+ for (const entry of entries) {
961
+ if (!entry.isDirectory() || !entry.name.startsWith("pm-")) {
962
+ continue;
963
+ }
964
+ const candidateRoot = path5.join(packagesRoot, entry.name);
965
+ if (!await pathExists(path5.join(candidateRoot, "package.json"))) {
966
+ continue;
967
+ }
968
+ const manifest = await readPmPackageManifest(candidateRoot);
969
+ const aliases = manifest.aliases && manifest.aliases.length > 0 ? manifest.aliases : [derivePackageAlias(entry.name)];
970
+ for (const alias of aliases) {
971
+ const normalizedAlias = alias.trim().toLowerCase();
972
+ if (normalizedAlias.length === 0 || entriesByAlias.has(normalizedAlias)) {
973
+ continue;
974
+ }
975
+ entriesByAlias.set(normalizedAlias, {
976
+ alias: normalizedAlias,
977
+ package_directory: entry.name,
978
+ package_root: candidateRoot
979
+ });
980
+ }
981
+ }
982
+ }
983
+ for (const [alias, legacy] of Object.entries(LEGACY_BUNDLED_PACKAGE_ALIASES)) {
984
+ if (entriesByAlias.has(alias)) {
985
+ continue;
986
+ }
987
+ for (const packageRoot of resolvePackageRootCandidates()) {
988
+ const packagePath = path5.join(packageRoot, "packages", legacy.package_directory);
989
+ if (await pathExists(path5.join(packagePath, "package.json"))) {
990
+ entriesByAlias.set(alias, {
991
+ alias,
992
+ package_directory: legacy.package_directory,
993
+ package_root: packagePath
994
+ });
995
+ break;
996
+ }
997
+ }
998
+ }
999
+ return [...entriesByAlias.values()].sort((left, right) => left.alias.localeCompare(right.alias));
1000
+ }
1001
+ async function listBundledPackageAliases() {
1002
+ return (await collectBundledPackageEntries()).map((entry) => entry.alias);
1003
+ }
1004
+ async function resolveBundledPackageRoot(alias) {
1005
+ const normalized = alias.trim().toLowerCase();
1006
+ const entry = (await collectBundledPackageEntries()).find((candidate) => candidate.alias === normalized);
1007
+ return entry?.package_root ?? null;
1008
+ }
1009
+ async function resolveBundledAliasManifestName(input) {
1010
+ const bundledAliasSource = await resolveBundledExtensionAliasSource(input);
1011
+ if (!bundledAliasSource) {
1012
+ return null;
1013
+ }
1014
+ try {
1015
+ const extensionDirectories = await collectPackageExtensionDirectories(bundledAliasSource);
1016
+ if (extensionDirectories.length !== 1) {
1017
+ return null;
1018
+ }
1019
+ const validated = await validateExtensionDirectory(extensionDirectories[0]);
1020
+ return validated.manifest.name;
1021
+ } catch {
1022
+ return null;
1023
+ }
1024
+ }
1025
+ async function buildBundledPackageCatalog(scope, global2, options = {}) {
1026
+ const roots = resolveExtensionRoots(resolvePmRoot(process.cwd(), global2.path), process.cwd());
1027
+ const selectedRoot = scope === "global" ? roots.global : roots.project;
1028
+ const managedStateRead = await readManagedExtensionState(selectedRoot);
1029
+ const installedLocations = new Set(managedStateRead.state.entries.filter((entry) => entry.scope === scope).filter((entry) => entry.source.kind !== "builtin").map((entry) => path5.resolve(entry.source.location)));
1030
+ const installedBuiltinAliases = new Set(managedStateRead.state.entries.filter((entry) => entry.scope === scope && entry.source.kind === "builtin").flatMap((entry) => [entry.source.name, entry.source.input, entry.source.location]).filter((value) => typeof value === "string" && value.trim().length > 0).map((value) => value.trim().toLowerCase()));
1031
+ const packages = [];
1032
+ for (const alias of await listBundledPackageAliases()) {
1033
+ const packageRoot = await resolveBundledPackageRoot(alias);
1034
+ const installScopeFlag = scope === "global" ? "--global" : "--project";
1035
+ if (!packageRoot) {
1036
+ packages.push({
1037
+ alias,
1038
+ bundled: true,
1039
+ available: false,
1040
+ installed: false,
1041
+ install_target: alias,
1042
+ install_command: `pm install ${alias} ${installScopeFlag}`
1043
+ });
1044
+ continue;
1045
+ }
1046
+ const manifest = await readPmPackageManifest(packageRoot);
1047
+ const repository = manifest.catalog?.links?.repository ?? manifest.package_repository_url;
1048
+ const report = manifest.catalog?.links?.report ?? manifest.package_bugs_url;
1049
+ const docs = manifest.catalog?.links?.docs ?? manifest.package_homepage;
1050
+ const npm = manifest.catalog?.links?.npm ?? (manifest.package_name && manifest.package_private !== true ? `https://www.npmjs.com/package/${encodeURIComponent(manifest.package_name)}` : void 0);
1051
+ const metadataOnlyResources = Object.fromEntries(PM_PACKAGE_RESOURCE_KINDS.filter((resourceKind) => resourceKind !== "extensions").map((resourceKind) => [resourceKind, manifest.resources[resourceKind] ?? []]).filter(([, entries]) => Array.isArray(entries) && entries.length > 0));
1052
+ packages.push({
1053
+ alias,
1054
+ bundled: true,
1055
+ available: true,
1056
+ installed: installedBuiltinAliases.has(alias) || installedLocations.has(path5.resolve(packageRoot)),
1057
+ install_target: alias,
1058
+ install_command: `pm install ${alias} ${installScopeFlag}`,
1059
+ package_name: manifest.package_name,
1060
+ package_version: manifest.package_version,
1061
+ description: manifest.catalog?.summary ?? manifest.package_description,
1062
+ keywords: manifest.package_keywords ?? [],
1063
+ resources: manifest.resources,
1064
+ installable_resources: {
1065
+ extensions: manifest.resources.extensions ?? []
1066
+ },
1067
+ metadata_only_resources: metadataOnlyResources,
1068
+ catalog: {
1069
+ display_name: manifest.catalog?.display_name,
1070
+ category: manifest.catalog?.category,
1071
+ tags: manifest.catalog?.tags ?? manifest.package_keywords ?? [],
1072
+ links: {
1073
+ docs,
1074
+ npm,
1075
+ repository,
1076
+ report
1077
+ },
1078
+ media: manifest.catalog?.media
1079
+ }
1080
+ });
1081
+ }
1082
+ const fields = parsePackageCatalogFields(options.fields);
1083
+ const outputPackages = fields ? packages.map((entry) => projectPackageCatalogEntry(entry, fields)) : packages;
1084
+ return {
1085
+ total: outputPackages.length,
1086
+ scope,
1087
+ installable_resource_kinds: ["extensions"],
1088
+ metadata_only_resource_kinds: PM_PACKAGE_RESOURCE_KINDS.filter((resourceKind) => resourceKind !== "extensions"),
1089
+ packages: outputPackages
1090
+ };
1091
+ }
1092
+ var PACKAGE_CATALOG_FIELD_KEYS = /* @__PURE__ */ new Set([
1093
+ "alias",
1094
+ "bundled",
1095
+ "available",
1096
+ "installed",
1097
+ "install_target",
1098
+ "install_command",
1099
+ "package_name",
1100
+ "package_version",
1101
+ "description",
1102
+ "keywords",
1103
+ "resources",
1104
+ "installable_resources",
1105
+ "metadata_only_resources",
1106
+ "catalog",
1107
+ "category",
1108
+ "display_name"
1109
+ ]);
1110
+ function parsePackageCatalogFields(raw) {
1111
+ if (raw === void 0) {
1112
+ return void 0;
1113
+ }
1114
+ const fields = splitCommaList(raw);
1115
+ if (fields.length === 0) {
1116
+ throw new PmCliError("Package catalog --fields requires a comma-separated list of field names", EXIT_CODE.USAGE);
1117
+ }
1118
+ const unknown = fields.filter((field) => !PACKAGE_CATALOG_FIELD_KEYS.has(field));
1119
+ if (unknown.length > 0) {
1120
+ throw new PmCliError(`Unknown package catalog --fields value(s): ${unknown.join(", ")}`, EXIT_CODE.USAGE, {
1121
+ examples: [
1122
+ "pm package list --project --fields alias,installed,install_command",
1123
+ "pm package catalog --project --fields alias,package_name,category"
1124
+ ]
1125
+ });
1126
+ }
1127
+ return fields;
1128
+ }
1129
+ function projectPackageCatalogEntry(entry, fields) {
1130
+ const projected = {};
1131
+ for (const field of fields) {
1132
+ if (field === "category") {
1133
+ projected[field] = entry.catalog?.category ?? null;
1134
+ } else if (field === "display_name") {
1135
+ projected[field] = entry.catalog?.display_name ?? null;
1136
+ } else {
1137
+ projected[field] = entry[field] ?? null;
1138
+ }
1139
+ }
1140
+ return projected;
1141
+ }
1142
+
1143
+ // dist/cli/commands/extension/scaffold.js
1144
+ import fs6 from "node:fs/promises";
1145
+ import path6 from "node:path";
1146
+ !(function() {
1147
+ try {
1148
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
1149
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "6ba6d57e-c873-51ad-b55d-3f35c6f9ef55");
1150
+ } catch (e2) {
1151
+ }
1152
+ })();
1153
+ function buildStarterExtensionScaffoldFiles(extensionName, commandName, vocabulary) {
1154
+ const packageName = `pm-${extensionName}`;
1155
+ const manifest = `${JSON.stringify({
1156
+ name: extensionName,
1157
+ version: "0.1.0",
1158
+ entry: "./index.js",
1159
+ capabilities: ["commands"]
1160
+ }, null, 2)}
1161
+ `;
1162
+ const entrypoint = vocabulary === "package" ? [
1163
+ 'import { defineExtension } from "@unbrained/pm-cli/sdk";',
1164
+ "",
1165
+ "export default defineExtension({",
1166
+ " activate(api) {",
1167
+ " api.registerCommand({",
1168
+ ` name: ${JSON.stringify(commandName)},`,
1169
+ ' description: "Starter scaffold command. Replace with your own behavior.",',
1170
+ " run: async (context) => ({",
1171
+ " ok: true,",
1172
+ ` source: ${JSON.stringify(extensionName)},`,
1173
+ " command: context.command,",
1174
+ ' message: "Starter extension scaffold is active.",',
1175
+ " }),",
1176
+ " });",
1177
+ " },",
1178
+ "});",
1179
+ ""
1180
+ ].join("\n") : [
1181
+ '/** @param {import("@unbrained/pm-cli/sdk").ExtensionApi} api */',
1182
+ "export function activate(api) {",
1183
+ " api.registerCommand({",
1184
+ ` name: ${JSON.stringify(commandName)},`,
1185
+ ' description: "Starter scaffold command. Replace with your own behavior.",',
1186
+ " run: async (context) => ({",
1187
+ " ok: true,",
1188
+ ` source: ${JSON.stringify(extensionName)},`,
1189
+ " command: context.command,",
1190
+ ' message: "Starter extension scaffold is active.",',
1191
+ " }),",
1192
+ " });",
1193
+ "}",
1194
+ "",
1195
+ "export default {",
1196
+ " activate,",
1197
+ "};",
1198
+ ""
1199
+ ].join("\n");
1200
+ if (vocabulary === "package") {
1201
+ const packageJson = `${JSON.stringify({
1202
+ name: packageName,
1203
+ version: "0.1.0",
1204
+ private: true,
1205
+ type: "module",
1206
+ keywords: ["pm-package"],
1207
+ peerDependencies: {
1208
+ "@unbrained/pm-cli": "*"
1209
+ },
1210
+ pm: {
1211
+ aliases: [extensionName],
1212
+ extensions: [`extensions/${extensionName}`],
1213
+ docs: ["README.md"],
1214
+ examples: ["README.md"],
1215
+ catalog: {
1216
+ display_name: extensionName,
1217
+ category: "workflow",
1218
+ summary: "Starter pm package scaffold.",
1219
+ tags: ["starter"]
1220
+ }
1221
+ }
1222
+ }, null, 2)}
1223
+ `;
1224
+ const packageReadme = [
1225
+ `# ${packageName}`,
1226
+ "",
1227
+ "Generated by `pm package init`.",
1228
+ "",
1229
+ "## Included Files",
1230
+ "- `package.json`: package metadata and `pm` resource manifest.",
1231
+ `- \`extensions/${extensionName}/manifest.json\`: extension metadata and capabilities.`,
1232
+ `- \`extensions/${extensionName}/index.js\`: starter command registration using the \`commands\` capability.`,
1233
+ "",
1234
+ "## Quick Start",
1235
+ "```bash",
1236
+ "pm install --project <package-path>",
1237
+ `pm ${commandName}`,
1238
+ "pm package doctor --project --detail summary",
1239
+ "```",
1240
+ "",
1241
+ "## Notes",
1242
+ "- Keep package metadata in `package.json` and runtime behavior under `extensions/`.",
1243
+ "- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.",
1244
+ "- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",
1245
+ ""
1246
+ ].join("\n");
1247
+ return {
1248
+ "package.json": packageJson,
1249
+ [`extensions/${extensionName}/manifest.json`]: manifest,
1250
+ [`extensions/${extensionName}/index.js`]: entrypoint,
1251
+ "README.md": packageReadme
1252
+ };
1253
+ }
1254
+ const readme = [
1255
+ `# ${extensionName}`,
1256
+ "",
1257
+ "Generated by `pm extension init`.",
1258
+ "",
1259
+ "## Included Files",
1260
+ "- `manifest.json`: extension metadata and capabilities.",
1261
+ "- `index.js`: starter command registration using the `commands` capability.",
1262
+ "",
1263
+ "## Quick Start",
1264
+ "```bash",
1265
+ "pm extension --install --project <scaffold-path>",
1266
+ `pm ${commandName}`,
1267
+ "pm extension --doctor --project --detail summary",
1268
+ "```",
1269
+ "",
1270
+ "## Notes",
1271
+ "- This scaffold uses ESM exports so it works in package scopes with `type: module`.",
1272
+ "- Update `manifest.json` capabilities and `index.js` command behavior as your extension evolves.",
1273
+ ""
1274
+ ].join("\n");
1275
+ return {
1276
+ "manifest.json": manifest,
1277
+ "index.js": entrypoint,
1278
+ "README.md": readme
1279
+ };
1280
+ }
1281
+ async function scaffoldExtensionProject(target, vocabulary = "extension") {
1282
+ const normalizedTarget = target.trim();
1283
+ const targetPath = path6.resolve(process.cwd(), normalizedTarget);
1284
+ const extensionName = normalizeManagedDirectoryName(path6.basename(targetPath));
1285
+ const commandName = `${extensionName} ping`;
1286
+ const scaffoldFiles = buildStarterExtensionScaffoldFiles(extensionName, commandName, vocabulary);
1287
+ let createdDirectory = false;
1288
+ if (await pathExists(targetPath)) {
1289
+ const existingTargetStats = await fs6.stat(targetPath);
1290
+ if (!existingTargetStats.isDirectory()) {
1291
+ throw new PmCliError(`Scaffold target "${targetPath}" exists and is not a directory.`, EXIT_CODE.CONFLICT);
1292
+ }
1293
+ } else {
1294
+ await fs6.mkdir(targetPath, { recursive: true });
1295
+ createdDirectory = true;
1296
+ }
1297
+ for (const [relativePath, content] of Object.entries(scaffoldFiles)) {
1298
+ const absolutePath = path6.join(targetPath, relativePath);
1299
+ if (!await pathExists(absolutePath)) {
1300
+ continue;
1301
+ }
1302
+ const existingContent = await fs6.readFile(absolutePath, "utf8");
1303
+ if (existingContent !== content) {
1304
+ throw new PmCliError(`Scaffold file "${relativePath}" already exists with different content in "${targetPath}". Choose a new target path or remove conflicting files.`, EXIT_CODE.CONFLICT);
1305
+ }
1306
+ }
1307
+ const files = [];
1308
+ for (const [relativePath, content] of Object.entries(scaffoldFiles)) {
1309
+ const absolutePath = path6.join(targetPath, relativePath);
1310
+ if (await pathExists(absolutePath)) {
1311
+ files.push({
1312
+ path: relativePath,
1313
+ status: "unchanged"
1314
+ });
1315
+ continue;
1316
+ }
1317
+ await fs6.mkdir(path6.dirname(absolutePath), { recursive: true });
1318
+ await fs6.writeFile(absolutePath, content, "utf8");
1319
+ files.push({
1320
+ path: relativePath,
1321
+ status: "created"
1322
+ });
1323
+ }
1324
+ return {
1325
+ extension_name: extensionName,
1326
+ command_name: commandName,
1327
+ target_path: targetPath,
1328
+ created_directory: createdDirectory,
1329
+ files
1330
+ };
1331
+ }
1332
+
1333
+ // dist/cli/commands/extension/doctor.js
1334
+ !(function() {
1335
+ try {
1336
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
1337
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "71448117-1b4c-5c35-8233-433f32151c95");
1338
+ } catch (e2) {
1339
+ }
1340
+ })();
1341
+ function applyDoctorRuntimeActivationState(extensions, loadResult, activationResult) {
1342
+ const loadedNames = new Set(loadResult.loaded.map((entry) => normalizeExtensionNameForMatch(entry.name)));
1343
+ const loadFailedNames = new Set(loadResult.failed.map((entry) => normalizeExtensionNameForMatch(entry.name)));
1344
+ const activationFailedNames = new Set(activationResult.failed.map((entry) => normalizeExtensionNameForMatch(entry.name)));
1345
+ const commandPathsByExtension = /* @__PURE__ */ new Map();
1346
+ const actionPathsByExtension = /* @__PURE__ */ new Map();
1347
+ const addCommandPath = (extensionName, commandPath) => {
1348
+ const normalizedName = normalizeExtensionNameForMatch(extensionName);
1349
+ const normalizedCommandPath = commandPath.trim();
1350
+ if (normalizedName.length === 0 || normalizedCommandPath.length === 0) {
1351
+ return;
1352
+ }
1353
+ const existing = commandPathsByExtension.get(normalizedName) ?? /* @__PURE__ */ new Set();
1354
+ existing.add(normalizedCommandPath);
1355
+ commandPathsByExtension.set(normalizedName, existing);
1356
+ };
1357
+ const addActionPath = (extensionName, actionPath) => {
1358
+ const normalizedName = normalizeExtensionNameForMatch(extensionName);
1359
+ const normalizedActionPath = actionPath.trim();
1360
+ if (normalizedName.length === 0 || normalizedActionPath.length === 0) {
1361
+ return;
1362
+ }
1363
+ const existing = actionPathsByExtension.get(normalizedName) ?? /* @__PURE__ */ new Set();
1364
+ existing.add(normalizedActionPath);
1365
+ actionPathsByExtension.set(normalizedName, existing);
1366
+ };
1367
+ for (const registration of activationResult.registrations.commands) {
1368
+ addCommandPath(registration.name, registration.command);
1369
+ addActionPath(registration.name, registration.action);
1370
+ }
1371
+ for (const handler of activationResult.commands.handlers) {
1372
+ addCommandPath(handler.name, handler.command);
1373
+ }
1374
+ for (const override of activationResult.commands.overrides) {
1375
+ addCommandPath(override.name, override.command);
1376
+ }
1377
+ const sortedPaths = (values) => {
1378
+ if (!values || values.size === 0) {
1379
+ return void 0;
1380
+ }
1381
+ return [...values].sort((left, right) => left.localeCompare(right));
1382
+ };
1383
+ return extensions.map((entry) => {
1384
+ const normalizedName = normalizeExtensionNameForMatch(entry.name);
1385
+ const commandPaths = sortedPaths(commandPathsByExtension.get(normalizedName));
1386
+ const actionPaths = sortedPaths(actionPathsByExtension.get(normalizedName));
1387
+ const runtimeMetadata = {
1388
+ ...commandPaths ? { command_paths: commandPaths } : {},
1389
+ ...actionPaths ? { action_paths: actionPaths } : {}
1390
+ };
1391
+ if (!entry.enabled) {
1392
+ return {
1393
+ ...entry,
1394
+ runtime_active: false,
1395
+ activation_status: "not_loaded",
1396
+ ...runtimeMetadata
1397
+ };
1398
+ }
1399
+ if (loadFailedNames.has(normalizedName) || activationFailedNames.has(normalizedName)) {
1400
+ return {
1401
+ ...entry,
1402
+ runtime_active: false,
1403
+ activation_status: "failed",
1404
+ ...runtimeMetadata
1405
+ };
1406
+ }
1407
+ if (loadedNames.has(normalizedName)) {
1408
+ return {
1409
+ ...entry,
1410
+ runtime_active: true,
1411
+ activation_status: "ok",
1412
+ ...runtimeMetadata
1413
+ };
1414
+ }
1415
+ return {
1416
+ ...entry,
1417
+ runtime_active: false,
1418
+ activation_status: "not_loaded",
1419
+ ...runtimeMetadata
1420
+ };
1421
+ });
1422
+ }
1423
+ function summarizePolicyWarnings(warnings) {
1424
+ let warningCount = 0;
1425
+ let violationCount = 0;
1426
+ let blockedCount = 0;
1427
+ for (const warning of warnings) {
1428
+ if (!warning.startsWith("extension_policy_")) {
1429
+ continue;
1430
+ }
1431
+ warningCount += 1;
1432
+ if (warning.startsWith("extension_policy_violation_")) {
1433
+ violationCount += 1;
1434
+ continue;
1435
+ }
1436
+ if (warning.startsWith("extension_policy_blocked_")) {
1437
+ blockedCount += 1;
1438
+ }
1439
+ }
1440
+ return {
1441
+ warning_count: warningCount,
1442
+ violation_count: violationCount,
1443
+ blocked_count: blockedCount
1444
+ };
1445
+ }
1446
+ function lifecycleFlagCommand(options, action) {
1447
+ return options.vocabulary === "package" ? `pm package --${action}` : `pm extension --${action}`;
1448
+ }
1449
+ function classifyDoctorLoadFailureWarnings(loadFailures) {
1450
+ const warnings = [];
1451
+ for (const failure of loadFailures) {
1452
+ const normalizedError = failure.error.toLowerCase();
1453
+ if (normalizedError.includes("cannot find package '@unbrained/pm-cli'") || normalizedError.includes('cannot find module "@unbrained/pm-cli"') || normalizedError.includes("cannot find module '@unbrained/pm-cli'")) {
1454
+ warnings.push(`extension_load_failed_sdk_dependency_missing:${failure.name}`);
1455
+ }
1456
+ if (normalizedError.includes("cannot use import statement outside a module") || normalizedError.includes("to load an es module") || normalizedError.includes("must use import to load es module")) {
1457
+ warnings.push(`extension_load_failed_module_mode_mismatch:${failure.name}`);
1458
+ }
1459
+ }
1460
+ return [...new Set(warnings)].sort((left, right) => left.localeCompare(right));
1461
+ }
1462
+ function buildExtensionTriageSummary(scope, warnings, extensions, options = {}) {
1463
+ const normalizedWarnings = [...new Set(warnings)].sort((left, right) => left.localeCompare(right));
1464
+ const managedTotal = extensions.filter((entry) => entry.managed).length;
1465
+ const enabledTotal = extensions.filter((entry) => entry.enabled).length;
1466
+ const activeTotal = extensions.filter((entry) => entry.active).length;
1467
+ const updateAvailableTotal = extensions.filter((entry) => entry.update_available === true).length;
1468
+ const unmanagedExtensions = extensions.filter((entry) => entry.managed === false);
1469
+ const unmanagedExpectedExtensions = unmanagedExtensions.filter((entry) => isExpectedUnmanagedExtension(entry)).map((entry) => entry.name).sort((left, right) => left.localeCompare(right));
1470
+ const unmanagedActionRequiredExtensions = unmanagedExtensions.filter((entry) => !isExpectedUnmanagedExtension(entry)).map((entry) => entry.name).sort((left, right) => left.localeCompare(right));
1471
+ const updateCheckStatusTotals = {
1472
+ checked: 0,
1473
+ skipped_unmanaged: 0,
1474
+ skipped_non_github: 0,
1475
+ failed: 0,
1476
+ not_checked: 0
1477
+ };
1478
+ for (const entry of extensions) {
1479
+ updateCheckStatusTotals[entry.update_check_status] += 1;
1480
+ }
1481
+ const updateCheckFailedTotal = updateCheckStatusTotals.failed;
1482
+ const skippedUnmanagedTotal = updateCheckStatusTotals.skipped_unmanaged;
1483
+ const skippedNonGithubTotal = updateCheckStatusTotals.skipped_non_github;
1484
+ const updateHealthPartial = unmanagedActionRequiredExtensions.length > 0;
1485
+ const updateHealthCoverage = updateHealthPartial ? "partial" : "full";
1486
+ const partialCoverageWarnings = updateHealthPartial ? [`extension_update_health_partial_coverage:skipped_unmanaged:${unmanagedActionRequiredExtensions.length}`] : [];
1487
+ const effectiveWarnings = [.../* @__PURE__ */ new Set([...normalizedWarnings, ...partialCoverageWarnings])].sort((left, right) => left.localeCompare(right));
1488
+ const warningCodes = [...new Set(effectiveWarnings.map((value) => warningCode(value)))].sort((left, right) => left.localeCompare(right));
1489
+ const policyWarnings = summarizePolicyWarnings(effectiveWarnings);
1490
+ const scopeFlag = scope === "global" ? "--global" : "--project";
1491
+ const remediation = [];
1492
+ if (normalizedWarnings.length > 0) {
1493
+ if (normalizedWarnings.some((warning) => warning.startsWith("extension_manifest_"))) {
1494
+ remediation.push(`Run ${lifecycleFlagCommand(options, "explore")} ${scopeFlag} to inspect discovered manifests and directories.`);
1495
+ }
1496
+ if (normalizedWarnings.some((warning) => warning.startsWith("extension_capability_unknown:"))) {
1497
+ remediation.push(`Unknown extension capabilities detected. Allowed capabilities: ${KNOWN_EXTENSION_CAPABILITIES.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`);
1498
+ }
1499
+ if (normalizedWarnings.some((warning) => warning.startsWith("extension_capability_legacy_alias:"))) {
1500
+ remediation.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema).");
1501
+ }
1502
+ if (normalizedWarnings.some((warning) => warning.startsWith("extension_command_definition_legacy_handler_alias:"))) {
1503
+ remediation.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility.");
1504
+ }
1505
+ if (normalizedWarnings.some((warning) => warning.startsWith("extension_load_failed_sdk_dependency_missing:"))) {
1506
+ remediation.push(`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${lifecycleFlagCommand(options, "doctor")} ${scopeFlag}.`);
1507
+ }
1508
+ if (normalizedWarnings.some((warning) => warning.startsWith("extension_load_failed_module_mode_mismatch:"))) {
1509
+ remediation.push(`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${lifecycleFlagCommand(options, "doctor")} ${scopeFlag}.`);
1510
+ }
1511
+ if (updateCheckFailedTotal > 0) {
1512
+ remediation.push(`Run ${lifecycleFlagCommand(options, "manage")} ${scopeFlag} after validating network and repository access.`);
1513
+ }
1514
+ if (normalizedWarnings.some((warning) => warning.startsWith("extension_manager_state_"))) {
1515
+ remediation.push(`Review and repair ${scope} managed extension state file if schema/read warnings persist.`);
1516
+ }
1517
+ if (policyWarnings.warning_count > 0) {
1518
+ remediation.push("Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces.");
1519
+ }
1520
+ }
1521
+ if (updateHealthPartial) {
1522
+ remediation.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${lifecycleFlagCommand(options, "manage")} ${scopeFlag} --fix-managed-state (or ${lifecycleFlagCommand(options, "adopt-all")} ${scopeFlag}, ${lifecycleFlagCommand(options, "adopt")} <name> ${scopeFlag}, or reinstall via ${lifecycleFlagCommand(options, "install")} ${scopeFlag} <source>).`);
1523
+ } else if (skippedUnmanagedTotal > 0) {
1524
+ remediation.push(`Loaded unmanaged extensions are currently treated as informational. Use ${lifecycleFlagCommand(options, "manage")} ${scopeFlag} --fix-managed-state to adopt them for update checks.`);
1525
+ }
1526
+ if (skippedNonGithubTotal > 0) {
1527
+ remediation.push(`Non-GitHub managed extensions are skipped by update checks. Use doctor output for non-update diagnostics.`);
1528
+ }
1529
+ if (updateAvailableTotal > 0) {
1530
+ remediation.push(`Update available managed extensions via ${lifecycleFlagCommand(options, "install")} ${scopeFlag} <source>.`);
1531
+ }
1532
+ if (remediation.length === 0) {
1533
+ remediation.push(`No immediate action required. Re-run ${lifecycleFlagCommand(options, "manage")} ${scopeFlag} after extension changes.`);
1534
+ }
1535
+ return {
1536
+ status: effectiveWarnings.length === 0 ? "ok" : "warn",
1537
+ warning_count: effectiveWarnings.length,
1538
+ warning_codes: warningCodes,
1539
+ warnings: effectiveWarnings,
1540
+ policy_warning_count: policyWarnings.warning_count,
1541
+ policy_violation_count: policyWarnings.violation_count,
1542
+ policy_blocked_count: policyWarnings.blocked_count,
1543
+ total_extensions: extensions.length,
1544
+ managed_total: managedTotal,
1545
+ enabled_total: enabledTotal,
1546
+ active_total: activeTotal,
1547
+ update_available_total: updateAvailableTotal,
1548
+ update_health_coverage: updateHealthCoverage,
1549
+ update_health_partial: updateHealthPartial,
1550
+ unmanaged_loaded_extension_count: unmanagedExtensions.length,
1551
+ unmanaged_loaded_extensions: unmanagedExtensions.map((entry) => entry.name).sort((left, right) => left.localeCompare(right)),
1552
+ unmanaged_expected_extension_count: unmanagedExpectedExtensions.length,
1553
+ unmanaged_expected_extensions: unmanagedExpectedExtensions,
1554
+ unmanaged_action_required_extension_count: unmanagedActionRequiredExtensions.length,
1555
+ unmanaged_action_required_extensions: unmanagedActionRequiredExtensions,
1556
+ update_check_status_totals: updateCheckStatusTotals,
1557
+ update_check_failed_total: updateCheckFailedTotal,
1558
+ top_warnings: effectiveWarnings.slice(0, 8),
1559
+ remediation
1560
+ };
1561
+ }
1562
+ function parseDoctorDetailMode(raw) {
1563
+ if (!raw || raw.trim().length === 0) {
1564
+ return "summary";
1565
+ }
1566
+ const normalized = raw.trim().toLowerCase();
1567
+ if (normalized === "summary" || normalized === "deep") {
1568
+ return normalized;
1569
+ }
1570
+ throw new PmCliError(`Invalid --detail value "${raw}". Expected summary or deep.`, EXIT_CODE.USAGE);
1571
+ }
1572
+ function warningCode(value) {
1573
+ const normalized = value.trim();
1574
+ const separator = normalized.indexOf(":");
1575
+ if (separator === -1) {
1576
+ return normalized;
1577
+ }
1578
+ return normalized.slice(0, separator);
1579
+ }
1580
+ function collectUnknownCapabilityGuidance(warnings) {
1581
+ const seen = /* @__PURE__ */ new Set();
1582
+ const guidance = [];
1583
+ for (const warning of warnings) {
1584
+ const parsedDetails = (() => {
1585
+ const unknownWarning = parseUnknownExtensionCapabilityWarning(warning);
1586
+ if (unknownWarning) {
1587
+ return [unknownWarning];
1588
+ }
1589
+ return parseLegacyExtensionCapabilityAliasWarning(warning);
1590
+ })();
1591
+ for (const parsed of parsedDetails) {
1592
+ const key = `${parsed.layer}:${parsed.name}:${parsed.capability}`;
1593
+ if (seen.has(key)) {
1594
+ continue;
1595
+ }
1596
+ seen.add(key);
1597
+ guidance.push(parsed);
1598
+ }
1599
+ }
1600
+ return guidance;
1601
+ }
1602
+ function buildCapabilityContractMetadata() {
1603
+ return {
1604
+ version: EXTENSION_CAPABILITY_CONTRACT.version,
1605
+ capabilities: [...EXTENSION_CAPABILITY_CONTRACT.capabilities],
1606
+ legacy_aliases: { ...EXTENSION_CAPABILITY_CONTRACT.legacy_aliases }
1607
+ };
1608
+ }
1609
+ function isExpectedUnmanagedExtension(entry) {
1610
+ const normalizedName = normalizeExtensionNameForMatch(entry.name);
1611
+ const normalizedDirectory = normalizeExtensionNameForMatch(entry.directory);
1612
+ if (normalizedName.startsWith("builtin-")) {
1613
+ return true;
1614
+ }
1615
+ return normalizedDirectory === "beads" || normalizedDirectory === "todos";
1616
+ }
1617
+ function buildDoctorConsistencySummary(scope, installedExtensions, loadedExtensions, failedLoads, disabledByFlag) {
1618
+ if (scope !== "project" || disabledByFlag) {
1619
+ return {
1620
+ warnings: [],
1621
+ summary: {
1622
+ active_project_count: 0,
1623
+ loaded_project_count: 0,
1624
+ active_project_names: [],
1625
+ loaded_project_names: [],
1626
+ missing_active_project_names: []
1627
+ }
1628
+ };
1629
+ }
1630
+ const activeProjectNames = [
1631
+ ...new Set(installedExtensions.filter((entry) => entry.active).map((entry) => normalizeExtensionNameForMatch(entry.name)))
1632
+ ].sort((left, right) => left.localeCompare(right));
1633
+ const loadedProjectNames = [
1634
+ ...new Set(loadedExtensions.filter((entry) => entry.layer === "project").map((entry) => normalizeExtensionNameForMatch(entry.name)))
1635
+ ].sort((left, right) => left.localeCompare(right));
1636
+ const failedLoadNames = new Set(failedLoads.map((entry) => normalizeExtensionNameForMatch(entry.name)));
1637
+ const missingActiveProjectNames = activeProjectNames.filter((name) => !loadedProjectNames.includes(name) && !failedLoadNames.has(name)).sort((left, right) => left.localeCompare(right));
1638
+ const warnings = missingActiveProjectNames.length > 0 ? [`extension_doctor_consistency_active_not_loaded:${missingActiveProjectNames.join(",")}`] : [];
1639
+ return {
1640
+ warnings,
1641
+ summary: {
1642
+ active_project_count: activeProjectNames.length,
1643
+ loaded_project_count: loadedProjectNames.length,
1644
+ active_project_names: activeProjectNames,
1645
+ loaded_project_names: loadedProjectNames,
1646
+ missing_active_project_names: missingActiveProjectNames
1647
+ }
1648
+ };
1649
+ }
1650
+
1651
+ // dist/cli/commands/extension.js
1652
+ !(function() {
1653
+ try {
1654
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
1655
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "dc0411c0-3d3c-5495-9be5-d221c8a9498d");
1656
+ } catch (e2) {
1657
+ }
1658
+ })();
1659
+ var execFileAsync2 = promisify2(execFile2);
1660
+ var EXTENSION_INSTALL_COPY_ATTEMPTS = 3;
1661
+ var EXTENSION_INSTALL_LOCK_ATTEMPTS = 120;
1662
+ var EXTENSION_INSTALL_LOCK_DELAY_MS = 250;
1663
+ var EXTENSION_INSTALL_LOCK_STALE_MS = 12e4;
1664
+ function buildExtensionPolicyDetails(policy) {
1665
+ const overrides = (policy.extension_overrides ?? []).map((override) => ({
1666
+ name: override.name.trim(),
1667
+ disabled: override.disabled === true ? true : void 0,
1668
+ require_trusted: override.require_trusted === true ? true : void 0,
1669
+ require_provenance: override.require_provenance === true ? true : void 0,
1670
+ sandbox_profile: override.sandbox_profile,
1671
+ allowed_capabilities: normalizeStringList(override.allowed_capabilities ?? []),
1672
+ blocked_capabilities: normalizeStringList(override.blocked_capabilities ?? []),
1673
+ allowed_surfaces: normalizeStringList(override.allowed_surfaces ?? []),
1674
+ blocked_surfaces: normalizeStringList(override.blocked_surfaces ?? []),
1675
+ allowed_commands: normalizeStringList(override.allowed_commands ?? []),
1676
+ blocked_commands: normalizeStringList(override.blocked_commands ?? []),
1677
+ allowed_actions: normalizeStringList(override.allowed_actions ?? []),
1678
+ blocked_actions: normalizeStringList(override.blocked_actions ?? []),
1679
+ allowed_services: normalizeStringList(override.allowed_services ?? []),
1680
+ blocked_services: normalizeStringList(override.blocked_services ?? [])
1681
+ })).filter((override) => override.name.length > 0).sort((left, right) => left.name.localeCompare(right.name));
1682
+ return {
1683
+ mode: policy.mode,
1684
+ trust_mode: policy.trust_mode,
1685
+ require_provenance: policy.require_provenance === true,
1686
+ trusted_extensions: normalizeStringList(policy.trusted_extensions ?? []),
1687
+ default_sandbox_profile: policy.default_sandbox_profile ?? "none",
1688
+ allowed_extensions: normalizeStringList(policy.allowed_extensions ?? []),
1689
+ blocked_extensions: normalizeStringList(policy.blocked_extensions ?? []),
1690
+ allowed_capabilities: normalizeStringList(policy.allowed_capabilities ?? []),
1691
+ blocked_capabilities: normalizeStringList(policy.blocked_capabilities ?? []),
1692
+ allowed_surfaces: normalizeStringList(policy.allowed_surfaces ?? []),
1693
+ blocked_surfaces: normalizeStringList(policy.blocked_surfaces ?? []),
1694
+ allowed_commands: normalizeStringList(policy.allowed_commands ?? []),
1695
+ blocked_commands: normalizeStringList(policy.blocked_commands ?? []),
1696
+ allowed_actions: normalizeStringList(policy.allowed_actions ?? []),
1697
+ blocked_actions: normalizeStringList(policy.blocked_actions ?? []),
1698
+ allowed_services: normalizeStringList(policy.allowed_services ?? []),
1699
+ blocked_services: normalizeStringList(policy.blocked_services ?? []),
1700
+ extension_overrides: overrides.map((override) => ({
1701
+ name: override.name,
1702
+ ...override.disabled === true ? { disabled: true } : {},
1703
+ ...override.require_trusted === true ? { require_trusted: true } : {},
1704
+ ...override.require_provenance === true ? { require_provenance: true } : {},
1705
+ ...override.sandbox_profile ? { sandbox_profile: override.sandbox_profile } : {},
1706
+ ...override.allowed_capabilities.length > 0 ? { allowed_capabilities: override.allowed_capabilities } : {},
1707
+ ...override.blocked_capabilities.length > 0 ? { blocked_capabilities: override.blocked_capabilities } : {},
1708
+ ...override.allowed_surfaces.length > 0 ? { allowed_surfaces: override.allowed_surfaces } : {},
1709
+ ...override.blocked_surfaces.length > 0 ? { blocked_surfaces: override.blocked_surfaces } : {},
1710
+ ...override.allowed_commands.length > 0 ? { allowed_commands: override.allowed_commands } : {},
1711
+ ...override.blocked_commands.length > 0 ? { blocked_commands: override.blocked_commands } : {},
1712
+ ...override.allowed_actions.length > 0 ? { allowed_actions: override.allowed_actions } : {},
1713
+ ...override.blocked_actions.length > 0 ? { blocked_actions: override.blocked_actions } : {},
1714
+ ...override.allowed_services.length > 0 ? { allowed_services: override.allowed_services } : {},
1715
+ ...override.blocked_services.length > 0 ? { blocked_services: override.blocked_services } : {}
1716
+ }))
1717
+ };
1718
+ }
1719
+ function isRetriableExtensionInstallCopyError(error) {
1720
+ if (typeof error !== "object" || error === null || !("code" in error)) {
1721
+ return false;
1722
+ }
1723
+ const code = error.code;
1724
+ return code === "EEXIST" || code === "ENOTEMPTY" || code === "ENOENT";
1725
+ }
1726
+ function isErrnoCode(error, code) {
1727
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
1728
+ }
1729
+ function sleep(ms) {
1730
+ return new Promise((resolve) => {
1731
+ setTimeout(resolve, ms);
1732
+ });
1733
+ }
1734
+ async function copyExtensionDirectoryForInstall(sourceDirectory, destinationDirectory, copyDirectory = fs7.cp) {
1735
+ for (let attempt = 1; attempt <= EXTENSION_INSTALL_COPY_ATTEMPTS; attempt += 1) {
1736
+ try {
1737
+ if (await pathExists(destinationDirectory)) {
1738
+ await fs7.rm(destinationDirectory, { recursive: true, force: true });
1739
+ }
1740
+ await copyExtensionDirectoryWithoutSelfNesting(sourceDirectory, destinationDirectory, copyDirectory);
1741
+ return;
1742
+ } catch (error) {
1743
+ if (!isRetriableExtensionInstallCopyError(error) || attempt === EXTENSION_INSTALL_COPY_ATTEMPTS) {
1744
+ throw error;
1745
+ }
1746
+ await sleep(EXTENSION_INSTALL_LOCK_DELAY_MS);
1747
+ }
1748
+ }
1749
+ }
1750
+ async function copyExtensionDirectoryWithoutSelfNesting(sourceDirectory, destinationDirectory, copyDirectory) {
1751
+ const resolvedSource = path7.resolve(sourceDirectory);
1752
+ const resolvedDestination = path7.resolve(destinationDirectory);
1753
+ if (resolvedSource === resolvedDestination) {
1754
+ return;
1755
+ }
1756
+ if (!isPathWithinDirectory(resolvedSource, resolvedDestination)) {
1757
+ await copyDirectory(sourceDirectory, destinationDirectory, { recursive: true, force: true });
1758
+ return;
1759
+ }
1760
+ const stagingRoot = await fs7.mkdtemp(path7.join(os2.tmpdir(), "pm-extension-copy-"));
1761
+ const stagedDirectory = path7.join(stagingRoot, "extension");
1762
+ try {
1763
+ await copyDirectory(sourceDirectory, stagedDirectory, { recursive: true, force: true });
1764
+ await copyDirectory(stagedDirectory, destinationDirectory, { recursive: true, force: true });
1765
+ } finally {
1766
+ await fs7.rm(stagingRoot, { recursive: true, force: true });
1767
+ }
1768
+ }
1769
+ async function withExtensionInstallLock(settingsRoot, destinationDirectoryName, run) {
1770
+ const lockRoot = path7.join(settingsRoot, "runtime", "extension-install-locks");
1771
+ const lockPath = path7.join(lockRoot, `${destinationDirectoryName}.lock`);
1772
+ await fs7.mkdir(lockRoot, { recursive: true });
1773
+ let acquired = false;
1774
+ for (let attempt = 1; attempt <= EXTENSION_INSTALL_LOCK_ATTEMPTS; attempt += 1) {
1775
+ try {
1776
+ await fs7.mkdir(lockPath);
1777
+ acquired = true;
1778
+ await fs7.writeFile(path7.join(lockPath, "owner.json"), `${JSON.stringify({ pid: process.pid, created_at: nowIso(), destination: destinationDirectoryName }, null, 2)}
1779
+ `, "utf8");
1780
+ break;
1781
+ } catch (error) {
1782
+ if (!isErrnoCode(error, "EEXIST")) {
1783
+ throw error;
1784
+ }
1785
+ const stat = await fs7.stat(lockPath).catch(() => null);
1786
+ if (stat && Date.now() - stat.mtimeMs > EXTENSION_INSTALL_LOCK_STALE_MS) {
1787
+ await fs7.rm(lockPath, { recursive: true, force: true });
1788
+ continue;
1789
+ }
1790
+ await sleep(EXTENSION_INSTALL_LOCK_DELAY_MS);
1791
+ }
1792
+ }
1793
+ if (!acquired) {
1794
+ throw new PmCliError(`Timed out waiting for extension install lock for "${destinationDirectoryName}".`, EXIT_CODE.CONFLICT);
1795
+ }
1796
+ try {
1797
+ return await run();
1798
+ } finally {
1799
+ await fs7.rm(lockPath, { recursive: true, force: true }).catch(() => void 0);
1800
+ }
1801
+ }
1802
+ async function resolveInstalledExtensionCandidate(installed, extensionTarget) {
1803
+ const lookupValues = [extensionTarget];
1804
+ const bundledAliasManifestName = await resolveBundledAliasManifestName(extensionTarget);
1805
+ if (bundledAliasManifestName) {
1806
+ lookupValues.push(bundledAliasManifestName);
1807
+ }
1808
+ const normalizedLookups = [...new Set(lookupValues.map((value) => normalizeExtensionNameForMatch(value)).filter((value) => value.length > 0))];
1809
+ for (const lookup of normalizedLookups) {
1810
+ const byName = installed.find((entry) => normalizeExtensionNameForMatch(entry.name) === lookup);
1811
+ if (byName) {
1812
+ return byName;
1813
+ }
1814
+ const byDirectory = installed.find((entry) => normalizeExtensionNameForMatch(entry.directory) === lookup);
1815
+ if (byDirectory) {
1816
+ return byDirectory;
1817
+ }
1818
+ }
1819
+ return void 0;
1820
+ }
1821
+ function isExtensionEnabled(settings, name) {
1822
+ const normalizedName = name.trim();
1823
+ const enabled = new Set(normalizeStringList(settings.extensions.enabled));
1824
+ const disabled = new Set(normalizeStringList(settings.extensions.disabled));
1825
+ if (disabled.has(normalizedName)) {
1826
+ return false;
1827
+ }
1828
+ if (enabled.size === 0) {
1829
+ return true;
1830
+ }
1831
+ return enabled.has(normalizedName);
1832
+ }
1833
+ function ensureActivated(settings, name) {
1834
+ const normalizedName = name.trim();
1835
+ const enabled = new Set(normalizeStringList(settings.extensions.enabled));
1836
+ const disabled = new Set(normalizeStringList(settings.extensions.disabled));
1837
+ const previousEnabled = [...enabled];
1838
+ const previousDisabled = [...disabled];
1839
+ disabled.delete(normalizedName);
1840
+ if (enabled.size > 0) {
1841
+ enabled.add(normalizedName);
1842
+ }
1843
+ settings.extensions.enabled = [...enabled].sort((left, right) => left.localeCompare(right));
1844
+ settings.extensions.disabled = [...disabled].sort((left, right) => left.localeCompare(right));
1845
+ return settings.extensions.enabled.join("\0") !== previousEnabled.join("\0") || settings.extensions.disabled.join("\0") !== previousDisabled.join("\0");
1846
+ }
1847
+ function ensureDeactivated(settings, name) {
1848
+ const normalizedName = name.trim();
1849
+ const enabled = new Set(normalizeStringList(settings.extensions.enabled));
1850
+ const disabled = new Set(normalizeStringList(settings.extensions.disabled));
1851
+ const previousEnabled = [...enabled];
1852
+ const previousDisabled = [...disabled];
1853
+ enabled.delete(normalizedName);
1854
+ disabled.add(normalizedName);
1855
+ settings.extensions.enabled = [...enabled].sort((left, right) => left.localeCompare(right));
1856
+ settings.extensions.disabled = [...disabled].sort((left, right) => left.localeCompare(right));
1857
+ return settings.extensions.enabled.join("\0") !== previousEnabled.join("\0") || settings.extensions.disabled.join("\0") !== previousDisabled.join("\0");
1858
+ }
1859
+ function clearExtensionState(settings, name) {
1860
+ const normalizedName = name.trim();
1861
+ const enabled = new Set(normalizeStringList(settings.extensions.enabled));
1862
+ const disabled = new Set(normalizeStringList(settings.extensions.disabled));
1863
+ const previousEnabled = [...enabled];
1864
+ const previousDisabled = [...disabled];
1865
+ enabled.delete(normalizedName);
1866
+ disabled.delete(normalizedName);
1867
+ settings.extensions.enabled = [...enabled].sort((left, right) => left.localeCompare(right));
1868
+ settings.extensions.disabled = [...disabled].sort((left, right) => left.localeCompare(right));
1869
+ return settings.extensions.enabled.join("\0") !== previousEnabled.join("\0") || settings.extensions.disabled.join("\0") !== previousDisabled.join("\0");
1870
+ }
1871
+ function resolveAction(target, options) {
1872
+ const selected = [...new Set([
1873
+ options.install ? "install" : null,
1874
+ options.uninstall ? "uninstall" : null,
1875
+ options.explore ? "explore" : null,
1876
+ options.manage ? "manage" : null,
1877
+ options.reload ? "reload" : null,
1878
+ options.doctor ? "doctor" : null,
1879
+ options.catalog ? "catalog" : null,
1880
+ options.init ? "init" : null,
1881
+ options.scaffold ? "init" : null,
1882
+ options.adopt ? "adopt" : null,
1883
+ options.adoptAll ? "adopt-all" : null,
1884
+ options.activate ? "activate" : null,
1885
+ options.deactivate ? "deactivate" : null
1886
+ ].filter((value) => value !== null))];
1887
+ if (selected.length === 0) {
1888
+ if (typeof target === "string" && target.trim().toLowerCase() === "doctor") {
1889
+ return "doctor";
1890
+ }
1891
+ if (typeof target === "string" && target.trim().toLowerCase() === "reload") {
1892
+ return "reload";
1893
+ }
1894
+ if (typeof target === "string" && target.trim().toLowerCase() === "catalog") {
1895
+ return "catalog";
1896
+ }
1897
+ if (typeof target === "string" && (target.trim().toLowerCase() === "init" || target.trim().toLowerCase() === "scaffold")) {
1898
+ return "init";
1899
+ }
1900
+ if (typeof target === "string" && target.trim().toLowerCase() === "explore") {
1901
+ return "explore";
1902
+ }
1903
+ if (typeof target === "string" && target.trim().toLowerCase() === "manage") {
1904
+ return "manage";
1905
+ }
1906
+ if (typeof target === "string" && (target.trim().toLowerCase() === "list" || target.trim() === "")) {
1907
+ return "explore";
1908
+ }
1909
+ if (target === void 0) {
1910
+ return "explore";
1911
+ }
1912
+ throw new PmCliError("One action flag is required. Use one of: --install, --uninstall, --explore, --manage, --reload, --doctor, --catalog, --init/--scaffold, --adopt, --adopt-all, --activate, --deactivate. Bare `pm package` and `pm extension` default to --explore.", EXIT_CODE.USAGE);
1913
+ }
1914
+ if (selected.length > 1) {
1915
+ throw new PmCliError("Extension action flags are mutually exclusive.", EXIT_CODE.USAGE);
1916
+ }
1917
+ return selected[0];
1918
+ }
1919
+ function resolveScope(options) {
1920
+ const projectLike = options.project === true || options.local === true;
1921
+ const global2 = options.global === true;
1922
+ if (projectLike && global2) {
1923
+ throw new PmCliError('Options "--project/--local" and "--global" are mutually exclusive.', EXIT_CODE.USAGE);
1924
+ }
1925
+ return global2 ? "global" : "project";
1926
+ }
1927
+ function resolveUpdateCheckResolution(managedEntry) {
1928
+ if (!managedEntry) {
1929
+ return {
1930
+ status: "skipped_unmanaged",
1931
+ reason: "extension_not_managed"
1932
+ };
1933
+ }
1934
+ if (managedEntry.source.kind !== "github") {
1935
+ return {
1936
+ status: "skipped_non_github",
1937
+ reason: `managed_source_kind_${managedEntry.source.kind}`
1938
+ };
1939
+ }
1940
+ const updateError = typeof managedEntry.update_error === "string" ? managedEntry.update_error.trim() : "";
1941
+ if (updateError.length > 0) {
1942
+ return {
1943
+ status: "failed",
1944
+ reason: updateError
1945
+ };
1946
+ }
1947
+ if (typeof managedEntry.last_update_check_at === "string" && managedEntry.last_update_check_at.trim().length > 0) {
1948
+ if (managedEntry.update_available === true) {
1949
+ return {
1950
+ status: "checked",
1951
+ reason: "update_available"
1952
+ };
1953
+ }
1954
+ if (managedEntry.update_available === false) {
1955
+ return {
1956
+ status: "checked",
1957
+ reason: "up_to_date"
1958
+ };
1959
+ }
1960
+ return {
1961
+ status: "checked",
1962
+ reason: "checked_without_commit_baseline"
1963
+ };
1964
+ }
1965
+ return {
1966
+ status: "not_checked",
1967
+ reason: "no_update_check_recorded"
1968
+ };
1969
+ }
1970
+ async function listInstalledExtensions(extensionsRoot, scope, settings, state) {
1971
+ if (!await pathExists(extensionsRoot)) {
1972
+ return {
1973
+ extensions: [],
1974
+ warnings: []
1975
+ };
1976
+ }
1977
+ const entries = await fs7.readdir(extensionsRoot, { withFileTypes: true });
1978
+ const directories = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((left, right) => left.localeCompare(right));
1979
+ const managedByName = /* @__PURE__ */ new Map();
1980
+ const managedByDirectory = /* @__PURE__ */ new Map();
1981
+ for (const managedEntry of state.entries) {
1982
+ managedByName.set(normalizeExtensionNameForMatch(managedEntry.name), managedEntry);
1983
+ managedByDirectory.set(normalizeExtensionNameForMatch(managedEntry.directory), managedEntry);
1984
+ }
1985
+ const warnings = [];
1986
+ const summaries = [];
1987
+ for (const directoryName of directories) {
1988
+ const extensionDirectory = path7.join(extensionsRoot, directoryName);
1989
+ const manifestPath = path7.join(extensionDirectory, "manifest.json");
1990
+ if (!await pathExists(manifestPath)) {
1991
+ warnings.push(`extension_manifest_missing:${scope}:${directoryName}`);
1992
+ const managedEntry2 = managedByDirectory.get(normalizeExtensionNameForMatch(directoryName));
1993
+ const updateCheck2 = resolveUpdateCheckResolution(managedEntry2);
1994
+ const enabled2 = managedEntry2 ? isExtensionEnabled(settings, managedEntry2.name) : false;
1995
+ summaries.push({
1996
+ name: managedEntry2?.name ?? directoryName,
1997
+ directory: directoryName,
1998
+ version: managedEntry2?.manifest_version ?? "unknown",
1999
+ entry: managedEntry2?.manifest_entry ?? "unknown",
2000
+ scope,
2001
+ active: enabled2,
2002
+ enabled: enabled2,
2003
+ runtime_active: null,
2004
+ activation_status: "unknown",
2005
+ managed: Boolean(managedEntry2),
2006
+ source: managedEntry2?.source,
2007
+ update_available: managedEntry2?.update_available,
2008
+ last_update_check_at: managedEntry2?.last_update_check_at,
2009
+ last_update_remote_commit: managedEntry2?.last_update_remote_commit,
2010
+ update_error: managedEntry2?.update_error,
2011
+ update_check_status: updateCheck2.status,
2012
+ update_check_reason: updateCheck2.reason
2013
+ });
2014
+ continue;
2015
+ }
2016
+ let rawManifest;
2017
+ try {
2018
+ rawManifest = JSON.parse(await fs7.readFile(manifestPath, "utf8"));
2019
+ } catch {
2020
+ warnings.push(`extension_manifest_invalid_json:${scope}:${directoryName}`);
2021
+ continue;
2022
+ }
2023
+ const manifest = parseExtensionManifest(rawManifest);
2024
+ if (!manifest) {
2025
+ warnings.push(`extension_manifest_invalid:${scope}:${directoryName}`);
2026
+ continue;
2027
+ }
2028
+ const managedEntry = managedByName.get(normalizeExtensionNameForMatch(manifest.name)) ?? managedByDirectory.get(normalizeExtensionNameForMatch(directoryName));
2029
+ const updateCheck = resolveUpdateCheckResolution(managedEntry);
2030
+ const enabled = isExtensionEnabled(settings, manifest.name);
2031
+ summaries.push({
2032
+ name: manifest.name,
2033
+ directory: directoryName,
2034
+ version: manifest.version,
2035
+ entry: manifest.entry,
2036
+ scope,
2037
+ active: enabled,
2038
+ enabled,
2039
+ runtime_active: null,
2040
+ activation_status: "unknown",
2041
+ managed: Boolean(managedEntry),
2042
+ source: managedEntry?.source,
2043
+ update_available: managedEntry?.update_available,
2044
+ last_update_check_at: managedEntry?.last_update_check_at,
2045
+ last_update_remote_commit: managedEntry?.last_update_remote_commit,
2046
+ update_error: managedEntry?.update_error,
2047
+ update_check_status: updateCheck.status,
2048
+ update_check_reason: updateCheck.reason
2049
+ });
2050
+ }
2051
+ return {
2052
+ extensions: summaries.sort((left, right) => left.name.localeCompare(right.name)),
2053
+ warnings: warnings.sort((left, right) => left.localeCompare(right))
2054
+ };
2055
+ }
2056
+ async function checkGithubUpdate(source) {
2057
+ const checkedAt = nowIso();
2058
+ if (source.kind !== "github" || !source.repository) {
2059
+ return {
2060
+ checked_at: checkedAt,
2061
+ available: null,
2062
+ error: "not_a_github_managed_source"
2063
+ };
2064
+ }
2065
+ try {
2066
+ const ref = source.ref && source.ref.trim().length > 0 ? source.ref.trim() : "HEAD";
2067
+ const output = await runGitCommand(["ls-remote", source.repository, ref]);
2068
+ const firstLine = output.split(/\r?\n/).map((line) => line.trim()).find((line) => line.length > 0);
2069
+ if (!firstLine) {
2070
+ return {
2071
+ checked_at: checkedAt,
2072
+ available: null,
2073
+ error: "no_remote_reference_found"
2074
+ };
2075
+ }
2076
+ const [remoteCommit] = firstLine.split(/\s+/);
2077
+ if (typeof remoteCommit !== "string" || remoteCommit.length === 0) {
2078
+ return {
2079
+ checked_at: checkedAt,
2080
+ available: null,
2081
+ error: "invalid_remote_reference"
2082
+ };
2083
+ }
2084
+ if (typeof source.commit === "string" && source.commit.trim().length > 0) {
2085
+ return {
2086
+ checked_at: checkedAt,
2087
+ remote_commit: remoteCommit,
2088
+ available: remoteCommit !== source.commit.trim()
2089
+ };
2090
+ }
2091
+ return {
2092
+ checked_at: checkedAt,
2093
+ remote_commit: remoteCommit,
2094
+ available: null,
2095
+ error: "missing_installed_commit"
2096
+ };
2097
+ } catch (error) {
2098
+ return {
2099
+ checked_at: checkedAt,
2100
+ available: null,
2101
+ error: error instanceof Error ? error.message : String(error)
2102
+ };
2103
+ }
2104
+ }
2105
+ async function adoptUnmanagedExtensions(extensionsRoot, scope, installedExtensions, state) {
2106
+ const unmanagedCandidates = installedExtensions.filter((entry) => !entry.managed);
2107
+ const sortedCandidates = [...unmanagedCandidates].sort((left, right) => {
2108
+ const byName = left.name.localeCompare(right.name);
2109
+ if (byName !== 0) {
2110
+ return byName;
2111
+ }
2112
+ return left.directory.localeCompare(right.directory);
2113
+ });
2114
+ let nextState = state;
2115
+ const adoptedEntries = [];
2116
+ for (const candidate of sortedCandidates) {
2117
+ const extensionDirectory = path7.join(extensionsRoot, candidate.directory);
2118
+ const validated = await validateExtensionDirectory(extensionDirectory);
2119
+ const now = nowIso();
2120
+ const sourceRecord = {
2121
+ kind: "local",
2122
+ input: candidate.name,
2123
+ location: extensionDirectory
2124
+ };
2125
+ nextState = upsertManagedEntry(nextState, {
2126
+ name: validated.manifest.name,
2127
+ directory: candidate.directory,
2128
+ scope,
2129
+ manifest_version: validated.manifest.version,
2130
+ manifest_entry: validated.manifest.entry,
2131
+ capabilities: [...validated.manifest.capabilities],
2132
+ installed_at: now,
2133
+ updated_at: now,
2134
+ source: sourceRecord
2135
+ });
2136
+ adoptedEntries.push({
2137
+ name: validated.manifest.name,
2138
+ directory: candidate.directory,
2139
+ version: validated.manifest.version,
2140
+ entry: validated.manifest.entry,
2141
+ source: sourceRecord
2142
+ });
2143
+ }
2144
+ if (adoptedEntries.length > 0) {
2145
+ await writeManagedExtensionState(extensionsRoot, nextState);
2146
+ }
2147
+ return {
2148
+ state: nextState,
2149
+ adopted_entries: adoptedEntries,
2150
+ unmanaged_candidates: sortedCandidates,
2151
+ already_managed_count: installedExtensions.length - unmanagedCandidates.length
2152
+ };
2153
+ }
2154
+ function resolveExtensionRootsForScope(scope, global2) {
2155
+ const pmRoot = resolvePmRoot(process.cwd(), global2.path);
2156
+ const roots = resolveExtensionRoots(pmRoot, process.cwd());
2157
+ const settingsRoot = scope === "global" ? resolveGlobalPmRoot(process.cwd()) : pmRoot;
2158
+ const selectedRoot = scope === "global" ? roots.global : roots.project;
2159
+ return {
2160
+ pm_root: pmRoot,
2161
+ scope,
2162
+ settings_root: settingsRoot,
2163
+ selected_root: selectedRoot,
2164
+ roots
2165
+ };
2166
+ }
2167
+ function resolveGithubOption(options) {
2168
+ if (typeof options.gh === "string" && typeof options.github === "string" && options.gh.trim() !== options.github.trim()) {
2169
+ throw new PmCliError('Options "--gh" and "--github" must match when both are provided.', EXIT_CODE.USAGE);
2170
+ }
2171
+ if (typeof options.gh === "string" && options.gh.trim().length > 0) {
2172
+ return options.gh.trim();
2173
+ }
2174
+ if (typeof options.github === "string" && options.github.trim().length > 0) {
2175
+ return options.github.trim();
2176
+ }
2177
+ return void 0;
2178
+ }
2179
+ function requireTarget(target, action) {
2180
+ const normalized = target?.trim();
2181
+ if (!normalized) {
2182
+ if (action === "init") {
2183
+ throw new PmCliError('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).', EXIT_CODE.USAGE);
2184
+ }
2185
+ throw new PmCliError(`Action "${action}" requires an extension name or source target argument.`, EXIT_CODE.USAGE);
2186
+ }
2187
+ return normalized;
2188
+ }
2189
+ async function runExtension(target, options, global2) {
2190
+ const action = resolveAction(target, options);
2191
+ if ((options.strictExit === true || options.failOnWarn === true) && action !== "doctor") {
2192
+ throw new PmCliError("--strict-exit and --fail-on-warn are only valid with --doctor.", EXIT_CODE.USAGE);
2193
+ }
2194
+ if (options.trace === true && action !== "doctor") {
2195
+ throw new PmCliError("--trace is only valid with --doctor.", EXIT_CODE.USAGE);
2196
+ }
2197
+ if (options.watch === true && action !== "reload") {
2198
+ throw new PmCliError("--watch is only valid with --reload.", EXIT_CODE.USAGE);
2199
+ }
2200
+ if (options.runtimeProbe === true && action !== "manage") {
2201
+ throw new PmCliError("--runtime-probe is only valid with --manage.", EXIT_CODE.USAGE);
2202
+ }
2203
+ if (options.fixManagedState === true && action !== "manage" && action !== "doctor") {
2204
+ throw new PmCliError("--fix-managed-state is only valid with --manage or --doctor.", EXIT_CODE.USAGE);
2205
+ }
2206
+ const normalizedTarget = (() => {
2207
+ const normalizedInput = target?.trim().toLowerCase();
2208
+ if (action === "doctor" && normalizedInput === "doctor") {
2209
+ return void 0;
2210
+ }
2211
+ if (action === "reload" && normalizedInput === "reload") {
2212
+ return void 0;
2213
+ }
2214
+ if (action === "catalog" && normalizedInput === "catalog") {
2215
+ return void 0;
2216
+ }
2217
+ const inferredInitAlias = action === "init" && options.init !== true && options.scaffold !== true && (normalizedInput === "init" || normalizedInput === "scaffold");
2218
+ if (inferredInitAlias) {
2219
+ return void 0;
2220
+ }
2221
+ return target;
2222
+ })();
2223
+ const scope = resolveScope(options);
2224
+ const resolvedRoots = resolveExtensionRootsForScope(scope, global2);
2225
+ const warnings = [];
2226
+ const withResult = (details) => ({
2227
+ ok: true,
2228
+ action,
2229
+ scope,
2230
+ roots: action === "catalog" && typeof options.fields === "string" && options.fields.trim().length > 0 ? {
2231
+ project: "project",
2232
+ global: "global",
2233
+ selected: scope,
2234
+ settings_root: "project"
2235
+ } : {
2236
+ project: resolvedRoots.roots.project,
2237
+ global: resolvedRoots.roots.global,
2238
+ selected: resolvedRoots.selected_root,
2239
+ settings_root: resolvedRoots.settings_root
2240
+ },
2241
+ warnings: [...new Set(warnings)].sort((left, right) => left.localeCompare(right)),
2242
+ details
2243
+ });
2244
+ if (action === "init") {
2245
+ const githubOption = resolveGithubOption(options);
2246
+ if (githubOption !== void 0 || typeof options.ref === "string" && options.ref.trim().length > 0) {
2247
+ throw new PmCliError('Action "init" does not accept --gh/--github/--ref options.', EXIT_CODE.USAGE);
2248
+ }
2249
+ const scaffoldTarget = requireTarget(normalizedTarget, action);
2250
+ const scaffold = await scaffoldExtensionProject(scaffoldTarget, options.vocabulary ?? "extension");
2251
+ const quotedTargetPath = JSON.stringify(scaffold.target_path);
2252
+ return withResult({
2253
+ scaffolded: scaffold.created_directory || scaffold.files.some((entry) => entry.status === "created"),
2254
+ extension: {
2255
+ name: scaffold.extension_name,
2256
+ command: scaffold.command_name
2257
+ },
2258
+ target_path: scaffold.target_path,
2259
+ created_directory: scaffold.created_directory,
2260
+ files: scaffold.files,
2261
+ next_steps: [
2262
+ `Install the scaffold: ${options.vocabulary === "package" ? "pm install --project" : "pm extension --install --project"} ${quotedTargetPath}`,
2263
+ `Smoke-test command path: pm ${scaffold.command_name}`,
2264
+ `Run diagnostics: ${options.vocabulary === "package" ? "pm package doctor" : "pm extension --doctor"} --project --detail summary`
2265
+ ]
2266
+ });
2267
+ }
2268
+ if (action === "reload") {
2269
+ if (normalizedTarget !== void 0) {
2270
+ throw new PmCliError('Action "reload" does not accept a target argument.', EXIT_CODE.USAGE);
2271
+ }
2272
+ const settings = await readSettings(resolvedRoots.settings_root);
2273
+ const reloadToken = nextExtensionReloadToken();
2274
+ const reloaded = await loadExtensions({
2275
+ pmRoot: resolvedRoots.settings_root,
2276
+ settings,
2277
+ cwd: process.cwd(),
2278
+ noExtensions: global2.noExtensions,
2279
+ reload_token: reloadToken,
2280
+ cache_bust: true
2281
+ });
2282
+ warnings.push(...reloaded.warnings);
2283
+ const activation = await activateExtensions(reloaded);
2284
+ warnings.push(...activation.warnings);
2285
+ const details = {
2286
+ reload: {
2287
+ token: reloadToken,
2288
+ cache_bust: true,
2289
+ watch: options.watch === true
2290
+ },
2291
+ loaded_count: reloaded.loaded.length,
2292
+ failed_count: reloaded.failed.length,
2293
+ activated_count: Math.max(0, reloaded.loaded.length - activation.failed.length),
2294
+ activation_failed_count: activation.failed.length,
2295
+ loaded_extensions: reloaded.loaded.map((entry) => ({
2296
+ name: entry.name,
2297
+ layer: entry.layer,
2298
+ version: entry.version
2299
+ })),
2300
+ failed_extensions: reloaded.failed.map((entry) => ({
2301
+ name: entry.name,
2302
+ layer: entry.layer,
2303
+ error: entry.error
2304
+ })),
2305
+ activation_failures: activation.failed.map((entry) => ({
2306
+ name: entry.name,
2307
+ layer: entry.layer,
2308
+ error: entry.error
2309
+ }))
2310
+ };
2311
+ if (options.watch === true) {
2312
+ warnings.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only");
2313
+ }
2314
+ return withResult(details);
2315
+ }
2316
+ if (action === "catalog") {
2317
+ if (typeof normalizedTarget === "string" && normalizedTarget.length > 0 && normalizedTarget !== "catalog") {
2318
+ throw new PmCliError('Action "catalog" does not accept a package target.', EXIT_CODE.USAGE);
2319
+ }
2320
+ return withResult(await buildBundledPackageCatalog(scope, global2, options));
2321
+ }
2322
+ if (action === "install") {
2323
+ const githubOption = resolveGithubOption(options);
2324
+ const explicitSourceInput = githubOption ?? requireTarget(normalizedTarget, action);
2325
+ if (typeof githubOption !== "string" && isBundledPackageInstallAllTarget(explicitSourceInput)) {
2326
+ if (typeof options.ref === "string" && options.ref.trim().length > 0) {
2327
+ throw new PmCliError('Action "install all" does not accept --ref.', EXIT_CODE.USAGE);
2328
+ }
2329
+ const aliases = await listBundledPackageAliases();
2330
+ const packages = [];
2331
+ for (const alias of aliases) {
2332
+ packages.push({
2333
+ alias,
2334
+ result: await runExtension(alias, { ...options, install: true }, global2)
2335
+ });
2336
+ }
2337
+ for (const entry of packages) {
2338
+ warnings.push(...entry.result.warnings);
2339
+ }
2340
+ return withResult({
2341
+ installed_all: true,
2342
+ installed_count: packages.length,
2343
+ packages: packages.map((entry) => ({
2344
+ alias: entry.alias,
2345
+ ok: entry.result.ok,
2346
+ extension: entry.result.details.extension,
2347
+ source: entry.result.details.source,
2348
+ destination_path: entry.result.details.destination_path,
2349
+ activated: entry.result.details.activated,
2350
+ settings_changed: entry.result.details.settings_changed,
2351
+ warnings: entry.result.warnings
2352
+ }))
2353
+ });
2354
+ }
2355
+ const bundledAliasSource = typeof githubOption === "string" ? null : await resolveBundledExtensionAliasSource(explicitSourceInput);
2356
+ const bundledAliasName = bundledAliasSource === null ? null : explicitSourceInput.trim().toLowerCase();
2357
+ const sourceInput = bundledAliasSource ?? explicitSourceInput;
2358
+ const installSource = parseExtensionInstallSource(sourceInput, {
2359
+ forceGithub: typeof githubOption === "string",
2360
+ ref: options.ref
2361
+ });
2362
+ const resolvedSource = await resolveInstallSource(installSource);
2363
+ try {
2364
+ const validated = await validateExtensionDirectory(resolvedSource.directory);
2365
+ const destinationDirectoryName = normalizeManagedDirectoryName(validated.manifest.name);
2366
+ return await withExtensionInstallLock(resolvedRoots.settings_root, destinationDirectoryName, async () => {
2367
+ const settings = await readSettings(resolvedRoots.settings_root);
2368
+ const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);
2369
+ warnings.push(...managedStateRead.warnings);
2370
+ const destinationDirectory = path7.join(resolvedRoots.selected_root, destinationDirectoryName);
2371
+ const destinationExists = await pathExists(destinationDirectory);
2372
+ const installInPlace = await areDirectoriesEquivalent(validated.directory, destinationDirectory);
2373
+ await fs7.mkdir(resolvedRoots.selected_root, { recursive: true });
2374
+ if (!installInPlace) {
2375
+ await copyExtensionDirectoryForInstall(validated.directory, destinationDirectory);
2376
+ }
2377
+ const sourceRecord = bundledAliasName ? {
2378
+ kind: "builtin",
2379
+ input: bundledAliasName,
2380
+ location: bundledAliasName,
2381
+ name: bundledAliasName
2382
+ } : installSource.kind === "local" ? {
2383
+ kind: "local",
2384
+ input: installSource.input,
2385
+ location: installSource.absolute_path
2386
+ } : installSource.kind === "npm" ? {
2387
+ kind: "npm",
2388
+ input: installSource.input,
2389
+ location: resolvedSource.resolved_subpath ?? ".",
2390
+ package: resolvedSource.npm_package,
2391
+ version: resolvedSource.npm_version
2392
+ } : {
2393
+ kind: "github",
2394
+ input: installSource.input,
2395
+ location: resolvedSource.resolved_subpath ?? installSource.subpath ?? ".",
2396
+ repository: installSource.repository,
2397
+ owner: installSource.owner,
2398
+ repo: installSource.repo,
2399
+ ref: installSource.ref,
2400
+ subpath: resolvedSource.resolved_subpath ?? installSource.subpath,
2401
+ commit: resolvedSource.commit
2402
+ };
2403
+ const now = nowIso();
2404
+ const existingManagedEntry = managedStateRead.state.entries.find((entry) => normalizeExtensionNameForMatch(entry.name) === normalizeExtensionNameForMatch(validated.manifest.name));
2405
+ const sourceUnchanged = existingManagedEntry !== void 0 && existingManagedEntry.manifest_version === validated.manifest.version && managedExtensionSourcesEquivalent(existingManagedEntry.source, sourceRecord);
2406
+ const managedState = upsertManagedEntry(managedStateRead.state, {
2407
+ name: validated.manifest.name,
2408
+ directory: destinationDirectoryName,
2409
+ scope,
2410
+ manifest_version: validated.manifest.version,
2411
+ manifest_entry: validated.manifest.entry,
2412
+ capabilities: [...validated.manifest.capabilities],
2413
+ installed_at: existingManagedEntry?.installed_at ?? now,
2414
+ updated_at: sourceUnchanged ? existingManagedEntry.updated_at : now,
2415
+ source: sourceRecord
2416
+ });
2417
+ await writeManagedExtensionState(resolvedRoots.selected_root, managedState);
2418
+ const activationChanged = ensureActivated(settings, validated.manifest.name);
2419
+ if (activationChanged) {
2420
+ await writeSettings(resolvedRoots.settings_root, settings, "settings:write");
2421
+ }
2422
+ return withResult({
2423
+ extension: {
2424
+ name: validated.manifest.name,
2425
+ version: validated.manifest.version,
2426
+ entry: validated.manifest.entry,
2427
+ capabilities: validated.manifest.capabilities,
2428
+ directory: destinationDirectoryName
2429
+ },
2430
+ source: sourceRecord,
2431
+ destination_path: destinationDirectory,
2432
+ overwritten: destinationExists && !installInPlace,
2433
+ installed_in_place: installInPlace,
2434
+ activated: true,
2435
+ settings_changed: activationChanged
2436
+ });
2437
+ });
2438
+ } finally {
2439
+ if (resolvedSource.cleanup) {
2440
+ await resolvedSource.cleanup();
2441
+ }
2442
+ }
2443
+ }
2444
+ if (action === "adopt-all") {
2445
+ if (normalizedTarget !== void 0) {
2446
+ throw new PmCliError('Action "adopt-all" does not accept a target argument.', EXIT_CODE.USAGE);
2447
+ }
2448
+ const githubOption = resolveGithubOption(options);
2449
+ if (githubOption !== void 0 || typeof options.ref === "string" && options.ref.trim().length > 0) {
2450
+ throw new PmCliError('Action "adopt-all" does not accept --gh/--github/--ref options.', EXIT_CODE.USAGE);
2451
+ }
2452
+ const settings = await readSettings(resolvedRoots.settings_root);
2453
+ const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);
2454
+ warnings.push(...managedStateRead.warnings);
2455
+ const installed = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedStateRead.state);
2456
+ warnings.push(...installed.warnings);
2457
+ const adoption = await adoptUnmanagedExtensions(resolvedRoots.selected_root, scope, installed.extensions, managedStateRead.state);
2458
+ const refreshedInstalled = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, adoption.state);
2459
+ warnings.push(...refreshedInstalled.warnings);
2460
+ const triage = buildExtensionTriageSummary(scope, warnings, refreshedInstalled.extensions, options);
2461
+ warnings.push(...triage.warnings);
2462
+ const adoptedDetails = adoption.adopted_entries.map((entry) => {
2463
+ const refreshedEntry = refreshedInstalled.extensions.find((candidate) => normalizeExtensionNameForMatch(candidate.name) === normalizeExtensionNameForMatch(entry.name) && normalizeExtensionNameForMatch(candidate.directory) === normalizeExtensionNameForMatch(entry.directory)) ?? refreshedInstalled.extensions.find((candidate) => normalizeExtensionNameForMatch(candidate.directory) === normalizeExtensionNameForMatch(entry.directory));
2464
+ return {
2465
+ ...entry,
2466
+ update_check_status: refreshedEntry?.update_check_status ?? null,
2467
+ update_check_reason: refreshedEntry?.update_check_reason ?? null
2468
+ };
2469
+ });
2470
+ return withResult({
2471
+ adopted_all: adoptedDetails.length > 0,
2472
+ adopted_count: adoptedDetails.length,
2473
+ already_managed_count: adoption.already_managed_count,
2474
+ extensions: adoptedDetails,
2475
+ triage,
2476
+ warning_codes: triage.warning_codes,
2477
+ update_health_partial: triage.update_health_partial,
2478
+ update_health_coverage: triage.update_health_coverage
2479
+ });
2480
+ }
2481
+ if (action === "adopt") {
2482
+ const extensionTarget = requireTarget(normalizedTarget, action);
2483
+ const githubOption = resolveGithubOption(options);
2484
+ const settings = await readSettings(resolvedRoots.settings_root);
2485
+ const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);
2486
+ warnings.push(...managedStateRead.warnings);
2487
+ const installed = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedStateRead.state);
2488
+ warnings.push(...installed.warnings);
2489
+ const candidate = await resolveInstalledExtensionCandidate(installed.extensions, extensionTarget);
2490
+ if (!candidate) {
2491
+ throw new PmCliError(`Installed extension "${extensionTarget}" was not found in ${scope} scope.`, EXIT_CODE.NOT_FOUND);
2492
+ }
2493
+ if (candidate.managed) {
2494
+ return withResult({
2495
+ adopted: false,
2496
+ already_managed: true,
2497
+ extension: {
2498
+ name: candidate.name,
2499
+ directory: candidate.directory
2500
+ }
2501
+ });
2502
+ }
2503
+ const extensionDirectory = path7.join(resolvedRoots.selected_root, candidate.directory);
2504
+ const validated = await validateExtensionDirectory(extensionDirectory);
2505
+ const now = nowIso();
2506
+ const sourceRecord = githubOption === void 0 ? {
2507
+ kind: "local",
2508
+ input: extensionTarget,
2509
+ location: extensionDirectory
2510
+ } : (() => {
2511
+ const parsed = parseExtensionInstallSource(githubOption, {
2512
+ forceGithub: true,
2513
+ ref: options.ref
2514
+ });
2515
+ if (parsed.kind !== "github") {
2516
+ throw new PmCliError(`Invalid GitHub shorthand "${githubOption}".`, EXIT_CODE.USAGE);
2517
+ }
2518
+ return {
2519
+ kind: "github",
2520
+ input: parsed.input,
2521
+ location: parsed.subpath ?? ".",
2522
+ repository: parsed.repository,
2523
+ owner: parsed.owner,
2524
+ repo: parsed.repo,
2525
+ ref: parsed.ref,
2526
+ subpath: parsed.subpath
2527
+ };
2528
+ })();
2529
+ const managedState = upsertManagedEntry(managedStateRead.state, {
2530
+ name: validated.manifest.name,
2531
+ directory: candidate.directory,
2532
+ scope,
2533
+ manifest_version: validated.manifest.version,
2534
+ manifest_entry: validated.manifest.entry,
2535
+ capabilities: [...validated.manifest.capabilities],
2536
+ installed_at: now,
2537
+ updated_at: now,
2538
+ source: sourceRecord
2539
+ });
2540
+ await writeManagedExtensionState(resolvedRoots.selected_root, managedState);
2541
+ const refreshedInstalled = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedState);
2542
+ warnings.push(...refreshedInstalled.warnings);
2543
+ const refreshedEntry = refreshedInstalled.extensions.find((entry) => normalizeExtensionNameForMatch(entry.name) === normalizeExtensionNameForMatch(validated.manifest.name)) ?? refreshedInstalled.extensions.find((entry) => normalizeExtensionNameForMatch(entry.directory) === normalizeExtensionNameForMatch(candidate.directory));
2544
+ return withResult({
2545
+ adopted: true,
2546
+ extension: {
2547
+ name: validated.manifest.name,
2548
+ directory: candidate.directory,
2549
+ version: validated.manifest.version,
2550
+ entry: validated.manifest.entry
2551
+ },
2552
+ source: sourceRecord,
2553
+ update_check_status: refreshedEntry?.update_check_status ?? null,
2554
+ update_check_reason: refreshedEntry?.update_check_reason ?? null
2555
+ });
2556
+ }
2557
+ if (action === "uninstall") {
2558
+ const extensionTarget = requireTarget(normalizedTarget, action);
2559
+ const settings = await readSettings(resolvedRoots.settings_root);
2560
+ const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);
2561
+ warnings.push(...managedStateRead.warnings);
2562
+ const installed = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedStateRead.state);
2563
+ warnings.push(...installed.warnings);
2564
+ const candidate = await resolveInstalledExtensionCandidate(installed.extensions, extensionTarget);
2565
+ if (!candidate) {
2566
+ throw new PmCliError(`Installed extension "${extensionTarget}" was not found in ${scope} scope.`, EXIT_CODE.NOT_FOUND);
2567
+ }
2568
+ const destinationDirectory = path7.join(resolvedRoots.selected_root, candidate.directory);
2569
+ await fs7.rm(destinationDirectory, { recursive: true, force: true });
2570
+ const updatedState = {
2571
+ ...managedStateRead.state,
2572
+ updated_at: nowIso(),
2573
+ entries: managedStateRead.state.entries.filter((entry) => normalizeExtensionNameForMatch(entry.name) !== normalizeExtensionNameForMatch(candidate.name) && normalizeExtensionNameForMatch(entry.directory) !== normalizeExtensionNameForMatch(candidate.directory))
2574
+ };
2575
+ await writeManagedExtensionState(resolvedRoots.selected_root, updatedState);
2576
+ const stateChanged = clearExtensionState(settings, candidate.name);
2577
+ if (stateChanged) {
2578
+ await writeSettings(resolvedRoots.settings_root, settings, "settings:write");
2579
+ }
2580
+ return withResult({
2581
+ removed: true,
2582
+ extension: {
2583
+ name: candidate.name,
2584
+ directory: candidate.directory
2585
+ },
2586
+ destination_path: destinationDirectory,
2587
+ settings_changed: stateChanged
2588
+ });
2589
+ }
2590
+ if (action === "activate" || action === "deactivate") {
2591
+ const extensionTarget = requireTarget(normalizedTarget, action);
2592
+ const settings = await readSettings(resolvedRoots.settings_root);
2593
+ const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);
2594
+ warnings.push(...managedStateRead.warnings);
2595
+ const installed = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedStateRead.state);
2596
+ warnings.push(...installed.warnings);
2597
+ const candidate = await resolveInstalledExtensionCandidate(installed.extensions, extensionTarget);
2598
+ if (!candidate) {
2599
+ throw new PmCliError(`Installed extension "${extensionTarget}" was not found in ${scope} scope.`, EXIT_CODE.NOT_FOUND);
2600
+ }
2601
+ const settingsChanged = action === "activate" ? ensureActivated(settings, candidate.name) : ensureDeactivated(settings, candidate.name);
2602
+ if (settingsChanged) {
2603
+ await writeSettings(resolvedRoots.settings_root, settings, "settings:write");
2604
+ }
2605
+ return withResult({
2606
+ extension: {
2607
+ name: candidate.name,
2608
+ directory: candidate.directory
2609
+ },
2610
+ active: action === "activate",
2611
+ settings_changed: settingsChanged,
2612
+ settings: {
2613
+ enabled: [...settings.extensions.enabled],
2614
+ disabled: [...settings.extensions.disabled]
2615
+ }
2616
+ });
2617
+ }
2618
+ if (action === "doctor") {
2619
+ if (normalizedTarget && normalizedTarget.trim().length > 0) {
2620
+ throw new PmCliError('Action "doctor" does not accept a target argument.', EXIT_CODE.USAGE);
2621
+ }
2622
+ const detailMode = parseDoctorDetailMode(options.detail);
2623
+ const includeTrace = options.trace === true;
2624
+ if (includeTrace && detailMode !== "deep") {
2625
+ throw new PmCliError("--trace requires --detail deep with --doctor.", EXIT_CODE.USAGE);
2626
+ }
2627
+ const settings = await readSettings(resolvedRoots.settings_root);
2628
+ const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);
2629
+ warnings.push(...managedStateRead.warnings);
2630
+ const installed = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedStateRead.state);
2631
+ warnings.push(...installed.warnings);
2632
+ let managedState = managedStateRead.state;
2633
+ const managedStateFix = options.fixManagedState === true ? await adoptUnmanagedExtensions(resolvedRoots.selected_root, scope, installed.extensions, managedStateRead.state) : null;
2634
+ if (managedStateFix) {
2635
+ managedState = managedStateFix.state;
2636
+ }
2637
+ const refreshedInstalled = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedState);
2638
+ warnings.push(...refreshedInstalled.warnings);
2639
+ const loadResult = await loadExtensions({
2640
+ pmRoot: resolvedRoots.pm_root,
2641
+ settings,
2642
+ cwd: process.cwd(),
2643
+ noExtensions: global2.noExtensions === true
2644
+ });
2645
+ const activationResult = await activateExtensions({
2646
+ ...loadResult,
2647
+ loaded: loadResult.loaded
2648
+ });
2649
+ warnings.push(...loadResult.warnings);
2650
+ warnings.push(...classifyDoctorLoadFailureWarnings(loadResult.failed));
2651
+ warnings.push(...activationResult.warnings);
2652
+ const runtimeInstalledExtensions = applyDoctorRuntimeActivationState(refreshedInstalled.extensions, loadResult, activationResult);
2653
+ const doctorConsistency = buildDoctorConsistencySummary(scope, runtimeInstalledExtensions, loadResult.loaded.map((entry) => ({ layer: entry.layer, name: entry.name })), loadResult.failed.map((entry) => ({ name: entry.name })), loadResult.disabled_by_flag);
2654
+ warnings.push(...doctorConsistency.warnings);
2655
+ const updateCheckWarnings = runtimeInstalledExtensions.filter((entry) => entry.update_check_status === "failed").map((entry) => `extension_update_check_failed:${entry.name}`);
2656
+ warnings.push(...updateCheckWarnings);
2657
+ const triage = buildExtensionTriageSummary(scope, warnings, runtimeInstalledExtensions, options);
2658
+ warnings.push(...triage.warnings);
2659
+ const normalizedWarnings = [...triage.warnings];
2660
+ const policySummary = {
2661
+ mode: loadResult.policy.mode,
2662
+ trust_mode: loadResult.policy.trust_mode,
2663
+ require_provenance: loadResult.policy.require_provenance,
2664
+ default_sandbox_profile: loadResult.policy.default_sandbox_profile,
2665
+ trusted_extensions_count: loadResult.policy.trusted_extensions.length,
2666
+ allowed_extensions_count: loadResult.policy.allowed_extensions.length,
2667
+ blocked_extensions_count: loadResult.policy.blocked_extensions.length,
2668
+ allowed_capabilities_count: loadResult.policy.allowed_capabilities.length,
2669
+ blocked_capabilities_count: loadResult.policy.blocked_capabilities.length,
2670
+ allowed_surfaces_count: loadResult.policy.allowed_surfaces.length,
2671
+ blocked_surfaces_count: loadResult.policy.blocked_surfaces.length,
2672
+ allowed_commands_count: loadResult.policy.allowed_commands.length,
2673
+ blocked_commands_count: loadResult.policy.blocked_commands.length,
2674
+ allowed_actions_count: loadResult.policy.allowed_actions.length,
2675
+ blocked_actions_count: loadResult.policy.blocked_actions.length,
2676
+ allowed_services_count: loadResult.policy.allowed_services.length,
2677
+ blocked_services_count: loadResult.policy.blocked_services.length,
2678
+ extension_override_count: loadResult.policy.extension_overrides.length
2679
+ };
2680
+ const capabilityGuidance = collectUnknownCapabilityGuidance(normalizedWarnings);
2681
+ const capabilityContract = buildCapabilityContractMetadata();
2682
+ const warningCodes = triage.warning_codes;
2683
+ const remediation = [
2684
+ ...new Set([
2685
+ ...triage.remediation,
2686
+ ...loadResult.failed.length > 0 ? [
2687
+ options.vocabulary === "package" ? "Run pm package explore --project and pm package explore --global to inspect load failures." : "Run pm extension --explore --project and pm extension --explore --global to inspect load failures."
2688
+ ] : [],
2689
+ ...activationResult.failed.length > 0 ? [
2690
+ options.vocabulary === "package" ? "Review activation failures in pm package doctor --detail deep output." : "Review activation failures in pm extension --doctor --detail deep output."
2691
+ ] : [],
2692
+ ...managedStateFix && managedStateFix.adopted_entries.length > 0 ? [`Managed-state fix adopted ${managedStateFix.adopted_entries.length} extension(s).`] : []
2693
+ ].map((entry) => entry.trim()).filter((entry) => entry.length > 0))
2694
+ ];
2695
+ const summary = {
2696
+ status: triage.status,
2697
+ scope,
2698
+ warning_count: triage.warning_count,
2699
+ warning_codes: warningCodes,
2700
+ total_extensions: runtimeInstalledExtensions.length,
2701
+ managed_total: runtimeInstalledExtensions.filter((entry) => entry.managed).length,
2702
+ enabled_total: runtimeInstalledExtensions.filter((entry) => entry.enabled).length,
2703
+ active_total: runtimeInstalledExtensions.filter((entry) => entry.active).length,
2704
+ unmanaged_loaded_extension_count: triage.unmanaged_loaded_extension_count,
2705
+ unmanaged_action_required_extension_count: triage.unmanaged_action_required_extension_count,
2706
+ unmanaged_expected_extension_count: triage.unmanaged_expected_extension_count,
2707
+ runtime_active_total: runtimeInstalledExtensions.filter((entry) => entry.runtime_active === true).length,
2708
+ activation_status_totals: {
2709
+ ok: runtimeInstalledExtensions.filter((entry) => entry.activation_status === "ok").length,
2710
+ failed: runtimeInstalledExtensions.filter((entry) => entry.activation_status === "failed").length,
2711
+ not_loaded: runtimeInstalledExtensions.filter((entry) => entry.activation_status === "not_loaded").length,
2712
+ unknown: runtimeInstalledExtensions.filter((entry) => entry.activation_status === "unknown").length
2713
+ },
2714
+ unknown_capability_count: capabilityGuidance.length,
2715
+ capability_contract_version: capabilityContract.version,
2716
+ update_available_total: runtimeInstalledExtensions.filter((entry) => entry.update_available === true).length,
2717
+ update_health_coverage: triage.update_health_coverage,
2718
+ update_health_partial: triage.update_health_partial,
2719
+ update_check_failed_total: runtimeInstalledExtensions.filter((entry) => entry.update_check_status === "failed").length,
2720
+ load_failure_count: loadResult.failed.length,
2721
+ activation_failure_count: activationResult.failed.length,
2722
+ blocking_failure_count: loadResult.failed.length + activationResult.failed.length,
2723
+ has_blocking_failures: loadResult.failed.length + activationResult.failed.length > 0,
2724
+ consistency_warning_count: doctorConsistency.warnings.length,
2725
+ trace_enabled: includeTrace,
2726
+ policy: policySummary,
2727
+ remediation
2728
+ };
2729
+ const managedStateFixSummary = managedStateFix ? {
2730
+ requested: true,
2731
+ applied: managedStateFix.adopted_entries.length > 0,
2732
+ adopted_count: managedStateFix.adopted_entries.length,
2733
+ already_managed_count: managedStateFix.already_managed_count,
2734
+ adopted_extensions: managedStateFix.adopted_entries.map((entry) => entry.name)
2735
+ } : {
2736
+ requested: false,
2737
+ applied: false,
2738
+ adopted_count: 0,
2739
+ already_managed_count: refreshedInstalled.extensions.filter((entry) => entry.managed).length,
2740
+ adopted_extensions: []
2741
+ };
2742
+ const details = {
2743
+ mode: detailMode,
2744
+ summary,
2745
+ triage,
2746
+ trace_enabled: includeTrace,
2747
+ capability_contract: capabilityContract,
2748
+ capability_guidance: capabilityGuidance,
2749
+ managed_state_fix: managedStateFixSummary,
2750
+ policy: loadResult.policy
2751
+ };
2752
+ if (detailMode === "deep") {
2753
+ const activationFailedDetails = includeTrace ? activationResult.failed : activationResult.failed.map((entry) => {
2754
+ const { trace: _trace, ...rest } = entry;
2755
+ return rest;
2756
+ });
2757
+ details.deep = {
2758
+ warnings: normalizedWarnings,
2759
+ warning_codes: warningCodes,
2760
+ capability_contract: capabilityContract,
2761
+ capability_guidance: capabilityGuidance,
2762
+ trace_enabled: includeTrace,
2763
+ managed_state: {
2764
+ path: managedStateRead.path,
2765
+ count: managedState.entries.length,
2766
+ entries: managedState.entries
2767
+ },
2768
+ installed_extensions: runtimeInstalledExtensions,
2769
+ load: {
2770
+ roots: loadResult.roots,
2771
+ policy: loadResult.policy,
2772
+ warnings: loadResult.warnings,
2773
+ failed: loadResult.failed,
2774
+ loaded: loadResult.loaded.map((entry) => ({
2775
+ layer: entry.layer,
2776
+ directory: entry.directory,
2777
+ name: entry.name,
2778
+ version: entry.version,
2779
+ entry: entry.entry,
2780
+ priority: entry.priority
2781
+ }))
2782
+ },
2783
+ activation: {
2784
+ failed: activationFailedDetails,
2785
+ warnings: activationResult.warnings,
2786
+ hook_counts: activationResult.hook_counts,
2787
+ registration_counts: activationResult.registration_counts,
2788
+ parser_override_count: activationResult.parser_override_count,
2789
+ preflight_override_count: activationResult.preflight_override_count,
2790
+ service_override_count: activationResult.service_override_count,
2791
+ renderer_override_count: activationResult.renderer_override_count
2792
+ },
2793
+ consistency: doctorConsistency.summary
2794
+ };
2795
+ if (includeTrace) {
2796
+ details.deep.trace = {
2797
+ activation_failures: activationResult.failed.filter((entry) => entry.trace !== void 0).map((entry) => ({
2798
+ layer: entry.layer,
2799
+ name: entry.name,
2800
+ entry_path: entry.entry_path,
2801
+ error: entry.error,
2802
+ method: entry.trace?.method,
2803
+ command: entry.trace?.command,
2804
+ registration_index: entry.trace?.registration_index,
2805
+ expected_schema: entry.trace?.expected_schema,
2806
+ hint: entry.trace?.hint,
2807
+ received: entry.trace?.received
2808
+ }))
2809
+ };
2810
+ }
2811
+ }
2812
+ return withResult(details);
2813
+ }
2814
+ if (action === "explore" || action === "manage") {
2815
+ const settings = await readSettings(resolvedRoots.settings_root);
2816
+ const configuredPolicy = buildExtensionPolicyDetails(settings.extensions.policy);
2817
+ const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);
2818
+ warnings.push(...managedStateRead.warnings);
2819
+ const installed = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedStateRead.state);
2820
+ warnings.push(...installed.warnings);
2821
+ let managedState = managedStateRead.state;
2822
+ const managedStateFix = action === "manage" && options.fixManagedState === true ? await adoptUnmanagedExtensions(resolvedRoots.selected_root, scope, installed.extensions, managedStateRead.state) : null;
2823
+ if (managedStateFix) {
2824
+ managedState = managedStateFix.state;
2825
+ }
2826
+ if (action === "manage") {
2827
+ const updates = await Promise.all(managedState.entries.map(async (entry) => {
2828
+ if (entry.source.kind !== "github") {
2829
+ return entry;
2830
+ }
2831
+ const updateStatus = await checkGithubUpdate(entry.source);
2832
+ return {
2833
+ ...entry,
2834
+ last_update_check_at: updateStatus.checked_at,
2835
+ last_update_remote_commit: updateStatus.remote_commit,
2836
+ update_available: updateStatus.available,
2837
+ update_error: updateStatus.error
2838
+ };
2839
+ }));
2840
+ managedState = {
2841
+ ...managedState,
2842
+ updated_at: nowIso(),
2843
+ entries: sortManagedEntries(updates)
2844
+ };
2845
+ await writeManagedExtensionState(resolvedRoots.selected_root, managedState);
2846
+ }
2847
+ const refreshedInstalled = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedState);
2848
+ warnings.push(...refreshedInstalled.warnings);
2849
+ if (action === "manage") {
2850
+ const updateWarnings = refreshedInstalled.extensions.filter((entry) => entry.update_check_status === "failed").map((entry) => `extension_update_check_failed:${entry.name}`);
2851
+ warnings.push(...updateWarnings);
2852
+ }
2853
+ let runtimeProbeSummary;
2854
+ let runtimeInstalledExtensions = refreshedInstalled.extensions;
2855
+ if (action === "explore" || options.runtimeProbe === true) {
2856
+ const loadResult = await loadExtensions({
2857
+ pmRoot: resolvedRoots.pm_root,
2858
+ settings,
2859
+ cwd: process.cwd(),
2860
+ noExtensions: global2.noExtensions === true
2861
+ });
2862
+ const activationResult = await activateExtensions({
2863
+ ...loadResult,
2864
+ loaded: loadResult.loaded
2865
+ });
2866
+ warnings.push(...loadResult.warnings);
2867
+ warnings.push(...activationResult.warnings);
2868
+ runtimeInstalledExtensions = applyDoctorRuntimeActivationState(refreshedInstalled.extensions, loadResult, activationResult);
2869
+ runtimeProbeSummary = {
2870
+ requested: true,
2871
+ executed: true,
2872
+ reason: action === "explore" ? "explore_defaults_to_runtime_probe" : "runtime_probe_requested",
2873
+ load_failure_count: loadResult.failed.length,
2874
+ activation_failure_count: activationResult.failed.length,
2875
+ warning_count: [.../* @__PURE__ */ new Set([...loadResult.warnings, ...activationResult.warnings])].length,
2876
+ policy: loadResult.policy
2877
+ };
2878
+ } else if (action === "manage") {
2879
+ runtimeProbeSummary = {
2880
+ requested: false,
2881
+ executed: false
2882
+ };
2883
+ }
2884
+ const triage = buildExtensionTriageSummary(scope, warnings, runtimeInstalledExtensions, options);
2885
+ warnings.push(...triage.warnings);
2886
+ const details = {
2887
+ total: runtimeInstalledExtensions.length,
2888
+ managed_total: runtimeInstalledExtensions.filter((entry) => entry.managed).length,
2889
+ enabled_total: runtimeInstalledExtensions.filter((entry) => entry.enabled).length,
2890
+ active_total: runtimeInstalledExtensions.filter((entry) => entry.active).length,
2891
+ extensions: runtimeInstalledExtensions,
2892
+ triage,
2893
+ policy: configuredPolicy
2894
+ };
2895
+ if (action === "explore") {
2896
+ details.runtime_probe = runtimeProbeSummary;
2897
+ }
2898
+ if (action === "manage") {
2899
+ details.runtime_probe = runtimeProbeSummary;
2900
+ details.managed_state_fix = managedStateFix !== null ? {
2901
+ requested: true,
2902
+ applied: managedStateFix.adopted_entries.length > 0,
2903
+ adopted_count: managedStateFix.adopted_entries.length,
2904
+ adopted_extensions: managedStateFix.adopted_entries.map((entry) => entry.name),
2905
+ already_managed_count: managedStateFix.already_managed_count
2906
+ } : {
2907
+ requested: false,
2908
+ applied: false,
2909
+ adopted_count: 0,
2910
+ adopted_extensions: [],
2911
+ already_managed_count: runtimeInstalledExtensions.filter((entry) => entry.managed).length
2912
+ };
2913
+ }
2914
+ return withResult(details);
2915
+ }
2916
+ throw new PmCliError(`Unsupported extension action "${action}".`, EXIT_CODE.USAGE);
2917
+ }
2918
+
2919
+ export {
2920
+ parseExtensionManifest,
2921
+ validateExtensionDirectory,
2922
+ resolveManagedExtensionStatePath,
2923
+ readManagedExtensionState,
2924
+ writeManagedExtensionState,
2925
+ parseExtensionInstallSource,
2926
+ copyExtensionDirectoryForInstall,
2927
+ runExtension
2928
+ };
2929
+ //# sourceMappingURL=chunk-OGZEG5TT.js.map