@lesliechan721/aw 0.1.0-beta.10 → 0.1.0-beta.100

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 (820) hide show
  1. package/dist/authoring/assets/aw-config.d.mts +1 -50
  2. package/dist/authoring/assets/aw-config.mjs +58 -928
  3. package/dist/authoring/assets/aw-config.mjs.map +1 -1
  4. package/dist/authoring/assets/aw-runtime-config.d.mts +13 -0
  5. package/dist/authoring/assets/aw-runtime-config.mjs +221 -0
  6. package/dist/authoring/assets/aw-runtime-config.mjs.map +1 -0
  7. package/dist/authoring/assets/command-runtime-config.d.mts +9 -0
  8. package/dist/authoring/assets/command-runtime-config.mjs +134 -0
  9. package/dist/authoring/assets/command-runtime-config.mjs.map +1 -0
  10. package/dist/authoring/scripts/add-skill.mjs +16 -39
  11. package/dist/authoring/scripts/add-skill.mjs.map +1 -1
  12. package/dist/authoring/scripts/init-plugin.mjs +43 -71
  13. package/dist/authoring/scripts/init-plugin.mjs.map +1 -1
  14. package/dist/authoring/scripts/lib/plugin-root.mjs +4 -4
  15. package/dist/authoring/scripts/lib/plugin-root.mjs.map +1 -1
  16. package/dist/authoring/scripts/lib/plugin-version-check.d.mts +1 -0
  17. package/dist/authoring/scripts/lib/plugin-version-check.mjs +230 -9
  18. package/dist/authoring/scripts/lib/plugin-version-check.mjs.map +1 -1
  19. package/dist/authoring/scripts/lib/skill-scaffold.d.mts +3 -3
  20. package/dist/authoring/scripts/lib/skill-scaffold.mjs +5 -8
  21. package/dist/authoring/scripts/lib/skill-scaffold.mjs.map +1 -1
  22. package/dist/authoring/scripts/remove-plugin.mjs +1 -1
  23. package/dist/authoring/scripts/remove-plugin.mjs.map +1 -1
  24. package/dist/authoring/scripts/validate-plugin.mjs +408 -1748
  25. package/dist/authoring/scripts/validate-plugin.mjs.map +1 -1
  26. package/dist/authoring/scripts/validate-skill.mjs +1 -1
  27. package/dist/index.js +2 -6
  28. package/dist/index.js.map +1 -1
  29. package/dist/native-runtime/reader-runtime.mjs +34 -0
  30. package/dist/native-runtime/reader.d.mts +6 -0
  31. package/dist/native-runtime/reader.mjs +11 -0
  32. package/dist/scripts/aw-skill-eval-materializer.d.ts +11 -1
  33. package/dist/scripts/aw-skill-eval-materializer.js +119 -114
  34. package/dist/scripts/aw-skill-eval-materializer.js.map +1 -1
  35. package/dist/scripts/bundle-plugins.js +32 -7
  36. package/dist/scripts/bundle-plugins.js.map +1 -1
  37. package/dist/scripts/plugin-staging.d.ts +1 -1
  38. package/dist/scripts/plugin-staging.js +5 -2
  39. package/dist/scripts/plugin-staging.js.map +1 -1
  40. package/dist/scripts/plugin-test-context-guard.d.mts +1 -0
  41. package/dist/scripts/plugin-test-context-guard.mjs +59 -0
  42. package/dist/scripts/plugin-test-context-guard.mjs.map +1 -0
  43. package/dist/scripts/plugin-test-reporter.d.mts +2 -0
  44. package/dist/scripts/plugin-test-reporter.mjs +21 -0
  45. package/dist/scripts/plugin-test-reporter.mjs.map +1 -0
  46. package/dist/scripts/test-plugin-scripts.d.ts +5 -0
  47. package/dist/scripts/test-plugin-scripts.js +343 -58
  48. package/dist/scripts/test-plugin-scripts.js.map +1 -1
  49. package/dist/scripts/test-workers.d.mts +24 -0
  50. package/dist/scripts/test-workers.mjs +59 -0
  51. package/dist/scripts/test-workers.mjs.map +1 -0
  52. package/dist/src/adapters/helpers.d.ts +7 -0
  53. package/dist/src/adapters/helpers.js.map +1 -1
  54. package/dist/src/authoring/workspace-commands.d.ts +3 -0
  55. package/dist/src/authoring/workspace-commands.js +7 -2
  56. package/dist/src/authoring/workspace-commands.js.map +1 -1
  57. package/dist/src/commands/aw-capabilities.d.ts +1 -1
  58. package/dist/src/commands/aw-capabilities.js +48 -19
  59. package/dist/src/commands/aw-capabilities.js.map +1 -1
  60. package/dist/src/commands/catalog-dev-source.d.ts +40 -3
  61. package/dist/src/commands/catalog-dev-source.js +333 -42
  62. package/dist/src/commands/catalog-dev-source.js.map +1 -1
  63. package/dist/src/commands/catalog-generation.d.ts +5 -0
  64. package/dist/src/commands/catalog-generation.js.map +1 -1
  65. package/dist/src/commands/catalog-publication-inspection.d.ts +11 -3
  66. package/dist/src/commands/catalog-publication-inspection.js +211 -59
  67. package/dist/src/commands/catalog-publication-inspection.js.map +1 -1
  68. package/dist/src/commands/catalog-publication-journal.d.ts +12 -0
  69. package/dist/src/commands/catalog-publication-journal.js +78 -1
  70. package/dist/src/commands/catalog-publication-journal.js.map +1 -1
  71. package/dist/src/commands/catalog-publish.d.ts +21 -1
  72. package/dist/src/commands/catalog-publish.js +133 -92
  73. package/dist/src/commands/catalog-publish.js.map +1 -1
  74. package/dist/src/commands/catalog-source.d.ts +25 -5
  75. package/dist/src/commands/catalog-source.js +153 -27
  76. package/dist/src/commands/catalog-source.js.map +1 -1
  77. package/dist/src/commands/catalog-status.js +2 -2
  78. package/dist/src/commands/catalog-status.js.map +1 -1
  79. package/dist/src/commands/catalog-store.d.ts +31 -7
  80. package/dist/src/commands/catalog-store.js +379 -42
  81. package/dist/src/commands/catalog-store.js.map +1 -1
  82. package/dist/src/commands/catalog-workspace-resolution.d.ts +4 -0
  83. package/dist/src/commands/catalog-workspace-resolution.js +18 -3
  84. package/dist/src/commands/catalog-workspace-resolution.js.map +1 -1
  85. package/dist/src/commands/console.js +33 -20
  86. package/dist/src/commands/console.js.map +1 -1
  87. package/dist/src/commands/dependency-operation-plan.d.ts +7 -0
  88. package/dist/src/commands/dependency-operation-plan.js +66 -30
  89. package/dist/src/commands/dependency-operation-plan.js.map +1 -1
  90. package/dist/src/commands/deployment-confirmation.d.ts +11 -0
  91. package/dist/src/commands/deployment-confirmation.js +101 -0
  92. package/dist/src/commands/deployment-confirmation.js.map +1 -0
  93. package/dist/src/commands/init.js +1 -1
  94. package/dist/src/commands/init.js.map +1 -1
  95. package/dist/src/commands/intent-command.d.ts +34 -0
  96. package/dist/src/commands/intent-command.js +174 -0
  97. package/dist/src/commands/intent-command.js.map +1 -0
  98. package/dist/src/commands/lifecycle-command-package.d.ts +45 -0
  99. package/dist/src/commands/lifecycle-command-package.js +199 -0
  100. package/dist/src/commands/lifecycle-command-package.js.map +1 -0
  101. package/dist/src/commands/managed-commands.d.ts +41 -0
  102. package/dist/src/commands/managed-commands.js +404 -0
  103. package/dist/src/commands/managed-commands.js.map +1 -0
  104. package/dist/src/commands/offline-cleanup-evidence.d.ts +12 -2
  105. package/dist/src/commands/offline-cleanup-evidence.js +57 -35
  106. package/dist/src/commands/offline-cleanup-evidence.js.map +1 -1
  107. package/dist/src/commands/operation-plan.d.ts +72 -2
  108. package/dist/src/commands/operation-plan.js +54 -3
  109. package/dist/src/commands/operation-plan.js.map +1 -1
  110. package/dist/src/commands/operation-planner.d.ts +6 -5
  111. package/dist/src/commands/operation-planner.js +23 -20
  112. package/dist/src/commands/operation-planner.js.map +1 -1
  113. package/dist/src/commands/options.d.ts +11 -16
  114. package/dist/src/commands/options.js +31 -25
  115. package/dist/src/commands/options.js.map +1 -1
  116. package/dist/src/commands/permission-batch.d.ts +5 -0
  117. package/dist/src/commands/permission-batch.js +83 -0
  118. package/dist/src/commands/permission-batch.js.map +1 -0
  119. package/dist/src/commands/plugin-capabilities.js +128 -58
  120. package/dist/src/commands/plugin-capabilities.js.map +1 -1
  121. package/dist/src/commands/public-config-confirmation.d.ts +14 -0
  122. package/dist/src/commands/public-config-confirmation.js +73 -0
  123. package/dist/src/commands/public-config-confirmation.js.map +1 -0
  124. package/dist/src/commands/public-interruption.d.ts +9 -0
  125. package/dist/src/commands/public-interruption.js +23 -0
  126. package/dist/src/commands/public-interruption.js.map +1 -0
  127. package/dist/src/commands/public-lifecycle-result.d.ts +106 -0
  128. package/dist/src/commands/public-lifecycle-result.js +536 -0
  129. package/dist/src/commands/public-lifecycle-result.js.map +1 -0
  130. package/dist/src/commands/public-lifecycle.d.ts +27 -0
  131. package/dist/src/commands/public-lifecycle.js +569 -0
  132. package/dist/src/commands/public-lifecycle.js.map +1 -0
  133. package/dist/src/commands/public-plugin-query.d.ts +16 -0
  134. package/dist/src/commands/public-plugin-query.js +231 -0
  135. package/dist/src/commands/public-plugin-query.js.map +1 -0
  136. package/dist/src/commands/rebuild-command.d.ts +177 -16
  137. package/dist/src/commands/rebuild-command.js +3370 -1559
  138. package/dist/src/commands/rebuild-command.js.map +1 -1
  139. package/dist/src/commands/rebuild-integration.d.ts +100 -55
  140. package/dist/src/commands/rebuild-integration.js +866 -3275
  141. package/dist/src/commands/rebuild-integration.js.map +1 -1
  142. package/dist/src/commands/rebuild-operations.d.ts +68 -13
  143. package/dist/src/commands/rebuild-operations.js +309 -120
  144. package/dist/src/commands/rebuild-operations.js.map +1 -1
  145. package/dist/src/commands/rebuild-platform-integration.d.ts +99 -0
  146. package/dist/src/commands/rebuild-platform-integration.js +2329 -0
  147. package/dist/src/commands/rebuild-platform-integration.js.map +1 -0
  148. package/dist/src/commands/reconcile-operation-plan.d.ts +14 -9
  149. package/dist/src/commands/reconcile-operation-plan.js +26 -6
  150. package/dist/src/commands/reconcile-operation-plan.js.map +1 -1
  151. package/dist/src/commands/review-inspection.d.ts +60 -0
  152. package/dist/src/commands/review-inspection.js +437 -0
  153. package/dist/src/commands/review-inspection.js.map +1 -0
  154. package/dist/src/commands/review-preparation.d.ts +51 -0
  155. package/dist/src/commands/review-preparation.js +400 -0
  156. package/dist/src/commands/review-preparation.js.map +1 -0
  157. package/dist/src/commands/runtime.d.ts +5 -1
  158. package/dist/src/commands/runtime.js +41 -8
  159. package/dist/src/commands/runtime.js.map +1 -1
  160. package/dist/src/commands/skill-eval.d.ts +8 -0
  161. package/dist/src/commands/skill-eval.js +126 -73
  162. package/dist/src/commands/skill-eval.js.map +1 -1
  163. package/dist/src/commands/status-v6.d.ts +148 -35
  164. package/dist/src/commands/status-v6.js +1166 -307
  165. package/dist/src/commands/status-v6.js.map +1 -1
  166. package/dist/src/commands/targets-command.d.ts +38 -0
  167. package/dist/src/commands/targets-command.js +182 -0
  168. package/dist/src/commands/targets-command.js.map +1 -0
  169. package/dist/src/commands/wizard.d.ts +7 -3
  170. package/dist/src/commands/wizard.js +7 -4
  171. package/dist/src/commands/wizard.js.map +1 -1
  172. package/dist/src/commands/write-commands.d.ts +7 -1
  173. package/dist/src/commands/write-commands.js +129 -38
  174. package/dist/src/commands/write-commands.js.map +1 -1
  175. package/dist/src/constants.d.ts +2 -3
  176. package/dist/src/constants.js +2 -3
  177. package/dist/src/constants.js.map +1 -1
  178. package/dist/src/eval/manifest-v1.d.ts +6 -3
  179. package/dist/src/eval/manifest-v1.js +44 -33
  180. package/dist/src/eval/manifest-v1.js.map +1 -1
  181. package/dist/src/generators/local-plugin.d.ts +4 -2
  182. package/dist/src/generators/local-plugin.js +319 -353
  183. package/dist/src/generators/local-plugin.js.map +1 -1
  184. package/dist/src/generators/permissions.d.ts +20 -2
  185. package/dist/src/generators/permissions.js +82 -15
  186. package/dist/src/generators/permissions.js.map +1 -1
  187. package/dist/src/index.d.ts +2 -33
  188. package/dist/src/index.js +1575 -1919
  189. package/dist/src/index.js.map +1 -1
  190. package/dist/src/intent/deployment-preferences.d.ts +63 -0
  191. package/dist/src/intent/deployment-preferences.js +170 -0
  192. package/dist/src/intent/deployment-preferences.js.map +1 -0
  193. package/dist/src/intent/diagnostics.d.ts +11 -0
  194. package/dist/src/intent/diagnostics.js +14 -0
  195. package/dist/src/intent/diagnostics.js.map +1 -0
  196. package/dist/src/intent/intent-codec.d.ts +19 -0
  197. package/dist/src/intent/intent-codec.js +117 -0
  198. package/dist/src/intent/intent-codec.js.map +1 -0
  199. package/dist/src/intent/intent-store.d.ts +43 -0
  200. package/dist/src/intent/intent-store.js +118 -0
  201. package/dist/src/intent/intent-store.js.map +1 -0
  202. package/dist/src/intent/scope-context.d.ts +35 -0
  203. package/dist/src/intent/scope-context.js +179 -0
  204. package/dist/src/intent/scope-context.js.map +1 -0
  205. package/dist/src/intent/work-context.d.ts +13 -0
  206. package/dist/src/intent/work-context.js +22 -0
  207. package/dist/src/intent/work-context.js.map +1 -0
  208. package/dist/src/output/command-receipt.d.ts +6 -2
  209. package/dist/src/output/command-receipt.js +67 -32
  210. package/dist/src/output/command-receipt.js.map +1 -1
  211. package/dist/src/output/component-delivery.d.ts +28 -0
  212. package/dist/src/output/component-delivery.js +141 -0
  213. package/dist/src/output/component-delivery.js.map +1 -0
  214. package/dist/src/output/public-result.d.ts +69 -0
  215. package/dist/src/output/public-result.js +403 -0
  216. package/dist/src/output/public-result.js.map +1 -0
  217. package/dist/src/output/rebuild-progress.d.ts +3 -0
  218. package/dist/src/output/rebuild-progress.js +34 -9
  219. package/dist/src/output/rebuild-progress.js.map +1 -1
  220. package/dist/src/output/receipt-projection.d.ts +7 -0
  221. package/dist/src/output/receipt-projection.js +664 -0
  222. package/dist/src/output/receipt-projection.js.map +1 -0
  223. package/dist/src/output/skill-invocation-notices.d.ts +18 -0
  224. package/dist/src/output/skill-invocation-notices.js +84 -0
  225. package/dist/src/output/skill-invocation-notices.js.map +1 -0
  226. package/dist/src/platforms/antigravity-permissions.d.ts +50 -0
  227. package/dist/src/platforms/antigravity-permissions.js +388 -0
  228. package/dist/src/platforms/antigravity-permissions.js.map +1 -0
  229. package/dist/src/platforms/capabilities.d.ts +9 -0
  230. package/dist/src/platforms/capabilities.js +125 -0
  231. package/dist/src/platforms/capabilities.js.map +1 -0
  232. package/dist/src/platforms/contracts.d.ts +394 -0
  233. package/dist/src/platforms/contracts.js +2 -0
  234. package/dist/src/platforms/contracts.js.map +1 -0
  235. package/dist/src/platforms/cursor-workspace-hook.d.ts +28 -0
  236. package/dist/src/platforms/cursor-workspace-hook.js +198 -0
  237. package/dist/src/platforms/cursor-workspace-hook.js.map +1 -0
  238. package/dist/src/platforms/discovery.d.ts +100 -0
  239. package/dist/src/platforms/discovery.js +779 -0
  240. package/dist/src/platforms/discovery.js.map +1 -0
  241. package/dist/src/platforms/grok-permission-config.d.ts +23 -0
  242. package/dist/src/platforms/grok-permission-config.js +184 -0
  243. package/dist/src/platforms/grok-permission-config.js.map +1 -0
  244. package/dist/src/platforms/grok-permission-document.d.ts +4 -0
  245. package/dist/src/platforms/grok-permission-document.js +145 -0
  246. package/dist/src/platforms/grok-permission-document.js.map +1 -0
  247. package/dist/src/platforms/grok-permissions.d.ts +17 -0
  248. package/dist/src/platforms/grok-permissions.js +311 -0
  249. package/dist/src/platforms/grok-permissions.js.map +1 -0
  250. package/dist/src/platforms/host-permission-policy.d.ts +38 -0
  251. package/dist/src/platforms/host-permission-policy.js +86 -0
  252. package/dist/src/platforms/host-permission-policy.js.map +1 -0
  253. package/dist/src/platforms/identity.d.ts +4 -0
  254. package/dist/src/platforms/identity.js +22 -0
  255. package/dist/src/platforms/identity.js.map +1 -0
  256. package/dist/src/platforms/inspection-grok.d.ts +4 -0
  257. package/dist/src/platforms/inspection-grok.js +380 -0
  258. package/dist/src/platforms/inspection-grok.js.map +1 -0
  259. package/dist/src/platforms/inspection-native.d.ts +8 -0
  260. package/dist/src/platforms/inspection-native.js +584 -0
  261. package/dist/src/platforms/inspection-native.js.map +1 -0
  262. package/dist/src/platforms/inspection-opencode.d.ts +4 -0
  263. package/dist/src/platforms/inspection-opencode.js +98 -0
  264. package/dist/src/platforms/inspection-opencode.js.map +1 -0
  265. package/dist/src/platforms/inspection-pi.d.ts +9 -0
  266. package/dist/src/platforms/inspection-pi.js +490 -0
  267. package/dist/src/platforms/inspection-pi.js.map +1 -0
  268. package/dist/src/platforms/inspection-query.d.ts +26 -0
  269. package/dist/src/platforms/inspection-query.js +118 -0
  270. package/dist/src/platforms/inspection-query.js.map +1 -0
  271. package/dist/src/platforms/inspection.d.ts +20 -0
  272. package/dist/src/platforms/inspection.js +259 -0
  273. package/dist/src/platforms/inspection.js.map +1 -0
  274. package/dist/src/platforms/layout.d.ts +35 -0
  275. package/dist/src/platforms/layout.js +332 -0
  276. package/dist/src/platforms/layout.js.map +1 -0
  277. package/dist/src/platforms/lifecycle-native-services.d.ts +3 -0
  278. package/dist/src/platforms/lifecycle-native-services.js +213 -0
  279. package/dist/src/platforms/lifecycle-native-services.js.map +1 -0
  280. package/dist/src/platforms/lifecycle-native.d.ts +14 -0
  281. package/dist/src/platforms/lifecycle-native.js +234 -0
  282. package/dist/src/platforms/lifecycle-native.js.map +1 -0
  283. package/dist/src/platforms/lifecycle.d.ts +29 -0
  284. package/dist/src/platforms/lifecycle.js +688 -0
  285. package/dist/src/platforms/lifecycle.js.map +1 -0
  286. package/dist/src/platforms/opencode-permission-config.d.ts +13 -0
  287. package/dist/src/platforms/opencode-permission-config.js +253 -0
  288. package/dist/src/platforms/opencode-permission-config.js.map +1 -0
  289. package/dist/src/platforms/opencode-permissions.d.ts +39 -0
  290. package/dist/src/platforms/opencode-permissions.js +212 -0
  291. package/dist/src/platforms/opencode-permissions.js.map +1 -0
  292. package/dist/src/platforms/opencode-related-permissions.d.ts +40 -0
  293. package/dist/src/platforms/opencode-related-permissions.js +177 -0
  294. package/dist/src/platforms/opencode-related-permissions.js.map +1 -0
  295. package/dist/src/platforms/permission-ownership.d.ts +89 -0
  296. package/dist/src/platforms/permission-ownership.js +543 -0
  297. package/dist/src/platforms/permission-ownership.js.map +1 -0
  298. package/dist/src/platforms/permission-sidecar.d.ts +70 -0
  299. package/dist/src/platforms/permission-sidecar.js +215 -0
  300. package/dist/src/platforms/permission-sidecar.js.map +1 -0
  301. package/dist/src/platforms/projection-code-extension.d.ts +8 -0
  302. package/dist/src/platforms/projection-code-extension.js +126 -0
  303. package/dist/src/platforms/projection-code-extension.js.map +1 -0
  304. package/dist/src/platforms/projection-command-resources.d.ts +7 -0
  305. package/dist/src/platforms/projection-command-resources.js +74 -0
  306. package/dist/src/platforms/projection-command-resources.js.map +1 -0
  307. package/dist/src/platforms/projection-files.d.ts +28 -0
  308. package/dist/src/platforms/projection-files.js +113 -0
  309. package/dist/src/platforms/projection-files.js.map +1 -0
  310. package/dist/src/platforms/projection-marketplace.d.ts +19 -0
  311. package/dist/src/platforms/projection-marketplace.js +42 -0
  312. package/dist/src/platforms/projection-marketplace.js.map +1 -0
  313. package/dist/src/platforms/projection.d.ts +13 -0
  314. package/dist/src/platforms/projection.js +578 -0
  315. package/dist/src/platforms/projection.js.map +1 -0
  316. package/dist/src/platforms/read-only-retry-policy.d.ts +34 -0
  317. package/dist/src/platforms/read-only-retry-policy.js +70 -0
  318. package/dist/src/platforms/read-only-retry-policy.js.map +1 -0
  319. package/dist/src/platforms/registry.d.ts +4 -0
  320. package/dist/src/platforms/registry.js +30 -0
  321. package/dist/src/platforms/registry.js.map +1 -0
  322. package/dist/src/platforms/retirement-native.d.ts +6 -0
  323. package/dist/src/platforms/retirement-native.js +95 -0
  324. package/dist/src/platforms/retirement-native.js.map +1 -0
  325. package/dist/src/platforms/supplement-layout.d.ts +20 -0
  326. package/dist/src/platforms/supplement-layout.js +54 -0
  327. package/dist/src/platforms/supplement-layout.js.map +1 -0
  328. package/dist/src/platforms/supplement-state.d.ts +13 -0
  329. package/dist/src/platforms/supplement-state.js +93 -0
  330. package/dist/src/platforms/supplement-state.js.map +1 -0
  331. package/dist/src/portable/commands.d.ts +60 -11
  332. package/dist/src/portable/commands.js +88 -346
  333. package/dist/src/portable/commands.js.map +1 -1
  334. package/dist/src/portable/historical-materialization.d.ts +25 -0
  335. package/dist/src/portable/historical-materialization.js +148 -0
  336. package/dist/src/portable/historical-materialization.js.map +1 -0
  337. package/dist/src/portable/materializer.d.ts +46 -2
  338. package/dist/src/portable/materializer.js +262 -259
  339. package/dist/src/portable/materializer.js.map +1 -1
  340. package/dist/src/portable/recovery-layout.d.ts +17 -0
  341. package/dist/src/portable/recovery-layout.js +42 -0
  342. package/dist/src/portable/recovery-layout.js.map +1 -0
  343. package/dist/src/portable/recovery.d.ts +177 -0
  344. package/dist/src/portable/recovery.js +597 -0
  345. package/dist/src/portable/recovery.js.map +1 -0
  346. package/dist/src/portable/writer.d.ts +67 -0
  347. package/dist/src/portable/writer.js +321 -0
  348. package/dist/src/portable/writer.js.map +1 -0
  349. package/dist/src/recovery/coordinator.d.ts +175 -0
  350. package/dist/src/recovery/coordinator.js +1624 -0
  351. package/dist/src/recovery/coordinator.js.map +1 -0
  352. package/dist/src/recovery/demand.d.ts +53 -0
  353. package/dist/src/recovery/demand.js +189 -0
  354. package/dist/src/recovery/demand.js.map +1 -0
  355. package/dist/src/recovery/install-concurrency.d.ts +48 -0
  356. package/dist/src/recovery/install-concurrency.js +196 -0
  357. package/dist/src/recovery/install-concurrency.js.map +1 -0
  358. package/dist/src/recovery/interruption.d.ts +19 -0
  359. package/dist/src/recovery/interruption.js +43 -0
  360. package/dist/src/recovery/interruption.js.map +1 -0
  361. package/dist/src/recovery/joint-coordinator.d.ts +46 -0
  362. package/dist/src/recovery/joint-coordinator.js +1723 -0
  363. package/dist/src/recovery/joint-coordinator.js.map +1 -0
  364. package/dist/src/recovery/joint-demand.d.ts +72 -0
  365. package/dist/src/recovery/joint-demand.js +332 -0
  366. package/dist/src/recovery/joint-demand.js.map +1 -0
  367. package/dist/src/recovery/joint-install-execution.d.ts +19 -0
  368. package/dist/src/recovery/joint-install-execution.js +308 -0
  369. package/dist/src/recovery/joint-install-execution.js.map +1 -0
  370. package/dist/src/recovery/joint-install-native-rebase.d.ts +4 -0
  371. package/dist/src/recovery/joint-install-native-rebase.js +67 -0
  372. package/dist/src/recovery/joint-install-native-rebase.js.map +1 -0
  373. package/dist/src/recovery/performance.d.ts +4 -0
  374. package/dist/src/recovery/performance.js +26 -0
  375. package/dist/src/recovery/performance.js.map +1 -0
  376. package/dist/src/recovery/receipt.d.ts +131 -0
  377. package/dist/src/recovery/receipt.js +91 -0
  378. package/dist/src/recovery/receipt.js.map +1 -0
  379. package/dist/src/recovery/retirement.d.ts +47 -0
  380. package/dist/src/recovery/retirement.js +499 -0
  381. package/dist/src/recovery/retirement.js.map +1 -0
  382. package/dist/src/recovery/status.d.ts +143 -0
  383. package/dist/src/recovery/status.js +1528 -0
  384. package/dist/src/recovery/status.js.map +1 -0
  385. package/dist/src/recovery/types.d.ts +85 -0
  386. package/dist/src/recovery/types.js +2 -0
  387. package/dist/src/recovery/types.js.map +1 -0
  388. package/dist/src/review/eval-source-input.d.ts +44 -0
  389. package/dist/src/review/eval-source-input.js +213 -0
  390. package/dist/src/review/eval-source-input.js.map +1 -0
  391. package/dist/src/review/platform-profile.d.ts +5 -0
  392. package/dist/src/review/platform-profile.js +13 -0
  393. package/dist/src/review/platform-profile.js.map +1 -0
  394. package/dist/src/review/review-profile.d.ts +20 -0
  395. package/dist/src/review/review-profile.js +286 -0
  396. package/dist/src/review/review-profile.js.map +1 -0
  397. package/dist/src/review/review-selection.d.ts +20 -0
  398. package/dist/src/review/review-selection.js +502 -0
  399. package/dist/src/review/review-selection.js.map +1 -0
  400. package/dist/src/review/review-types.d.ts +71 -0
  401. package/dist/src/review/review-types.js +16 -0
  402. package/dist/src/review/review-types.js.map +1 -0
  403. package/dist/src/review/skill-materialization.d.ts +67 -0
  404. package/dist/src/review/skill-materialization.js +235 -0
  405. package/dist/src/review/skill-materialization.js.map +1 -0
  406. package/dist/src/review/source-binding.d.ts +203 -0
  407. package/dist/src/review/source-binding.js +791 -0
  408. package/dist/src/review/source-binding.js.map +1 -0
  409. package/dist/src/tui/agent-management.d.ts +23 -0
  410. package/dist/src/tui/agent-management.js +319 -0
  411. package/dist/src/tui/agent-management.js.map +1 -0
  412. package/dist/src/tui/agent-settings.d.ts +47 -0
  413. package/dist/src/tui/agent-settings.js +97 -0
  414. package/dist/src/tui/agent-settings.js.map +1 -0
  415. package/dist/src/tui/catalog-generation.d.ts +9 -0
  416. package/dist/src/tui/catalog-generation.js +96 -6
  417. package/dist/src/tui/catalog-generation.js.map +1 -1
  418. package/dist/src/tui/catalog-sources/projection.d.ts +2 -2
  419. package/dist/src/tui/catalog-sources/screens.js +19 -12
  420. package/dist/src/tui/catalog-sources/screens.js.map +1 -1
  421. package/dist/src/tui/catalog-sources/session.d.ts +11 -1
  422. package/dist/src/tui/catalog-sources/session.js +80 -5
  423. package/dist/src/tui/catalog-sources/session.js.map +1 -1
  424. package/dist/src/tui/catalog-sources/types.d.ts +15 -2
  425. package/dist/src/tui/catalog-store-task.d.ts +16 -0
  426. package/dist/src/tui/catalog-store-task.js +19 -0
  427. package/dist/src/tui/catalog-store-task.js.map +1 -0
  428. package/dist/src/tui/clipboard.d.ts +13 -0
  429. package/dist/src/tui/clipboard.js +95 -0
  430. package/dist/src/tui/clipboard.js.map +1 -0
  431. package/dist/src/tui/components.d.ts +113 -3
  432. package/dist/src/tui/components.js +201 -34
  433. package/dist/src/tui/components.js.map +1 -1
  434. package/dist/src/tui/config-array-draft.d.ts +30 -0
  435. package/dist/src/tui/config-array-draft.js +51 -0
  436. package/dist/src/tui/config-array-draft.js.map +1 -0
  437. package/dist/src/tui/config-leaf-editor.d.ts +44 -0
  438. package/dist/src/tui/config-leaf-editor.js +227 -0
  439. package/dist/src/tui/config-leaf-editor.js.map +1 -0
  440. package/dist/src/tui/config-object-suggestions.d.ts +15 -0
  441. package/dist/src/tui/config-object-suggestions.js +71 -0
  442. package/dist/src/tui/config-object-suggestions.js.map +1 -0
  443. package/dist/src/tui/config-references.d.ts +38 -0
  444. package/dist/src/tui/config-references.js +82 -0
  445. package/dist/src/tui/config-references.js.map +1 -0
  446. package/dist/src/tui/config-suggestions.d.ts +27 -0
  447. package/dist/src/tui/config-suggestions.js +62 -0
  448. package/dist/src/tui/config-suggestions.js.map +1 -0
  449. package/dist/src/tui/config-value-presentation.d.ts +23 -0
  450. package/dist/src/tui/config-value-presentation.js +151 -0
  451. package/dist/src/tui/config-value-presentation.js.map +1 -0
  452. package/dist/src/tui/console-app-v4.d.ts +14 -5
  453. package/dist/src/tui/console-app-v4.js +9779 -2488
  454. package/dist/src/tui/console-app-v4.js.map +1 -1
  455. package/dist/src/tui/content-item-card.d.ts +13 -0
  456. package/dist/src/tui/content-item-card.js +51 -0
  457. package/dist/src/tui/content-item-card.js.map +1 -0
  458. package/dist/src/tui/controller-runtime.d.ts +4 -3
  459. package/dist/src/tui/controller-runtime.js +1610 -590
  460. package/dist/src/tui/controller-runtime.js.map +1 -1
  461. package/dist/src/tui/controller.d.ts +583 -80
  462. package/dist/src/tui/controller.js +3362 -263
  463. package/dist/src/tui/controller.js.map +1 -1
  464. package/dist/src/tui/dependency-graph-view.d.ts +39 -0
  465. package/dist/src/tui/dependency-graph-view.js +121 -0
  466. package/dist/src/tui/dependency-graph-view.js.map +1 -0
  467. package/dist/src/tui/dependency-graph.d.ts +81 -0
  468. package/dist/src/tui/dependency-graph.js +452 -0
  469. package/dist/src/tui/dependency-graph.js.map +1 -0
  470. package/dist/src/tui/deployment-view.d.ts +14 -0
  471. package/dist/src/tui/deployment-view.js +175 -0
  472. package/dist/src/tui/deployment-view.js.map +1 -0
  473. package/dist/src/tui/diagnostic-projection.d.ts +31 -0
  474. package/dist/src/tui/diagnostic-projection.js +681 -0
  475. package/dist/src/tui/diagnostic-projection.js.map +1 -0
  476. package/dist/src/tui/diagnostics.d.ts +6 -2
  477. package/dist/src/tui/diagnostics.js +14 -2
  478. package/dist/src/tui/diagnostics.js.map +1 -1
  479. package/dist/src/tui/entity-cards.d.ts +56 -0
  480. package/dist/src/tui/entity-cards.js +327 -0
  481. package/dist/src/tui/entity-cards.js.map +1 -0
  482. package/dist/src/tui/glossary.d.ts +25 -0
  483. package/dist/src/tui/glossary.js +78 -0
  484. package/dist/src/tui/glossary.js.map +1 -0
  485. package/dist/src/tui/guided-setup.d.ts +25 -0
  486. package/dist/src/tui/guided-setup.js +101 -0
  487. package/dist/src/tui/guided-setup.js.map +1 -0
  488. package/dist/src/tui/index.d.ts +4 -1
  489. package/dist/src/tui/index.js +4 -1
  490. package/dist/src/tui/index.js.map +1 -1
  491. package/dist/src/tui/input-display.d.ts +1 -0
  492. package/dist/src/tui/input-display.js +23 -1
  493. package/dist/src/tui/input-display.js.map +1 -1
  494. package/dist/src/tui/keys.d.ts +44 -0
  495. package/dist/src/tui/keys.js +43 -15
  496. package/dist/src/tui/keys.js.map +1 -1
  497. package/dist/src/tui/lifecycle-action-view.d.ts +6 -0
  498. package/dist/src/tui/lifecycle-action-view.js +36 -0
  499. package/dist/src/tui/lifecycle-action-view.js.map +1 -0
  500. package/dist/src/tui/model.d.ts +141 -28
  501. package/dist/src/tui/model.js +968 -285
  502. package/dist/src/tui/model.js.map +1 -1
  503. package/dist/src/tui/operation-diagnostic-screens.d.ts +8 -0
  504. package/dist/src/tui/operation-diagnostic-screens.js +76 -0
  505. package/dist/src/tui/operation-diagnostic-screens.js.map +1 -0
  506. package/dist/src/tui/operation-history.d.ts +91 -0
  507. package/dist/src/tui/operation-history.js +167 -0
  508. package/dist/src/tui/operation-history.js.map +1 -0
  509. package/dist/src/tui/operation-review-planner.d.ts +7 -0
  510. package/dist/src/tui/operation-review-planner.js +980 -146
  511. package/dist/src/tui/operation-review-planner.js.map +1 -1
  512. package/dist/src/tui/plugin-content.d.ts +33 -0
  513. package/dist/src/tui/plugin-content.js +245 -0
  514. package/dist/src/tui/plugin-content.js.map +1 -0
  515. package/dist/src/tui/plugin-detail.d.ts +75 -0
  516. package/dist/src/tui/plugin-detail.js +267 -0
  517. package/dist/src/tui/plugin-detail.js.map +1 -0
  518. package/dist/src/tui/plugin-write-task.d.ts +69 -0
  519. package/dist/src/tui/plugin-write-task.js +286 -0
  520. package/dist/src/tui/plugin-write-task.js.map +1 -0
  521. package/dist/src/tui/query-header.d.ts +30 -0
  522. package/dist/src/tui/query-header.js +40 -0
  523. package/dist/src/tui/query-header.js.map +1 -0
  524. package/dist/src/tui/reader.d.ts +38 -0
  525. package/dist/src/tui/reader.js +49 -0
  526. package/dist/src/tui/reader.js.map +1 -0
  527. package/dist/src/tui/router.d.ts +170 -39
  528. package/dist/src/tui/router.js +338 -50
  529. package/dist/src/tui/router.js.map +1 -1
  530. package/dist/src/tui/scoped-flow.d.ts +49 -0
  531. package/dist/src/tui/scoped-flow.js +212 -0
  532. package/dist/src/tui/scoped-flow.js.map +1 -0
  533. package/dist/src/tui/scoped-inventory.d.ts +139 -0
  534. package/dist/src/tui/scoped-inventory.js +295 -0
  535. package/dist/src/tui/scoped-inventory.js.map +1 -0
  536. package/dist/src/tui/screen-registry.d.ts +696 -0
  537. package/dist/src/tui/screen-registry.js +226 -0
  538. package/dist/src/tui/screen-registry.js.map +1 -0
  539. package/dist/src/tui/session-console-app.d.ts +8 -0
  540. package/dist/src/tui/session-console-app.js +24 -0
  541. package/dist/src/tui/session-console-app.js.map +1 -0
  542. package/dist/src/tui/session-host.d.ts +45 -0
  543. package/dist/src/tui/session-host.js +219 -0
  544. package/dist/src/tui/session-host.js.map +1 -0
  545. package/dist/src/tui/source-detail-card.d.ts +29 -0
  546. package/dist/src/tui/source-detail-card.js +45 -0
  547. package/dist/src/tui/source-detail-card.js.map +1 -0
  548. package/dist/src/tui/theme.d.ts +12 -0
  549. package/dist/src/tui/theme.js +12 -0
  550. package/dist/src/tui/theme.js.map +1 -1
  551. package/dist/src/tui/viewport.d.ts +1 -0
  552. package/dist/src/tui/viewport.js +23 -0
  553. package/dist/src/tui/viewport.js.map +1 -1
  554. package/dist/src/tui/wizard.js +26 -4
  555. package/dist/src/tui/wizard.js.map +1 -1
  556. package/dist/src/types.d.ts +105 -83
  557. package/dist/src/types.js +1 -1
  558. package/dist/src/types.js.map +1 -1
  559. package/dist/src/utils/agent-version.d.ts +10 -4
  560. package/dist/src/utils/agent-version.js +6 -8
  561. package/dist/src/utils/agent-version.js.map +1 -1
  562. package/dist/src/utils/artifact-plan.d.ts +18 -25
  563. package/dist/src/utils/artifact-plan.js +59 -445
  564. package/dist/src/utils/artifact-plan.js.map +1 -1
  565. package/dist/src/utils/artifact-renderer.d.ts +64 -90
  566. package/dist/src/utils/artifact-renderer.js +202 -303
  567. package/dist/src/utils/artifact-renderer.js.map +1 -1
  568. package/dist/src/utils/artifact-request.d.ts +19 -14
  569. package/dist/src/utils/artifact-request.js +51 -36
  570. package/dist/src/utils/artifact-request.js.map +1 -1
  571. package/dist/src/utils/artifact-sources.d.ts +4 -8
  572. package/dist/src/utils/artifact-sources.js +15 -6
  573. package/dist/src/utils/artifact-sources.js.map +1 -1
  574. package/dist/src/utils/aw-home-mutation-lock.js +2 -1
  575. package/dist/src/utils/aw-home-mutation-lock.js.map +1 -1
  576. package/dist/src/utils/bundle-layout.d.ts +2 -0
  577. package/dist/src/utils/bundle-layout.js +88 -158
  578. package/dist/src/utils/bundle-layout.js.map +1 -1
  579. package/dist/src/utils/catalog-capability-projection.d.ts +8 -0
  580. package/dist/src/utils/catalog-capability-projection.js +14 -0
  581. package/dist/src/utils/catalog-capability-projection.js.map +1 -0
  582. package/dist/src/utils/catalog-digests.d.ts +2 -12
  583. package/dist/src/utils/catalog-digests.js +7 -55
  584. package/dist/src/utils/catalog-digests.js.map +1 -1
  585. package/dist/src/utils/catalog-generation-resolver.d.ts +28 -4
  586. package/dist/src/utils/catalog-generation-resolver.js +146 -40
  587. package/dist/src/utils/catalog-generation-resolver.js.map +1 -1
  588. package/dist/src/utils/catalog-generation-service.d.ts +24 -2
  589. package/dist/src/utils/catalog-generation-service.js +92 -48
  590. package/dist/src/utils/catalog-generation-service.js.map +1 -1
  591. package/dist/src/utils/catalog-generation-state.js +1 -1
  592. package/dist/src/utils/catalog-generation-state.js.map +1 -1
  593. package/dist/src/utils/catalog-generation-store.d.ts +4 -0
  594. package/dist/src/utils/catalog-generation-store.js +68 -10
  595. package/dist/src/utils/catalog-generation-store.js.map +1 -1
  596. package/dist/src/utils/catalog-operation-context.d.ts +61 -4
  597. package/dist/src/utils/catalog-operation-context.js +225 -4
  598. package/dist/src/utils/catalog-operation-context.js.map +1 -1
  599. package/dist/src/utils/catalog-public-error.js +4 -0
  600. package/dist/src/utils/catalog-public-error.js.map +1 -1
  601. package/dist/src/utils/catalog-runtime-projection.d.ts +4 -3
  602. package/dist/src/utils/catalog-runtime-projection.js.map +1 -1
  603. package/dist/src/utils/catalog-snapshot.d.ts +3 -0
  604. package/dist/src/utils/catalog-snapshot.js +4 -1
  605. package/dist/src/utils/catalog-snapshot.js.map +1 -1
  606. package/dist/src/utils/catalog-source-impact.d.ts +3 -2
  607. package/dist/src/utils/catalog-source-impact.js +142 -20
  608. package/dist/src/utils/catalog-source-impact.js.map +1 -1
  609. package/dist/src/utils/catalog-source-references.d.ts +57 -1
  610. package/dist/src/utils/catalog-source-references.js +755 -162
  611. package/dist/src/utils/catalog-source-references.js.map +1 -1
  612. package/dist/src/utils/catalog-sources.d.ts +1 -1
  613. package/dist/src/utils/catalog-sources.js +21 -5
  614. package/dist/src/utils/catalog-sources.js.map +1 -1
  615. package/dist/src/utils/codex-config.d.ts +3 -0
  616. package/dist/src/utils/codex-config.js +7 -0
  617. package/dist/src/utils/codex-config.js.map +1 -1
  618. package/dist/src/utils/codex-executable-discovery.d.ts +28 -0
  619. package/dist/src/utils/codex-executable-discovery.js +431 -0
  620. package/dist/src/utils/codex-executable-discovery.js.map +1 -0
  621. package/dist/src/utils/codex-manager.d.ts +23 -42
  622. package/dist/src/utils/codex-manager.js +79 -767
  623. package/dist/src/utils/codex-manager.js.map +1 -1
  624. package/dist/src/utils/codex-native-observation.d.ts +40 -1
  625. package/dist/src/utils/codex-native-observation.js +172 -0
  626. package/dist/src/utils/codex-native-observation.js.map +1 -1
  627. package/dist/src/utils/codex-reconciler.d.ts +2 -7
  628. package/dist/src/utils/codex-reconciler.js +33 -5
  629. package/dist/src/utils/codex-reconciler.js.map +1 -1
  630. package/dist/src/utils/codex-shared-native.d.ts +8 -26
  631. package/dist/src/utils/codex-shared-native.js +63 -83
  632. package/dist/src/utils/codex-shared-native.js.map +1 -1
  633. package/dist/src/utils/codex-skill-staging.d.ts +4 -3
  634. package/dist/src/utils/codex-skill-staging.js.map +1 -1
  635. package/dist/src/utils/codex-skills-root.d.ts +4 -0
  636. package/dist/src/utils/codex-skills-root.js +29 -0
  637. package/dist/src/utils/codex-skills-root.js.map +1 -0
  638. package/dist/src/utils/codex-surface-analysis.d.ts +6 -2
  639. package/dist/src/utils/codex-surface-analysis.js +31 -56
  640. package/dist/src/utils/codex-surface-analysis.js.map +1 -1
  641. package/dist/src/utils/component-agent-binding.d.ts +17 -0
  642. package/dist/src/utils/component-agent-binding.js +119 -0
  643. package/dist/src/utils/component-agent-binding.js.map +1 -0
  644. package/dist/src/utils/component-command-preparation.d.ts +33 -0
  645. package/dist/src/utils/component-command-preparation.js +129 -0
  646. package/dist/src/utils/component-command-preparation.js.map +1 -0
  647. package/dist/src/utils/component-gap.d.ts +4 -0
  648. package/dist/src/utils/component-gap.js +16 -0
  649. package/dist/src/utils/component-gap.js.map +1 -0
  650. package/dist/src/utils/component-resources.d.ts +53 -0
  651. package/dist/src/utils/component-resources.js +340 -0
  652. package/dist/src/utils/component-resources.js.map +1 -0
  653. package/dist/src/utils/config-platforms.d.ts +21 -0
  654. package/dist/src/utils/config-platforms.js +51 -0
  655. package/dist/src/utils/config-platforms.js.map +1 -0
  656. package/dist/src/utils/dynamic-skill-tree.d.ts +18 -6
  657. package/dist/src/utils/dynamic-skill-tree.js +33 -40
  658. package/dist/src/utils/dynamic-skill-tree.js.map +1 -1
  659. package/dist/src/utils/git-catalog-provider.d.ts +3 -0
  660. package/dist/src/utils/git-catalog-provider.js +49 -3
  661. package/dist/src/utils/git-catalog-provider.js.map +1 -1
  662. package/dist/src/utils/inventory-recovery-diagnostic.d.ts +4 -0
  663. package/dist/src/utils/inventory-recovery-diagnostic.js +15 -0
  664. package/dist/src/utils/inventory-recovery-diagnostic.js.map +1 -0
  665. package/dist/src/utils/local-marketplace.d.ts +19 -12
  666. package/dist/src/utils/local-marketplace.js +97 -194
  667. package/dist/src/utils/local-marketplace.js.map +1 -1
  668. package/dist/src/utils/managed-command-cli-review.d.ts +53 -0
  669. package/dist/src/utils/managed-command-cli-review.js +431 -0
  670. package/dist/src/utils/managed-command-cli-review.js.map +1 -0
  671. package/dist/src/utils/managed-command-closure.d.ts +14 -0
  672. package/dist/src/utils/managed-command-closure.js +156 -0
  673. package/dist/src/utils/managed-command-closure.js.map +1 -0
  674. package/dist/src/utils/managed-command-errors.d.ts +5 -0
  675. package/dist/src/utils/managed-command-errors.js +10 -0
  676. package/dist/src/utils/managed-command-errors.js.map +1 -0
  677. package/dist/src/utils/managed-command-materialization.d.ts +90 -0
  678. package/dist/src/utils/managed-command-materialization.js +375 -0
  679. package/dist/src/utils/managed-command-materialization.js.map +1 -0
  680. package/dist/src/utils/managed-command-preparation.d.ts +30 -0
  681. package/dist/src/utils/managed-command-preparation.js +39 -0
  682. package/dist/src/utils/managed-command-preparation.js.map +1 -0
  683. package/dist/src/utils/managed-command-review.d.ts +33 -0
  684. package/dist/src/utils/managed-command-review.js +80 -0
  685. package/dist/src/utils/managed-command-review.js.map +1 -0
  686. package/dist/src/utils/managed-command-runtime.d.ts +36 -0
  687. package/dist/src/utils/managed-command-runtime.js +126 -0
  688. package/dist/src/utils/managed-command-runtime.js.map +1 -0
  689. package/dist/src/utils/managed-command-snapshots.d.ts +24 -0
  690. package/dist/src/utils/managed-command-snapshots.js +89 -0
  691. package/dist/src/utils/managed-command-snapshots.js.map +1 -0
  692. package/dist/src/utils/managed-command-store.d.ts +141 -0
  693. package/dist/src/utils/managed-command-store.js +839 -0
  694. package/dist/src/utils/managed-command-store.js.map +1 -0
  695. package/dist/src/utils/multi-source-catalog.d.ts +6 -1
  696. package/dist/src/utils/multi-source-catalog.js +9 -4
  697. package/dist/src/utils/multi-source-catalog.js.map +1 -1
  698. package/dist/src/utils/native-cli-interruption.d.ts +8 -0
  699. package/dist/src/utils/native-cli-interruption.js +65 -0
  700. package/dist/src/utils/native-cli-interruption.js.map +1 -0
  701. package/dist/src/utils/native-cli.d.ts +37 -6
  702. package/dist/src/utils/native-cli.js +523 -60
  703. package/dist/src/utils/native-cli.js.map +1 -1
  704. package/dist/src/utils/native-demand.d.ts +29 -0
  705. package/dist/src/utils/native-demand.js +4 -0
  706. package/dist/src/utils/native-demand.js.map +1 -0
  707. package/dist/src/utils/native-tool-context.d.ts +17 -0
  708. package/dist/src/utils/native-tool-context.js +40 -0
  709. package/dist/src/utils/native-tool-context.js.map +1 -0
  710. package/dist/src/utils/native-tool-review.d.ts +8 -0
  711. package/dist/src/utils/native-tool-review.js +14 -0
  712. package/dist/src/utils/native-tool-review.js.map +1 -0
  713. package/dist/src/utils/ownership.d.ts +38 -3
  714. package/dist/src/utils/ownership.js +118 -11
  715. package/dist/src/utils/ownership.js.map +1 -1
  716. package/dist/src/utils/package-content.d.ts +7 -0
  717. package/dist/src/utils/package-content.js +70 -0
  718. package/dist/src/utils/package-content.js.map +1 -0
  719. package/dist/src/utils/path-catalog-provider.js +2 -0
  720. package/dist/src/utils/path-catalog-provider.js.map +1 -1
  721. package/dist/src/utils/paths.d.ts +1 -1
  722. package/dist/src/utils/paths.js +5 -2
  723. package/dist/src/utils/paths.js.map +1 -1
  724. package/dist/src/utils/platform-empty-state.d.ts +69 -0
  725. package/dist/src/utils/platform-empty-state.js +249 -0
  726. package/dist/src/utils/platform-empty-state.js.map +1 -0
  727. package/dist/src/utils/platform-support.d.ts +1 -1
  728. package/dist/src/utils/platform-support.js +1 -1
  729. package/dist/src/utils/platform-support.js.map +1 -1
  730. package/dist/src/utils/plugin-config-command-apply.d.ts +33 -0
  731. package/dist/src/utils/plugin-config-command-apply.js +142 -0
  732. package/dist/src/utils/plugin-config-command-apply.js.map +1 -0
  733. package/dist/src/utils/plugin-config-diagnostics.d.ts +16 -0
  734. package/dist/src/utils/plugin-config-diagnostics.js +44 -0
  735. package/dist/src/utils/plugin-config-diagnostics.js.map +1 -0
  736. package/dist/src/utils/plugin-config-impact.d.ts +76 -0
  737. package/dist/src/utils/plugin-config-impact.js +359 -0
  738. package/dist/src/utils/plugin-config-impact.js.map +1 -0
  739. package/dist/src/utils/plugin-config-references.d.ts +116 -0
  740. package/dist/src/utils/plugin-config-references.js +379 -0
  741. package/dist/src/utils/plugin-config-references.js.map +1 -0
  742. package/dist/src/utils/plugin-config-suggestion-runner.d.ts +83 -0
  743. package/dist/src/utils/plugin-config-suggestion-runner.js +308 -0
  744. package/dist/src/utils/plugin-config-suggestion-runner.js.map +1 -0
  745. package/dist/src/utils/plugin-config-suggestions.d.ts +50 -0
  746. package/dist/src/utils/plugin-config-suggestions.js +322 -0
  747. package/dist/src/utils/plugin-config-suggestions.js.map +1 -0
  748. package/dist/src/utils/plugin-config-write.d.ts +108 -19
  749. package/dist/src/utils/plugin-config-write.js +781 -568
  750. package/dist/src/utils/plugin-config-write.js.map +1 -1
  751. package/dist/src/utils/plugin-config.d.ts +122 -43
  752. package/dist/src/utils/plugin-config.js +574 -610
  753. package/dist/src/utils/plugin-config.js.map +1 -1
  754. package/dist/src/utils/plugin-dependencies.d.ts +1 -1
  755. package/dist/src/utils/plugin-dependencies.js.map +1 -1
  756. package/dist/src/utils/plugin-scripts.d.ts +41 -17
  757. package/dist/src/utils/plugin-scripts.js +586 -123
  758. package/dist/src/utils/plugin-scripts.js.map +1 -1
  759. package/dist/src/utils/process-lock.js +14 -5
  760. package/dist/src/utils/process-lock.js.map +1 -1
  761. package/dist/src/utils/process-tree.d.ts +2 -2
  762. package/dist/src/utils/process-tree.js +1 -1
  763. package/dist/src/utils/process-tree.js.map +1 -1
  764. package/dist/src/utils/project-boundary.d.ts +11 -1
  765. package/dist/src/utils/project-boundary.js +33 -11
  766. package/dist/src/utils/project-boundary.js.map +1 -1
  767. package/dist/src/utils/rendered-contract.js +24 -1
  768. package/dist/src/utils/rendered-contract.js.map +1 -1
  769. package/dist/src/utils/runtime-config.d.ts +18 -0
  770. package/dist/src/utils/runtime-config.js +64 -0
  771. package/dist/src/utils/runtime-config.js.map +1 -0
  772. package/dist/src/utils/runtime-skill-closure.d.ts +2 -2
  773. package/dist/src/utils/runtime-skill-closure.js +50 -7
  774. package/dist/src/utils/runtime-skill-closure.js.map +1 -1
  775. package/dist/src/utils/safe-operation-diagnostic.d.ts +15 -0
  776. package/dist/src/utils/safe-operation-diagnostic.js +33 -0
  777. package/dist/src/utils/safe-operation-diagnostic.js.map +1 -0
  778. package/dist/src/utils/sensitive-content.d.ts +4 -0
  779. package/dist/src/utils/sensitive-content.js +36 -0
  780. package/dist/src/utils/sensitive-content.js.map +1 -0
  781. package/dist/src/utils/skill-invocation-warning.d.ts +19 -0
  782. package/dist/src/utils/skill-invocation-warning.js +43 -0
  783. package/dist/src/utils/skill-invocation-warning.js.map +1 -0
  784. package/dist/src/utils/skill-validation.js +0 -5
  785. package/dist/src/utils/skill-validation.js.map +1 -1
  786. package/dist/src/utils/state-paths.d.ts +8 -3
  787. package/dist/src/utils/state-paths.js +53 -16
  788. package/dist/src/utils/state-paths.js.map +1 -1
  789. package/dist/src/utils/target-eligibility.d.ts +2 -2
  790. package/dist/src/utils/target-eligibility.js.map +1 -1
  791. package/dist/src/utils/windows-claude-shim.d.ts +7 -0
  792. package/dist/src/utils/windows-claude-shim.js +10 -0
  793. package/dist/src/utils/windows-claude-shim.js.map +1 -0
  794. package/dist/src/utils/windows-npm-shim.d.ts +16 -0
  795. package/dist/src/utils/windows-npm-shim.js +155 -0
  796. package/dist/src/utils/windows-npm-shim.js.map +1 -0
  797. package/dist/vitest.config.js +109 -9
  798. package/dist/vitest.config.js.map +1 -1
  799. package/package.json +20 -12
  800. package/dist/authoring/templates/aw-config-runtime.d.mts +0 -2
  801. package/dist/authoring/templates/aw-config-runtime.mjs +0 -407
  802. package/dist/authoring/templates/aw-config-runtime.mjs.map +0 -1
  803. package/dist/src/commands/review-publication.d.ts +0 -99
  804. package/dist/src/commands/review-publication.js +0 -904
  805. package/dist/src/commands/review-publication.js.map +0 -1
  806. package/dist/src/commands/sync-command.d.ts +0 -23
  807. package/dist/src/commands/sync-command.js +0 -242
  808. package/dist/src/commands/sync-command.js.map +0 -1
  809. package/dist/src/portable/skills-cli.d.ts +0 -43
  810. package/dist/src/portable/skills-cli.js +0 -148
  811. package/dist/src/portable/skills-cli.js.map +0 -1
  812. package/dist/src/utils/codex-native-render-receipt.d.ts +0 -40
  813. package/dist/src/utils/codex-native-render-receipt.js +0 -205
  814. package/dist/src/utils/codex-native-render-receipt.js.map +0 -1
  815. package/dist/src/utils/plugin-intent-state.d.ts +0 -34
  816. package/dist/src/utils/plugin-intent-state.js +0 -289
  817. package/dist/src/utils/plugin-intent-state.js.map +0 -1
  818. package/dist/src/utils/slash-commands.d.ts +0 -1
  819. package/dist/src/utils/slash-commands.js +0 -2
  820. package/dist/src/utils/slash-commands.js.map +0 -1
package/dist/src/index.js CHANGED
@@ -1,50 +1,60 @@
1
1
  #!/usr/bin/env node
2
+ import { describeNativeToolClosure } from './utils/native-tool-review.js';
3
+ import { preparePublicConfigConfirmation } from './commands/public-config-confirmation.js';
4
+ import { createPublicCommandInterruption } from './commands/public-interruption.js';
5
+ import { CLI_OUTPUT_SCHEMA_VERSION, commandResult, publicExitCode, renderPublicResult, safePublicMessage } from './output/public-result.js';
6
+ import { projectReceipt } from './output/receipt-projection.js';
7
+ import { observePreferences } from './intent/deployment-preferences.js';
8
+ import { assertConfigLayerWritable, ConfigLayerError, resolveActiveConfigPlatforms } from './utils/config-platforms.js';
9
+ import { SKILL_INVOCATION_NOTICE } from './utils/skill-invocation-warning.js';
10
+ import { runPublicLifecycle } from './commands/public-lifecycle.js';
11
+ import { runPublicPluginList, runPublicPluginShow, runPublicPluginStatus } from './commands/public-plugin-query.js';
2
12
  import fs from 'node:fs';
3
13
  import path from 'node:path';
4
- import { spawn } from 'node:child_process';
14
+ import { defaultPluginProcessRunner } from './utils/plugin-scripts.js';
5
15
  import { fileURLToPath } from 'node:url';
6
- import { Command, CommanderError, Option } from 'commander';
16
+ import { withNativeCliInterruption } from './utils/native-cli-interruption.js';
17
+ import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';
7
18
  import { doctorEvalProviders } from '@lesliechan721/agent-skill-eval';
8
- import { initCommand } from './commands/init.js';
9
- import { resolveCatalogWorkspaceRoot } from './commands/catalog-workspace-resolution.js';
10
- import { addCatalogSourceCommand, explicitRefPolicy, listCatalogSources, removeCatalogSourceCommand, setPrimaryCatalogSourceCommand, updateCatalogSourceCommand, } from './commands/catalog-source.js';
19
+ import { compilePluginConfigDefinition, selectPluginConfigProfile, PLATFORM_TARGETS, CONFIG_SUGGESTIONS_TIMEOUT_MIN_MS, CONFIG_SUGGESTIONS_TIMEOUT_MAX_MS, } from '@lesliechan721/aw-plugin-core/manifest';
20
+ import { CatalogWorkspaceMissingError, resolveCatalogWorkspaceRoot } from './commands/catalog-workspace-resolution.js';
21
+ import { addCatalogSourceCommand, describeSourceCommandRebinding, preflightCatalogSourceMutation, explicitRefPolicy, listCatalogSources, removeCatalogSourceCommand, updateCatalogSourceCommand, } from './commands/catalog-source.js';
11
22
  import { catalogSourceStatusCommand, syncCatalogSourceCommand, } from './commands/catalog-generation.js';
12
- import { catalogStorePrune, catalogStoreStatus } from './commands/catalog-store.js';
13
- import { cleanupWriteCommand as cleanupCommand, installWriteCommand as installCommand, reinstallWriteCommand as reinstallCommand, uninstallWriteCommand as uninstallCommand, } from './commands/write-commands.js';
14
- import { syncCommand } from './commands/sync-command.js';
15
- import { formatInteractiveConsoleUnavailableMessage, runConsoleController, } from './commands/console.js';
16
- import { runCommandWizard, toWizardCandidates, WizardExecutionError, } from './commands/wizard.js';
23
+ import { catalogStoreErrorCode, catalogStorePrune, catalogStoreStatus, } from './commands/catalog-store.js';
24
+ import { WizardExecutionError, } from './commands/wizard.js';
17
25
  import { createCliExecutionContext, emitCommandEvent, } from './commands/runtime.js';
18
- import { loadConsoleItemsResult, statusCommandV7 } from './commands/status-v6.js';
19
- import { normalizeUninstallCommandOptions, normalizeCleanupCommandOptions, resolveConfigReadResolution, resolveConfigWriteScope, normalizeInstallCommandOptions, normalizeReinstallCommandOptions, } from './commands/options.js';
20
- import { isCommandWarningError, } from './types.js';
21
- import { formatWarnings } from './output/reporter.js';
26
+ import { parseContextValue, parsePlatformTargetValue, parseScopeValue, resolveScriptTimeoutMs, } from './commands/options.js';
27
+ import { createNoopReporter, formatWarnings } from './output/reporter.js';
22
28
  import { redactString, redactValue } from './output/redact.js';
23
- import { renderShellCommand, } from './output/equivalent-command.js';
24
- import { buildRebuildReceiptJson, buildInitReceiptJson, renderRebuildReceipt, renderInitReceipt, } from './output/command-receipt.js';
25
29
  import { resolveCliPackageRoot } from './utils/paths.js';
26
- import { findConfigFieldEntry, listNamespacedPluginConfigStores, listPluginConfigStorePluginNames, readPluginConfigStore, renderPluginConfigValueForDisplay, resolveConfigRead, } from './utils/plugin-config.js';
27
- import { applyPluginConfigWrite, buildConfigMutationReceipt, describeResetAffectedFields, resetPluginConfigWithHelper, } from './utils/plugin-config-write.js';
30
+ import { coercePluginConfigUpdates, assertPluginConfigMutationCandidate, findConfigFieldEntry, formatPluginConfigSetRecoveryCommand, listNamespacedPluginConfigStores, PluginConfigValueValidationError, readPluginConfigStore, renderPluginConfigValueForDisplay, resolveConfigRead, } from './utils/plugin-config.js';
31
+ import { applyPluginConfigWrite, ConfigApplyInterruptedError, applyPluginConfig, buildConfigMutationReceipt, configApplyLayerFailure, configActiveAvailabilityError, configWriteStateForError, resetPluginConfigWithHelper, } from './utils/plugin-config-write.js';
28
32
  import { assertStrictSemVer } from './utils/manifest.js';
29
- import { writeCandidateEligibility } from './utils/target-eligibility.js';
30
33
  import { assertCatalogSourceReferencesSupported, inventoryLegacyConfigReferences, } from './utils/catalog-source-references.js';
31
- import { parsePluginId, withResolvedCatalogPlugin, withResolvedMultiSourceCatalog, } from './utils/multi-source-catalog.js';
34
+ import { CatalogLeaseEscapeError, CatalogPluginNotFoundError, parsePluginId, withResolvedCatalogPlugin, withResolvedMultiSourceCatalog, } from './utils/multi-source-catalog.js';
35
+ import { ConfigSuggestionArgumentError, parseConfigSuggestionDependencyOverrides, parseConfigSuggestionFieldPath, preparePluginConfigSuggestions, } from './utils/plugin-config-suggestions.js';
32
36
  import { sanitizeCatalogSourceError, sanitizeCatalogSourceErrorMessage, } from './utils/catalog-public-error.js';
33
37
  import { catalogGenerationErrorCode } from './utils/catalog-generation-error.js';
34
38
  import { resolveCatalogOperationContext, } from './utils/catalog-operation-context.js';
35
39
  import { withAwHomeMutationLock, } from './utils/aw-home-mutation-lock.js';
36
- import { installPortableSkills, materializePortableSkillsToDirectory, PortableCommandError, renderPortableReview, } from './portable/commands.js';
37
- import { SkillsCliError } from './portable/skills-cli.js';
38
- import { computeReviewComponentDigest, listReviewRecords, parseReviewAttachment, publishReviewRecord, showReviewRecord, verifyReviewRecord, } from './commands/review-publication.js';
39
- import { resolveRepoRoot } from './utils/state-paths.js';
40
+ import { recoveryInterruptionCode } from './recovery/interruption.js';
41
+ import { materializePortableSkillsToDirectory, PortableCommandError } from './portable/commands.js';
42
+ import { createReviewInspectionFailure, getReviewInspectionExitCode, inspectReviewTarget, } from './commands/review-inspection.js';
43
+ import { prepareReviewTarget, } from './commands/review-preparation.js';
40
44
  import { runCatalogBuildCommand, runCatalogInitCommand, runCatalogValidateCommand, runCatalogVersionCommand, runPluginBuildCommand, runPluginTestCommand, } from './authoring/workspace-commands.js';
41
- import { runCatalogPublishApplyCommand, runCatalogPublishPlanCommand, } from './commands/catalog-publish.js';
42
- import { catalogPublicationFailure, CatalogPublicationInspectionError, } from './commands/catalog-publication-inspection.js';
45
+ import { CatalogPublicationApplyFailure, runCatalogPublishApplyCommand, runCatalogPublishPlanCommand, } from './commands/catalog-publish.js';
46
+ import { catalogPublicationFailure, } from './commands/catalog-publication-inspection.js';
43
47
  import { getCatalogStatus, renderCatalogStatus } from './commands/catalog-status.js';
44
48
  import { activateCatalogDevSource, catalogDevSourceError, createCatalogDevFailureReceipt, deactivateCatalogDevSource, getCatalogDevSourceStatus, } from './commands/catalog-dev-source.js';
45
49
  import { getPluginCapabilitiesResult, parsePluginCapabilitySurface, renderPluginCapabilities, } from './commands/plugin-capabilities.js';
46
50
  import { AwCapabilityUnsupportedError, checkCurrentAw, describeCurrentAw, inspectPluginRequirements, } from './commands/aw-capabilities.js';
47
51
  import { prepareSkillEval } from './commands/skill-eval.js';
52
+ import { targetsSet, targetsList, targetsChangeExclusion } from './commands/targets-command.js';
53
+ import { runCursorWorkspaceHookCli } from './platforms/cursor-workspace-hook.js';
54
+ import { normalizeAgents } from './intent/deployment-preferences.js';
55
+ import { resolveWorkContext } from './intent/work-context.js';
56
+ import { registerManagedCommandCli, runManagedCommandCli } from './commands/managed-commands.js';
57
+ const receiptSinks = new WeakMap();
48
58
  function createDefaultIo() {
49
59
  return {
50
60
  stdout: (text) => process.stdout.write(text),
@@ -54,6 +64,41 @@ function createDefaultIo() {
54
64
  function writeLine(write, line) {
55
65
  write(`${line}\n`);
56
66
  }
67
+ function strictValueOption(flags, description, choices) {
68
+ let seen = false;
69
+ const option = new Option(flags, description);
70
+ if (choices)
71
+ option.choices([...choices]);
72
+ return option.argParser((value) => {
73
+ if (seen)
74
+ throw new InvalidArgumentError(`${option.long} can be specified only once.`);
75
+ if (choices && !choices.includes(value)) {
76
+ throw new InvalidArgumentError(`${option.long} must be one of: ${choices.join(', ')}.`);
77
+ }
78
+ seen = true;
79
+ return value;
80
+ });
81
+ }
82
+ function collectUniqueOption(value, previous = []) {
83
+ return previous.includes(value) ? previous : [...previous, value];
84
+ }
85
+ function renderReviewSkills(write, skills, issues) {
86
+ for (const skill of skills) {
87
+ writeLine(write, `${skill.skill}\t${skill.profile.platform}/${skill.profile.scope}\t${skill.state}\t${skill.finalPath ?? '-'}`);
88
+ }
89
+ for (const issue of issues)
90
+ writeLine(write, `${issue.code}: ${issue.message}`);
91
+ }
92
+ function renderReviewInspection(write, receipt) {
93
+ writeLine(write, `Review inspection (${receipt.view}): ${receipt.ok ? 'ok' : 'failed'}`);
94
+ renderReviewSkills(write, receipt.skills, receipt.issues);
95
+ }
96
+ function renderReviewPreparation(write, receipt) {
97
+ writeLine(write, `Review preparation: ${receipt.ok ? 'complete' : 'failed'}`);
98
+ if (receipt.sourceBindingPath)
99
+ writeLine(write, `Source binding: ${receipt.sourceBindingPath}`);
100
+ renderReviewSkills(write, receipt.skills, receipt.issues);
101
+ }
57
102
  function writeWarnings(write, warnings, options = {}) {
58
103
  for (const warning of formatWarnings(warnings, options)) {
59
104
  writeLine(write, warning);
@@ -64,9 +109,6 @@ function resolveCliVersion() {
64
109
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
65
110
  return assertStrictSemVer(packageJson.version, 'packages/cli/package.json version');
66
111
  }
67
- function resolveCommandReceiptExitCode(result) {
68
- return result.overallState === 'succeeded' ? 0 : 1;
69
- }
70
112
  class WriteCommandRequestError extends Error {
71
113
  code = 'invalidArguments';
72
114
  }
@@ -78,201 +120,16 @@ function normalizeWriteRequest(normalize) {
78
120
  throw new WriteCommandRequestError(error instanceof Error ? error.message : String(error));
79
121
  }
80
122
  }
81
- function writeCommandFailure(error) {
82
- const message = redactString(error instanceof Error ? error.message : String(error));
83
- if (error instanceof CommanderError || error instanceof WriteCommandRequestError) {
84
- return { code: 'invalidArguments', message };
85
- }
86
- const explicitCode = error?.code;
87
- if (typeof explicitCode === 'string' && /^[A-Za-z][A-Za-z0-9]*$/u.test(explicitCode)) {
88
- return { code: explicitCode, message };
89
- }
90
- const separator = message.indexOf(':');
91
- const prefix = separator > 0 ? message.slice(0, separator) : '';
92
- return {
93
- code: /^[A-Za-z][A-Za-z0-9]*$/u.test(prefix) ? prefix : 'writeCommandFailed',
94
- message,
95
- };
96
- }
97
- function preparseWriteReceiptRequest(argv) {
98
- const request = { json: false, plugins: [] };
99
- let positionalOnly = false;
100
- for (let index = 1; index < argv.length; index += 1) {
101
- const token = argv[index];
102
- if (positionalOnly) {
103
- request.plugins.push(token);
104
- continue;
105
- }
106
- if (token === '--') {
107
- positionalOnly = true;
108
- continue;
109
- }
110
- if (token === '--json') {
111
- request.json = true;
112
- continue;
113
- }
114
- if (token === '--platform' || token === '--scope') {
115
- const value = argv[index + 1];
116
- if (token === '--platform')
117
- request.platform = value;
118
- else
119
- request.scope = value;
120
- index += 1;
121
- continue;
122
- }
123
- if (token.startsWith('--platform=')) {
124
- request.platform = token.slice('--platform='.length);
125
- continue;
126
- }
127
- if (token.startsWith('--scope=')) {
128
- request.scope = token.slice('--scope='.length);
129
- continue;
130
- }
131
- if (token === '--dependency-scope' || token === '--script-timeout' || token === '--log-file') {
132
- index += 1;
133
- continue;
134
- }
135
- if (token.startsWith('--'))
136
- continue;
137
- if (token.startsWith('-') && token !== '-') {
138
- const shortOptions = token.slice(1);
139
- for (let offset = 0; offset < shortOptions.length; offset += 1) {
140
- const option = shortOptions[offset];
141
- if (option === 'j') {
142
- request.json = true;
143
- continue;
144
- }
145
- if (option === 'p' || option === 's') {
146
- const value = shortOptions.slice(offset + 1) || argv[index + 1];
147
- if (option === 'p')
148
- request.platform = value;
149
- else
150
- request.scope = value;
151
- if (shortOptions.length === offset + 1)
152
- index += 1;
153
- break;
154
- }
155
- }
156
- continue;
157
- }
158
- request.plugins.push(token);
159
- }
160
- return request;
161
- }
162
- function jsonWriteCommandRequest(argv) {
163
- const command = argv[0];
164
- if (!['install', 'reinstall', 'uninstall', 'cleanup', 'sync'].includes(command ?? '')) {
165
- return null;
166
- }
167
- const request = preparseWriteReceiptRequest(argv);
168
- if (!request.json)
169
- return null;
170
- const rawPlatform = request.platform;
171
- const platform = rawPlatform === 'codex' || rawPlatform === 'claude' || rawPlatform === 'both'
172
- ? rawPlatform
173
- : 'codex';
174
- return {
175
- command: command,
176
- plugins: request.plugins,
177
- platform,
178
- scope: request.scope === 'project' ? 'project' : 'user',
179
- };
180
- }
181
- function writeCommandFailureReceipt(write, request, error) {
182
- const platforms = request.platform === 'both'
183
- ? ['codex', 'claude']
184
- : [request.platform];
185
- writeJsonReceipt(write, buildRebuildReceiptJson(request.command, {
186
- platforms,
187
- plugins: request.plugins,
188
- warnings: [],
189
- overallState: 'failed',
190
- errors: [writeCommandFailure(error)],
191
- receiptTargets: request.plugins.flatMap((selector) => platforms.map((platform) => {
192
- let pluginName = selector;
193
- let sourceId;
194
- try {
195
- const parsed = parsePluginId(selector);
196
- pluginName = parsed.pluginName;
197
- sourceId = parsed.sourceId;
198
- }
199
- catch {
200
- // Keep the raw selector in the failed receipt.
201
- }
202
- return {
203
- pluginName,
204
- pluginId: selector,
205
- ...(sourceId ? { sourceId } : {}),
206
- platform,
207
- scope: request.scope,
208
- };
209
- })),
210
- }));
211
- }
212
- function scanConfigMutationShortOptions(token, command) {
213
- if (!/^-[^-].*/u.test(token))
214
- return { json: false, consumesNextValue: false };
215
- let json = false;
216
- for (let index = 1; index < token.length; index += 1) {
217
- const option = token[index];
218
- if (option === 's') {
219
- return {
220
- json,
221
- consumesNextValue: index === token.length - 1,
222
- };
223
- }
224
- if (option === 'j') {
225
- json = true;
226
- continue;
227
- }
228
- if (option === 'v' || option === 'D' || (option === 'y' && command === 'config:reset')) {
229
- continue;
230
- }
231
- break;
232
- }
233
- return { json, consumesNextValue: false };
234
- }
235
- function jsonConfigMutationRequest(argv) {
236
- if (argv[0] !== 'config' || !['set', 'unset', 'reset'].includes(argv[1] ?? '')) {
237
- return null;
238
- }
239
- const command = `config:${argv[1]}`;
240
- let json = false;
241
- let plugin;
242
- const valueOptions = new Set(['--scope', '--value-json', '--preset', '--log-file']);
243
- for (let index = 2; index < argv.length; index += 1) {
244
- const token = argv[index];
245
- if (token === '--')
246
- break;
247
- if (valueOptions.has(token)) {
248
- index += 1;
249
- continue;
250
- }
251
- if (token === '--json') {
252
- json = true;
253
- continue;
254
- }
255
- const shortOptions = scanConfigMutationShortOptions(token, command);
256
- if (shortOptions.json)
257
- json = true;
258
- if (shortOptions.consumesNextValue)
259
- index += 1;
260
- if (token.startsWith('-'))
261
- continue;
262
- plugin ??= token;
263
- }
264
- if (!json)
265
- return null;
266
- return {
267
- command,
268
- ...(plugin ? { plugin } : {}),
269
- };
270
- }
271
123
  function configMutationFailure(error, env, cwd) {
124
+ if (error instanceof ConfigApplyInterruptedError)
125
+ return { code: error.code, message: error.operationDiagnostic.safeMessage,
126
+ configWrite: error.configWrite, apply: error.apply };
127
+ const configWrite = error?.configWrite === 'succeeded' ? 'succeeded' : configWriteStateForError(error);
272
128
  if (error instanceof CommanderError) {
273
129
  return {
274
130
  code: 'invalidArguments',
275
131
  message: 'error: invalid config mutation arguments',
132
+ configWrite,
276
133
  };
277
134
  }
278
135
  const message = catalogPublicationFailure({
@@ -281,29 +138,29 @@ function configMutationFailure(error, env, cwd) {
281
138
  sensitiveRoots: [cwd],
282
139
  }).message;
283
140
  if (message.includes('Usage:'))
284
- return { code: 'invalidArguments', message };
141
+ return { code: 'invalidArguments', message, configWrite };
285
142
  const generationCode = catalogGenerationErrorCode(error);
286
143
  if (generationCode === 'catalogGenerationUnavailable'
287
144
  || generationCode === 'catalogGenerationSourceMissing') {
288
- return { code: 'catalogSourceUnavailable', message };
145
+ return { code: 'catalogSourceUnavailable', message, configWrite };
289
146
  }
290
147
  if (generationCode !== 'catalogGenerationFailed')
291
- return { code: generationCode, message };
148
+ return { code: generationCode, message, configWrite };
292
149
  const explicitCode = error?.code;
293
150
  if (typeof explicitCode === 'string' && /^[A-Za-z][A-Za-z0-9]*$/u.test(explicitCode)) {
294
- return { code: explicitCode, message };
151
+ return { code: explicitCode, message, configWrite };
295
152
  }
296
153
  if (message.includes('legacyStateUnsupported'))
297
- return { code: 'legacyStateUnsupported', message };
154
+ return { code: 'legacyStateUnsupported', message, configWrite };
298
155
  if (message.includes('sourceChanged'))
299
- return { code: 'sourceChanged', message };
156
+ return { code: 'sourceChanged', message, configWrite };
300
157
  if (message.includes('sourceMissing'))
301
- return { code: 'sourceMissing', message };
158
+ return { code: 'sourceMissing', message, configWrite };
302
159
  if (message.startsWith('Cannot resolve required catalog sources:')) {
303
- return { code: 'catalogSourceUnavailable', message };
160
+ return { code: 'catalogSourceUnavailable', message, configWrite };
304
161
  }
305
162
  const prefix = message.match(/^([A-Za-z][A-Za-z0-9]*):/u)?.[1];
306
- return { code: prefix ?? 'configMutationFailed', message };
163
+ return { code: prefix ?? 'configMutationFailed', message, configWrite };
307
164
  }
308
165
  function writeConfigMutationFailureReceipt(write, request, failure) {
309
166
  let plugin;
@@ -318,30 +175,33 @@ function writeConfigMutationFailureReceipt(write, request, failure) {
318
175
  }
319
176
  writeJsonReceipt(write, buildConfigMutationReceipt(request.command, {
320
177
  ok: false,
321
- overallState: 'failed',
178
+ overallState: failure.apply ? 'partial' : 'failed',
179
+ configWrite: failure.configWrite,
180
+ ...(failure.apply ? { apply: failure.apply } : {}),
322
181
  ...(plugin ? { plugin } : {}),
323
- errors: [failure],
182
+ errors: [{ code: failure.code, message: failure.message }],
324
183
  }));
325
184
  }
326
185
  async function runAuthoringScript(options) {
327
186
  const scriptPath = path.join(resolveCliPackageRoot(), 'dist', 'authoring', 'scripts', options.scriptName);
328
- return new Promise((resolve, reject) => {
329
- const child = spawn(process.execPath, [scriptPath, ...options.args], {
330
- cwd: options.cwd,
331
- env: options.env,
332
- stdio: ['ignore', 'pipe', 'pipe'],
333
- });
334
- child.stdout.on('data', (chunk) => options.io.stdout(String(chunk)));
335
- child.stderr.on('data', (chunk) => options.io.stderr(String(chunk)));
336
- child.once('error', reject);
337
- child.once('close', (code, signal) => {
338
- if (signal) {
339
- reject(new Error(`Plugin authoring command terminated by signal ${signal}.`));
340
- return;
341
- }
342
- resolve(code ?? 1);
187
+ try {
188
+ const result = await defaultPluginProcessRunner.run({ command: process.execPath, args: [scriptPath, ...options.args], cwd: options.cwd, env: options.env }, {
189
+ // Authoring has no CLI timeout option. Keep the largest Node timer while
190
+ // using the existing process-tree cleanup contract for interruption.
191
+ timeoutMs: 2_147_483_647, signal: options.interruption?.signal, maxStdoutBytes: 32 * 1024 * 1024,
343
192
  });
344
- });
193
+ options.io.stdout(result.stdout);
194
+ options.io.stderr(result.stderr);
195
+ return result.exitCode ?? 1;
196
+ }
197
+ catch (error) {
198
+ if (options.interruption?.signal.aborted && error !== options.interruption.signal.reason)
199
+ options.interruption.cleanupFailed = true;
200
+ if (options.interruption?.signal.aborted && ['init-plugin.mjs', 'add-skill.mjs', 'remove-plugin.mjs'].includes(options.scriptName)) {
201
+ throw Object.assign(new Error('The authoring command was interrupted after execution started.'), { code: 'operationInterrupted', authoringChanges: 'unknown' });
202
+ }
203
+ throw error;
204
+ }
345
205
  }
346
206
  function toCliDiagnosticsOptions(commandName, rawOptions, runtimeDiagnostics) {
347
207
  return {
@@ -355,163 +215,12 @@ function toCliDiagnosticsOptions(commandName, rawOptions, runtimeDiagnostics) {
355
215
  function isWizardAvailable(context, rawOptions) {
356
216
  return context.interactive && context.isTty && !context.isCi && rawOptions.json !== true;
357
217
  }
358
- function shellCommand(tokens) {
359
- return renderShellCommand(tokens, 'posix');
360
- }
361
- function optionTokens(flag, value) {
362
- return value === undefined ? [] : [flag, value];
363
- }
364
- function writeCommandUsage(command) {
365
- const cardinality = command === 'reinstall' || command === 'cleanup' ? '<plugin>' : '<plugin...>';
366
- const scope = command === 'cleanup' ? ' --scope <project|user>' : ' [--scope <project|user>]';
367
- return [
368
- `${command} 命令缺少必要参数。`,
369
- `Usage: aw ${command} ${cardinality} --platform <codex|claude|both>${scope}`,
370
- `Example: aw ${command} example-plugin --platform codex --scope user`,
371
- ].join('\n');
372
- }
373
- function configCommandUsage(command) {
374
- const argumentsByCommand = {
375
- list: '<plugin>',
376
- get: '<plugin> [key]',
377
- set: '<plugin> <field> --scope <project|user> (--value-json <json> | --preset <id>)',
378
- unset: '<plugin> <key>',
379
- reset: '<plugin> --scope <project|user> --yes',
380
- };
381
- return [
382
- `config ${command} 命令缺少必要参数。`,
383
- `Usage: aw config ${command} ${argumentsByCommand[command]}`,
384
- `Example: aw config ${command} example-plugin${command === 'set' ? ' mode --scope user --value-json \'"safe"\'' : command === 'unset' ? ' key' : command === 'reset' ? ' --scope user --yes' : ''}`,
385
- ].join('\n');
386
- }
387
- function equivalentWriteCommand(command, selection, rawOptions) {
388
- return shellCommand(buildEquivalentWriteCommandTokens(command, selection, rawOptions));
389
- }
390
- export function buildEquivalentWriteCommandTokens(command, selection, rawOptions) {
391
- return [
392
- 'aw',
393
- command,
394
- '--platform',
395
- selection.platform ?? 'both',
396
- '--scope',
397
- selection.scope ?? 'user',
398
- ...(rawOptions.allowManagedCodexInstall === true
399
- ? ['--allow-managed-codex-install']
400
- : []),
401
- ...(command === 'install'
402
- ? (rawOptions.dependencyScope ?? []).flatMap((value) => ['--dependency-scope', value])
403
- : []),
404
- ...(command === 'cleanup' ? [] : optionTokens('--script-timeout', rawOptions.scriptTimeout)),
405
- ...(selection.plugins.length > 0 ? ['--', ...selection.plugins] : []),
406
- ];
407
- }
408
- function equivalentConfigCommand(options) {
409
- return shellCommand(buildEquivalentConfigCommandTokens(options));
410
- }
411
- function equivalentConfigCommandProjection(resolve) {
412
- return {
413
- equivalentCommand: (selection) => equivalentConfigCommand(resolve(selection)),
414
- equivalentCommandTokens: (selection) => buildEquivalentConfigCommandTokens(resolve(selection)),
415
- };
416
- }
417
- export function buildEquivalentConfigCommandTokens(options) {
418
- return [
419
- 'aw',
420
- 'config',
421
- options.command,
422
- ...optionTokens('--scope', options.scope),
423
- ...optionTokens('--value-json', options.valueJson),
424
- ...optionTokens('--preset', options.preset),
425
- ...(options.confirmed ? ['--yes'] : []),
426
- '--',
427
- options.plugin,
428
- ...(options.key === undefined ? [] : [options.key]),
429
- ...(options.value === undefined ? [] : [options.value]),
430
- ];
431
- }
432
- function hasSelectableWriteCandidate(command, candidates, selection, options) {
433
- const platforms = options.missingPlatform
434
- ? ['codex', 'claude', 'both']
435
- : [selection.platform ?? 'both'];
436
- const scopes = options.missingScope ? ['user', 'project'] : [selection.scope ?? 'user'];
437
- return candidates.some((candidate) => platforms.some((platform) => scopes.some((scope) => writeCandidateEligibility(command, candidate, { ...selection, platform, scope }).selectable)));
438
- }
439
- function hasConfigSchemaKeys(candidate) {
440
- return candidate.configSchema !== undefined && Object.keys(candidate.configSchema).length > 0;
441
- }
442
- async function loadWizardCandidates(context, rawOptions) {
443
- const loaded = await loadConsoleItemsResult({
444
- cwd: context.cwd,
445
- scope: rawOptions.scope,
446
- platform: rawOptions.platform,
447
- }, context);
448
- return toWizardCandidates(loaded.items);
449
- }
450
- function mergeWizardCandidates(current, stored) {
451
- const merged = new Map(current.map((candidate) => [candidate.pluginName, candidate]));
452
- for (const candidate of stored) {
453
- const existing = merged.get(candidate.pluginName);
454
- if (!existing) {
455
- merged.set(candidate.pluginName, candidate);
456
- }
457
- else if (!existing.configSchema) {
458
- merged.set(candidate.pluginName, { ...candidate, ...existing });
459
- }
460
- }
461
- return [...merged.values()];
462
- }
463
- async function loadStoredConfigWizardCandidates(context, locations, options = {}) {
464
- const legacy = await listPluginConfigStorePluginNames({ cwd: context.cwd, env: context.env });
465
- if (legacy.length > 0) {
466
- throw new Error('legacyStateUnsupported: legacy bare-name config stores are not supported.');
467
- }
468
- const storesByPlugin = new Map();
469
- for (const location of locations) {
470
- const stores = await listNamespacedPluginConfigStores({
471
- cwd: context.cwd,
472
- env: context.env,
473
- scope: location.scope,
474
- });
475
- for (const store of stores) {
476
- const keys = Object.keys(store.values);
477
- if (keys.length === 0 && options.includeEmptyStores !== true)
478
- continue;
479
- const existing = storesByPlugin.get(store.pluginId) ?? {
480
- sourceId: store.sourceId,
481
- sourceIdentity: store.sourceIdentity,
482
- keys: new Set(),
483
- };
484
- if (existing.sourceIdentity !== store.sourceIdentity) {
485
- throw new Error(`sourceChanged: ${store.pluginId} config stores have different source identities.`);
486
- }
487
- for (const key of keys)
488
- existing.keys.add(key);
489
- storesByPlugin.set(store.pluginId, existing);
490
- }
218
+ async function readUtf8Stdin(stdin) {
219
+ const chunks = [];
220
+ for await (const chunk of stdin) {
221
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : Buffer.from(chunk));
491
222
  }
492
- return [...storesByPlugin]
493
- .sort(([left], [right]) => left.localeCompare(right))
494
- .map(([pluginId, store]) => ({
495
- pluginName: pluginId,
496
- pluginId,
497
- sourceId: store.sourceId,
498
- sourceIdentity: store.sourceIdentity,
499
- targets: [],
500
- configKeys: [...store.keys].sort((left, right) => left.localeCompare(right)),
501
- }));
502
- }
503
- function configReadStoreLocations(rawOptions) {
504
- if (rawOptions.scope === 'user')
505
- return [{ scope: 'user' }];
506
- if (rawOptions.scope === 'project')
507
- return [{ scope: 'project' }];
508
- return [
509
- { scope: 'user' },
510
- { scope: 'project' },
511
- ];
512
- }
513
- function overallResultState(value) {
514
- return value.overallState === 'succeeded' ? 'succeeded' : 'failed';
223
+ return Buffer.concat(chunks).toString('utf8');
515
224
  }
516
225
  async function resolveStoredConfigResetIdentity(options) {
517
226
  const parsed = parsePluginId(options.selector);
@@ -538,26 +247,24 @@ async function resolveStoredConfigResetIdentity(options) {
538
247
  pluginName: match.pluginName,
539
248
  pluginId: match.pluginId,
540
249
  sourceId: match.sourceId,
541
- sourceIdentity: match.sourceIdentity,
250
+ sourceIdentity: match.binding.sourceIdentity,
542
251
  };
543
252
  }
544
253
  async function resolveStoredOnlyConfigIdentity(options) {
545
254
  const parsed = parsePluginId(options.selector);
546
255
  if (!parsed.sourceId)
547
256
  throw new Error(`Plugin "${options.selector}" is not a qualified stored config target.`);
548
- const stores = (await Promise.all(options.locations.map((location) => listNamespacedPluginConfigStores({
549
- cwd: options.context.cwd,
550
- env: options.context.env,
551
- scope: location.scope,
552
- })))).flat().filter((store) => store.pluginId === options.selector);
257
+ const stores = (await listNamespacedPluginConfigStores({
258
+ cwd: options.context.cwd, env: options.context.env, scope: 'user',
259
+ })).filter((store) => store.pluginId === options.selector);
553
260
  if (stores.length === 0)
554
261
  throw new Error(`Plugin "${options.selector}" does not have a namespaced config store.`);
555
- const identities = new Set(stores.map((store) => store.sourceIdentity));
556
- if (identities.size !== 1) {
557
- throw new Error(`sourceChanged: ${options.selector} config stores have different source identities.`);
262
+ const sourceBindings = stores.flatMap((store) => store.binding.kind === 'source'
263
+ ? [store.binding.sourceIdentity] : []);
264
+ if (new Set(sourceBindings).size > 1) {
265
+ throw new Error(`identityMismatch: ${options.selector} config stores have different bindings.`);
558
266
  }
559
- const sourceIdentity = [...identities][0];
560
- await withResolvedMultiSourceCatalog({
267
+ const currentSource = await withResolvedMultiSourceCatalog({
561
268
  cliVersion: resolveCliVersion(),
562
269
  sourceIds: [parsed.sourceId],
563
270
  env: options.context.env,
@@ -566,39 +273,49 @@ async function resolveStoredOnlyConfigIdentity(options) {
566
273
  if (!source?.resolution) {
567
274
  throw source?.error ?? new Error(`Catalog source "${parsed.sourceId}" is unavailable.`);
568
275
  }
569
- if (source.resolution.sourceIdentity !== sourceIdentity) {
570
- throw new Error(`sourceChanged: ${options.selector} config source identity does not match the current source.`);
571
- }
276
+ return {
277
+ sourceIdentity: source.resolution.sourceIdentity,
278
+ logicalIdentity: source.resolution.logicalIdentity,
279
+ };
572
280
  },
573
281
  });
282
+ if (sourceBindings[0] && sourceBindings[0] !== currentSource.sourceIdentity) {
283
+ throw new Error(`identityMismatch: ${options.selector} user config does not match the current source identity.`);
284
+ }
574
285
  return {
575
286
  pluginName: parsed.pluginName,
576
287
  pluginId: options.selector,
577
288
  sourceId: parsed.sourceId,
578
- sourceIdentity,
289
+ sourceIdentity: currentSource.sourceIdentity,
290
+ logicalIdentity: currentSource.logicalIdentity,
579
291
  };
580
292
  }
581
293
  async function resolveMultiSourceConfigRead(options) {
582
- const inventory = await inventoryLegacyConfigReferences({
583
- cwd: options.context.cwd,
584
- env: options.context.env,
585
- });
586
- assertCatalogSourceReferencesSupported(inventory);
294
+ if (!options.schemaOnly) {
295
+ const inventory = await inventoryLegacyConfigReferences({
296
+ cwd: options.context.cwd,
297
+ env: options.context.env,
298
+ scope: options.rawOptions.context === 'project' ? 'project' : 'user',
299
+ });
300
+ assertCatalogSourceReferencesSupported(inventory);
301
+ }
587
302
  return withResolvedCatalogPlugin({
588
303
  selector: options.selector,
589
304
  cliVersion: resolveCliVersion(),
590
305
  env: options.context.env,
591
306
  consume: async ({ pluginId, source, plugin }) => {
592
307
  const result = await resolveConfigRead({
308
+ schemaOnly: options.schemaOnly,
593
309
  pluginName: plugin.manifest.name,
594
310
  plugin,
595
- scope: resolveConfigReadResolution(options.rawOptions.scope),
311
+ scope: options.rawOptions.context === 'project' ? 'project' : 'user',
312
+ platform: options.rawOptions.platform,
596
313
  cwd: options.context.cwd,
597
314
  env: options.context.env,
598
315
  });
599
316
  if (options.key !== undefined) {
600
317
  const field = findConfigFieldEntry(result.fields, options.key);
601
- if (!field && plugin.manifest.config?.fields?.[options.key] === undefined) {
318
+ if (!field && compilePluginConfigDefinition(plugin.manifest.config, options.rawOptions.platform).fields[options.key] === undefined) {
602
319
  throw new Error(`Unknown config key "${options.key}".`);
603
320
  }
604
321
  if (field)
@@ -619,14 +336,16 @@ async function resolveMultiSourceConfigRead(options) {
619
336
  const stored = await resolveStoredOnlyConfigIdentity({
620
337
  selector: options.selector,
621
338
  context: options.context,
622
- locations: configReadStoreLocations(options.rawOptions),
623
339
  });
624
340
  const result = await resolveConfigRead({
341
+ schemaOnly: options.schemaOnly,
625
342
  sourceId: stored.sourceId,
626
343
  sourceIdentity: stored.sourceIdentity,
344
+ logicalIdentity: stored.logicalIdentity,
627
345
  pluginName: stored.pluginName,
628
346
  plugin: null,
629
- scope: resolveConfigReadResolution(options.rawOptions.scope),
347
+ scope: options.rawOptions.context === 'project' ? 'project' : 'user',
348
+ platform: options.rawOptions.platform,
630
349
  cwd: options.context.cwd,
631
350
  env: options.context.env,
632
351
  });
@@ -639,114 +358,41 @@ async function resolveMultiSourceConfigRead(options) {
639
358
  return { ...stored, result };
640
359
  });
641
360
  }
642
- export function createManagedCodexAuthorizer(rawOptions, context) {
643
- if (rawOptions.allowManagedCodexInstall === true)
644
- return async () => true;
645
- if (!(context.interactive && context.isTty && !context.isCi && rawOptions.json !== true)
646
- || !context.prompt.confirm)
647
- return undefined;
648
- return async () => {
649
- const response = await context.prompt.confirm({
650
- message: '系统中没有可用的 Codex CLI。是否获取本次操作所需的 AW-managed Codex runtime?',
651
- defaultValue: false,
652
- });
653
- return !response.cancelled && response.value === true;
654
- };
655
- }
656
- async function executeWriteCommand(command, pluginNames, rawOptions, context, directCli = false) {
657
- const raw = { cwd: context.cwd, ...rawOptions };
658
- const commandOptions = normalizeWriteRequest(() => command === 'install'
659
- ? normalizeInstallCommandOptions(raw)
660
- : command === 'uninstall'
661
- ? normalizeUninstallCommandOptions(raw)
662
- : command === 'cleanup'
663
- ? normalizeCleanupCommandOptions(raw)
664
- : normalizeReinstallCommandOptions(raw));
665
- await emitCommandEvent(context, {
666
- type: 'options:normalized',
667
- data: { plugins: pluginNames, options: commandOptions },
668
- });
669
- const managedCodexAuthorizer = createManagedCodexAuthorizer(rawOptions, context);
670
- const runtime = {
671
- ...context,
672
- directCli,
673
- ...(managedCodexAuthorizer ? { managedCodexAuthorizer } : {}),
674
- };
675
- switch (command) {
676
- case 'install': return installCommand(pluginNames, commandOptions, runtime);
677
- case 'uninstall': return uninstallCommand(pluginNames, commandOptions, runtime);
678
- case 'cleanup': return cleanupCommand(pluginNames, commandOptions, runtime);
679
- case 'reinstall': return reinstallCommand(pluginNames, commandOptions, runtime);
680
- }
681
- }
682
- async function runWriteCommandAction(command, pluginNames, rawOptions, context) {
683
- if ((command === 'cleanup' || command === 'reinstall') && pluginNames.length > 1) {
684
- throw new WriteCommandRequestError(`${command} 命令当前只支持单个插件目标。`);
685
- }
686
- const missingPlugin = pluginNames.length === 0;
687
- const missingPlatform = rawOptions.platform === undefined;
688
- const missingScope = command === 'cleanup' && rawOptions.scope === undefined;
689
- const missing = missingPlugin || missingPlatform || missingScope;
690
- // Validate every value already supplied by the caller before opening the TUI.
691
- const validationOptions = {
692
- cwd: context.cwd,
693
- ...rawOptions,
694
- platform: rawOptions.platform ?? 'both',
695
- ...(command === 'cleanup' ? { scope: rawOptions.scope ?? 'user' } : {}),
696
- };
697
- void validationOptions;
698
- if (!missing) {
699
- return {
700
- cancelled: false,
701
- result: await executeWriteCommand(command, pluginNames, rawOptions, context, true),
702
- };
361
+ function renderRecoveryReceipt(write, value) {
362
+ writeLine(write, `${value.command} [${value.scope}]: ${value.ok ? 'ok' : 'failed'}`);
363
+ writeLine(write, `需求:${value.intent.roots?.join('、') || (value.intent.roots === null ? '不可读' : '无')}`);
364
+ writeLine(write, `本机工具:${value.selection.agents.join('、') || '未配置'}`);
365
+ writeLine(write, `变化:声明 ${value.declarationChanged ? '已保存' : '无'};偏好 ${value.preferencesChanged ? '已保存' : '无'};配置 ${value.configChanged ? '已保存' : '无'};输出 ${value.outputsMayHaveChanged ? '可能已变更' : '无'}`);
366
+ for (const target of value.targetResults) {
367
+ writeLine(write, `${target.pluginId} / ${target.agent} [${target.scope}]: ${target.execution}; ${target.content ?? target.observation}`);
703
368
  }
704
- if (!isWizardAvailable(context, rawOptions)) {
705
- throw new WriteCommandRequestError(writeCommandUsage(command));
369
+ for (const result of value.commandResults ?? []) {
370
+ writeLine(write, `托管命令 ${result.selector} [${result.packageId}] ${result.action} / ${result.availability} (${result.state})`);
706
371
  }
707
- const loaded = await loadConsoleItemsResult({
708
- cwd: context.cwd,
709
- scope: rawOptions.scope,
710
- platform: rawOptions.platform,
711
- }, context);
712
- if (loaded.catalogUnavailable) {
713
- throw new Error('插件目录不可用。请运行 `aw init` 或 `aw init --force`,或使用完整参数重试。');
372
+ for (const change of value.nativeToolChanges ?? []) {
373
+ for (const phase of ['before', 'after']) {
374
+ const closure = change[phase];
375
+ if (closure)
376
+ for (const description of describeNativeToolClosure(closure)) {
377
+ writeLine(write, `原生工具 ${change.producer.sourceId}/${change.producer.pluginName} ${phase}: ${description}`);
378
+ }
379
+ }
714
380
  }
715
- const candidates = missingPlugin ? toWizardCandidates(loaded.items) : [];
716
- const initialSelection = {
717
- plugins: pluginNames,
718
- platform: rawOptions.platform,
719
- scope: (rawOptions.scope ?? 'user'),
381
+ const diagnostics = new Map([...value.blockers, ...value.errors,
382
+ ...value.targetResults.flatMap((target) => target.blockers),
383
+ ...(value.commandResults ?? []).flatMap((result) => result.errors),
384
+ ].map((item) => [`${item.code}:${item.message}`, item]));
385
+ for (const item of diagnostics.values())
386
+ writeLine(write, `${item.code}: ${item.message}`);
387
+ for (const action of value.recoveryActions)
388
+ writeLine(write, action);
389
+ }
390
+ function recoveryRuntime(context, rawOptions, directCli) {
391
+ return {
392
+ ...context,
393
+ directCli,
394
+ preApplyConfirmed: rawOptions.yes === true,
720
395
  };
721
- if (missingPlugin && !hasSelectableWriteCandidate(command, candidates, initialSelection, {
722
- missingPlatform,
723
- missingScope,
724
- })) {
725
- throw new Error('没有可执行此操作的目标。请运行 `aw status` 检查当前状态。');
726
- }
727
- const result = await runCommandWizard(context, {
728
- command,
729
- candidates,
730
- initial: initialSelection,
731
- pluginMode: missingPlugin
732
- ? command === 'cleanup' || command === 'reinstall' ? 'single' : 'multiple'
733
- : 'none',
734
- promptForPlatform: missingPlatform,
735
- promptForScope: missingScope,
736
- destructive: command === 'uninstall' || command === 'cleanup',
737
- equivalentCommand: (selection) => equivalentWriteCommand(command, selection, rawOptions),
738
- equivalentCommandTokens: (selection) => buildEquivalentWriteCommandTokens(command, selection, rawOptions),
739
- isPluginSelectable: (candidate, selection) => writeCandidateEligibility(command, candidate, selection),
740
- resultState: overallResultState,
741
- execute: (selection) => executeWriteCommand(command, selection.plugins, {
742
- ...rawOptions,
743
- platform: selection.platform,
744
- scope: selection.scope,
745
- }, context),
746
- });
747
- if (result.cancelled)
748
- return { cancelled: true };
749
- return { cancelled: false, result: result.value };
750
396
  }
751
397
  function parseBareConsoleOptions(argv) {
752
398
  if (argv.length === 0) {
@@ -805,7 +451,7 @@ async function runActionWithContext(context, action) {
805
451
  Promise.resolve().then(() => context.debugLogger.flush?.()),
806
452
  ]);
807
453
  if (context.diagnostics.debug && context.debugLogger.logFile) {
808
- writeLine(context.io.stderr, `调试日志:${context.debugLogger.logFile}`);
454
+ writeLine(context.io.stderr, `Debug log: ${context.debugLogger.logFile}`);
809
455
  }
810
456
  return result;
811
457
  }
@@ -845,41 +491,96 @@ async function runActionWithContext(context, action) {
845
491
  Promise.resolve().then(() => context.debugLogger.flush?.()),
846
492
  ]);
847
493
  if (context.diagnostics.debug && context.debugLogger.logFile) {
848
- writeLine(context.io.stderr, `调试日志:${context.debugLogger.logFile}`);
494
+ writeLine(context.io.stderr, `Debug log: ${context.debugLogger.logFile}`);
849
495
  }
850
496
  throw error;
851
497
  }
852
498
  }
853
499
  function writeJsonReceipt(write, payload) {
854
- writeLine(write, JSON.stringify(payload, null, 2));
855
- }
856
- function configLayerLabel(scope) {
857
- if (scope === 'user') {
858
- return '个人';
859
- }
860
- return '当前项目';
500
+ const sink = receiptSinks.get(write);
501
+ if (sink)
502
+ sink(payload);
503
+ else
504
+ writeLine(write, JSON.stringify(payload, null, 2));
861
505
  }
862
506
  function writeConfigApplyNotice(write, receipt) {
863
- if (receipt.targetResults.length === 0) {
864
- const message = receipt.applySkippedReason === 'noConfigChange'
865
- ? '配置内容没有变化,因此没有运行 reinstall。'
866
- : receipt.applySkippedReason === 'invalidConfig'
867
- ? '配置已保存,但当前配置无效,因此没有运行 reinstall。请先修复无效字段。'
868
- : '配置已保存。当前没有可见的 AW 安装目标,因此没有应用配置。';
507
+ const sanitizeMessage = (message) => redactString(message)
508
+ .replace(/https?:\/\/\S+/giu, '[REDACTED URL]')
509
+ .replace(/file:\/\/\S+/giu, '[REDACTED PATH]')
510
+ .replace(/(?:file:\/\/)?(?:\/[\w.@+-]+){2,}/gu, '[REDACTED PATH]')
511
+ .replace(/[A-Za-z]:\\(?:[^\s\\]+\\)+[^\s\\]*/gu, '[REDACTED PATH]');
512
+ const writeTargetFailures = () => {
513
+ for (const entry of receipt.apply.targetResults.filter((target) => target.state === 'failed' || target.state === 'skipped')) {
514
+ const reason = entry.message
515
+ ? `${entry.errorCode ? `[${entry.errorCode}] ` : ''}${sanitizeMessage(entry.message)}`
516
+ : entry.errorCode
517
+ ? `失败原因:${entry.errorCode}。`
518
+ : '未提供安全失败原因。';
519
+ const command = `aw plugin sync ${receipt.plugin} --rebuild --target ${entry.target.platform} --context ${entry.target.scope}`;
520
+ const recovery = entry.partialDelivery
521
+ ? ' 部分输出已验证。请检查尚未完成的输出后再重新准备应用。'
522
+ : entry.errorCode === 'invalidConfig'
523
+ ? ` 请修复无效配置后运行 ${command}。`
524
+ : entry.errorCode === 'preApplyAuthorizationRequired'
525
+ || entry.errorCode === 'sharedNativeConfigApplyConfirmationRequired'
526
+ || entry.errorCode === 'sharedNativeImpactAuthorizationRequired'
527
+ ? ` 请运行 ${command} --yes 重试。`
528
+ : entry.state === 'failed'
529
+ ? ` 请在解决失败原因后运行 ${command}。`
530
+ : '';
531
+ writeLine(write, `${entry.target.platform}/${entry.target.scope}:${reason}${recovery}`);
532
+ }
533
+ };
534
+ const targetResults = receipt.apply.targetResults;
535
+ if (receipt.apply.state === 'skipped') {
536
+ const message = receipt.apply.reason === 'noConfigChange'
537
+ ? '配置内容没有变化,因此没有刷新输出。'
538
+ : receipt.apply.reason === 'noEffectiveConfigChange'
539
+ ? '配置存储已更新,但有效配置没有变化,因此没有刷新输出。'
540
+ : receipt.apply.reason === 'notRequested'
541
+ ? '配置已保存,但未请求应用配置。'
542
+ : '配置已保存。当前没有可见的 AW 安装目标,因此没有应用配置。';
869
543
  writeLine(write, message);
870
544
  }
871
- else {
872
- const completed = receipt.targetResults.filter((entry) => entry.state === 'completed').length;
873
- const failed = receipt.targetResults.filter((entry) => entry.state === 'failed');
874
- writeLine(write, `配置已保存。已重装 ${completed} 个当前可见目标;失败 ${failed.length} 个。`);
875
- for (const entry of failed) {
876
- writeLine(write, `${entry.target.platform}/${entry.target.scope}:${entry.message ?? 'reinstall 失败。'} `
877
- + `请重试 aw reinstall ${receipt.plugin} -p ${entry.target.platform} -s ${entry.target.scope}。`);
878
- }
545
+ else if (receipt.apply.state === 'unavailable') {
546
+ const fallbackMessages = {
547
+ invalidConfig: '可见目标的有效配置无效。',
548
+ schemaUnavailable: '配置 schema 不可用。',
549
+ sourceUnavailable: '插件来源不可用。',
550
+ effectiveConfigUnavailable: '无法读取有效配置。',
551
+ targetDiscoveryFailed: '无法发现可应用配置的目标。',
552
+ };
553
+ const detail = receipt.apply.error
554
+ ? `${receipt.apply.error.code}:${sanitizeMessage(receipt.apply.error.message)}`
555
+ : `${receipt.apply.reason}:${fallbackMessages[receipt.apply.reason]}`;
556
+ const recovery = receipt.apply.reason === 'invalidConfig'
557
+ ? '请修复无效配置,再运行 aw plugin sync <source/plugin>。'
558
+ : receipt.apply.reason === 'effectiveConfigUnavailable'
559
+ ? '请修复配置,再运行 aw plugin sync <source/plugin>。'
560
+ : receipt.apply.reason === 'schemaUnavailable' || receipt.apply.reason === 'sourceUnavailable'
561
+ ? '请修复插件来源或配置,再运行 aw plugin sync <source/plugin>。'
562
+ : '请修复来源或配置,再运行 aw plugin sync <source/plugin>。';
563
+ writeLine(write, `配置已保存,但当前无法应用配置。${detail} ${recovery}`);
564
+ writeTargetFailures();
879
565
  }
880
- if (receipt.otherProjectsRequireReinstall) {
881
- writeLine(write, '其它项目没有被扫描。请进入每个项目目录并运行对应的 aw reinstall 命令。');
566
+ else {
567
+ const completed = targetResults.filter((entry) => entry.state === 'completed').length;
568
+ const partiallyDelivered = targetResults.filter((entry) => entry.partialDelivery).length;
569
+ const failed = targetResults.filter((entry) => entry.state === 'failed' && !entry.partialDelivery).length;
570
+ const skipped = targetResults.filter((entry) => entry.state === 'skipped').length;
571
+ const partialSummary = partiallyDelivered > 0 ? `部分完成 ${partiallyDelivered} 个;` : '';
572
+ writeLine(write, `配置已保存。已刷新 ${completed} 个当前可见目标;${partialSummary}失败 ${failed} 个;跳过 ${skipped} 个。`);
573
+ writeTargetFailures();
882
574
  }
575
+ if (receipt.apply.state !== 'skipped')
576
+ for (const entry of receipt.apply.commandResults ?? []) {
577
+ writeLine(write, `托管命令 ${entry.selector} [${entry.packageId}] ${entry.action} / ${entry.availability} (${entry.state})`);
578
+ for (const error of entry.errors)
579
+ writeLine(write, `[${error.code}] ${sanitizeMessage(error.message)}`);
580
+ for (const action of entry.recoveryActions)
581
+ writeLine(write, action);
582
+ }
583
+ writeWarnings(write, receipt.warnings);
883
584
  }
884
585
  function renderConfigFieldState(field) {
885
586
  if (field.valueState === 'invalid') {
@@ -898,12 +599,14 @@ function writeConfigReadHuman(write, resolved, pluginName) {
898
599
  writeLine(write, ` stored=${field.storedSourceLayer} ${renderPluginConfigValueForDisplay(field.storedValue)}`);
899
600
  }
900
601
  if (field.kind === 'manifest' && field.valueState === 'invalid') {
901
- const sourceScope = field.sourceLayer === 'project'
902
- ? ' -s project'
903
- : ' -s user';
904
- writeLine(write, ` aw config set ${pluginName} ${field.key}${sourceScope} --value-json '<json>'`);
905
- writeLine(write, ` aw config unset ${pluginName} ${field.key}${sourceScope}`);
906
- writeLine(write, ` aw config reset ${pluginName}${sourceScope}`);
602
+ const context = resolved.context ?? 'user';
603
+ const definition = resolved.fieldDefinitions?.[field.key];
604
+ if (definition) {
605
+ writeLine(write, ` ${formatPluginConfigSetRecoveryCommand(pluginName, field.key, definition, context, resolved.platform)}`);
606
+ }
607
+ const profileOptions = ` --context ${context}${resolved.platform ? ` --platform ${resolved.platform}` : ''}`;
608
+ writeLine(write, ` aw plugin config unset ${pluginName} ${field.key}${profileOptions}`);
609
+ writeLine(write, ` aw plugin config reset ${pluginName}${profileOptions} --yes`);
907
610
  }
908
611
  }
909
612
  }
@@ -920,10 +623,13 @@ export function buildProgram(options = {}) {
920
623
  cwd,
921
624
  env,
922
625
  io,
923
- interactive: options.interactive,
626
+ interactive: false,
627
+ reporter: options.reporter ?? createNoopReporter(),
924
628
  diagnostics: toCliDiagnosticsOptions(commandName, rawOptions, options.diagnostics),
925
629
  });
926
- const program = new Command();
630
+ if (io.result)
631
+ receiptSinks.set(io.stdout, io.result);
632
+ const program = new Command().enablePositionalOptions();
927
633
  program
928
634
  .name('aw')
929
635
  .description('Agent workflow marketplace installer')
@@ -934,9 +640,15 @@ export function buildProgram(options = {}) {
934
640
  writeErr: (text) => io.stderr(text),
935
641
  outputError: (text, write) => write(text),
936
642
  });
643
+ const dev = program.command('dev').description('Create, validate, build, and publish author sources');
644
+ const devPlugin = dev.command('plugin').description('Manage plugin source code');
937
645
  const plugin = program
938
646
  .command('plugin')
939
- .description('Create and validate AW plugin source');
647
+ .description('Manage plugin demand, outputs, configuration, and author sources');
648
+ registerManagedCommandCli(program, (rawOptions = {}) => createActionContext('command', rawOptions), {
649
+ cliEntry: fileURLToPath(import.meta.url),
650
+ cliVersion: resolveCliVersion(),
651
+ }, (code) => { commandExitState.exitCode = code; });
940
652
  const self = program
941
653
  .command('self')
942
654
  .description('Describe and check this AW executable');
@@ -960,10 +672,10 @@ export function buildProgram(options = {}) {
960
672
  writeJsonReceipt(io.stdout, result);
961
673
  commandExitState.exitCode = result.ok ? 0 : 1;
962
674
  });
963
- plugin
675
+ devPlugin
964
676
  .command('capabilities')
965
677
  .description('Show the current plugin manifest authoring surface')
966
- .option('--surface <surface>', 'manifest | build-config | extensions | slash-commands | mcp-apps | config | post-apply | artifacts')
678
+ .option('--surface <surface>', 'manifest | build-config | extensions | mcp | config | pre-apply | artifacts | platform-components | platform-capabilities | hook-handlers | managed-commands | native-tools')
967
679
  .option('--json', 'emit one machine-readable JSON object', false)
968
680
  .action((rawOptions) => {
969
681
  try {
@@ -985,7 +697,7 @@ export function buildProgram(options = {}) {
985
697
  commandExitState.exitCode = 1;
986
698
  }
987
699
  });
988
- plugin
700
+ devPlugin
989
701
  .command('requirements')
990
702
  .description('Inspect or update effective AW capabilities required by a plugin')
991
703
  .argument('<plugin-directory>', 'plugin source directory')
@@ -1008,6 +720,8 @@ export function buildProgram(options = {}) {
1008
720
  }
1009
721
  }
1010
722
  catch (error) {
723
+ if (error instanceof CatalogWorkspaceMissingError)
724
+ throw error;
1011
725
  writeJsonReceipt(io.stdout, {
1012
726
  schemaVersion: 1,
1013
727
  command: 'plugin:requirements',
@@ -1017,19 +731,21 @@ export function buildProgram(options = {}) {
1017
731
  commandExitState.exitCode = 1;
1018
732
  }
1019
733
  });
1020
- const skill = program
734
+ const skill = dev
1021
735
  .command('skill')
1022
736
  .description('Install, materialize, or validate Agent Skills');
1023
- const skillEval = skill
737
+ const skillEval = dev
1024
738
  .command('eval')
1025
739
  .description('Prepare or diagnose deterministic Agent Skill Eval inputs');
1026
740
  skillEval
1027
- .command('doctor')
741
+ .command('check')
1028
742
  .description('Inspect Agent Skill Eval provider readiness without model execution')
1029
743
  .requiredOption('--json', 'emit one provider doctor JSON object')
1030
744
  .action(async () => {
1031
745
  try {
1032
- writeJsonReceipt(io.stdout, await doctorEvalProviders({ sourceEnv: env }));
746
+ writeJsonReceipt(io.stdout, await doctorEvalProviders({
747
+ sourceEnv: env,
748
+ }));
1033
749
  }
1034
750
  catch (error) {
1035
751
  writeJsonReceipt(io.stdout, {
@@ -1046,6 +762,7 @@ export function buildProgram(options = {}) {
1046
762
  .argument('<skill>', 'owner Skill name')
1047
763
  .option('--suite <suite>', 'Eval suite ID')
1048
764
  .option('--profile <profile>', 'Eval profile ID')
765
+ .option('--config-file <path>', 'non-sensitive plugin config overrides for the Eval profile')
1049
766
  .option('--workspace-root <root>', 'Catalog Workspace root')
1050
767
  .option('--split <split>', 'case split filter')
1051
768
  .option('--case <id>', 'case ID filter')
@@ -1077,6 +794,7 @@ export function buildProgram(options = {}) {
1077
794
  skillName,
1078
795
  ...(rawOptions.suite === undefined ? {} : { suiteId: rawOptions.suite }),
1079
796
  ...(rawOptions.profile === undefined ? {} : { profileId: rawOptions.profile }),
797
+ ...(rawOptions.configFile === undefined ? {} : { configFile: path.resolve(cwd, rawOptions.configFile) }),
1080
798
  output: rawOptions.output,
1081
799
  cwd,
1082
800
  env,
@@ -1095,6 +813,8 @@ export function buildProgram(options = {}) {
1095
813
  writeJsonReceipt(io.stdout, receipt);
1096
814
  }
1097
815
  catch (error) {
816
+ if (error instanceof CatalogWorkspaceMissingError)
817
+ throw error;
1098
818
  writeJsonReceipt(io.stdout, {
1099
819
  schemaVersion: 1,
1100
820
  command: 'skill:eval:prepare',
@@ -1107,312 +827,136 @@ export function buildProgram(options = {}) {
1107
827
  commandExitState.exitCode = 1;
1108
828
  }
1109
829
  });
1110
- const review = program
830
+ const review = dev
1111
831
  .command('review')
1112
- .description('Publish and inspect immutable review records');
1113
- const reviewRecordDir = (repoRoot, record) => path.relative(fs.realpathSync(repoRoot), record.root).split(path.sep).join('/');
1114
- const reviewJsonRecord = (repoRoot, record) => ({
1115
- recordDir: reviewRecordDir(repoRoot, record),
1116
- manifest: record.manifest,
1117
- });
1118
- review
1119
- .command('digest')
1120
- .description('Compute one canonical workflow component digest')
1121
- .argument('<path>', 'repository file or directory')
1122
- .option('--json', 'emit one component digest JSON object', false)
1123
- .action(async (componentPath, rawOptions) => {
1124
- const repoRoot = await resolveRepoRoot(cwd);
1125
- const result = await computeReviewComponentDigest({ repoRoot, path: componentPath });
1126
- if (rawOptions.json) {
1127
- writeJsonReceipt(io.stdout, {
1128
- schemaVersion: 1,
1129
- command: 'review:digest',
1130
- ok: true,
1131
- ...result,
1132
- });
1133
- return;
1134
- }
1135
- writeLine(io.stdout, `${result.path}: ${result.digest}`);
1136
- });
832
+ .description('Inspect and prepare Skill review materializations');
1137
833
  review
1138
- .command('publish')
1139
- .description('Publish one immutable review record')
1140
- .requiredOption('--kind <skill|workflow|aw-plugin|aw-workflow>', 'review target kind')
1141
- .requiredOption('--target <path-or-id>', 'review target path or ID')
1142
- .requiredOption('--report <report.md>', 'review report Markdown file')
1143
- .option('--scope <scope.json>', 'workflow scope JSON file')
1144
- .option('--result <review-result.json>', 'review result JSON file')
1145
- .option('--check <kind=path>', 'archive one JSON check attachment', (value, previous) => [
1146
- ...previous,
1147
- parseReviewAttachment(value, 'Check'),
1148
- ], [])
1149
- .option('--evidence <kind=path>', 'archive one JSON evidence attachment', (value, previous) => [
1150
- ...previous,
1151
- parseReviewAttachment(value, 'Evidence'),
1152
- ], [])
1153
- .option('--release-check <release-check.json>', 'release check JSON file')
1154
- .option('--supersedes <review-id>', 'review ID that this record supersedes')
1155
- .option('--json', 'emit one review record JSON object', false)
1156
- .action(async (rawOptions) => {
1157
- const repoRoot = await resolveRepoRoot(cwd);
1158
- const record = await publishReviewRecord({
1159
- repoRoot,
1160
- kind: rawOptions.kind,
1161
- target: rawOptions.target,
1162
- report: rawOptions.report,
1163
- ...(rawOptions.scope === undefined ? {} : { scope: rawOptions.scope }),
1164
- ...(rawOptions.result === undefined ? {} : { result: rawOptions.result }),
1165
- ...(rawOptions.check.length === 0 ? {} : { checks: rawOptions.check }),
1166
- ...(rawOptions.evidence.length === 0 ? {} : { evidence: rawOptions.evidence }),
1167
- ...(rawOptions.releaseCheck === undefined ? {} : { releaseCheck: rawOptions.releaseCheck }),
1168
- ...(rawOptions.supersedes === undefined ? {} : { supersedes: rawOptions.supersedes }),
1169
- });
1170
- const recordDir = reviewRecordDir(repoRoot, record);
1171
- if (rawOptions.json) {
1172
- writeJsonReceipt(io.stdout, {
1173
- schemaVersion: 1,
1174
- command: 'review:publish',
1175
- ok: true,
1176
- ...reviewJsonRecord(repoRoot, record),
1177
- existing: record.existing,
834
+ .command('inspect')
835
+ .description('Inspect current AW Review source and materialization facts')
836
+ .argument('<target>', 'Catalog Workspace, Plugin, or source Skill path')
837
+ .addOption(strictValueOption('--workspace-root <root>', 'explicit Catalog Workspace root'))
838
+ .option('--skill <name>', 'select one declared Skill', collectUniqueOption, [])
839
+ .addOption(strictValueOption('--platform <platform>', 'select a canonical platform target', PLATFORM_TARGETS))
840
+ .addOption(strictValueOption('--scope <scope>', 'select user or project scope', ['user', 'project']))
841
+ .addOption(strictValueOption('--config <file>', 'review config JSON file'))
842
+ .option('--materialization <receipt>', 'validate one aw-source-binding receipt', collectUniqueOption, [])
843
+ .addOption(strictValueOption('--view <view>', 'select the review navigation view', ['review']).default('review'))
844
+ .option('--json', 'emit one Review inspection JSON object', false)
845
+ .action(async (target, rawOptions) => {
846
+ try {
847
+ const receipt = await inspectReviewTarget({
848
+ cwd,
849
+ target,
850
+ ...(rawOptions.workspaceRoot === undefined
851
+ ? {}
852
+ : { workspaceRoot: rawOptions.workspaceRoot }),
853
+ skills: rawOptions.skill,
854
+ ...(rawOptions.platform === undefined ? {} : { platform: rawOptions.platform }),
855
+ ...(rawOptions.scope === undefined ? {} : { scope: rawOptions.scope }),
856
+ ...(rawOptions.config === undefined ? {} : { configFile: rawOptions.config }),
857
+ materializations: [...new Set(rawOptions.materialization
858
+ .map((entry) => path.resolve(cwd, entry)))],
859
+ view: rawOptions.view,
860
+ env,
1178
861
  });
1179
- return;
862
+ if (rawOptions.json)
863
+ writeJsonReceipt(io.stdout, receipt);
864
+ else
865
+ renderReviewInspection(io.stdout, receipt);
866
+ commandExitState.exitCode = 0;
1180
867
  }
1181
- writeLine(io.stdout, `${record.existing ? 'Existing' : 'Published'} review ${record.manifest.reviewId}: ${recordDir}`);
1182
- });
1183
- review
1184
- .command('verify')
1185
- .description('Verify one archived review record')
1186
- .argument('<report-dir>', 'review record directory')
1187
- .option('--json', 'emit one review record JSON object', false)
1188
- .action(async (reportDir, rawOptions) => {
1189
- const repoRoot = await resolveRepoRoot(cwd);
1190
- const record = await verifyReviewRecord({ repoRoot, reportDir });
1191
- const relativeRecordDir = reviewRecordDir(repoRoot, record);
1192
- if (rawOptions.json) {
1193
- writeJsonReceipt(io.stdout, {
1194
- schemaVersion: 1,
1195
- command: 'review:verify',
1196
- ok: true,
1197
- ...reviewJsonRecord(repoRoot, record),
1198
- });
1199
- return;
868
+ catch (error) {
869
+ const receipt = createReviewInspectionFailure(error);
870
+ if (rawOptions.json)
871
+ writeJsonReceipt(io.stdout, receipt);
872
+ else
873
+ renderReviewInspection(io.stdout, receipt);
874
+ commandExitState.exitCode = getReviewInspectionExitCode(error);
1200
875
  }
1201
- writeLine(io.stdout, `Verified review ${record.manifest.reviewId}: ${relativeRecordDir}`);
1202
876
  });
1203
877
  review
1204
- .command('list')
1205
- .description('List immutable review records')
1206
- .option('--kind <kind>', 'filter by review target kind')
1207
- .option('--target <id>', 'filter by review target ID')
1208
- .option('--json', 'emit one review records JSON object', false)
1209
- .action(async (rawOptions) => {
1210
- const repoRoot = await resolveRepoRoot(cwd);
1211
- const records = await listReviewRecords({
1212
- repoRoot,
1213
- ...(rawOptions.kind === undefined ? {} : { kind: rawOptions.kind }),
1214
- ...(rawOptions.target === undefined ? {} : { targetId: rawOptions.target }),
878
+ .command('prepare')
879
+ .description('Prepare deterministic Skill finals for AW Review')
880
+ .argument('<target>', 'Plugin or source Skill path')
881
+ .addOption(strictValueOption('--workspace-root <root>', 'explicit Catalog Workspace root'))
882
+ .option('--skill <name>', 'select one declared Skill', collectUniqueOption, [])
883
+ .addOption(strictValueOption('--platform <platform>', 'select a canonical platform target', PLATFORM_TARGETS).makeOptionMandatory())
884
+ .addOption(strictValueOption('--scope <scope>', 'select user or project scope', ['user', 'project']).makeOptionMandatory())
885
+ .addOption(strictValueOption('--config <file>', 'review config JSON file'))
886
+ .addOption(strictValueOption('--out <new-dir>', 'new output directory').makeOptionMandatory())
887
+ .option('--json', 'emit one Review preparation JSON object', false)
888
+ .action(async (target, rawOptions) => {
889
+ const result = await prepareReviewTarget({
890
+ cwd,
891
+ target,
892
+ ...(rawOptions.workspaceRoot === undefined
893
+ ? {}
894
+ : { workspaceRoot: rawOptions.workspaceRoot }),
895
+ skills: rawOptions.skill,
896
+ platform: rawOptions.platform,
897
+ scope: rawOptions.scope,
898
+ ...(rawOptions.config === undefined ? {} : { configFile: rawOptions.config }),
899
+ out: rawOptions.out,
900
+ env,
1215
901
  });
1216
- if (rawOptions.json) {
1217
- writeJsonReceipt(io.stdout, {
1218
- schemaVersion: 1,
1219
- command: 'review:list',
1220
- ok: true,
1221
- records: records.map((record) => reviewJsonRecord(repoRoot, record)),
1222
- });
1223
- return;
1224
- }
1225
- for (const record of records) {
1226
- writeLine(io.stdout, [
1227
- record.manifest.reviewId,
1228
- record.manifest.target.kind,
1229
- record.manifest.target.id,
1230
- record.manifest.publishedAt,
1231
- ].join(' '));
1232
- }
1233
- });
1234
- review
1235
- .command('show')
1236
- .description('Show one immutable review record')
1237
- .argument('<review-id>', 'review record ID')
1238
- .option('--json', 'emit one review record JSON object', false)
1239
- .action(async (reviewId, rawOptions) => {
1240
- const repoRoot = await resolveRepoRoot(cwd);
1241
- const record = await showReviewRecord({ repoRoot, reviewId });
1242
- if (rawOptions.json) {
1243
- writeJsonReceipt(io.stdout, {
1244
- schemaVersion: 1,
1245
- command: 'review:show',
1246
- ok: true,
1247
- ...reviewJsonRecord(repoRoot, record),
1248
- });
1249
- return;
1250
- }
1251
- const manifest = record.manifest;
1252
- writeLine(io.stdout, `Review: ${manifest.reviewId}`);
1253
- writeLine(io.stdout, `Target: ${manifest.target.kind} ${manifest.target.id}`);
1254
- writeLine(io.stdout, `Published: ${manifest.publishedAt}`);
1255
- writeLine(io.stdout, `Report: ${manifest.report.path}`);
1256
- writeLine(io.stdout, `Result: ${manifest.result?.path ?? 'none'}`);
1257
- writeLine(io.stdout, `Checks: ${manifest.checks.map((entry) => entry.kind).join(', ') || 'none'}`);
1258
- writeLine(io.stdout, `Evidence: ${manifest.evidence.map((entry) => entry.kind).join(', ') || 'none'}`);
1259
- writeLine(io.stdout, `Release check: ${manifest.releaseCheck?.path ?? 'none'}`);
1260
- writeLine(io.stdout, `Supersedes: ${manifest.supersedes ?? 'none'}`);
902
+ if (rawOptions.json)
903
+ writeJsonReceipt(io.stdout, result.receipt);
904
+ else
905
+ renderReviewPreparation(io.stdout, result.receipt);
906
+ commandExitState.exitCode = result.exitCode;
1261
907
  });
1262
908
  skill
1263
- .command('install')
1264
- .description('Install portable Skills through the skills CLI')
909
+ .command('export')
910
+ .description('Write portable Skills to a safe output directory')
1265
911
  .argument('<plugin>', 'plugin or source/plugin selector')
1266
- .requiredOption('-s, --scope <scope>', 'project or user')
1267
- .option('--skill <name...>', 'install only selected Skill names')
1268
- .option('--agent <id...>', 'install to explicit Agent IDs')
1269
- .option('-y, --yes', 'confirm the reviewed install', false)
912
+ .addOption(strictValueOption('--platform <target>', 'Platform target profile', PLATFORM_TARGETS).makeOptionMandatory())
913
+ .addOption(strictValueOption('-s, --scope <scope>', 'artifact scope', ['user', 'project']).makeOptionMandatory())
914
+ .requiredOption('--out <dir>', 'output directory')
915
+ .option('--skill <name...>', 'write only selected Skill names')
1270
916
  .option('-j, --json', 'emit one receipt v5 JSON object', false)
1271
917
  .action(async (selector, rawOptions) => {
1272
- const context = createActionContext('skill:install', {});
1273
- const writeFailure = (error) => {
918
+ const context = createActionContext('skill:materialize', {});
919
+ try {
920
+ const receipt = await runActionWithContext(context, () => materializePortableSkillsToDirectory({
921
+ selector,
922
+ platform: rawOptions.platform,
923
+ scope: rawOptions.scope,
924
+ out: rawOptions.out,
925
+ ...(rawOptions.skill ? { requestedSkills: rawOptions.skill } : {}),
926
+ cwd: context.cwd,
927
+ cliVersion: resolveCliVersion(),
928
+ env: context.env,
929
+ }));
930
+ if (rawOptions.json)
931
+ writeJsonReceipt(io.stdout, receipt);
932
+ else
933
+ writeLine(io.stdout, `portable Skill 已写入 ${receipt.out}:${receipt.selectedSkills.length} 项。`);
934
+ }
935
+ catch (error) {
936
+ if (!rawOptions.json)
937
+ throw error;
1274
938
  const capabilityError = error instanceof AwCapabilityUnsupportedError ? error : undefined;
1275
939
  const code = capabilityError?.code
1276
- ?? (error instanceof PortableCommandError || error instanceof SkillsCliError
940
+ ?? (error instanceof PortableCommandError
1277
941
  ? error.code
1278
- : 'portableInstallFailed');
942
+ : 'portableMaterializeFailed');
1279
943
  writeJsonReceipt(io.stdout, {
1280
944
  receiptSchemaVersion: 5,
1281
- command: 'skill:install',
945
+ command: 'skill:materialize',
1282
946
  ok: false,
1283
- status: 'failed',
1284
947
  plugin: { id: selector },
1285
948
  scope: rawOptions.scope,
949
+ platform: rawOptions.platform,
950
+ out: path.resolve(context.cwd, rawOptions.out),
1286
951
  selectedSkills: [],
1287
952
  ...(rawOptions.skill ? { requestedSkills: rawOptions.skill } : {}),
1288
- agentMode: rawOptions.agent ? 'explicit' : 'automatic',
1289
- requestedAgents: rawOptions.agent ?? [],
1290
- skillsCliVersion: null,
1291
- collisions: [],
1292
953
  dependencies: [],
954
+ configDigest: null,
1293
955
  materializationDigest: null,
1294
- verification: { records: [], missing: [] },
1295
- warnings: [],
1296
- failures: [{
956
+ outputDigest: null,
957
+ errors: [{
1297
958
  code,
1298
- message: capabilityError?.message ?? `${code}: portable Skill 安装未执行。`,
1299
- ...(capabilityError ? {
1300
- plugin: capabilityError.plugin,
1301
- missingCapabilities: capabilityError.missingCapabilities,
1302
- availableCapabilities: capabilityError.availableCapabilities,
1303
- } : {}),
1304
- }],
1305
- });
1306
- };
1307
- if (rawOptions.json && !rawOptions.yes) {
1308
- writeFailure(new PortableCommandError('confirmationRequired', '写入型 --json 必须同时使用 --yes。'));
1309
- commandExitState.exitCode = 1;
1310
- return;
1311
- }
1312
- try {
1313
- const receipt = await runActionWithContext(context, () => installPortableSkills({
1314
- selector,
1315
- scope: rawOptions.scope,
1316
- ...(rawOptions.skill ? { requestedSkills: rawOptions.skill } : {}),
1317
- ...(rawOptions.agent ? { requestedAgents: rawOptions.agent } : {}),
1318
- yes: rawOptions.yes,
1319
- cwd: context.cwd,
1320
- cliVersion: resolveCliVersion(),
1321
- env: context.env,
1322
- ...(context.interactive && context.prompt.confirm ? {
1323
- confirm: async () => context.prompt.confirm({
1324
- message: '确认按以上 Review 安装 portable Skills?',
1325
- defaultValue: false,
1326
- }),
1327
- } : {}),
1328
- ...(!rawOptions.json ? {
1329
- onReview: (review) => {
1330
- for (const line of renderPortableReview(review))
1331
- writeLine(io.stdout, line);
1332
- },
1333
- } : {}),
1334
- }));
1335
- if (rawOptions.json)
1336
- writeJsonReceipt(io.stdout, receipt);
1337
- else if (receipt.ok)
1338
- writeLine(io.stdout, `portable Skill 安装完成:${receipt.selectedSkills.length} 项。`);
1339
- else {
1340
- const sanitize = (value) => redactString(value)
1341
- .replace(/https?:\/\/\S+/giu, '[REDACTED URL]')
1342
- .replace(/(?:file:\/\/)?(?:\/[\w.@+-]+){2,}/gu, '[REDACTED PATH]')
1343
- .replace(/[A-Za-z]:\\(?:[^\s\\]+\\)+[^\s\\]*/gu, '[REDACTED PATH]');
1344
- const lines = new Set();
1345
- for (const failure of receipt.failures) {
1346
- lines.add(`${failure.code}: ${sanitize(failure.message)}`);
1347
- }
1348
- for (const warning of receipt.warnings)
1349
- lines.add(`警告:${sanitize(warning)}`);
1350
- const recoveries = receipt.failures.map((failure) => failure.recovery).filter(Boolean);
1351
- const recovery = recoveries.find((entry) => entry.includes('aw skill install')
1352
- && entry.includes('skills remove'))
1353
- ?? '重新运行 aw skill install;如需清理外部写入,请使用 skills remove。';
1354
- lines.add(`恢复:${sanitize(recovery)}`);
1355
- for (const line of lines)
1356
- writeLine(io.stderr, line);
1357
- }
1358
- commandExitState.exitCode = receipt.ok ? 0 : 1;
1359
- }
1360
- catch (error) {
1361
- if (!rawOptions.json)
1362
- throw error;
1363
- writeFailure(error);
1364
- commandExitState.exitCode = 1;
1365
- }
1366
- });
1367
- skill
1368
- .command('materialize')
1369
- .description('Write portable Skills to a safe output directory')
1370
- .argument('<plugin>', 'plugin or source/plugin selector')
1371
- .requiredOption('-s, --scope <scope>', 'project or user')
1372
- .requiredOption('--out <dir>', 'output directory')
1373
- .option('--skill <name...>', 'write only selected Skill names')
1374
- .option('-j, --json', 'emit one receipt v5 JSON object', false)
1375
- .action(async (selector, rawOptions) => {
1376
- const context = createActionContext('skill:materialize', {});
1377
- try {
1378
- const receipt = await runActionWithContext(context, () => materializePortableSkillsToDirectory({
1379
- selector,
1380
- scope: rawOptions.scope,
1381
- out: rawOptions.out,
1382
- ...(rawOptions.skill ? { requestedSkills: rawOptions.skill } : {}),
1383
- cwd: context.cwd,
1384
- cliVersion: resolveCliVersion(),
1385
- env: context.env,
1386
- }));
1387
- if (rawOptions.json)
1388
- writeJsonReceipt(io.stdout, receipt);
1389
- else
1390
- writeLine(io.stdout, `portable Skill 已写入 ${receipt.out}:${receipt.selectedSkills.length} 项。`);
1391
- }
1392
- catch (error) {
1393
- if (!rawOptions.json)
1394
- throw error;
1395
- const capabilityError = error instanceof AwCapabilityUnsupportedError ? error : undefined;
1396
- const code = capabilityError?.code
1397
- ?? (error instanceof PortableCommandError || error instanceof SkillsCliError
1398
- ? error.code
1399
- : 'portableMaterializeFailed');
1400
- writeJsonReceipt(io.stdout, {
1401
- receiptSchemaVersion: 5,
1402
- command: 'skill:materialize',
1403
- ok: false,
1404
- plugin: { id: selector },
1405
- scope: rawOptions.scope,
1406
- out: path.resolve(context.cwd, rawOptions.out),
1407
- selectedSkills: [],
1408
- ...(rawOptions.skill ? { requestedSkills: rawOptions.skill } : {}),
1409
- dependencies: [],
1410
- configDigest: null,
1411
- materializationDigest: null,
1412
- outputDigest: null,
1413
- errors: [{
1414
- code,
1415
- message: capabilityError?.message ?? `${code}: portable Skill 导出未执行。`,
959
+ message: capabilityError?.message ?? `${code}: portable Skill 导出未执行。`,
1416
960
  ...(capabilityError ? {
1417
961
  plugin: capabilityError.plugin,
1418
962
  missingCapabilities: capabilityError.missingCapabilities,
@@ -1423,14 +967,14 @@ export function buildProgram(options = {}) {
1423
967
  commandExitState.exitCode = 1;
1424
968
  }
1425
969
  });
1426
- plugin
1427
- .command('init')
970
+ devPlugin
971
+ .command('create')
1428
972
  .description('Create a new deterministic plugin scaffold')
1429
973
  .addHelpText('after', [
1430
974
  '',
1431
975
  'During development, keep the current stable target when production content changes.',
1432
- 'Next, run `aw plugin validate`, `aw plugin test`, `aw plugin build`, and `aw catalog build`.',
1433
- 'Publish only as an explicit later step; inspect `aw catalog publish plan --help` first.',
976
+ 'Next, run `aw dev plugin validate`, `aw dev plugin test`, `aw dev plugin build`, and `aw dev catalog build`.',
977
+ 'Publish only as an explicit later step; inspect `aw dev catalog publish plan --help` first.',
1434
978
  '',
1435
979
  ].join('\n'))
1436
980
  .argument('<plugin-name>', 'lowercase hyphen-case plugin name')
@@ -1439,52 +983,46 @@ export function buildProgram(options = {}) {
1439
983
  .option('--short-description <text>', 'short plugin UI description')
1440
984
  .option('--skill-name <name>', 'initial static Skill name')
1441
985
  .option('--skill-description <text>', 'initial Skill goal and discovery description')
1442
- .option('--skill-short-description <text>', 'initial Skill UI summary (25-64 characters)')
986
+ .option('--skill-short-description <text>', 'initial Skill UI summary (1-64 characters)')
1443
987
  .option('--skill-invocation <mode>', 'model | manual | claude-model-only (default: model)')
1444
988
  .option('--version <semver>', 'initial stable plugin version (default: 0.1.0)')
1445
989
  .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from current directory)')
1446
990
  .option('--no-skills', 'create the plugin without a skills directory')
1447
991
  .option('--with-mcp', 'add a minimal .mcp.json', false)
1448
- .option('--with-apps', 'add a minimal .app.json', false)
1449
992
  .option('--with-config-api', 'add AW config schema and helper', false)
1450
- .option('--with-post-apply', 'add a Node postApply script sample', false);
1451
- plugin
1452
- .command('add-skill')
993
+ .option('--with-pre-apply', 'add an idempotent Node preApply environment check', false);
994
+ skill
995
+ .command('create')
1453
996
  .description('Add one static Skill scaffold to an existing plugin')
1454
997
  .addHelpText('after', [
1455
998
  '',
1456
999
  'During development, keep the current stable target when production content changes.',
1457
- 'Next, run `aw plugin validate`, `aw plugin test`, `aw plugin build`, and `aw catalog build`.',
1458
- 'Publish only as an explicit later step; inspect `aw catalog publish plan --help` first.',
1000
+ 'Next, run `aw dev plugin validate`, `aw dev plugin test`, `aw dev plugin build`, and `aw dev catalog build`.',
1001
+ 'Publish only as an explicit later step; inspect `aw dev catalog publish plan --help` first.',
1459
1002
  '',
1460
1003
  ].join('\n'))
1461
- .argument('<plugin-name>', 'existing lowercase hyphen-case plugin name')
1004
+ .requiredOption('--plugin <name>', 'Plugin that owns the Skill')
1462
1005
  .option('--skill-name <name>', 'new static Skill name (required)')
1463
1006
  .option('--skill-description <text>', 'Skill goal and discovery description (required)')
1464
- .option('--skill-short-description <text>', 'Skill UI summary (25-64 characters)')
1007
+ .option('--skill-short-description <text>', 'Skill UI summary (1-64 characters)')
1465
1008
  .option('--skill-invocation <mode>', 'model | manual | claude-model-only (default: model)')
1466
1009
  .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from current directory)');
1467
- plugin
1468
- .command('remove')
1469
- .description('Remove one committed and unchanged canonical plugin source tree')
1470
- .argument('<plugin-name>', 'existing lowercase hyphen-case plugin name')
1471
- .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from current directory)')
1472
- .option('--yes', 'confirm plugin source deletion', false)
1473
- .option('--json', 'emit one schema 1 JSON object', false);
1474
- plugin
1010
+ devPlugin
1475
1011
  .command('validate')
1476
1012
  .description('Validate one source plugin directory')
1477
1013
  .argument('<plugin-directory>', 'source plugin directory')
1478
1014
  .option('--strict-agent-skills', 'allow only Agent Skills portable core frontmatter', false)
1479
- .option('--claude-skill-profile <profile>', 'minimum | current (default: minimum)')
1015
+ .option('--claude-skill-profile <profile>', 'current (default) | minimum (Claude 2.1.88 fields)')
1480
1016
  .option('--version-base <git-ref>', 'production bundle comparison base (default: HEAD)')
1481
1017
  .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from plugin directory)')
1482
1018
  .option('--json', 'emit one machine-readable JSON result', false);
1483
- plugin
1019
+ devPlugin
1484
1020
  .command('test')
1485
1021
  .description('Run deterministic Node tests declared by one source plugin')
1486
1022
  .argument('<plugin-directory>', 'source plugin directory')
1487
1023
  .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from plugin directory)')
1024
+ .option('--native-mode <mode>', 'fixture | installed | source-candidate (default: fixture)')
1025
+ .option('--native-context <path>', 'explicit tool context JSON for fixture or source-candidate mode')
1488
1026
  .option('--json', 'emit one machine-readable JSON result', false)
1489
1027
  .action(async (pluginDirectory, rawOptions) => {
1490
1028
  try {
@@ -1496,11 +1034,15 @@ export function buildProgram(options = {}) {
1496
1034
  commandExitState.exitCode = await runPluginTestCommand({
1497
1035
  ...workspace,
1498
1036
  pluginDirectory: path.resolve(cwd, pluginDirectory),
1037
+ nativeMode: rawOptions.nativeMode,
1038
+ nativeContext: rawOptions.nativeContext ? path.resolve(cwd, rawOptions.nativeContext) : undefined,
1499
1039
  json: rawOptions.json,
1500
1040
  io,
1501
1041
  });
1502
1042
  }
1503
1043
  catch (error) {
1044
+ if (error instanceof CatalogWorkspaceMissingError)
1045
+ throw error;
1504
1046
  const message = error instanceof Error ? error.message : String(error);
1505
1047
  if (rawOptions.json)
1506
1048
  writeJsonReceipt(io.stdout, { command: 'plugin:test', ok: false, errors: [{ message }] });
@@ -1508,7 +1050,7 @@ export function buildProgram(options = {}) {
1508
1050
  commandExitState.exitCode = 1;
1509
1051
  }
1510
1052
  });
1511
- plugin
1053
+ devPlugin
1512
1054
  .command('build')
1513
1055
  .description('Build and inspect one source plugin bundle')
1514
1056
  .argument('<plugin-directory>', 'source plugin directory')
@@ -1533,6 +1075,8 @@ export function buildProgram(options = {}) {
1533
1075
  });
1534
1076
  }
1535
1077
  catch (error) {
1078
+ if (error instanceof CatalogWorkspaceMissingError)
1079
+ throw error;
1536
1080
  const message = error instanceof Error ? error.message : String(error);
1537
1081
  if (rawOptions.json)
1538
1082
  writeJsonReceipt(io.stdout, { command: 'plugin:build', ok: false, errors: [{ message }] });
@@ -1540,14 +1084,6 @@ export function buildProgram(options = {}) {
1540
1084
  commandExitState.exitCode = 1;
1541
1085
  }
1542
1086
  });
1543
- plugin
1544
- .command('status')
1545
- .description('Show current plugin status or compare against an explicit Git base')
1546
- .argument('[plugin-name]', 'one explicit plugin name')
1547
- .option('--all', 'check every current Catalog Workspace plugin', false)
1548
- .option('--base <git-ref>', 'explicit Git comparison base')
1549
- .option('--json', 'emit one schema v3 JSON document', false)
1550
- .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from current directory)');
1551
1087
  skill
1552
1088
  .command('validate')
1553
1089
  .description('Validate one Agent Skill directory')
@@ -1555,11 +1091,11 @@ export function buildProgram(options = {}) {
1555
1091
  .option('--frontmatter-profile <profile>', 'portable-agent-skills | claude-2.1.88 | claude-current (default: portable-agent-skills)')
1556
1092
  .option('--codex-metadata <policy>', 'required | optional | ignore (default: optional)')
1557
1093
  .option('--json', 'emit one machine-readable JSON result', false);
1558
- const catalog = program
1094
+ const catalog = dev
1559
1095
  .command('catalog')
1560
1096
  .description('Build and manage catalogs');
1561
1097
  catalog
1562
- .command('init')
1098
+ .command('create')
1563
1099
  .description('Initialize a local AW Catalog Workspace')
1564
1100
  .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor, then Git worktree root, then current directory)')
1565
1101
  .option('--owner-name <name>', 'catalog owner name')
@@ -1613,6 +1149,8 @@ export function buildProgram(options = {}) {
1613
1149
  });
1614
1150
  }
1615
1151
  catch (error) {
1152
+ if (error instanceof CatalogWorkspaceMissingError)
1153
+ throw error;
1616
1154
  const message = error instanceof Error ? error.message : String(error);
1617
1155
  if (rawOptions.json)
1618
1156
  writeJsonReceipt(io.stdout, { command: 'catalog:version', ok: false, errors: [{ message }] });
@@ -1643,6 +1181,8 @@ export function buildProgram(options = {}) {
1643
1181
  });
1644
1182
  }
1645
1183
  catch (error) {
1184
+ if (error instanceof CatalogWorkspaceMissingError)
1185
+ throw error;
1646
1186
  const message = error instanceof Error ? error.message : String(error);
1647
1187
  if (rawOptions.json)
1648
1188
  writeJsonReceipt(io.stdout, { command: 'catalog:build', ok: false, errors: [{ message }] });
@@ -1724,6 +1264,8 @@ export function buildProgram(options = {}) {
1724
1264
  }
1725
1265
  }
1726
1266
  catch (error) {
1267
+ if (error instanceof CatalogWorkspaceMissingError)
1268
+ throw error;
1727
1269
  const failure = catalogPublicationFailure({
1728
1270
  error,
1729
1271
  env,
@@ -1777,10 +1319,12 @@ export function buildProgram(options = {}) {
1777
1319
  writeLine(io.stdout, `Branch: refs/heads/${result.branch}`);
1778
1320
  writeLine(io.stdout, `Tag: refs/tags/${result.tag}`);
1779
1321
  writeLine(io.stdout, `Commit: ${result.commit}`);
1780
- writeLine(io.stdout, `Add it as a source: aw catalog source add <id> --git ${result.fetchUrl} --ref refs/heads/${result.branch}`);
1322
+ writeLine(io.stdout, `Add it as a source: aw source add <id> --git ${result.fetchUrl} --ref refs/heads/${result.branch}`);
1781
1323
  }
1782
1324
  }
1783
1325
  catch (error) {
1326
+ if (error instanceof CatalogWorkspaceMissingError)
1327
+ throw error;
1784
1328
  const failure = catalogPublicationFailure({
1785
1329
  error,
1786
1330
  env,
@@ -1790,13 +1334,13 @@ export function buildProgram(options = {}) {
1790
1334
  ],
1791
1335
  });
1792
1336
  if (rawOptions.json)
1793
- writeJsonReceipt(io.stdout, failure);
1337
+ writeJsonReceipt(io.stdout, { ...failure, ...(error instanceof CatalogPublicationApplyFailure ? { overallState: 'partial', ...error.outcome } : {}) });
1794
1338
  writeLine(io.stderr, failure.message);
1795
1339
  commandExitState.exitCode = 1;
1796
1340
  }
1797
1341
  });
1798
- const catalogDev = catalog
1799
- .command('dev')
1342
+ const catalogDev = dev
1343
+ .command('source')
1800
1344
  .description('Manage the current Catalog Workspace development source');
1801
1345
  catalogDev
1802
1346
  .command('activate')
@@ -1822,6 +1366,8 @@ export function buildProgram(options = {}) {
1822
1366
  commandExitState.exitCode = receipt.ok ? 0 : 1;
1823
1367
  }
1824
1368
  catch (error) {
1369
+ if (error instanceof CatalogWorkspaceMissingError)
1370
+ throw error;
1825
1371
  const failure = catalogDevSourceError(error);
1826
1372
  writeJsonReceipt(io.stdout, createCatalogDevFailureReceipt({
1827
1373
  command: 'activate', cwd, workspaceRoot: rawOptions.workspaceRoot,
@@ -1833,7 +1379,7 @@ export function buildProgram(options = {}) {
1833
1379
  catalogDev
1834
1380
  .command('status')
1835
1381
  .option('--workspace-root <path>', 'explicit Catalog Workspace root')
1836
- .requiredOption('--json', 'emit one schema 3 JSON receipt')
1382
+ .requiredOption('--json', 'emit one schema 4 JSON receipt')
1837
1383
  .action(async (rawOptions) => {
1838
1384
  const receipt = await getCatalogDevSourceStatus({
1839
1385
  cwd,
@@ -1849,8 +1395,8 @@ export function buildProgram(options = {}) {
1849
1395
  .option('--workspace-root <path>', 'explicit Catalog Workspace root')
1850
1396
  .option('--source-id <id>', 'recover one managed source by exact ID')
1851
1397
  .option('--replacement-primary <id>', 'replacement when the target source is primary')
1852
- .option('-y, --yes', 'confirm recovery by source ID', false)
1853
- .requiredOption('--json', 'emit one schema 2 JSON receipt')
1398
+ .option('-y, --yes', 'confirm source impact or recovery by source ID', false)
1399
+ .requiredOption('--json', 'emit one schema 4 JSON receipt')
1854
1400
  .action(async (rawOptions) => {
1855
1401
  try {
1856
1402
  const receipt = await deactivateCatalogDevSource({
@@ -1865,6 +1411,8 @@ export function buildProgram(options = {}) {
1865
1411
  commandExitState.exitCode = receipt.ok ? 0 : 1;
1866
1412
  }
1867
1413
  catch (error) {
1414
+ if (error instanceof CatalogWorkspaceMissingError)
1415
+ throw error;
1868
1416
  const failure = catalogDevSourceError(error);
1869
1417
  writeJsonReceipt(io.stdout, createCatalogDevFailureReceipt({
1870
1418
  command: 'deactivate', cwd, workspaceRoot: rawOptions.workspaceRoot,
@@ -1873,7 +1421,7 @@ export function buildProgram(options = {}) {
1873
1421
  commandExitState.exitCode = 1;
1874
1422
  }
1875
1423
  });
1876
- const catalogSource = catalog
1424
+ const catalogSource = program
1877
1425
  .command('source')
1878
1426
  .description('Manage catalog sources');
1879
1427
  const writeCatalogSourceFailure = async (command, sourceId, json, error, sensitiveRoots = []) => {
@@ -1881,12 +1429,14 @@ export function buildProgram(options = {}) {
1881
1429
  const message = failure instanceof Error ? failure.message : String(error);
1882
1430
  if (json) {
1883
1431
  writeJsonReceipt(io.stdout, {
1884
- receiptSchemaVersion: 5,
1432
+ receiptSchemaVersion: 6,
1885
1433
  command,
1886
1434
  ok: false,
1887
1435
  changed: false,
1888
1436
  sourceId,
1437
+ primaryChange: failure.impact?.primaryChange ?? null,
1889
1438
  references: failure.impact?.references ?? failure.inventory?.references ?? [],
1439
+ impact: failure.impact ?? failure.inventory ?? null,
1890
1440
  errors: [{ code: failure.code ?? failure.name ?? 'catalogSourceMutationFailed', message }],
1891
1441
  });
1892
1442
  }
@@ -1900,7 +1450,7 @@ export function buildProgram(options = {}) {
1900
1450
  writeJsonReceipt(io.stdout, {
1901
1451
  ...(command === 'catalog:source:sync'
1902
1452
  ? { catalogGenerationSchemaVersion: 1 }
1903
- : { catalogGenerationStatusSchemaVersion: 1 }),
1453
+ : { catalogGenerationStatusSchemaVersion: 2 }),
1904
1454
  command,
1905
1455
  ok: false,
1906
1456
  ...(sourceId ? { sourceId } : {}),
@@ -1911,9 +1461,34 @@ export function buildProgram(options = {}) {
1911
1461
  writeLine(io.stderr, message);
1912
1462
  commandExitState.exitCode = 1;
1913
1463
  };
1464
+ const configLayerRecoveryResult = (result, error, pluginId) => {
1465
+ result.nextActions = error.nextActions;
1466
+ for (const diagnostic of result.diagnostics.filter(({ code }) => code === error.code)) {
1467
+ diagnostic.subject = { ...diagnostic.subject, ...(pluginId ? { pluginId } : {}),
1468
+ ...(error.target ? { target: error.target } : {}) };
1469
+ }
1470
+ return result;
1471
+ };
1914
1472
  const writeConfigMutationFailure = (command, plugin, json, error) => {
1915
1473
  const failure = configMutationFailure(error, env, cwd);
1916
- if (json) {
1474
+ if (error instanceof ConfigLayerError) {
1475
+ const result = projectReceipt(`plugin.${command.replace(':', '.')}`, buildConfigMutationReceipt(command, {
1476
+ ok: false, overallState: 'failed', configWrite: failure.configWrite,
1477
+ ...(plugin ? { pluginId: plugin } : {}),
1478
+ errors: [{ code: error.code, message: error.message }],
1479
+ }));
1480
+ result.status = 'blocked';
1481
+ writeJsonReceipt(io.stdout, configLayerRecoveryResult(result, error, plugin));
1482
+ commandExitState.exitCode = publicExitCode(result);
1483
+ return;
1484
+ }
1485
+ const confirmation = error?.confirmation;
1486
+ if (confirmation) {
1487
+ writeJsonReceipt(io.stdout, { command, ok: false, pluginId: plugin, configWrite: 'notStarted', confirmation, errors: [failure] });
1488
+ commandExitState.exitCode = 3;
1489
+ return;
1490
+ }
1491
+ if (json || io.result) {
1917
1492
  writeConfigMutationFailureReceipt(io.stdout, {
1918
1493
  command,
1919
1494
  ...(plugin ? { plugin } : {}),
@@ -1923,45 +1498,35 @@ export function buildProgram(options = {}) {
1923
1498
  ? failure.message
1924
1499
  : redactString(sanitizeCatalogSourceErrorMessage(error instanceof Error ? error.message : String(error), env, [cwd]));
1925
1500
  writeLine(io.stderr, message);
1926
- commandExitState.exitCode = 1;
1501
+ commandExitState.exitCode = failure.code === 'invalidArguments' ? 2
1502
+ : ['configSchemaUnavailable', 'schemaUnavailable', 'configUnavailable', 'requiredConfigMissing'].includes(failure.code) ? 3 : 1;
1927
1503
  };
1928
- const withResolvedConfigMutationPlugin = (context, selector, consume) => (async () => {
1504
+ const withResolvedConfigMutationPlugin = (context, selector, consume, options) => (async () => {
1929
1505
  const parsed = parsePluginId(selector);
1930
1506
  return withAwHomeMutationLock({
1931
1507
  env: context.env,
1508
+ signal: context.signal,
1932
1509
  action: async (awHomeMutationToken) => {
1933
1510
  const catalogOperationContext = await resolveCatalogOperationContext({
1934
1511
  ...(parsed.sourceId ? { sourceIds: [parsed.sourceId] } : {}),
1935
1512
  env: context.env,
1513
+ signal: context.signal,
1936
1514
  });
1937
1515
  return withResolvedCatalogPlugin({
1938
1516
  selector,
1939
1517
  cliVersion: resolveCliVersion(),
1940
1518
  operationContext: catalogOperationContext,
1941
1519
  env: context.env,
1520
+ signal: context.signal,
1521
+ retainCompletedResultOnAbort: options?.retainCompletedResultOnAbort,
1942
1522
  consume: (resolution) => consume(resolution, awHomeMutationToken, catalogOperationContext),
1943
1523
  });
1944
1524
  },
1945
1525
  });
1946
1526
  })();
1947
- catalogSource
1948
- .command('list')
1949
- .option('-j, --json', 'print catalog sources as JSON', false)
1950
- .action(async (rawOptions) => {
1951
- const payload = await listCatalogSources({ env });
1952
- if (rawOptions.json) {
1953
- writeJsonReceipt(io.stdout, payload);
1954
- return;
1955
- }
1956
- writeLine(io.stdout, `Primary source: ${payload.primarySourceId}`);
1957
- for (const source of payload.sources) {
1958
- writeLine(io.stdout, `${source.primary ? '*' : '-'} ${source.id} ${source.type} ${source.sourceIdentity}`);
1959
- }
1960
- });
1961
1527
  catalogSource
1962
1528
  .command('sync')
1963
1529
  .argument('<id>')
1964
- .option('--check', 'fetch and validate without changing the Catalog store or Active state', false)
1965
1530
  .option('--replace-damaged', 'replace a damaged Active entry with the current candidate', false)
1966
1531
  .option('-y, --yes', 'confirm affected, unknown, or damaged Active replacement impact', false)
1967
1532
  .option('-j, --json', 'print the source sync result as JSON', false)
@@ -1999,7 +1564,7 @@ export function buildProgram(options = {}) {
1999
1564
  catalogSource
2000
1565
  .command('status')
2001
1566
  .argument('[id]')
2002
- .option('-j, --json', 'print offline Catalog source status as JSON', false)
1567
+ .option('-j, --json', 'print offline Catalog source status schema 2 as JSON', false)
2003
1568
  .action(async (id, rawOptions) => {
2004
1569
  try {
2005
1570
  const result = await catalogSourceStatusCommand({ sourceId: id, env });
@@ -2011,7 +1576,9 @@ export function buildProgram(options = {}) {
2011
1576
  const active = source.active
2012
1577
  ? `Active ${source.active.snapshotDigest}`
2013
1578
  : 'no Active';
2014
- const readiness = source.activeReady ? 'ready' : 'not ready';
1579
+ const readiness = source.compatibility?.state === 'unsupported'
1580
+ ? `incompatible (required: ${source.compatibility.requiredCapabilities.join(', ')}; missing: ${source.compatibility.missingCapabilities.join(', ')})`
1581
+ : source.activeReady ? 'ready' : 'not ready';
2015
1582
  writeLine(io.stdout, `${source.sourceId}: ${active}, ${readiness}`);
2016
1583
  }
2017
1584
  }
@@ -2030,17 +1597,18 @@ export function buildProgram(options = {}) {
2030
1597
  .option('--subdir <path>', 'use a catalog snapshot below the Git repository root')
2031
1598
  .option('--no-auto-check', 'disable automatic update checks for this source')
2032
1599
  .option('--primary', 'make this source primary', false)
1600
+ .option('-y, --yes', 'confirm affected or unknown primary source references', false)
2033
1601
  .option('-j, --json', 'print mutation receipt as JSON', false)
2034
1602
  .action(async (id, rawOptions) => {
2035
1603
  try {
2036
1604
  if ((rawOptions.git === undefined) === (rawOptions.path === undefined)) {
2037
- throw new Error('catalog source add requires exactly one of `--git` or `--path`.');
1605
+ throw new WriteCommandRequestError('catalog source add requires exactly one of `--git` or `--path`.');
2038
1606
  }
2039
1607
  if (rawOptions.git !== undefined && ((rawOptions.ref === undefined) === (rawOptions.defaultRef !== true))) {
2040
- throw new Error('Git catalog source add requires exactly one of `--ref` or `--default-ref`.');
1608
+ throw new WriteCommandRequestError('Git catalog source add requires exactly one of `--ref` or `--default-ref`.');
2041
1609
  }
2042
1610
  if (rawOptions.path !== undefined && (rawOptions.ref !== undefined || rawOptions.defaultRef === true || rawOptions.subdir !== undefined)) {
2043
- throw new Error('Path catalog source add only accepts `--path`, `--primary`, and `--no-auto-check`.');
1611
+ throw new WriteCommandRequestError('Path catalog source add only accepts `--path`, `--primary`, `--no-auto-check`, and `--yes`.');
2044
1612
  }
2045
1613
  const source = rawOptions.git !== undefined
2046
1614
  ? {
@@ -2059,14 +1627,26 @@ export function buildProgram(options = {}) {
2059
1627
  path: rawOptions.path,
2060
1628
  ...(rawOptions.autoCheck === false ? { autoCheck: false } : {}),
2061
1629
  };
1630
+ const preview = source.primary
1631
+ ? await preflightCatalogSourceMutation({
1632
+ request: { action: 'add', source }, cwd, env,
1633
+ })
1634
+ : undefined;
2062
1635
  const receipt = await addCatalogSourceCommand({
2063
1636
  source,
2064
1637
  cliVersion: resolveCliVersion(),
2065
1638
  cwd,
2066
1639
  env,
1640
+ ...(preview ? {
1641
+ expectedConfigDigest: preview.configDigest,
1642
+ expectedProposedConfigDigest: preview.proposedConfigDigest,
1643
+ expectedImpactDigest: preview.impactDigest,
1644
+ } : {}),
1645
+ requireImpactConfirmation: true,
1646
+ confirmImpact: rawOptions.yes === true,
2067
1647
  });
2068
1648
  if (rawOptions.json)
2069
- writeJsonReceipt(io.stdout, receipt);
1649
+ writeJsonReceipt(io.stdout, { ...receipt, impact: preview?.references ?? null, confirmation: sourceConfirmation(id, rawOptions.yes, preview) });
2070
1650
  else
2071
1651
  writeLine(io.stdout, `Catalog source ${id} added.`);
2072
1652
  for (const diagnostic of receipt.errors)
@@ -2092,26 +1672,26 @@ export function buildProgram(options = {}) {
2092
1672
  .action(async (id, rawOptions) => {
2093
1673
  try {
2094
1674
  if (rawOptions.git !== undefined && rawOptions.path !== undefined) {
2095
- throw new Error('catalog source update cannot combine `--git` and `--path`.');
1675
+ throw new WriteCommandRequestError('catalog source update cannot combine `--git` and `--path`.');
2096
1676
  }
2097
1677
  if (rawOptions.ref !== undefined && rawOptions.defaultRef === true) {
2098
- throw new Error('catalog source update cannot combine `--ref` and `--default-ref`.');
1678
+ throw new WriteCommandRequestError('catalog source update cannot combine `--ref` and `--default-ref`.');
2099
1679
  }
2100
- const hasUpdate = rawOptions.git !== undefined
1680
+ const hasUpdate = rawOptions.primary === true || rawOptions.git !== undefined
2101
1681
  || rawOptions.path !== undefined
2102
1682
  || rawOptions.ref !== undefined
2103
1683
  || rawOptions.defaultRef === true
2104
1684
  || rawOptions.subdir !== undefined
2105
1685
  || rawOptions.autoCheck !== undefined;
2106
1686
  if (!hasUpdate)
2107
- throw new Error('catalog source update requires at least one update option.');
1687
+ throw new WriteCommandRequestError('catalog source update requires at least one update option.');
2108
1688
  if (rawOptions.path !== undefined && (rawOptions.ref !== undefined || rawOptions.defaultRef === true || rawOptions.subdir !== undefined))
2109
- throw new Error('Path catalog source update only accepts `--path` and auto-check options.');
1689
+ throw new WriteCommandRequestError('Path catalog source update only accepts `--path` and auto-check options.');
2110
1690
  const hasGitUpdate = rawOptions.git !== undefined
2111
1691
  || rawOptions.ref !== undefined
2112
1692
  || rawOptions.defaultRef === true
2113
1693
  || rawOptions.subdir !== undefined;
2114
- const update = rawOptions.path !== undefined
1694
+ const transportUpdate = rawOptions.path !== undefined
2115
1695
  ? {
2116
1696
  type: 'path',
2117
1697
  path: rawOptions.path,
@@ -2129,17 +1709,27 @@ export function buildProgram(options = {}) {
2129
1709
  : {}),
2130
1710
  }
2131
1711
  : { autoCheck: rawOptions.autoCheck };
1712
+ const update = transportUpdate;
1713
+ const preview = await preflightCatalogSourceMutation({
1714
+ request: { action: 'update', sourceId: id, update, ...(rawOptions.primary ? { primary: true } : {}) }, cwd, env,
1715
+ });
2132
1716
  const receipt = await updateCatalogSourceCommand({
2133
1717
  sourceId: id,
2134
1718
  update,
1719
+ ...(rawOptions.primary ? { primary: true } : {}),
1720
+ requireImpactConfirmation: true,
1721
+ confirmImpact: rawOptions.yes === true,
2135
1722
  cliVersion: resolveCliVersion(),
2136
1723
  cwd,
2137
1724
  env,
1725
+ expectedConfigDigest: preview.configDigest,
1726
+ expectedProposedConfigDigest: preview.proposedConfigDigest,
1727
+ expectedImpactDigest: preview.impactDigest,
2138
1728
  requireIdentityChangeConfirmation: true,
2139
1729
  confirmIdentityChange: rawOptions.yes === true,
2140
1730
  });
2141
1731
  if (rawOptions.json)
2142
- writeJsonReceipt(io.stdout, receipt);
1732
+ writeJsonReceipt(io.stdout, { ...receipt, impact: preview.references, confirmation: sourceConfirmation(id, rawOptions.yes, preview) });
2143
1733
  else
2144
1734
  writeLine(io.stdout, `Catalog source ${id} updated.`);
2145
1735
  for (const diagnostic of receipt.errors)
@@ -2149,22 +1739,6 @@ export function buildProgram(options = {}) {
2149
1739
  await writeCatalogSourceFailure('catalog:source:update', id, rawOptions.json === true, error, rawOptions.path === undefined ? [] : [rawOptions.path, path.resolve(cwd, rawOptions.path)]);
2150
1740
  }
2151
1741
  });
2152
- catalogSource
2153
- .command('set-primary')
2154
- .argument('<id>')
2155
- .option('-j, --json', 'print mutation receipt as JSON', false)
2156
- .action(async (id, rawOptions) => {
2157
- try {
2158
- const receipt = await setPrimaryCatalogSourceCommand({ sourceId: id, cwd, env });
2159
- if (rawOptions.json)
2160
- writeJsonReceipt(io.stdout, receipt);
2161
- else
2162
- writeLine(io.stdout, `Primary catalog source set to ${id}.`);
2163
- }
2164
- catch (error) {
2165
- await writeCatalogSourceFailure('catalog:source:set-primary', id, rawOptions.json === true, error);
2166
- }
2167
- });
2168
1742
  catalogSource
2169
1743
  .command('remove')
2170
1744
  .argument('<id>')
@@ -2172,6 +1746,7 @@ export function buildProgram(options = {}) {
2172
1746
  .option('-j, --json', 'print mutation receipt as JSON', false)
2173
1747
  .action(async (id, rawOptions) => {
2174
1748
  try {
1749
+ const preview = await preflightCatalogSourceMutation({ request: { action: 'remove', sourceId: id }, cwd, env });
2175
1750
  const receipt = await removeCatalogSourceCommand({
2176
1751
  sourceId: id,
2177
1752
  cwd,
@@ -2180,7 +1755,7 @@ export function buildProgram(options = {}) {
2180
1755
  confirmImpact: rawOptions.yes === true,
2181
1756
  });
2182
1757
  if (rawOptions.json)
2183
- writeJsonReceipt(io.stdout, receipt);
1758
+ writeJsonReceipt(io.stdout, { ...receipt, impact: preview.references, confirmation: sourceConfirmation(id, rawOptions.yes, preview) });
2184
1759
  else
2185
1760
  writeLine(io.stdout, `Catalog source ${id} removed.`);
2186
1761
  }
@@ -2188,8 +1763,8 @@ export function buildProgram(options = {}) {
2188
1763
  await writeCatalogSourceFailure('catalog:source:remove', id, rawOptions.json === true, error);
2189
1764
  }
2190
1765
  });
2191
- const catalogStore = catalog
2192
- .command('store')
1766
+ const catalogStore = program
1767
+ .command('cache')
2193
1768
  .description('Inspect or prune the immutable Catalog store');
2194
1769
  catalogStore
2195
1770
  .command('status')
@@ -2209,18 +1784,22 @@ export function buildProgram(options = {}) {
2209
1784
  writeLine(io.stdout, `${entry.storeKey}: ${entry.category}, ${entry.status}, ${entry.reason}, ${bytes}`);
2210
1785
  }
2211
1786
  writeLine(io.stdout, `Reclaimable: ${result.totals.reclaimableEntries} item(s).`);
1787
+ if (result.errors.length > 0) {
1788
+ writeLine(io.stderr, `${result.errors.length} item(s) could not be fully inspected and were retained.`);
1789
+ }
2212
1790
  }
1791
+ commandExitState.exitCode = result.ok ? 0 : 1;
2213
1792
  }
2214
1793
  catch (error) {
2215
1794
  const failure = sanitizeCatalogSourceError(error, env);
2216
1795
  const message = redactString(failure.message);
2217
1796
  if (rawOptions.json)
2218
1797
  writeJsonReceipt(io.stdout, {
2219
- catalogStoreSchemaVersion: 1,
1798
+ catalogStoreSchemaVersion: 2,
2220
1799
  command: 'catalog:store:status',
2221
1800
  ok: false,
2222
1801
  entries: [],
2223
- errors: [{ code: catalogGenerationErrorCode(error), message }],
1802
+ errors: [{ code: catalogStoreErrorCode(error), message }],
2224
1803
  });
2225
1804
  writeLine(io.stderr, message);
2226
1805
  commandExitState.exitCode = 1;
@@ -2245,25 +1824,24 @@ export function buildProgram(options = {}) {
2245
1824
  }
2246
1825
  else if (dryRun) {
2247
1826
  writeLine(io.stdout, `Dry run: ${result.entries.filter((entry) => entry.status === 'reclaimable').length} item(s) are reclaimable.`);
2248
- writeLine(io.stdout, 'Run `aw catalog store prune --yes` to delete them.');
1827
+ writeLine(io.stdout, 'Run `aw cache prune --yes` to delete them.');
1828
+ if (result.errors.length > 0)
1829
+ writeLine(io.stderr, `${result.errors.length} item(s) could not be fully inspected and were retained.`);
2249
1830
  }
2250
1831
  else {
2251
1832
  writeLine(io.stdout, `Deleted ${result.deleted.length} Catalog store item(s) (${result.deletedBytes} bytes).`);
2252
1833
  if (result.errors.length > 0)
2253
- writeLine(io.stderr, `${result.errors.length} item(s) could not be deleted and were retained.`);
1834
+ writeLine(io.stderr, `${result.errors.length} item(s) could not be fully inspected or deleted and were retained.`);
2254
1835
  }
2255
1836
  commandExitState.exitCode = result.ok ? 0 : 1;
2256
1837
  }
2257
1838
  catch (error) {
2258
1839
  const failure = sanitizeCatalogSourceError(error, env);
2259
1840
  const message = redactString(failure.message);
2260
- const explicitCode = error.code;
2261
- const code = typeof explicitCode === 'string'
2262
- ? explicitCode
2263
- : catalogGenerationErrorCode(error);
1841
+ const code = catalogStoreErrorCode(error);
2264
1842
  if (rawOptions.json)
2265
1843
  writeJsonReceipt(io.stdout, {
2266
- catalogStoreSchemaVersion: 1,
1844
+ catalogStoreSchemaVersion: 2,
2267
1845
  command: 'catalog:store:prune',
2268
1846
  ok: false,
2269
1847
  overallState: 'failed',
@@ -2279,1049 +1857,1127 @@ export function buildProgram(options = {}) {
2279
1857
  commandExitState.exitCode = 1;
2280
1858
  }
2281
1859
  });
2282
- program
2283
- .command('init')
2284
- .option('-j, --json', 'print receipt as JSON', false)
1860
+ const recoveryCommand = (command) => command
1861
+ .option('-j, --json', 'print one recovery receipt as JSON', false)
2285
1862
  .option('-v, --verbose', 'show command diagnostics', false)
2286
1863
  .option('-D, --debug', 'write debug diagnostics to a log file', false)
2287
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
1864
+ .option('--log-file <path>', 'write debug diagnostics to the specified file');
1865
+ const contextualCommand = (command) => recoveryCommand(command)
1866
+ .addOption(strictValueOption('--context <context>', 'user only, or user and current project', ['user', 'project']));
1867
+ const recoveryScope = (rawOptions) => normalizeWriteRequest(() => parseScopeValue(rawOptions.scope));
1868
+ const recoveryContext = (rawOptions) => rawOptions.context === undefined
1869
+ ? undefined : normalizeWriteRequest(() => parseContextValue(rawOptions.context));
1870
+ const runRecoveryAction = async (command, rawOptions, action) => {
1871
+ const context = createActionContext(command, rawOptions);
1872
+ const result = await runActionWithContext(context, () => action(context));
1873
+ if (rawOptions.json)
1874
+ writeJsonReceipt(io.stdout, result);
1875
+ else
1876
+ renderRecoveryReceipt(io.stdout, result);
1877
+ commandExitState.exitCode = result.ok ? 0
1878
+ : result.errors.some((error) => error.code === 'invalidArguments') ? 2 : 1;
1879
+ };
1880
+ const showWorkContext = async (context, rawOptions) => {
1881
+ if (rawOptions.scope === 'project' && rawOptions.context === 'user') {
1882
+ throw new WriteCommandRequestError('--scope project cannot be combined with --context user.');
1883
+ }
1884
+ const work = await resolveWorkContext({ cwd: context.cwd, context: recoveryContext(rawOptions),
1885
+ ...(rawOptions.scope === undefined ? {} : { scope: recoveryScope(rawOptions) }) });
1886
+ if (!rawOptions.json)
1887
+ writeLine(io.stdout, work.projectRoot
1888
+ ? `工作上下文:用户与当前项目 ${work.projectRoot}` : '工作上下文:仅用户');
1889
+ return work;
1890
+ };
1891
+ const targets = program.command('target').description('Manage the local platform policy');
1892
+ program.command('internal', { hidden: true }).description('AW host integration protocols')
1893
+ .command('cursor-workspace-open').description('Return current Cursor workspace plugin paths')
1894
+ .requiredOption('--scope <scope>', 'user or project scope')
1895
+ .option('--project-root <path>', 'the exact project workspace root')
1896
+ .option('--plugin-id <source/plugin>', 'return only the exact required plugin package')
2288
1897
  .action(async (rawOptions) => {
2289
- const context = createActionContext('init', rawOptions);
2290
- const result = await runActionWithContext(context, () => initCommand({
2291
- env: context.env,
2292
- }));
2293
- if (rawOptions.json) {
2294
- writeJsonReceipt(io.stdout, buildInitReceiptJson(result));
2295
- }
2296
- else {
2297
- for (const line of renderInitReceipt(result)) {
2298
- writeLine(io.stdout, line);
2299
- }
2300
- }
2301
- for (const source of result.sources) {
2302
- if (!source.ok && source.error)
2303
- writeLine(io.stderr, `${source.id}: ${source.error}`);
2304
- }
2305
- commandExitState.exitCode = result.ok ? 0 : 1;
1898
+ commandExitState.exitCode = await runCursorWorkspaceHookCli(['--scope', rawOptions.scope,
1899
+ ...(rawOptions.projectRoot ? ['--project-root', rawOptions.projectRoot] : []),
1900
+ ...(rawOptions.pluginId ? ['--plugin-id', rawOptions.pluginId] : [])], { cwd, env, stdin: options.stdin ?? process.stdin, stdout: io.stdout, stderr: io.stderr });
2306
1901
  });
2307
- program
2308
- .command('sync')
2309
- .description('Reconcile actual state from existing desired intent')
2310
- .argument('[plugins...]')
2311
- .requiredOption('-s, --scope <scope>', 'project or user')
2312
- .requiredOption('-p, --platform <platform>', 'codex, claude, or both')
2313
- .option('-a, --all', 'reconcile every desired plugin in the selected scope', false)
2314
- .option('--refresh', 'refresh only Catalog sources required by selected intent roots', false)
2315
- .option('-y, --yes', 'authorize shared native replacement or forced repair', false)
2316
- .option('--allow-managed-codex-install', 'allow this command to acquire or rebuild the pinned AW-managed Codex runtime', false)
2317
- .option('-j, --json', 'print sync receipt as JSON', false)
2318
- .option('-v, --verbose', 'show command diagnostics', false)
2319
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
2320
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2321
- .action(async (plugins, rawOptions) => {
2322
- const context = createActionContext('sync', rawOptions);
2323
- const normalized = normalizeWriteRequest(() => normalizeInstallCommandOptions({
2324
- cwd: context.cwd,
2325
- scope: rawOptions.scope,
2326
- platform: rawOptions.platform,
2327
- allowManagedCodexInstall: rawOptions.allowManagedCodexInstall,
2328
- }));
2329
- const syncPlatform = normalized.platform;
2330
- const result = await runActionWithContext(context, () => syncCommand(plugins ?? [], {
2331
- cwd: context.cwd,
2332
- env: context.env,
2333
- platform: syncPlatform,
2334
- scope: normalized.scope,
2335
- all: rawOptions.all,
2336
- refresh: rawOptions.refresh,
2337
- cliVersion: resolveCliVersion(),
2338
- yes: rawOptions.yes,
2339
- json: rawOptions.json,
2340
- interactive: context.interactive && context.isTty && !context.isCi,
2341
- prompt: context.prompt,
2342
- allowManagedCodexInstall: rawOptions.allowManagedCodexInstall,
2343
- }, context));
2344
- if (rawOptions.json) {
2345
- writeJsonReceipt(io.stdout, buildRebuildReceiptJson('sync', result));
2346
- }
2347
- else {
2348
- for (const line of renderRebuildReceipt('sync', result))
2349
- writeLine(io.stdout, line);
2350
- }
2351
- writeWarnings(io.stderr, result.warnings, { actionableOnly: true });
2352
- commandExitState.exitCode = resolveCommandReceiptExitCode(result);
2353
- });
2354
- program
2355
- .command('install')
2356
- .argument('[plugins...]')
2357
- .option('-s, --scope <scope>', 'project or user')
2358
- .option('-p, --platform <platform>', 'codex | claude | both')
2359
- .option('--dependency-scope <pluginId[#platform]=scope>', 'place one dependency at project or user scope; repeat for more dependencies', (value, previous) => [...previous, value], [])
2360
- .option('--script-timeout <ms>', 'override plugin postApply script timeout in milliseconds')
2361
- .option('--allow-managed-codex-install', 'allow this command to acquire or rebuild the pinned AW-managed Codex runtime', false)
2362
- .option('-y, --yes', 'authorize shared Codex native replacement', false)
2363
- .option('-j, --json', 'print receipt as JSON', false)
2364
- .option('-v, --verbose', 'show command diagnostics', false)
2365
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
2366
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2367
- .action(async (plugins, rawOptions) => {
2368
- const context = createActionContext('install', rawOptions);
2369
- const outcome = await runActionWithContext(context, () => runWriteCommandAction('install', plugins ?? [], rawOptions, context));
2370
- if (outcome.cancelled)
2371
- return;
2372
- const receipt = outcome.result;
2373
- if (rawOptions.json) {
2374
- writeJsonReceipt(io.stdout, buildRebuildReceiptJson('install', receipt));
2375
- }
2376
- else {
2377
- for (const line of renderRebuildReceipt('install', receipt)) {
2378
- writeLine(io.stdout, line);
2379
- }
2380
- }
2381
- writeWarnings(io.stderr, receipt.warnings, { actionableOnly: true });
2382
- commandExitState.exitCode = resolveCommandReceiptExitCode(receipt);
2383
- });
2384
- program
2385
- .command('uninstall')
2386
- .argument('[plugins...]')
2387
- .option('-s, --scope <scope>', 'project or user')
2388
- .option('-p, --platform <platform>', 'codex | claude | both')
2389
- .option('--script-timeout <ms>', 'override plugin postApply script timeout in milliseconds')
2390
- .option('--allow-managed-codex-install', 'allow this command to acquire or rebuild the pinned AW-managed Codex runtime', false)
2391
- .option('-j, --json', 'print receipt as JSON', false)
2392
- .option('-v, --verbose', 'show command diagnostics', false)
2393
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
2394
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2395
- .action(async (plugins, rawOptions) => {
2396
- const context = createActionContext('uninstall', rawOptions);
2397
- const outcome = await runActionWithContext(context, () => runWriteCommandAction('uninstall', plugins ?? [], rawOptions, context));
2398
- if (outcome.cancelled)
2399
- return;
2400
- const receipt = outcome.result;
2401
- if (rawOptions.json) {
2402
- writeJsonReceipt(io.stdout, buildRebuildReceiptJson('uninstall', receipt));
2403
- }
2404
- else {
2405
- for (const line of renderRebuildReceipt('uninstall', receipt)) {
2406
- writeLine(io.stdout, line);
2407
- }
2408
- }
2409
- writeWarnings(io.stderr, receipt.warnings, { actionableOnly: true });
2410
- commandExitState.exitCode = resolveCommandReceiptExitCode(receipt);
2411
- });
2412
- program
2413
- .command('cleanup')
2414
- .argument('[plugins...]')
2415
- .option('-s, --scope <scope>', 'project or user')
2416
- .option('-p, --platform <platform>', 'codex | claude | both')
2417
- .option('-j, --json', 'print cleanup result as JSON', false)
2418
- .option('--force', 'remove exclusively owned plugin output without dependency protection', false)
2419
- .option('--allow-managed-codex-install', 'allow this command to acquire or rebuild the pinned AW-managed Codex runtime', false)
2420
- .option('-v, --verbose', 'show command diagnostics', false)
2421
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
2422
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2423
- .action(async (plugins, rawOptions) => {
2424
- const context = createActionContext('cleanup', rawOptions);
2425
- const outcome = await runActionWithContext(context, () => runWriteCommandAction('cleanup', plugins ?? [], rawOptions, context));
2426
- if (outcome.cancelled)
2427
- return;
2428
- const result = outcome.result;
2429
- if (rawOptions.json) {
2430
- writeJsonReceipt(io.stdout, buildRebuildReceiptJson('cleanup', result));
2431
- }
2432
- else {
2433
- for (const line of renderRebuildReceipt('cleanup', result)) {
2434
- writeLine(io.stdout, line);
2435
- }
2436
- }
2437
- writeWarnings(io.stderr, result.warnings, { actionableOnly: true });
2438
- commandExitState.exitCode = resolveCommandReceiptExitCode(result);
1902
+ contextualCommand(targets.command('set').argument('[targets...]'))
1903
+ .option('--none', 'save an empty target set', false)
1904
+ .option('--force', 'save newly selected unavailable targets without bypassing installation requirements', false)
1905
+ .option('--apply', 'apply the saved target policy in this work context', false)
1906
+ .option('-y, --yes', 'confirm reviewed output changes', false)
1907
+ .action(async (agents, rawOptions) => {
1908
+ if (rawOptions.none ? agents.length > 0 : agents.length === 0) {
1909
+ throw new WriteCommandRequestError('Use target IDs or --none, but not both.');
1910
+ }
1911
+ const normalized = normalizeWriteRequest(() => normalizeAgents(agents));
1912
+ await runRecoveryAction('targets:set', rawOptions, async (context) => {
1913
+ await showWorkContext(context, rawOptions);
1914
+ return targetsSet({ cwd: context.cwd, env: context.env, targets: normalized,
1915
+ context: recoveryContext(rawOptions), apply: rawOptions.apply, yes: rawOptions.yes,
1916
+ force: rawOptions.force,
1917
+ cliVersion: resolveCliVersion(), runtime: recoveryRuntime(context, rawOptions, true) });
1918
+ });
2439
1919
  });
2440
- program
2441
- .command('reinstall')
2442
- .argument('[plugins...]')
2443
- .option('-s, --scope <scope>', 'project or user')
2444
- .option('-p, --platform <platform>', 'codex | claude | both')
2445
- .option('--script-timeout <ms>', 'override plugin postApply script timeout in milliseconds')
2446
- .option('--allow-managed-codex-install', 'allow this command to acquire or rebuild the pinned AW-managed Codex runtime', false)
2447
- .option('-y, --yes', 'authorize shared Codex native replacement or forced reinstall', false)
2448
- .option('-j, --json', 'print receipt as JSON', false)
1920
+ contextualCommand(targets.command('list'))
1921
+ .action(async (rawOptions) => runRecoveryAction('targets:list', rawOptions, (context) => targetsList({ cwd: context.cwd, env: context.env, context: recoveryContext(rawOptions),
1922
+ runtime: { nativeCliRunner: context.nativeCliRunner } })));
1923
+ for (const action of ['exclude', 'include']) {
1924
+ contextualCommand(targets.command(action).argument('<plugin>'))
1925
+ .addOption(strictValueOption('--target <target>', 'one canonical platform target', PLATFORM_TARGETS).makeOptionMandatory())
1926
+ .option('--apply', 'apply the saved exclusion policy in this work context', false)
1927
+ .option('-y, --yes', 'confirm reviewed output changes', false)
1928
+ .action(async (selector, rawOptions) => {
1929
+ await runRecoveryAction(`targets:${action}`, rawOptions, async (context) => {
1930
+ await showWorkContext(context, rawOptions);
1931
+ return targetsChangeExclusion({ cwd: context.cwd, env: context.env, context: recoveryContext(rawOptions),
1932
+ selector, target: rawOptions.target, excluded: action === 'exclude', apply: rawOptions.apply,
1933
+ yes: rawOptions.yes, cliVersion: resolveCliVersion(), runtime: recoveryRuntime(context, rawOptions, true) });
1934
+ });
1935
+ });
1936
+ }
1937
+ const config = plugin.command('config').description('Manage user common and platform configuration');
1938
+ const configCommand = (command) => command
1939
+ .addOption(strictValueOption('--platform <target>', 'configuration platform; omitted means common', PLATFORM_TARGETS))
1940
+ .addOption(strictValueOption('--context <context>', 'definition and reference context', ['user', 'project']))
1941
+ .option('-j, --json', 'print one JSON object', false)
2449
1942
  .option('-v, --verbose', 'show command diagnostics', false)
2450
1943
  .option('-D, --debug', 'write debug diagnostics to a log file', false)
2451
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2452
- .action(async (plugins, rawOptions) => {
2453
- const context = createActionContext('reinstall', rawOptions);
2454
- const outcome = await runActionWithContext(context, () => runWriteCommandAction('reinstall', plugins ?? [], rawOptions, context));
2455
- if (outcome.cancelled)
2456
- return;
2457
- const receipt = outcome.result;
2458
- if (rawOptions.json) {
2459
- writeJsonReceipt(io.stdout, buildRebuildReceiptJson('reinstall', receipt));
2460
- }
2461
- else {
2462
- const lines = renderRebuildReceipt('reinstall', receipt);
2463
- for (const line of lines) {
2464
- writeLine(io.stdout, line);
1944
+ .option('--log-file <path>', 'write debug diagnostics to the specified file');
1945
+ const configMutation = (command) => configCommand(command)
1946
+ .option('--apply', 'refresh existing affected outputs after saving', false)
1947
+ .option('--script-timeout <ms>', 'override plugin preApply timeout in milliseconds')
1948
+ .option('-y, --yes', 'confirm reviewed output changes', false);
1949
+ const configContext = async (context, rawOptions, apply = rawOptions.apply === true) => {
1950
+ const requested = rawOptions.context === undefined ? apply ? undefined : 'user'
1951
+ : normalizeWriteRequest(() => parseContextValue(rawOptions.context));
1952
+ const work = await resolveWorkContext({ cwd: context.cwd, context: requested });
1953
+ if (apply && !rawOptions.json)
1954
+ writeLine(io.stdout, work.projectRoot
1955
+ ? `工作上下文:用户与当前项目 ${work.projectRoot}` : '工作上下文:仅用户');
1956
+ return work;
1957
+ };
1958
+ const configPlatform = (rawOptions) => rawOptions.platform === undefined
1959
+ ? undefined : normalizeWriteRequest(() => parsePlatformTargetValue(rawOptions.platform));
1960
+ configCommand(config.command('suggestions').description('Query dynamic configuration suggestions without saving'))
1961
+ .argument('<plugin>', 'source-qualified plugin ID')
1962
+ .argument('<field-path>', 'dot-separated field path, with optional array indices')
1963
+ .option('--dep <key=value>', 'override a dependency value', (value, previous = []) => [...previous, value])
1964
+ .addOption(strictValueOption('--timeout-ms <ms>', 'suggestion provider timeout in milliseconds'))
1965
+ .action(async (selector, field, rawOptions) => {
1966
+ const command = 'plugin.config.suggestions';
1967
+ const context = createActionContext(command, rawOptions);
1968
+ const platform = configPlatform(rawOptions);
1969
+ let parseValidSelector = false;
1970
+ let fieldPath;
1971
+ try {
1972
+ const parsed = normalizeWriteRequest(() => parsePluginId(selector));
1973
+ if (!parsed.sourceId)
1974
+ throw new ConfigSuggestionArgumentError('Use the source-qualified plugin ID.');
1975
+ parseValidSelector = true;
1976
+ const parts = parseConfigSuggestionFieldPath(field);
1977
+ fieldPath = parts;
1978
+ const dependencyOverrides = parseConfigSuggestionDependencyOverrides(rawOptions.dep ?? []);
1979
+ const timeout = rawOptions.timeoutMs;
1980
+ const timeoutMs = timeout === undefined ? undefined : (/^[0-9]+$/u.test(timeout) ? Number(timeout) : NaN);
1981
+ if (timeoutMs !== undefined && (!Number.isInteger(timeoutMs) || timeoutMs < CONFIG_SUGGESTIONS_TIMEOUT_MIN_MS
1982
+ || timeoutMs > CONFIG_SUGGESTIONS_TIMEOUT_MAX_MS)) {
1983
+ throw new ConfigSuggestionArgumentError(`Use a decimal integer between ${CONFIG_SUGGESTIONS_TIMEOUT_MIN_MS} and ${CONFIG_SUGGESTIONS_TIMEOUT_MAX_MS} milliseconds.`);
2465
1984
  }
1985
+ const work = await configContext(context, rawOptions, false);
1986
+ const result = await runActionWithContext(context, () => withResolvedCatalogPlugin({
1987
+ selector, cliVersion: resolveCliVersion(), env: context.env, signal: context.signal,
1988
+ consume: async ({ plugin }) => {
1989
+ const prepared = await preparePluginConfigSuggestions({
1990
+ plugin, platform, context: work.context, cwd: context.cwd, env: context.env, fieldPath: parts,
1991
+ dependencyOverrides, timeoutMs, signal: context.signal,
1992
+ });
1993
+ const { status, items, message, diagnostics } = prepared.project(await prepared.run());
1994
+ const severity = status === 'unavailable' ? 'error' : status === 'ok' ? 'info' : 'warning';
1995
+ const entries = status !== 'ok' && !diagnostics?.length ? [{
1996
+ code: status === 'unavailable' ? 'configSuggestionsUnavailable'
1997
+ : status === 'not-applicable' ? 'configSuggestionsNotApplicable' : 'configSuggestionsNoProbe',
1998
+ message: message || (status === 'unavailable' ? 'Suggestions are unavailable.'
1999
+ : status === 'not-applicable' ? 'Suggestions do not apply to this selection.' : 'No suggestion probe for this selection.'),
2000
+ }] : diagnostics ?? [];
2001
+ return commandResult(command, { pluginId: prepared.pluginId, fieldPath: prepared.fieldPath, profile: prepared.profile,
2002
+ provider: prepared.provider, providerPluginId: prepared.providerPluginId, kind: prepared.kind, status, items,
2003
+ ...(message === undefined ? {} : { message }), ...(diagnostics === undefined ? {} : { diagnostics }) }, {
2004
+ status: status === 'unavailable' ? 'failed' : 'success',
2005
+ diagnostics: entries.map((entry) => ({ ...entry, severity, subject: {
2006
+ pluginId: prepared.providerPluginId, ...(platform === undefined ? {} : { target: platform }), field,
2007
+ } })),
2008
+ });
2009
+ },
2010
+ }));
2011
+ writeJsonReceipt(io.stdout, result);
2012
+ commandExitState.exitCode = publicExitCode(result);
2466
2013
  }
2467
- writeWarnings(io.stderr, receipt.warnings, { actionableOnly: true });
2468
- commandExitState.exitCode = resolveCommandReceiptExitCode(receipt);
2469
- });
2470
- const config = program
2471
- .command('config')
2472
- .description('Manage AW plugin configuration');
2473
- config
2474
- .command('list')
2475
- .argument('[plugin]')
2476
- .option('-s, --scope <scope>', 'read only project or user config')
2477
- .option('-j, --json', 'print config as JSON', false)
2478
- .option('-v, --verbose', 'show command diagnostics', false)
2479
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
2480
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2481
- .action(async (pluginName, rawOptions) => {
2482
- const context = createActionContext('config:list', rawOptions);
2483
- const outcome = await runActionWithContext(context, async () => {
2484
- resolveConfigReadResolution(rawOptions.scope);
2485
- const execute = async (selectedPlugin) => resolveMultiSourceConfigRead({
2486
- selector: selectedPlugin,
2487
- rawOptions,
2488
- context,
2489
- });
2490
- if (pluginName)
2491
- return { cancelled: false, pluginName, value: await execute(pluginName) };
2492
- if (!isWizardAvailable(context, rawOptions))
2493
- throw new Error(configCommandUsage('list'));
2494
- const currentCandidates = await loadWizardCandidates(context, {});
2495
- const storedCandidates = await loadStoredConfigWizardCandidates(context, configReadStoreLocations(rawOptions));
2496
- const candidates = mergeWizardCandidates(currentCandidates, storedCandidates);
2497
- if (candidates.length === 0) {
2498
- throw new Error('No plugin config candidates exist in the selected location.');
2014
+ catch (error) {
2015
+ context.signal?.throwIfAborted();
2016
+ if (error instanceof ConfigLayerError) {
2017
+ const result = commandResult(command, {}, { status: 'blocked', diagnostics: [{
2018
+ code: error.code, severity: 'error', message: error.message,
2019
+ subject: { pluginId: selector, ...(platform === undefined ? {} : { target: platform }), field },
2020
+ }], nextActions: error.nextActions });
2021
+ writeJsonReceipt(io.stdout, result);
2022
+ commandExitState.exitCode = publicExitCode(result);
2023
+ return;
2499
2024
  }
2500
- const result = await runCommandWizard(context, {
2501
- command: 'config:list',
2502
- candidates,
2503
- initial: { plugins: [], scope: rawOptions.scope },
2504
- pluginMode: 'single',
2505
- ...equivalentConfigCommandProjection((selection) => ({
2506
- command: 'list',
2507
- plugin: selection.plugins[0],
2508
- scope: rawOptions.scope,
2509
- })),
2510
- execute: (selection) => execute(selection.plugins[0]),
2511
- });
2512
- return result.cancelled
2513
- ? { cancelled: true }
2514
- : { cancelled: false, pluginName: result.selection.plugins[0], value: result.value };
2515
- });
2516
- if (outcome.cancelled)
2517
- return;
2518
- const resolved = outcome.value;
2519
- const selectedPluginName = resolved.pluginName;
2520
- if (rawOptions.json) {
2521
- writeJsonReceipt(io.stdout, {
2522
- ok: true,
2523
- configSchemaVersion: 4,
2524
- command: 'config:list',
2525
- plugin: selectedPluginName,
2526
- pluginName: selectedPluginName,
2527
- pluginId: resolved.pluginId,
2528
- sourceId: resolved.sourceId,
2529
- sourceIdentity: resolved.sourceIdentity,
2530
- scope: rawOptions.scope ?? 'effective',
2531
- ...(resolved.result.schema ? { schema: resolved.result.schema } : {}),
2532
- fields: resolved.result.fields,
2533
- });
2534
- }
2535
- else {
2536
- writeConfigReadHuman(io.stdout, resolved.result, resolved.pluginId);
2025
+ const argumentError = error instanceof ConfigSuggestionArgumentError || error instanceof WriteCommandRequestError
2026
+ || error instanceof CatalogPluginNotFoundError;
2027
+ const result = commandResult(command, {}, { status: 'failed', diagnostics: [{
2028
+ code: argumentError ? 'invalidArguments' : 'configSuggestionsUnavailable', severity: 'error',
2029
+ message: error instanceof ConfigSuggestionArgumentError || error instanceof WriteCommandRequestError ? error.message
2030
+ : error instanceof CatalogPluginNotFoundError ? 'The selected plugin is not in the active Catalog.'
2031
+ : 'The config suggestion provider could not be prepared.',
2032
+ subject: { ...(parseValidSelector ? { pluginId: selector } : {}),
2033
+ ...(platform === undefined ? {} : { target: platform }), ...(fieldPath === undefined ? {} : { field }) },
2034
+ }] });
2035
+ writeJsonReceipt(io.stdout, result);
2036
+ commandExitState.exitCode = publicExitCode(result, argumentError);
2537
2037
  }
2538
2038
  });
2539
- config
2540
- .command('get')
2541
- .argument('[plugin]')
2542
- .argument('[key]')
2543
- .option('-s, --scope <scope>', 'read only project or user config')
2544
- .option('-j, --json', 'print config as JSON', false)
2545
- .option('-v, --verbose', 'show command diagnostics', false)
2546
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
2547
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2548
- .action(async (pluginName, key, rawOptions) => {
2549
- const context = createActionContext('config:get', rawOptions);
2550
- const outcome = await runActionWithContext(context, async () => {
2551
- resolveConfigReadResolution(rawOptions.scope);
2552
- const execute = async (selectedPlugin) => resolveMultiSourceConfigRead({
2553
- selector: selectedPlugin,
2554
- ...(key === undefined ? {} : { key }),
2555
- rawOptions,
2556
- context,
2557
- });
2558
- if (pluginName)
2559
- return { cancelled: false, pluginName, value: await execute(pluginName) };
2560
- if (!isWizardAvailable(context, rawOptions))
2561
- throw new Error(configCommandUsage('get'));
2562
- const currentCandidates = await loadWizardCandidates(context, {});
2563
- const storedCandidates = await loadStoredConfigWizardCandidates(context, configReadStoreLocations(rawOptions));
2564
- const candidates = mergeWizardCandidates(currentCandidates, storedCandidates);
2565
- if (candidates.length === 0) {
2566
- throw new Error('No plugin config candidates exist in the selected location.');
2039
+ for (const command of ['schema', 'list', 'get']) {
2040
+ const entry = configCommand((command === 'list' ? new Command(command) : config.command(command)).argument('<plugin>'));
2041
+ if (command === 'get')
2042
+ entry.argument('[key]');
2043
+ entry.action(async (...args) => {
2044
+ const selector = args[0];
2045
+ const key = command === 'get' ? args[1] : undefined;
2046
+ const rawOptions = args[command === 'get' ? 2 : 1];
2047
+ const context = createActionContext(`config:${command}`, rawOptions);
2048
+ const work = await configContext(context, rawOptions);
2049
+ const resolved = await runActionWithContext(context, () => resolveMultiSourceConfigRead({
2050
+ selector, key, schemaOnly: command === 'schema', rawOptions: { ...rawOptions, context: work.context }, context,
2051
+ }));
2052
+ if (rawOptions.json || io.result) {
2053
+ const result = projectReceipt(`plugin.config.${command}`, {
2054
+ ok: true, configSchemaVersion: 5, command: `config:${command}`,
2055
+ plugin: resolved.pluginName, pluginName: resolved.pluginName, pluginId: resolved.pluginId,
2056
+ sourceId: resolved.sourceId, sourceIdentity: resolved.sourceIdentity,
2057
+ context: work, platform: configPlatform(rawOptions) ?? 'common',
2058
+ ...(resolved.result.schema ? { schema: resolved.result.schema } : {}),
2059
+ fields: command === 'schema' ? resolved.result.fieldDefinitions ?? {} : resolved.result.fields,
2060
+ ...(key === undefined ? {} : { key }),
2061
+ });
2062
+ if (command === 'get')
2063
+ for (const field of resolved.result.fields) {
2064
+ const definition = resolved.result.fieldDefinitions?.[field.key];
2065
+ if (field.kind !== 'manifest' || field.valueState !== 'invalid' || !definition?.sensitive)
2066
+ continue;
2067
+ result.nextActions.push({ kind: 'command',
2068
+ argv: ['aw', 'plugin', 'config', 'set', resolved.pluginId, field.key,
2069
+ '--context', work.context, ...(resolved.result.platform ? ['--platform', resolved.result.platform] : []), '--value-stdin'],
2070
+ reason: 'Replace the invalid sensitive configuration value through stdin.', requiresConfirmation: false });
2071
+ }
2072
+ writeJsonReceipt(io.stdout, result);
2567
2073
  }
2568
- const result = await runCommandWizard(context, {
2569
- command: 'config:get',
2570
- candidates,
2571
- initial: { plugins: [], key, scope: rawOptions.scope },
2572
- pluginMode: 'single',
2573
- ...equivalentConfigCommandProjection((selection) => ({
2574
- command: 'get',
2575
- plugin: selection.plugins[0],
2576
- key,
2577
- scope: rawOptions.scope,
2578
- })),
2579
- execute: (selection) => execute(selection.plugins[0]),
2580
- });
2581
- return result.cancelled
2582
- ? { cancelled: true }
2583
- : { cancelled: false, pluginName: result.selection.plugins[0], value: result.value };
2074
+ else if (command === 'schema')
2075
+ writeJsonReceipt(io.stdout, resolved.result.fieldDefinitions ?? {});
2076
+ else
2077
+ writeConfigReadHuman(io.stdout, resolved.result, resolved.pluginId);
2584
2078
  });
2585
- if (outcome.cancelled)
2586
- return;
2587
- const resolved = outcome.value;
2588
- const selectedPluginName = resolved.pluginName;
2589
- if (rawOptions.json) {
2590
- writeJsonReceipt(io.stdout, {
2591
- ok: true,
2592
- configSchemaVersion: 4,
2593
- command: 'config:get',
2594
- plugin: selectedPluginName,
2595
- pluginName: selectedPluginName,
2596
- pluginId: resolved.pluginId,
2597
- sourceId: resolved.sourceId,
2598
- sourceIdentity: resolved.sourceIdentity,
2599
- key,
2600
- scope: rawOptions.scope ?? 'effective',
2601
- ...(resolved.result.schema ? { schema: resolved.result.schema } : {}),
2602
- fields: resolved.result.fields,
2603
- });
2604
- }
2605
- else {
2606
- writeConfigReadHuman(io.stdout, resolved.result, resolved.pluginId);
2607
- }
2608
- });
2609
- config
2610
- .command('set')
2611
- .argument('[plugin]')
2612
- .argument('[field]')
2613
- .option('-s, --scope <scope>', 'project or user')
2614
- .option('--value-json <json>', 'set the field to an exact JSON value')
2615
- .option('--preset <id>', 'set the field to the current manifest preset value')
2616
- .option('--apply', 'apply the saved config to visible desired placements', false)
2617
- .option('-y, --yes', 'confirm shared Codex native config apply', false)
2618
- .option('-j, --json', 'print receipt as JSON', false)
2619
- .option('-v, --verbose', 'show command diagnostics', false)
2620
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
2621
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2622
- .action(async (pluginName, key, rawOptions) => {
2623
- if (!pluginName || !key)
2624
- throw new Error(configCommandUsage('set'));
2625
- const context = createActionContext('config:set', rawOptions);
2626
- let outcome;
2627
- try {
2628
- outcome = await runActionWithContext(context, async () => {
2629
- const scope = resolveConfigWriteScope(rawOptions.scope);
2630
- if ((rawOptions.valueJson === undefined) === (rawOptions.preset === undefined)) {
2631
- throw new Error('Use exactly one of --value-json <json> or --preset <id>.');
2079
+ }
2080
+ for (const command of ['set', 'edit', 'unset']) {
2081
+ const entry = configMutation((command === 'edit' ? new Command(command) : config.command(command)).argument('<plugin>'));
2082
+ if (command !== 'edit')
2083
+ entry.argument('<field>');
2084
+ if (command === 'set')
2085
+ entry
2086
+ .option('--value-json <json>', 'set an exact JSON value')
2087
+ .option('--value-stdin', 'read the exact string value until stdin EOF', false)
2088
+ .option('--preset <id>', 'use a declared preset');
2089
+ entry.action(async (...args) => {
2090
+ const selector = args[0];
2091
+ const rawOptions = args[command === 'edit' ? 1 : 2];
2092
+ let key = command === 'edit' ? undefined : args[1];
2093
+ const context = createActionContext(`config:${command}`, rawOptions);
2094
+ let resolvedPluginId;
2095
+ try {
2096
+ let cleanupApplyError;
2097
+ const work = await configContext(context, rawOptions);
2098
+ const platform = configPlatform(rawOptions);
2099
+ const scriptTimeoutMs = normalizeWriteRequest(() => resolveScriptTimeoutMs(rawOptions));
2100
+ if (command === 'edit' && (!isWizardAvailable(context, rawOptions) || !context.prompt.select || !context.prompt.input)) {
2101
+ throw new WriteCommandRequestError('config edit requires an interactive terminal. Use config set for scripts.');
2102
+ }
2103
+ const explicitValueCount = [rawOptions.valueJson !== undefined, rawOptions.valueStdin === true,
2104
+ rawOptions.preset !== undefined].filter(Boolean).length;
2105
+ if (command === 'set' && (explicitValueCount > 1 || explicitValueCount === 0
2106
+ && !(context.interactive && context.isTty && !context.isCi && !rawOptions.json))) {
2107
+ throw new WriteCommandRequestError('Use exactly one of --value-json, --value-stdin, or --preset.');
2632
2108
  }
2633
- return withResolvedConfigMutationPlugin(context, pluginName, async ({ pluginId, source, plugin }, awHomeMutationToken, catalogOperationContext) => {
2634
- if (!plugin.manifest.config?.fields) {
2635
- throw new Error(`configSchemaUnavailable: Plugin "${pluginName}" does not declare an AW config schema.`);
2109
+ const receipt = await runActionWithContext(context, () => withResolvedConfigMutationPlugin(context, selector, async ({ pluginId, source, plugin }, awHomeMutationToken, catalogOperationContext) => {
2110
+ resolvedPluginId = pluginId;
2111
+ const preferences = await observePreferences({ scope: 'user', cwd: context.cwd, env: context.env });
2112
+ if (command !== 'unset' || rawOptions.apply) {
2113
+ try {
2114
+ assertConfigLayerWritable(pluginId, plugin.manifest, preferences, platform);
2115
+ }
2116
+ catch (error) {
2117
+ if (command !== 'unset' || !(error instanceof ConfigLayerError))
2118
+ throw error;
2119
+ cleanupApplyError = error;
2120
+ }
2636
2121
  }
2637
- const field = plugin.manifest.config.fields[key];
2638
- if (!field) {
2639
- throw new Error(`Unknown config key "${key}".`);
2122
+ if (!plugin.manifest.config && command !== 'unset')
2123
+ throw Object.assign(new Error(`configSchemaUnavailable: Plugin "${plugin.manifest.name}" does not declare an AW config schema.`), { code: 'configSchemaUnavailable' });
2124
+ const fields = plugin.manifest.config ? selectPluginConfigProfile(plugin.manifest.config, platform).fields : {};
2125
+ if (command === 'edit') {
2126
+ const selected = await context.prompt.select({ message: `编辑用户${platform ?? 'common'}配置`,
2127
+ choices: Object.entries(fields).map(([value, field]) => ({ value, label: field.title ?? value })) });
2128
+ if (selected.cancelled || selected.action !== 'select' || selected.value === undefined)
2129
+ return undefined;
2130
+ key = selected.value;
2640
2131
  }
2132
+ const field = fields[key];
2133
+ const store = await readPluginConfigStore({ sourceId: source.sourceId,
2134
+ sourceIdentity: source.sourceIdentity, logicalIdentity: source.logicalIdentity,
2135
+ pluginName: plugin.manifest.name, scope: 'user', platform, cwd: context.cwd, env: context.env,
2136
+ schema: fields });
2137
+ if (command === 'unset') {
2138
+ if (!Object.hasOwn(store.values, key))
2139
+ throw new WriteCommandRequestError(`Unknown config key "${key}" in the selected layer.`);
2140
+ }
2141
+ else if (!field)
2142
+ throw new WriteCommandRequestError(`Unknown config key "${key}".`);
2641
2143
  let inputValue;
2642
- if (rawOptions.valueJson !== undefined) {
2144
+ if (command !== 'unset') {
2145
+ const sensitive = field.sensitive === true;
2146
+ if (sensitive && (rawOptions.valueJson !== undefined || rawOptions.preset !== undefined)) {
2147
+ throw Object.assign(new WriteCommandRequestError('Sensitive config requires --value-stdin.'), { code: 'sensitiveConfigInputUnsupported' });
2148
+ }
2149
+ if (rawOptions.valueStdin)
2150
+ inputValue = await readUtf8Stdin(context.stdin);
2151
+ else if (sensitive) {
2152
+ if (!context.interactive || !context.isTty || context.isCi || rawOptions.json || !context.prompt.password) {
2153
+ throw new Error('sensitiveConfigStdinRequired: Use --value-stdin outside an interactive terminal.');
2154
+ }
2155
+ const response = await context.prompt.password({ message: `输入 ${field.title ?? key}`, mask: true });
2156
+ if (response.cancelled || response.action !== 'select' || response.value === undefined)
2157
+ return undefined;
2158
+ inputValue = response.value;
2159
+ }
2160
+ else if (command === 'edit' || explicitValueCount === 0) {
2161
+ if (!context.prompt.input)
2162
+ throw new WriteCommandRequestError('Use --value-json, --value-stdin, or --preset.');
2163
+ const response = await context.prompt.input({ message: `输入 ${field.title ?? key} 的 JSON 值`,
2164
+ defaultValue: JSON.stringify(store.values[key]) });
2165
+ if (response.cancelled || response.action !== 'select' || response.value === undefined)
2166
+ return undefined;
2167
+ try {
2168
+ inputValue = JSON.parse(response.value);
2169
+ }
2170
+ catch {
2171
+ throw new WriteCommandRequestError('Enter a valid JSON value.');
2172
+ }
2173
+ }
2174
+ else if (rawOptions.valueJson !== undefined) {
2175
+ try {
2176
+ inputValue = JSON.parse(rawOptions.valueJson);
2177
+ }
2178
+ catch {
2179
+ throw new WriteCommandRequestError('--value-json must contain valid JSON.');
2180
+ }
2181
+ }
2182
+ else {
2183
+ const preset = field.choices?.presets.find((candidate) => candidate.id === rawOptions.preset);
2184
+ if (!preset)
2185
+ throw new WriteCommandRequestError(`Unknown preset "${rawOptions.preset}".`);
2186
+ inputValue = structuredClone(preset.value);
2187
+ }
2188
+ }
2189
+ if (command !== 'unset') {
2643
2190
  try {
2644
- inputValue = JSON.parse(rawOptions.valueJson);
2191
+ inputValue = (await coercePluginConfigUpdates({ schema: fields, updates: { [key]: inputValue }, cwd: context.cwd }))[key];
2645
2192
  }
2646
- catch {
2647
- throw new Error('--value-json must contain valid JSON.');
2193
+ catch (error) {
2194
+ throw new WriteCommandRequestError((error instanceof PluginConfigValueValidationError ? error.publicMessage : undefined)
2195
+ ?? `Invalid value for configuration field "${key}".`);
2648
2196
  }
2649
2197
  }
2650
- else {
2651
- const preset = field.choices?.presets.find((entry) => entry.id === rawOptions.preset);
2652
- if (!preset)
2653
- throw new Error(`Unknown preset "${rawOptions.preset}" for config key "${key}".`);
2654
- inputValue = structuredClone(preset.value);
2198
+ try {
2199
+ await assertPluginConfigMutationCandidate({ sourceId: source.sourceId, sourceIdentity: source.sourceIdentity,
2200
+ logicalIdentity: source.logicalIdentity, pluginName: plugin.manifest.name, manifest: plugin.manifest,
2201
+ scope: work.context, platform, cwd: context.cwd, env: context.env,
2202
+ updates: command === 'unset' ? {} : { [key]: inputValue }, removeKeys: command === 'unset' ? [key] : [] });
2655
2203
  }
2656
- const writeReceipt = await applyPluginConfigWrite({
2657
- plugin,
2658
- pluginName: plugin.manifest.name,
2659
- scope,
2660
- cwd: context.cwd,
2661
- env: context.env,
2662
- nativeCliRunner: context.nativeCliRunner,
2663
- rebuildRuntime: {
2664
- ...context,
2665
- awHomeMutationToken,
2666
- catalogOperationContext,
2667
- expectedGenerationSetDigest: catalogOperationContext.generationSetDigest,
2668
- },
2669
- awHomeMutationToken,
2670
- request: {
2671
- updates: { [key]: inputValue },
2672
- },
2673
- apply: rawOptions.apply === true,
2674
- sharedNativeApplyConfirmed: rawOptions.yes === true,
2675
- });
2676
- return buildConfigMutationReceipt('config:set', {
2677
- ok: writeReceipt.overallState === 'succeeded',
2678
- ...writeReceipt,
2679
- plugin: plugin.manifest.name,
2680
- pluginName: plugin.manifest.name,
2681
- pluginId,
2682
- sourceId: source.sourceId,
2683
- sourceIdentity: source.sourceIdentity,
2684
- affectedFields: [{
2685
- key,
2686
- title: field.title ?? key,
2687
- kind: 'manifest',
2688
- reserved: false,
2689
- action: 'set',
2690
- scope,
2691
- }],
2692
- });
2693
- });
2694
- });
2695
- }
2696
- catch (error) {
2697
- writeConfigMutationFailure('config:set', pluginName, rawOptions.json === true, error);
2698
- return;
2699
- }
2700
- const receipt = outcome;
2701
- if (rawOptions.json) {
2702
- writeJsonReceipt(io.stdout, receipt);
2703
- }
2704
- else {
2705
- writeLine(io.stdout, `已写入 ${receipt.plugin}.${key}(${configLayerLabel(receipt.scope)}配置)。`);
2706
- writeConfigApplyNotice(io.stderr, receipt);
2707
- }
2708
- commandExitState.exitCode = receipt.overallState === 'succeeded' ? 0 : 1;
2709
- });
2710
- config
2711
- .command('unset')
2712
- .argument('[plugin]')
2713
- .argument('[key]')
2714
- .option('-s, --scope <scope>', 'project or user')
2715
- .option('--apply', 'apply the saved config to visible desired placements', false)
2716
- .option('-y, --yes', 'confirm shared Codex native config apply', false)
2717
- .option('-j, --json', 'print receipt as JSON', false)
2718
- .option('-v, --verbose', 'show command diagnostics', false)
2719
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
2720
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2721
- .action(async (pluginName, key, rawOptions) => {
2722
- const context = createActionContext('config:unset', rawOptions);
2723
- let outcome;
2724
- try {
2725
- outcome = await runActionWithContext(context, async () => {
2726
- const scope = resolveConfigWriteScope(rawOptions.scope);
2727
- const execute = async (selectedPlugin, selectedKey) => withResolvedConfigMutationPlugin(context, selectedPlugin, async ({ pluginId, source, plugin }, awHomeMutationToken, catalogOperationContext) => {
2728
- if (plugin.manifest.config?.fields && !plugin.manifest.config.fields[selectedKey]) {
2729
- throw new Error(`Unknown config key "${selectedKey}".`);
2204
+ catch (error) {
2205
+ if (error?.code === 'configReferenceInvalid')
2206
+ throw new WriteCommandRequestError(`Invalid value or reference for configuration field "${key}".`);
2207
+ throw error;
2730
2208
  }
2731
- const store = await readPluginConfigStore({
2732
- sourceId: source.sourceId,
2733
- sourceIdentity: source.sourceIdentity,
2734
- pluginName: plugin.manifest.name,
2735
- scope,
2736
- cwd: context.cwd,
2737
- env: context.env,
2738
- schema: plugin.manifest.config?.fields,
2739
- });
2740
- const existed = Object.hasOwn(store.values, selectedKey);
2741
- if (!existed)
2742
- throw new Error(`Unknown config key "${selectedKey}".`);
2743
- const writeReceipt = await applyPluginConfigWrite({
2744
- plugin,
2745
- pluginName: plugin.manifest.name,
2746
- scope,
2747
- cwd: context.cwd,
2748
- env: context.env,
2749
- nativeCliRunner: context.nativeCliRunner,
2750
- rebuildRuntime: {
2751
- ...context,
2752
- awHomeMutationToken,
2753
- catalogOperationContext,
2209
+ const mutation = command === 'unset' ? { kind: 'patch', removeKeys: [key] } : { kind: 'patch', updates: { [key]: inputValue } };
2210
+ const apply = rawOptions.apply === true && !cleanupApplyError;
2211
+ const reviewed = apply ? await preparePublicConfigConfirmation({ plugin, scope: work.context,
2212
+ context: work.context, platform, cwd: context.cwd, env: context.env, cliVersion: resolveCliVersion(),
2213
+ nativeCliRunner: context.nativeCliRunner, awHomeMutationToken, yes: rawOptions.yes, mutation,
2214
+ rebuildRuntime: { ...context, awHomeMutationToken, catalogOperationContext,
2754
2215
  expectedGenerationSetDigest: catalogOperationContext.generationSetDigest,
2755
- },
2756
- awHomeMutationToken,
2757
- request: {
2758
- removeKeys: [selectedKey],
2759
- },
2760
- apply: rawOptions.apply === true,
2761
- sharedNativeApplyConfirmed: rawOptions.yes === true,
2762
- });
2763
- return buildConfigMutationReceipt('config:unset', {
2764
- ok: writeReceipt.overallState === 'succeeded',
2765
- ...writeReceipt,
2766
- plugin: plugin.manifest.name,
2767
- pluginName: plugin.manifest.name,
2768
- pluginId,
2769
- sourceId: source.sourceId,
2770
- sourceIdentity: source.sourceIdentity,
2771
- removedKey: selectedKey,
2772
- existed,
2773
- affectedFields: [{
2774
- key: selectedKey,
2775
- title: plugin?.manifest.config?.fields?.[selectedKey]?.title ?? selectedKey,
2776
- kind: 'manifest',
2777
- reserved: false,
2778
- action: 'unset',
2779
- scope,
2780
- }],
2216
+ ...(scriptTimeoutMs === undefined ? {} : { scriptTimeoutMs }) } })
2217
+ : undefined;
2218
+ const confirmation = reviewed?.confirmation ?? { required: false, provided: rawOptions.yes === true, effects: [] };
2219
+ const writeReceipt = await applyPluginConfigWrite({ plugin, pluginName: plugin.manifest.name,
2220
+ scope: work.context, context: work.context, platform, cliVersion: resolveCliVersion(),
2221
+ cwd: context.cwd, env: context.env, nativeCliRunner: context.nativeCliRunner,
2222
+ rebuildRuntime: { ...context, awHomeMutationToken, catalogOperationContext,
2223
+ expectedGenerationSetDigest: catalogOperationContext.generationSetDigest,
2224
+ ...(scriptTimeoutMs === undefined ? {} : { scriptTimeoutMs }) },
2225
+ awHomeMutationToken, request: command === 'unset' ? { removeKeys: [key] } : { updates: { [key]: inputValue } },
2226
+ expectedCommandPackageEvidence: reviewed?.commandPackageEvidence,
2227
+ expectedHostPermissionEffects: reviewed?.hostPermissionEffects,
2228
+ apply, sharedNativeApplyConfirmed: rawOptions.yes === true,
2229
+ preApplyConfirmed: rawOptions.yes === true });
2230
+ return buildConfigMutationReceipt(`config:${command}`, {
2231
+ ...writeReceipt, confirmation, ok: writeReceipt.overallState === 'succeeded' && !cleanupApplyError, plugin: plugin.manifest.name,
2232
+ ...(cleanupApplyError ? {
2233
+ overallState: 'partial',
2234
+ apply: configApplyLayerFailure(cleanupApplyError),
2235
+ } : {}),
2236
+ pluginName: plugin.manifest.name, pluginId, sourceId: source.sourceId, sourceIdentity: source.sourceIdentity,
2237
+ context: work, platform: platform ?? 'common',
2238
+ ...(command === 'unset' ? { removedKey: key, existed: true } : {}),
2239
+ affectedFields: [{ key: key, title: field?.title ?? key, kind: 'manifest', reserved: false,
2240
+ action: command === 'unset' ? 'unset' : 'set', scope: 'user',
2241
+ ...(writeReceipt.staleRemovedKeys?.includes(key) ? { stale: true } : {}) }],
2781
2242
  });
2782
- });
2783
- if (pluginName && key) {
2784
- return { cancelled: false, value: await execute(pluginName, key) };
2243
+ }));
2244
+ if (!receipt)
2245
+ return;
2246
+ if (cleanupApplyError) {
2247
+ const result = projectReceipt(`plugin.config.${command}`, receipt);
2248
+ writeJsonReceipt(io.stdout, configLayerRecoveryResult(result, cleanupApplyError, receipt.pluginId));
2785
2249
  }
2786
- if (!isWizardAvailable(context, rawOptions))
2787
- throw new Error(configCommandUsage('unset'));
2788
- const loadedCurrentCandidates = await loadWizardCandidates(context, {});
2789
- const currentCandidates = loadedCurrentCandidates.filter(hasConfigSchemaKeys);
2790
- const candidates = currentCandidates;
2791
- if (pluginName && !candidates.some((entry) => entry.pluginName === pluginName)) {
2792
- throw new Error(`Unknown plugin "${pluginName}".`);
2250
+ else if (rawOptions.json || io.result)
2251
+ writeJsonReceipt(io.stdout, receipt);
2252
+ else {
2253
+ writeLine(io.stdout, `已保存 ${receipt.plugin}.${key}(用户 ${platform ?? 'common'} 配置)。`);
2254
+ writeConfigApplyNotice(io.stderr, receipt);
2793
2255
  }
2794
- if (candidates.length === 0) {
2795
- throw new Error('No plugin config candidates exist in the selected location.');
2796
- }
2797
- const result = await runCommandWizard(context, {
2798
- command: 'config:unset',
2799
- candidates,
2800
- initial: { plugins: pluginName ? [pluginName] : [], key, scope },
2801
- pluginMode: pluginName ? 'none' : 'single',
2802
- promptForKey: key === undefined,
2803
- destructive: true,
2804
- ...equivalentConfigCommandProjection((selection) => ({
2805
- command: 'unset',
2806
- plugin: selection.plugins[0],
2807
- key: selection.key,
2808
- scope: selection.scope ?? 'user',
2809
- })),
2810
- resultState: overallResultState,
2811
- execute: (selection) => execute(selection.plugins[0], selection.key),
2812
- });
2813
- return result.cancelled
2814
- ? { cancelled: true }
2815
- : { cancelled: false, value: result.value };
2816
- });
2817
- }
2818
- catch (error) {
2819
- writeConfigMutationFailure('config:unset', pluginName, rawOptions.json === true, error);
2820
- return;
2821
- }
2822
- if (outcome.cancelled)
2823
- return;
2824
- const receipt = outcome.value;
2825
- if (rawOptions.json) {
2826
- writeJsonReceipt(io.stdout, receipt);
2827
- }
2828
- else {
2829
- writeLine(io.stdout, receipt.existed
2830
- ? `已删除 ${receipt.plugin}.${receipt.removedKey}(${configLayerLabel(receipt.scope)}配置)。`
2831
- : `${receipt.plugin}.${receipt.removedKey}(${configLayerLabel(receipt.scope)}配置)原本不存在。`);
2832
- writeConfigApplyNotice(io.stderr, receipt);
2833
- }
2834
- commandExitState.exitCode = receipt.overallState === 'succeeded' ? 0 : 1;
2835
- });
2836
- config
2837
- .command('reset')
2838
- .argument('[plugin]')
2839
- .option('-s, --scope <scope>', 'project or user')
2840
- .option('--apply', 'apply the saved config to visible desired placements', false)
2841
- .option('-y, --yes', 'confirm destructive reset', false)
2842
- .option('-j, --json', 'print receipt as JSON', false)
2843
- .option('-v, --verbose', 'show command diagnostics', false)
2844
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
2845
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2846
- .action(async (pluginName, rawOptions) => {
2256
+ commandExitState.exitCode = receipt.overallState === 'succeeded' ? 0 : 1;
2257
+ }
2258
+ catch (error) {
2259
+ writeConfigMutationFailure(`config:${command}`, resolvedPluginId ?? selector, rawOptions.json === true, error);
2260
+ }
2261
+ });
2262
+ }
2263
+ configMutation(config.command('reset').argument('<plugin>'))
2264
+ .action(async (selector, rawOptions) => {
2847
2265
  const context = createActionContext('config:reset', rawOptions);
2848
- let outcome;
2849
2266
  try {
2850
- outcome = await runActionWithContext(context, async () => {
2851
- const execute = async (selectedPlugin, selectedScope, confirmed) => {
2852
- if (!confirmed) {
2853
- throw new Error(`Reset requires confirmation. Re-run \`aw config reset ${selectedPlugin} -s ${selectedScope} --yes\` to delete this store.`);
2854
- }
2855
- const located = await resolveStoredConfigResetIdentity({
2856
- selector: selectedPlugin,
2857
- context,
2858
- scope: selectedScope,
2859
- });
2860
- const resetLocatedStore = async (plugin, pluginError) => {
2861
- const affectedFields = await describeResetAffectedFields({
2862
- sourceId: located.sourceId,
2863
- sourceIdentity: located.sourceIdentity,
2864
- pluginName: located.pluginName,
2865
- plugin,
2866
- pluginError,
2867
- scope: selectedScope,
2868
- cwd: context.cwd,
2869
- env: context.env,
2870
- }).catch(() => []);
2871
- const resetReceipt = await resetPluginConfigWithHelper({
2872
- sourceId: located.sourceId,
2873
- sourceIdentity: located.sourceIdentity,
2874
- pluginName: located.pluginName,
2875
- scope: selectedScope,
2876
- cwd: context.cwd,
2877
- env: context.env,
2878
- nativeCliRunner: context.nativeCliRunner,
2879
- plugin,
2880
- pluginError,
2881
- apply: rawOptions.apply === true,
2882
- });
2883
- return buildConfigMutationReceipt('config:reset', {
2884
- ok: resetReceipt.overallState === 'succeeded',
2885
- ...resetReceipt,
2886
- plugin: located.pluginName,
2887
- pluginName: located.pluginName,
2888
- pluginId: located.pluginId,
2889
- sourceId: located.sourceId,
2890
- ...(located.sourceIdentity ? { sourceIdentity: located.sourceIdentity } : {}),
2891
- affectedFields,
2892
- });
2893
- };
2894
- let resetStarted = false;
2267
+ let cleanupApplyError;
2268
+ const work = await configContext(context, rawOptions);
2269
+ const platform = configPlatform(rawOptions);
2270
+ if (!rawOptions.yes) {
2271
+ if (!isWizardAvailable(context, rawOptions) || !context.prompt.confirm)
2272
+ throw new WriteCommandRequestError('config reset requires --yes.');
2273
+ const confirmed = await context.prompt.confirm({ message: `删除 ${selector} 的用户 ${platform ?? 'common'} 覆盖?`, defaultValue: false });
2274
+ if (confirmed.cancelled || confirmed.value !== true)
2275
+ return;
2276
+ }
2277
+ const located = await resolveStoredConfigResetIdentity({ selector, context, scope: 'user' });
2278
+ const resetStore = async (plugin, pluginError, awHomeMutationToken, catalogOperationContext) => {
2279
+ if (plugin && rawOptions.apply) {
2895
2280
  try {
2896
- return await withResolvedCatalogPlugin({
2897
- selector: located.pluginId,
2898
- cliVersion: resolveCliVersion(),
2899
- env: context.env,
2900
- consume: async ({ plugin }) => {
2901
- resetStarted = true;
2902
- return resetLocatedStore(plugin, null);
2903
- },
2904
- });
2281
+ assertConfigLayerWritable(located.pluginId, plugin.manifest, await observePreferences({
2282
+ scope: 'user', cwd: context.cwd, env: context.env,
2283
+ }), platform);
2905
2284
  }
2906
2285
  catch (error) {
2907
- if (resetStarted)
2286
+ if (!(error instanceof ConfigLayerError))
2908
2287
  throw error;
2909
- return resetLocatedStore(null, error instanceof Error ? error : new Error(String(error)));
2288
+ cleanupApplyError = error;
2910
2289
  }
2911
- };
2912
- const scope = resolveConfigWriteScope(rawOptions.scope);
2913
- const needsWizard = pluginName === undefined || rawOptions.yes !== true;
2914
- if (!needsWizard) {
2915
- return {
2916
- cancelled: false,
2917
- value: await execute(pluginName, scope, true),
2918
- };
2919
- }
2920
- if (!isWizardAvailable(context, rawOptions)) {
2921
- if (!pluginName)
2922
- throw new Error(configCommandUsage('reset'));
2923
- return {
2924
- cancelled: false,
2925
- value: await execute(pluginName, scope, false),
2926
- };
2927
- }
2928
- const currentCandidates = pluginName ? [] : await loadWizardCandidates(context, {});
2929
- const candidatesByScope = new Map();
2930
- if (!pluginName && (rawOptions.scope === undefined || scope === 'user')) {
2931
- candidatesByScope.set('user', mergeWizardCandidates(currentCandidates, await loadStoredConfigWizardCandidates(context, [{ scope: 'user' }], { includeEmptyStores: true })));
2932
2290
  }
2933
- if (!pluginName && (rawOptions.scope === undefined || scope === 'project')) {
2934
- candidatesByScope.set('project', mergeWizardCandidates(currentCandidates, await loadStoredConfigWizardCandidates(context, [{ scope: 'project' }], { includeEmptyStores: true })));
2935
- }
2936
- const candidates = mergeWizardCandidates(candidatesByScope.get('user') ?? [], candidatesByScope.get('project') ?? []);
2937
- if (!pluginName && candidates.length === 0) {
2938
- throw new Error('No plugin config candidates exist in the selected location.');
2939
- }
2940
- const result = await runCommandWizard(context, {
2941
- command: 'config:reset',
2942
- candidates,
2943
- initial: { plugins: pluginName ? [pluginName] : [], scope },
2944
- pluginMode: pluginName ? 'none' : 'single',
2945
- promptForScope: rawOptions.scope === undefined,
2946
- destructive: true,
2947
- isPluginVisible: (candidate, selection) => candidatesByScope
2948
- .get(selection.scope ?? 'user')
2949
- ?.some((entry) => entry.pluginName === candidate.pluginName) !== false,
2950
- ...equivalentConfigCommandProjection((selection) => ({
2951
- command: 'reset',
2952
- plugin: selection.plugins[0],
2953
- scope: selection.scope ?? 'user',
2954
- confirmed: true,
2955
- })),
2956
- resultState: overallResultState,
2957
- execute: (selection) => execute(selection.plugins[0], selection.scope ?? 'user', true),
2958
- });
2959
- return result.cancelled
2960
- ? { cancelled: true }
2961
- : { cancelled: false, value: result.value };
2962
- });
2291
+ const apply = rawOptions.apply === true && !cleanupApplyError;
2292
+ const rebuildRuntime = { ...context, awHomeMutationToken, catalogOperationContext,
2293
+ expectedGenerationSetDigest: catalogOperationContext?.generationSetDigest, scriptTimeoutMs: resolveScriptTimeoutMs(rawOptions) };
2294
+ const reviewed = plugin && apply ? await preparePublicConfigConfirmation({ plugin,
2295
+ scope: work.context, context: work.context, platform, cwd: context.cwd, env: context.env,
2296
+ cliVersion: resolveCliVersion(), nativeCliRunner: context.nativeCliRunner, awHomeMutationToken,
2297
+ yes: rawOptions.yes, mutation: { kind: 'reset' }, rebuildRuntime }) : null;
2298
+ const receipt = await resetPluginConfigWithHelper({ ...located, plugin, pluginError, platform, scope: work.context,
2299
+ context: work.context, cliVersion: resolveCliVersion(), cwd: context.cwd, env: context.env, awHomeMutationToken,
2300
+ nativeCliRunner: context.nativeCliRunner, apply,
2301
+ expectedCommandPackageEvidence: reviewed?.commandPackageEvidence, expectedHostPermissionEffects: reviewed?.hostPermissionEffects, rebuildRuntime,
2302
+ sharedNativeApplyConfirmed: true, preApplyConfirmed: rawOptions.yes === true });
2303
+ return { ...receipt, confirmation: reviewed?.confirmation ?? null,
2304
+ ...(cleanupApplyError ? {
2305
+ overallState: 'partial',
2306
+ apply: configApplyLayerFailure(cleanupApplyError),
2307
+ } : {}),
2308
+ };
2309
+ };
2310
+ const resetReceipt = await runActionWithContext(context, () => withAwHomeMutationLock({
2311
+ env: context.env, signal: context.signal, action: async (token) => {
2312
+ let started = false;
2313
+ try {
2314
+ const operationContext = await resolveCatalogOperationContext({ sourceIds: [located.sourceId],
2315
+ env: context.env, signal: context.signal });
2316
+ return await withResolvedCatalogPlugin({ selector: located.pluginId, cliVersion: resolveCliVersion(),
2317
+ operationContext, env: context.env, signal: context.signal, consume: ({ plugin }) => {
2318
+ started = true;
2319
+ return resetStore(plugin, null, token, operationContext);
2320
+ } });
2321
+ }
2322
+ catch (error) {
2323
+ if (started || context.signal?.aborted || error instanceof CatalogLeaseEscapeError)
2324
+ throw error;
2325
+ return resetStore(null, error instanceof Error ? error : new Error(String(error)), token);
2326
+ }
2327
+ },
2328
+ }));
2329
+ const receipt = buildConfigMutationReceipt('config:reset', { ...resetReceipt,
2330
+ ok: resetReceipt.overallState === 'succeeded', ...located, plugin: located.pluginName,
2331
+ context: work, platform: platform ?? 'common' });
2332
+ if (cleanupApplyError) {
2333
+ const result = projectReceipt('plugin.config.reset', { ...receipt, confirmation: undefined }, { yes: rawOptions.yes });
2334
+ writeJsonReceipt(io.stdout, configLayerRecoveryResult(result, cleanupApplyError, receipt.pluginId));
2335
+ }
2336
+ else if (rawOptions.json || io.result)
2337
+ writeJsonReceipt(io.stdout, receipt);
2338
+ else {
2339
+ writeLine(io.stdout, `已恢复 ${receipt.plugin} 的用户 ${platform ?? 'common'} 默认配置。`);
2340
+ writeConfigApplyNotice(io.stderr, receipt);
2341
+ }
2342
+ commandExitState.exitCode = receipt.overallState === 'succeeded' ? 0 : 1;
2963
2343
  }
2964
2344
  catch (error) {
2965
- writeConfigMutationFailure('config:reset', pluginName, rawOptions.json === true, error);
2966
- return;
2345
+ writeConfigMutationFailure('config:reset', selector, rawOptions.json === true, error);
2967
2346
  }
2968
- if (outcome.cancelled)
2347
+ });
2348
+ contextualCommand(config.command('apply').argument('<plugin>'))
2349
+ .addOption(strictValueOption('--platform <target>', 'apply the selected configuration profile', PLATFORM_TARGETS))
2350
+ .option('--target <target>', 'limit existing-output refresh to this platform target', collectUniqueOption)
2351
+ .option('-y, --yes', 'confirm reviewed output changes', false)
2352
+ .option('--script-timeout <ms>', 'override plugin preApply timeout in milliseconds')
2353
+ .action(async (selector, rawOptions) => {
2354
+ const context = createActionContext('config:apply', rawOptions);
2355
+ const work = await configContext(context, rawOptions, true);
2356
+ const platform = configPlatform(rawOptions);
2357
+ const targets = rawOptions.target?.map((target) => normalizeWriteRequest(() => parsePlatformTargetValue(target)));
2358
+ let resolved;
2359
+ let confirmed;
2360
+ const receipt = await runActionWithContext(context, () => withResolvedConfigMutationPlugin(context, selector, async ({ plugin, pluginId, source }, awHomeMutationToken, catalogOperationContext) => {
2361
+ const identity = { plugin: plugin.manifest.name, pluginId, sourceId: source.sourceId };
2362
+ resolved = identity;
2363
+ const preferences = await observePreferences({ scope: 'user', cwd: context.cwd, env: context.env });
2364
+ resolveActiveConfigPlatforms(pluginId, plugin.manifest, preferences);
2365
+ for (const selected of [...(platform ? [platform] : []), ...(targets ?? [])]) {
2366
+ assertConfigLayerWritable(pluginId, plugin.manifest, preferences, selected);
2367
+ }
2368
+ const rebuildRuntime = { ...context, catalogOperationContext,
2369
+ expectedGenerationSetDigest: catalogOperationContext.generationSetDigest, scriptTimeoutMs: resolveScriptTimeoutMs(rawOptions) };
2370
+ const reviewed = await preparePublicConfigConfirmation({ plugin, scope: work.context, context: work.context, platform, targets,
2371
+ cwd: context.cwd, env: context.env, cliVersion: resolveCliVersion(), nativeCliRunner: context.nativeCliRunner,
2372
+ awHomeMutationToken, yes: rawOptions.yes, rebuildRuntime });
2373
+ confirmed = reviewed.confirmation;
2374
+ const applied = await applyPluginConfig({ plugin, scope: work.context, context: work.context, platform, targets,
2375
+ expectedEvidence: reviewed.evidence,
2376
+ expectedHostPermissionEffects: reviewed.hostPermissionEffects,
2377
+ cliVersion: resolveCliVersion(), cwd: context.cwd, env: context.env, awHomeMutationToken,
2378
+ nativeCliRunner: context.nativeCliRunner, sharedNativeApplyConfirmed: rawOptions.yes === true,
2379
+ preApplyConfirmed: rawOptions.yes === true, rebuildRuntime,
2380
+ }).catch((error) => {
2381
+ if (!(error instanceof ConfigApplyInterruptedError))
2382
+ throw error;
2383
+ const { code, message } = configMutationFailure(error, context.env, context.cwd);
2384
+ return { configWrite: error.configWrite, overallState: 'partial',
2385
+ apply: error.apply, errors: [{ code, message }] };
2386
+ });
2387
+ return { ...applied, ...identity, confirmation: reviewed.confirmation, context: work, platform: platform ?? 'common' };
2388
+ }, { retainCompletedResultOnAbort: true })).catch((error) => {
2389
+ if (error instanceof ConfigLayerError) {
2390
+ writeConfigMutationFailure('config:apply', resolved?.pluginId ?? selector, rawOptions.json === true, error);
2391
+ return undefined;
2392
+ }
2393
+ if (error instanceof CatalogLeaseEscapeError)
2394
+ throw error;
2395
+ const sourceError = configActiveAvailabilityError(error);
2396
+ if (!resolved && sourceError) {
2397
+ return { plugin: selector, confirmation: null, context: work, configWrite: 'notStarted',
2398
+ overallState: 'failed', errors: [sourceError] };
2399
+ }
2400
+ const code = recoveryInterruptionCode(error, context.signal);
2401
+ if (!code)
2402
+ throw error;
2403
+ if (!resolved)
2404
+ parsePluginId(selector);
2405
+ const message = code === 'processCleanupUnconfirmed' ? 'Process cleanup could not be confirmed.'
2406
+ : 'The command was interrupted before configuration apply completed.';
2407
+ return { ...(resolved ?? { plugin: selector }), confirmation: confirmed ?? null,
2408
+ context: work, configWrite: 'notStarted',
2409
+ overallState: 'failed', errors: [{ code, message }] };
2410
+ });
2411
+ if (!receipt)
2969
2412
  return;
2970
- const receipt = outcome.value;
2971
- if (rawOptions.json) {
2972
- writeJsonReceipt(io.stdout, receipt);
2973
- }
2413
+ const result = buildConfigMutationReceipt('config:apply', { ...receipt,
2414
+ ok: receipt.overallState === 'succeeded' });
2415
+ if (rawOptions.json || io.result)
2416
+ writeJsonReceipt(io.stdout, result);
2974
2417
  else {
2975
- writeLine(io.stdout, receipt.deleted
2976
- ? `已重置 ${receipt.plugin} 的${configLayerLabel(receipt.scope)}配置。`
2977
- : `${receipt.plugin} 没有可重置的${configLayerLabel(receipt.scope)}配置。`);
2978
- writeConfigApplyNotice(io.stderr, receipt);
2979
- }
2980
- commandExitState.exitCode = receipt.overallState === 'succeeded' ? 0 : 1;
2981
- });
2982
- program
2983
- .command('status')
2984
- .argument('[plugins...]')
2985
- .option('-s, --scope <scope>', 'filter by scope')
2986
- .option('-p, --platform <platform>', 'filter by platform')
2987
- .option('-v, --verbose', 'show status details and command diagnostics', false)
2988
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
2989
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2990
- .option('-j, --json', 'print status as JSON', false)
2991
- .action(async (plugins, rawOptions) => {
2992
- const context = createActionContext('status', rawOptions);
2993
- const result = await runActionWithContext(context, () => statusCommandV7({
2994
- plugins: plugins ?? [],
2995
- cwd,
2996
- env: context.env,
2997
- cliVersion: resolveCliVersion(),
2998
- platform: rawOptions.platform,
2999
- scope: rawOptions.scope,
3000
- json: rawOptions.json,
3001
- verbose: rawOptions.verbose,
3002
- }));
3003
- commandExitState.exitCode = result.hasErrors ? 1 : 0;
3004
- writeLine(io.stdout, result.output);
3005
- for (const source of result.payload.catalog.sources) {
3006
- if (source.error)
3007
- writeLine(io.stderr, `${source.id}: ${source.error}`);
3008
- }
3009
- for (const error of result.payload.errors) {
3010
- if (error.code !== 'nativeStateUnreadable' && error.code !== 'stateInventoryFailed') {
3011
- writeLine(io.stderr, error.message);
2418
+ const outcome = result.ok ? '完成' : result.overallState === 'partial' ? '部分失败' : '失败';
2419
+ writeLine(io.stdout, `配置应用:${outcome}。`);
2420
+ if ('apply' in result && result.apply) {
2421
+ writeConfigApplyNotice(io.stderr, { ...result, apply: result.apply, warnings: [] });
2422
+ }
2423
+ else if ('errors' in result) {
2424
+ for (const error of result.errors ?? [])
2425
+ writeLine(io.stderr, error.message);
3012
2426
  }
3013
2427
  }
2428
+ commandExitState.exitCode = result.ok ? 0 : 1;
3014
2429
  });
2430
+ configurePublicCommands(program, options, io, commandExitState);
3015
2431
  Object.assign(program, { __awCommandExitState: commandExitState });
3016
2432
  return program;
3017
2433
  }
3018
- function handleCliError(error, writeError) {
3019
- if (error instanceof CommanderError) {
3020
- return error.exitCode;
3021
- }
3022
- if (isCommandWarningError(error)) {
3023
- writeWarnings(writeError, error.warnings);
3024
- writeLine(writeError, error.message);
3025
- return error.exitCode;
3026
- }
3027
- writeLine(writeError, error instanceof Error ? error.message : String(error));
3028
- return 1;
3029
- }
3030
- export async function runCli(argv, options = {}) {
3031
- const io = {
3032
- ...createDefaultIo(),
3033
- ...options.io,
2434
+ /** Invoke the packaged author tool. Its JSON remains an internal child-process protocol. */
2435
+ async function runAuthoringCliAdapter(argv, options) {
2436
+ const io = { ...createDefaultIo(), ...options.io };
2437
+ const authoringPluginCommand = argv[0] === 'plugin';
2438
+ const explicitWorkspace = argv.some((token) => token === '--workspace-root' || token.startsWith('--workspace-root='));
2439
+ const authoringScriptByCommand = {
2440
+ init: 'init-plugin.mjs',
2441
+ 'add-skill': 'add-skill.mjs',
2442
+ remove: 'remove-plugin.mjs',
2443
+ validate: 'validate-plugin.mjs',
2444
+ status: 'plugin-status.mjs',
3034
2445
  };
3035
- const jsonAuthoringCommand = argv.includes('--json')
3036
- && ((argv[0] === 'catalog' && ['init', 'context', 'version', 'build', 'validate', 'status', 'publish'].includes(argv[1] ?? ''))
3037
- || (argv[0] === 'plugin' && ['build', 'test', 'validate', 'status', 'remove'].includes(argv[1] ?? '')))
3038
- ? `${argv[0]}:${argv[1]}`
3039
- : null;
3040
- const jsonCatalogDevCommand = argv.includes('--json')
3041
- && argv[0] === 'catalog'
3042
- && argv[1] === 'dev'
3043
- && ['activate', 'status', 'deactivate'].includes(argv[2] ?? '')
3044
- ? argv[2]
3045
- : null;
3046
- const jsonWriteRequest = jsonWriteCommandRequest(argv);
3047
- const jsonConfigMutation = jsonConfigMutationRequest(argv);
3048
- try {
3049
- const authoringScriptByCommand = {
3050
- init: 'init-plugin.mjs',
3051
- 'add-skill': 'add-skill.mjs',
3052
- remove: 'remove-plugin.mjs',
3053
- validate: 'validate-plugin.mjs',
3054
- status: 'plugin-status.mjs',
3055
- };
3056
- const authoringScript = argv[0] === 'plugin'
3057
- ? authoringScriptByCommand[argv[1] ?? '']
3058
- : argv[0] === 'skill' && argv[1] === 'validate'
3059
- ? 'validate-skill.mjs'
3060
- : undefined;
3061
- if (authoringScript && !argv.includes('--help') && !argv.includes('-h')) {
3062
- const authoringArgs = argv.slice(2);
3063
- let authoringEnv = options.env ?? process.env;
3064
- if (argv[0] === 'plugin'
3065
- && !authoringArgs.some((token) => token === '--plugin-root' || token.startsWith('--plugin-root='))) {
3066
- let explicitRoot;
2446
+ const authoringScript = authoringPluginCommand
2447
+ ? authoringScriptByCommand[argv[1] ?? '']
2448
+ : argv[0] === 'skill' && argv[1] === 'validate'
2449
+ ? 'validate-skill.mjs'
2450
+ : undefined;
2451
+ if (authoringScript && ((!argv.includes('--help') && !argv.includes('-h'))
2452
+ || explicitWorkspace && ['remove', 'status'].includes(argv[1] ?? ''))) {
2453
+ const authoringArgs = argv.slice(2);
2454
+ let authoringEnv = options.env ?? process.env;
2455
+ if (argv[0] === 'plugin'
2456
+ && !authoringArgs.some((token) => token === '--plugin-root' || token.startsWith('--plugin-root='))) {
2457
+ let explicitRoot;
2458
+ for (let index = 0; index < authoringArgs.length; index += 1) {
2459
+ const token = authoringArgs[index];
2460
+ if (token.startsWith('--workspace-root='))
2461
+ explicitRoot = token.slice('--workspace-root='.length);
2462
+ if (token === '--workspace-root')
2463
+ explicitRoot = authoringArgs[index + 1];
2464
+ }
2465
+ const originalCwd = options.cwd ?? process.cwd();
2466
+ let discoveryCwd = originalCwd;
2467
+ if (argv[1] === 'validate') {
2468
+ const valueOptions = new Set(['--workspace-root', '--claude-skill-profile', '--version-base']);
3067
2469
  for (let index = 0; index < authoringArgs.length; index += 1) {
3068
2470
  const token = authoringArgs[index];
3069
- if (token.startsWith('--workspace-root='))
3070
- explicitRoot = token.slice('--workspace-root='.length);
3071
- if (token === '--workspace-root')
3072
- explicitRoot = authoringArgs[index + 1];
3073
- }
3074
- const originalCwd = options.cwd ?? process.cwd();
3075
- let discoveryCwd = originalCwd;
3076
- if (argv[1] === 'validate') {
3077
- const valueOptions = new Set(['--workspace-root', '--claude-skill-profile', '--version-base']);
3078
- for (let index = 0; index < authoringArgs.length; index += 1) {
3079
- const token = authoringArgs[index];
3080
- if (valueOptions.has(token)) {
3081
- index += 1;
3082
- continue;
3083
- }
3084
- if (!token.startsWith('-')) {
3085
- discoveryCwd = path.resolve(originalCwd, token);
3086
- authoringArgs[index] = discoveryCwd;
3087
- break;
3088
- }
2471
+ if (valueOptions.has(token)) {
2472
+ index += 1;
2473
+ continue;
2474
+ }
2475
+ if (!token.startsWith('-')) {
2476
+ discoveryCwd = path.resolve(originalCwd, token);
2477
+ authoringArgs[index] = discoveryCwd;
2478
+ break;
3089
2479
  }
3090
2480
  }
3091
- const workspace = await resolveCatalogWorkspaceRoot({
3092
- cwd: discoveryCwd,
3093
- ...(explicitRoot === undefined ? {} : { explicitRoot: path.resolve(options.cwd ?? process.cwd(), explicitRoot) }),
3094
- mode: 'existing',
3095
- });
3096
- authoringEnv = {
3097
- ...authoringEnv,
3098
- AW_AUTHORING_WORKSPACE_ROOT: workspace.workspaceRoot,
3099
- AW_AUTHORING_WORKSPACE_ROOT_RESOLVED_FROM: workspace.workspaceRootResolvedFrom,
3100
- };
3101
- if (explicitRoot === undefined)
3102
- authoringArgs.push('--workspace-root', workspace.workspaceRoot);
3103
2481
  }
3104
- return runAuthoringScript({
3105
- scriptName: authoringScript,
3106
- args: authoringArgs,
3107
- cwd: options.cwd ?? process.cwd(),
3108
- env: authoringEnv,
3109
- io,
2482
+ const workspace = await resolveCatalogWorkspaceRoot({
2483
+ cwd: discoveryCwd,
2484
+ ...(explicitRoot === undefined ? {} : { explicitRoot: path.resolve(options.cwd ?? process.cwd(), explicitRoot) }),
2485
+ mode: 'existing',
3110
2486
  });
2487
+ authoringEnv = {
2488
+ ...authoringEnv,
2489
+ AW_AUTHORING_WORKSPACE_ROOT: workspace.workspaceRoot,
2490
+ AW_AUTHORING_WORKSPACE_ROOT_RESOLVED_FROM: workspace.workspaceRootResolvedFrom,
2491
+ };
2492
+ if (explicitRoot === undefined)
2493
+ authoringArgs.push('--workspace-root', workspace.workspaceRoot);
2494
+ }
2495
+ return runAuthoringScript({
2496
+ scriptName: authoringScript,
2497
+ args: authoringArgs,
2498
+ cwd: options.cwd ?? process.cwd(),
2499
+ env: authoringEnv,
2500
+ io,
2501
+ interruption: options.interruption,
2502
+ });
2503
+ }
2504
+ throw new Error('No authoring script is registered for this operation.');
2505
+ }
2506
+ function sourceConfirmation(sourceId, yes, preview) {
2507
+ const required = preview !== undefined && (preview.identityChanged || !preview.references.inventoryComplete || preview.references.references.length > 0);
2508
+ const message = preview?.identityChanged ? describeSourceCommandRebinding(sourceId)
2509
+ : 'Change the source used by the affected or unobserved plugin references.';
2510
+ return { required, provided: yes === true, effects: required ? [{ code: 'changeSource', message, subject: { sourceId }, impact: preview?.references.inventoryComplete ? 'shared' : 'unknown' }] : [] };
2511
+ }
2512
+ function commandId(command) {
2513
+ const names = [];
2514
+ for (let current = command; current?.parent; current = current.parent)
2515
+ names.unshift(current.name());
2516
+ return names.join('.');
2517
+ }
2518
+ function configurePublicCommands(program, options, io, exit) {
2519
+ const find = (parent, name) => {
2520
+ const result = parent.commands.find((entry) => entry.name() === name);
2521
+ if (!result)
2522
+ throw new Error(`Missing registered command: ${name}`);
2523
+ return result;
2524
+ };
2525
+ const plugin = find(program, 'plugin');
2526
+ const dev = find(program, 'dev');
2527
+ const devPlugin = find(dev, 'plugin');
2528
+ const catalog = find(dev, 'catalog');
2529
+ const source = find(program, 'source');
2530
+ const sourceUpdate = find(source, 'update');
2531
+ sourceUpdate.option('--primary', 'Make this source primary');
2532
+ const sourceStatus = find(source, 'status');
2533
+ sourceStatus.option('--remote', 'Check remote candidates without changing stored state');
2534
+ sourceStatus.action(async (id, raw) => {
2535
+ const env = options.env ?? process.env;
2536
+ const [observed, configured] = await Promise.all([catalogSourceStatusCommand({ sourceId: id, env }), listCatalogSources({ env })]);
2537
+ const result = { ...observed, primarySourceId: configured.primarySourceId, sources: observed.sources.map((source) => ({ ...source, configuration: configured.sources.find((entry) => entry.id === source.sourceId) ?? null })) };
2538
+ if (!raw.remote) {
2539
+ io.result?.(result);
2540
+ return;
3111
2541
  }
3112
- if (!jsonConfigMutation
3113
- && argv.some((token) => token === '--subdir' || token.startsWith('--subdir='))
3114
- && argv.includes('--no-subdir')) {
3115
- const message = 'option --subdir cannot be used with option --no-subdir';
3116
- if (argv.includes('--json') && argv[0] === 'catalog' && argv[1] === 'source' && argv[2] === 'update') {
3117
- writeJsonReceipt(io.stdout, {
3118
- receiptSchemaVersion: 5,
3119
- command: 'catalog:source:update',
3120
- ok: false,
3121
- changed: false,
3122
- sourceId: argv[3] ?? '',
3123
- references: [],
3124
- errors: [{ code: 'catalogSourceOptionConflict', message }],
3125
- });
3126
- }
3127
- writeLine(io.stderr, `error: ${message}`);
3128
- return 1;
3129
- }
3130
- if (argv[0] === 'catalog' && argv[1] === 'source' && argv[2] === 'update'
3131
- && argv.includes('--auto-check') && argv.includes('--no-auto-check')) {
3132
- const message = 'option --auto-check cannot be used with option --no-auto-check';
3133
- if (argv.includes('--json') || argv.includes('-j')) {
3134
- writeJsonReceipt(io.stdout, {
3135
- receiptSchemaVersion: 5,
3136
- command: 'catalog:source:update',
3137
- ok: false,
3138
- changed: false,
3139
- sourceId: argv[3] ?? '',
3140
- references: [],
3141
- errors: [{ code: 'catalogSourceOptionConflict', message }],
3142
- });
2542
+ const remote = await Promise.all(result.sources.map(async (source) => {
2543
+ try {
2544
+ const probe = await syncCatalogSourceCommand({ sourceId: source.sourceId, cliVersion: resolveCliVersion(), cwd: options.cwd, check: true, env });
2545
+ return { sourceId: source.sourceId, checked: true, candidate: probe.resolution, outcome: probe.outcome };
3143
2546
  }
3144
- writeLine(io.stderr, `error: ${message}`);
3145
- return 1;
3146
- }
3147
- const bareConsoleOptions = parseBareConsoleOptions(argv);
3148
- if (bareConsoleOptions) {
3149
- const context = createCliExecutionContext({
3150
- ...options,
3151
- io,
3152
- env: options.env ?? process.env,
3153
- diagnostics: {
3154
- ...toCliDiagnosticsOptions('console', bareConsoleOptions, options.diagnostics),
3155
- metadata: {
3156
- ...options.diagnostics?.metadata,
3157
- argCount: argv.length,
3158
- },
3159
- },
3160
- });
3161
- if (!context.interactive) {
3162
- writeLine(io.stderr, formatInteractiveConsoleUnavailableMessage(context));
3163
- return 1;
2547
+ catch (error) {
2548
+ const safe = sanitizeCatalogSourceError(error, env);
2549
+ return { sourceId: source.sourceId, checked: false, error: { code: catalogGenerationErrorCode(error), message: safe.message } };
3164
2550
  }
3165
- return await runActionWithContext(context, () => runConsoleController(context));
3166
- }
3167
- let catalogPublicationActionStarted = false;
3168
- let configMutationActionStarted = false;
3169
- const programIo = jsonCatalogDevCommand || jsonWriteRequest
3170
- ? { ...io, stderr: () => undefined }
3171
- : jsonConfigMutation
3172
- ? {
3173
- ...io,
3174
- stderr: (text) => {
3175
- if (configMutationActionStarted)
3176
- io.stderr(text);
3177
- },
3178
- }
3179
- : jsonAuthoringCommand === 'catalog:publish'
3180
- ? {
3181
- ...io,
3182
- stderr: (text) => {
3183
- if (catalogPublicationActionStarted)
3184
- io.stderr(text);
3185
- },
3186
- }
3187
- : io;
3188
- const program = buildProgram({
3189
- ...options,
3190
- io: programIo,
3191
- diagnostics: {
3192
- ...options.diagnostics,
3193
- metadata: {
3194
- ...options.diagnostics?.metadata,
3195
- argCount: argv.length,
3196
- },
3197
- },
2551
+ }));
2552
+ const failures = remote.filter((entry) => !entry.checked);
2553
+ const projected = projectReceipt('source.status', { ...result, remote, complete: failures.length === 0 });
2554
+ projected.diagnostics.push(...failures.map((entry) => ({ code: entry.error.code, severity: 'error', message: safePublicMessage(entry.error.message), subject: { sourceId: entry.sourceId } })));
2555
+ io.result?.(projected);
2556
+ });
2557
+ const context = (name, raw = {}) => createCliExecutionContext({ ...options, io, interactive: false, reporter: options.reporter ?? createNoopReporter(), diagnostics: toCliDiagnosticsOptions(name, raw, options.diagnostics) });
2558
+ for (const name of ['install', 'remove', 'sync']) {
2559
+ const cmd = plugin.command(name).argument(name === 'sync' ? '[plugins...]' : '<plugins...>');
2560
+ if (name !== 'sync')
2561
+ cmd.addOption(strictValueOption('--scope <scope>', 'Requirement or physical scope', ['user', 'project']).makeOptionMandatory());
2562
+ cmd.addOption(strictValueOption('--context <context>', 'User or current project context', ['user', 'project']))
2563
+ .option('--target <target>', 'Select an execution target', collectUniqueOption)
2564
+ .option('-y, --yes', 'Confirm the listed effects');
2565
+ if (name !== 'sync')
2566
+ cmd.addOption(strictValueOption('--only <mode>', 'Limit the effects', name === 'install' ? ['requirements'] : ['requirements', 'outputs']));
2567
+ if (name === 'remove')
2568
+ cmd.description('Remove requirements and owned output, including orphan dependencies')
2569
+ .option('--delete-config', 'Delete all local plugin configuration')
2570
+ .option('--keep-dependencies', 'Keep orphan dependency output during normal removal')
2571
+ .option('--force', 'Bypass the dependency guard; with --only outputs, recover provably owned damaged output');
2572
+ if (name !== 'remove')
2573
+ cmd.option('--script-timeout <ms>', 'Plugin script timeout');
2574
+ if (name === 'sync')
2575
+ cmd.option('--rebuild', 'Rebuild selected owned output').option('--refresh', 'Refresh required Catalog sources');
2576
+ cmd.action(async (plugins, raw) => {
2577
+ io.result?.(await runPublicLifecycle(name, plugins, { ...raw, cwd: options.cwd ?? process.cwd(), env: options.env, cliVersion: resolveCliVersion() }, context(`plugin.${name}`, raw)));
3198
2578
  });
3199
- if (jsonAuthoringCommand === 'catalog:publish') {
3200
- program.hook('preAction', () => {
3201
- catalogPublicationActionStarted = true;
3202
- });
2579
+ }
2580
+ plugin.command('list').description('List available plugins or direct requirements')
2581
+ .option('--requested', 'List direct requirement roots')
2582
+ .addOption(strictValueOption('--scope <scope>', 'Requirement scope', ['user', 'project']))
2583
+ .action(async (raw) => { io.result?.(await runPublicPluginList({ ...raw, cwd: options.cwd ?? process.cwd(), env: options.env, cliVersion: resolveCliVersion() }, context('plugin.list', raw))); });
2584
+ plugin.command('show').description('Show one plugin').argument('<plugin>')
2585
+ .action(async (selector) => { io.result?.(await runPublicPluginShow(selector, { cwd: options.cwd ?? process.cwd(), env: options.env, cliVersion: resolveCliVersion() }, context('plugin.show'))); });
2586
+ plugin.command('status').description('Inspect requirements, outputs, and coverage').argument('[plugins...]')
2587
+ .addOption(strictValueOption('--context <context>', 'Observation context', ['user', 'project']))
2588
+ .option('--observe-native', 'Start OpenCode when selected to observe plugin loading')
2589
+ .action(async (plugins, raw) => { io.result?.(await runPublicPluginStatus(plugins, { ...raw, cwd: options.cwd ?? process.cwd(), env: options.env, cliVersion: resolveCliVersion() }, context('plugin.status', raw))); });
2590
+ devPlugin.command('remove').description('Delete one owned plugin source tree').argument('<plugin>')
2591
+ .option('--workspace-root <path>', 'Catalog Workspace root').option('-y, --yes', 'Confirm source deletion');
2592
+ devPlugin.command('status').description('Check source plugin version policy').argument('[plugin]')
2593
+ .option('--all', 'Check all source plugins').option('--base <ref>', 'Git comparison base').option('--workspace-root <path>', 'Catalog Workspace root');
2594
+ find(devPlugin, 'build').option('-y, --yes', 'Confirm replacement of generated output');
2595
+ find(catalog, 'build').option('-y, --yes', 'Confirm replacement of generated output');
2596
+ const scriptRoutes = {
2597
+ 'dev.plugin.create': ['plugin', 'init'], 'dev.plugin.validate': ['plugin', 'validate'],
2598
+ 'dev.plugin.remove': ['plugin', 'remove'], 'dev.plugin.status': ['plugin', 'status'],
2599
+ 'dev.skill.create': ['plugin', 'add-skill'], 'dev.skill.validate': ['skill', 'validate'],
2600
+ };
2601
+ const attach = (parent) => {
2602
+ for (const cmd of parent.commands) {
2603
+ const id = commandId(cmd);
2604
+ if (scriptRoutes[id])
2605
+ cmd.action(async (...args) => {
2606
+ const selected = args.at(-1);
2607
+ const raw = selected.opts();
2608
+ const tokens = [...scriptRoutes[id], ...(id === 'dev.skill.create' ? [String(raw.plugin)] : selected.args)];
2609
+ for (const option of selected.options) {
2610
+ const value = selected.getOptionValue(option.attributeName());
2611
+ if (['json', 'plugin', 'verbose', 'debug', 'logFile'].includes(option.attributeName()) || value === undefined || value === false && !option.negate || value === true && option.negate)
2612
+ continue;
2613
+ tokens.push(option.long);
2614
+ if (value !== true && !option.negate)
2615
+ tokens.push(String(value));
2616
+ }
2617
+ const hasProtocol = !['dev.plugin.create', 'dev.skill.create'].includes(id);
2618
+ if (hasProtocol)
2619
+ tokens.push('--json');
2620
+ if (['dev.plugin.remove', 'dev.plugin.status'].includes(id) && !raw.workspaceRoot) {
2621
+ const workspace = await resolveCatalogWorkspaceRoot({ cwd: options.cwd ?? process.cwd(), mode: 'existing', env: options.env });
2622
+ tokens.push('--workspace-root', workspace.workspaceRoot);
2623
+ }
2624
+ let protocol = '';
2625
+ let scriptDiagnostics = '';
2626
+ exit.exitCode = await runAuthoringCliAdapter(tokens, { ...options, interactive: false, io: { stdout: (text) => { if (hasProtocol)
2627
+ protocol += text;
2628
+ else
2629
+ io.stderr(text); }, stderr: (text) => { scriptDiagnostics += text; io.stderr(text); } } });
2630
+ if (hasProtocol && protocol.trim()) {
2631
+ let value;
2632
+ try {
2633
+ value = JSON.parse(protocol);
2634
+ }
2635
+ catch {
2636
+ throw new Error('The authoring tool returned invalid structured output.');
2637
+ }
2638
+ io.result?.(value);
2639
+ }
2640
+ else
2641
+ io.result?.({ ok: exit.exitCode === 0, pluginName: raw.plugin ?? selected.args[0], workspaceRoot: raw.workspaceRoot ?? options.cwd, ...(exit.exitCode ? { errors: [{ code: 'authoringFailed', message: scriptDiagnostics.trim() || 'The authoring tool did not complete.' }] } : {}) });
2642
+ });
2643
+ if (!cmd.options.some((option) => option.long === '--json'))
2644
+ cmd.option('-j, --json', 'Output one JSON result');
2645
+ const json = cmd.options.find((option) => option.long === '--json');
2646
+ json.makeOptionMandatory(false);
2647
+ if (!json.short)
2648
+ json.short = '-j';
2649
+ if (!cmd.options.some((option) => option.long === '--verbose'))
2650
+ cmd.option('-v, --verbose', 'Show additional details');
2651
+ if (!cmd.options.some((option) => option.long === '--debug'))
2652
+ cmd.option('-D, --debug', 'Write diagnostic logs');
2653
+ if (!cmd.options.some((option) => option.long === '--log-file'))
2654
+ cmd.option('--log-file <path>', 'Diagnostic log path');
2655
+ attach(cmd);
3203
2656
  }
3204
- if (jsonConfigMutation) {
3205
- program.hook('preAction', () => {
3206
- configMutationActionStarted = true;
3207
- });
2657
+ };
2658
+ program.option('-j, --json', 'Output one JSON result').option('-v, --verbose', 'Show additional details').option('-D, --debug', 'Write diagnostic logs').option('--log-file <path>', 'Diagnostic log path');
2659
+ program.command('tui').description('Open the interactive console').action(() => undefined);
2660
+ attach(program);
2661
+ program.hook('preAction', (_root, action) => { action.setOptionValue('json', true); });
2662
+ }
2663
+ function resolveRegisteredCommand(program, argv) {
2664
+ let current = program;
2665
+ let commandIndex = -1;
2666
+ for (let index = 0; index < argv.length; index++) {
2667
+ const token = argv[index];
2668
+ if (token === '--')
2669
+ break;
2670
+ if (token.startsWith('-')) {
2671
+ const option = [...current.options, ...program.options].find((candidate) => candidate.long === token.split('=')[0] || candidate.short === token);
2672
+ if (option?.required && !token.includes('='))
2673
+ index++;
2674
+ continue;
3208
2675
  }
3209
- await program.parseAsync(['node', 'aw', ...argv]);
3210
- return program.__awCommandExitState?.exitCode ?? 0;
2676
+ const child = current.commands.find((entry) => entry.name() === token);
2677
+ if (child) {
2678
+ current = child;
2679
+ commandIndex = index;
2680
+ }
2681
+ else if (current.commands.length === 0 || current.registeredArguments.length > 0)
2682
+ break;
2683
+ else
2684
+ return { command: null, index: commandIndex };
3211
2685
  }
3212
- catch (error) {
3213
- if (jsonCatalogDevCommand) {
3214
- const workspaceRootIndex = argv.findIndex((token) => token === '--workspace-root');
3215
- const workspaceRootOption = argv.find((token) => token.startsWith('--workspace-root='));
3216
- const workspaceRoot = workspaceRootOption?.slice('--workspace-root='.length)
3217
- ?? (workspaceRootIndex >= 0 ? argv[workspaceRootIndex + 1] : undefined);
3218
- const sourceIdIndex = argv.findIndex((token) => token === '--source-id');
3219
- const sourceIdOption = argv.find((token) => token.startsWith('--source-id='));
3220
- const sourceId = sourceIdOption?.slice('--source-id='.length)
3221
- ?? (sourceIdIndex >= 0 ? argv[sourceIdIndex + 1] : undefined);
3222
- const failure = error instanceof CommanderError
3223
- ? { code: 'invalidArguments', message: error.message }
3224
- : catalogDevSourceError(error);
3225
- writeJsonReceipt(io.stdout, createCatalogDevFailureReceipt({
3226
- command: jsonCatalogDevCommand,
3227
- cwd: options.cwd ?? process.cwd(),
3228
- workspaceRoot,
3229
- sourceId,
3230
- ...failure,
3231
- }));
3232
- return 1;
3233
- }
3234
- if (jsonWriteRequest) {
3235
- writeCommandFailureReceipt(io.stdout, jsonWriteRequest, error);
3236
- return 1;
3237
- }
3238
- if (jsonConfigMutation) {
3239
- if (error instanceof CommanderError && error.exitCode === 0)
3240
- return 0;
3241
- const failure = configMutationFailure(error, options.env ?? process.env, options.cwd ?? process.cwd());
3242
- writeConfigMutationFailureReceipt(io.stdout, error instanceof CommanderError
3243
- ? { command: jsonConfigMutation.command }
3244
- : jsonConfigMutation, failure);
3245
- writeLine(io.stderr, failure.message);
3246
- return 1;
2686
+ return { command: current, index: commandIndex };
2687
+ }
2688
+ function helpResult(program, selected) {
2689
+ return commandResult('help', {
2690
+ command: commandId(selected) || 'aw', description: selected.description(),
2691
+ arguments: selected.registeredArguments.map((argument) => ({ name: argument.name(), required: argument.required, variadic: argument.variadic, description: argument.description })),
2692
+ options: [...selected.options, ...(selected === program ? [] : program.options)].map((option) => ({ flags: option.flags, description: option.description, required: option.mandatory, choices: option.argChoices ?? null, conflicts: [] })),
2693
+ commands: selected.commands.map((command) => ({ command: commandId(command), description: command.description() })),
2694
+ resultSchema: { schemaVersion: CLI_OUTPUT_SCHEMA_VERSION, statuses: ['success', 'partial', 'blocked', 'failed'] },
2695
+ rules: commandId(selected) === 'plugin.install' ? ['--scope is required.', '--only requirements cannot use --target or --script-timeout.'] : commandId(selected) === 'plugin.remove' ? ['--scope is required.', '--only outputs requires --target.', '--force cannot use --only requirements.', '--keep-dependencies cannot use --only.', '--delete-config cannot use --only.'] : [],
2696
+ effects: selected.options.some((option) => option.long === '--yes') ? ['Important effects require --yes.'] : [],
2697
+ examples: [selected === program ? ['aw', 'plugin', 'list'] : ['aw', ...commandId(selected).split('.'), '--help']],
2698
+ });
2699
+ }
2700
+ function scanPresentation(program, argv) {
2701
+ const result = { json: false, help: false, version: false };
2702
+ let command = program;
2703
+ for (let index = 0; index < argv.length; index++) {
2704
+ const token = argv[index];
2705
+ if (token === '--')
2706
+ break;
2707
+ if (!token.startsWith('-')) {
2708
+ command = command.commands.find((entry) => entry.name() === token) ?? command;
2709
+ continue;
3247
2710
  }
3248
- if (jsonAuthoringCommand === 'catalog:publish' && error instanceof CommanderError) {
3249
- const failure = catalogPublicationFailure({
3250
- error: new CatalogPublicationInspectionError('invalidArguments', error.message),
3251
- env: options.env,
3252
- sensitiveRoots: [options.cwd ?? process.cwd()],
3253
- });
3254
- writeJsonReceipt(io.stdout, failure);
3255
- writeLine(io.stderr, failure.message);
3256
- return 1;
2711
+ const available = [...command.options, ...program.options];
2712
+ if (token.startsWith('--')) {
2713
+ const flag = token.split('=')[0];
2714
+ const option = available.find((entry) => entry.long === flag);
2715
+ if (flag === '--json')
2716
+ result.json = true;
2717
+ if (flag === '--help')
2718
+ result.help = true;
2719
+ if (flag === '--version' && !option?.required)
2720
+ result.version = true;
2721
+ if (option?.required && !token.includes('='))
2722
+ index++;
3257
2723
  }
3258
- if (jsonAuthoringCommand && !(error instanceof CommanderError)) {
3259
- const message = error instanceof Error ? error.message : String(error);
3260
- if (jsonAuthoringCommand === 'plugin:validate') {
3261
- writeJsonReceipt(io.stdout, {
3262
- ok: false,
3263
- profile: 'unknown',
3264
- warnings: [],
3265
- errors: [message],
3266
- });
2724
+ else {
2725
+ for (let offset = 1; offset < token.length; offset++) {
2726
+ const flag = `-${token[offset]}`;
2727
+ const option = available.find((entry) => entry.short === flag);
2728
+ if (flag === '-j')
2729
+ result.json = true;
2730
+ if (flag === '-h')
2731
+ result.help = true;
2732
+ if (flag === '-V')
2733
+ result.version = true;
2734
+ if (option?.required) {
2735
+ if (offset === token.length - 1)
2736
+ index++;
2737
+ break;
2738
+ }
3267
2739
  }
3268
- else if (jsonAuthoringCommand === 'plugin:status') {
3269
- writeJsonReceipt(io.stdout, {
3270
- schemaVersion: 3,
3271
- policy: 'development',
3272
- ok: false,
3273
- base: null,
3274
- requestedBase: null,
3275
- baseCommit: null,
3276
- checkedPlugins: 0,
3277
- checks: [],
3278
- workspaceRoot: null,
3279
- workspaceRootResolvedFrom: null,
3280
- errors: [{ code: 'workspaceResolutionFailed', message }],
3281
- });
2740
+ }
2741
+ }
2742
+ return result;
2743
+ }
2744
+ export async function runCli(argv, options = {}) {
2745
+ const interruption = createPublicCommandInterruption();
2746
+ const io = { ...createDefaultIo(), ...options.io };
2747
+ if (argv[0] === 'internal' && argv[1] === 'cursor-workspace-open') {
2748
+ return runCursorWorkspaceHookCli(argv.slice(2), { cwd: options.cwd ?? process.cwd(), env: options.env,
2749
+ stdin: options.stdin ?? process.stdin, stdout: io.stdout, stderr: io.stderr });
2750
+ }
2751
+ const delimiter = argv.indexOf('--');
2752
+ const awArgs = delimiter < 0 ? argv : argv.slice(0, delimiter);
2753
+ const context = createCliExecutionContext({ ...options, io });
2754
+ let receipt;
2755
+ const stderr = [];
2756
+ const commandOptions = { ...options, interactive: false, io: {
2757
+ stdout: (text) => { stderr.push(text); }, stderr: (text) => { stderr.push(text); }, result: (value) => { receipt = value; },
2758
+ } };
2759
+ const program = buildProgram(commandOptions);
2760
+ const presentation = scanPresentation(program, awArgs);
2761
+ const json = presentation.json;
2762
+ const resolvedCommand = resolveRegisteredCommand(program, awArgs);
2763
+ const selected = resolvedCommand.command;
2764
+ const id = selected && selected !== program ? commandId(selected) : null;
2765
+ const controlledInterrupt = ['plugin.install', 'plugin.remove', 'plugin.sync', 'plugin.config.apply', 'plugin.config.suggestions',
2766
+ 'dev.plugin.create', 'dev.plugin.validate', 'dev.plugin.remove', 'dev.plugin.status',
2767
+ 'dev.skill.create', 'dev.skill.validate'].includes(id ?? '');
2768
+ if (controlledInterrupt) {
2769
+ commandOptions.interruption = interruption;
2770
+ commandOptions.signal = (id === 'plugin.config.apply' || id === 'plugin.config.suggestions') && options.signal
2771
+ ? AbortSignal.any([options.signal, interruption.signal]) : interruption.signal;
2772
+ }
2773
+ if (id === 'command.run' && !awArgs.some((arg) => arg === '--help' || arg === '-h')) {
2774
+ const prefix = argv.slice(0, resolvedCommand.index).filter((arg) => arg !== 'command');
2775
+ return runManagedCommandCli(['run', ...prefix, ...argv.slice(resolvedCommand.index + 1)], { ...context, interactive: false }, { cliEntry: fileURLToPath(import.meta.url), cliVersion: resolveCliVersion() });
2776
+ }
2777
+ let confirmation = null;
2778
+ const emit = (result, invalid = false) => {
2779
+ if (result.diagnostics.some((diagnostic) => diagnostic.code === 'catalogWorkspaceMissing')) {
2780
+ const workspaceRoot = selected?.getOptionValue('workspaceRoot');
2781
+ result.nextActions = result.nextActions.filter((action) => action.kind !== 'command'
2782
+ || action.argv.slice(0, 4).join(' ') !== 'aw dev catalog create');
2783
+ result.nextActions.push({ kind: 'command',
2784
+ argv: ['aw', 'dev', 'catalog', 'create', ...(typeof workspaceRoot === 'string' ? ['--workspace-root', workspaceRoot] : [])],
2785
+ reason: 'Create a Catalog Workspace explicitly before running authoring commands.', requiresConfirmation: false });
2786
+ }
2787
+ interruption.cleanupFailed ||= result.diagnostics.some((entry) => entry.code === 'processCleanupUnconfirmed');
2788
+ if (interruption.exitCode || interruption.cleanupFailed) {
2789
+ const code = interruption.cleanupFailed ? 'processCleanupUnconfirmed' : 'operationInterrupted';
2790
+ if (!result.diagnostics.some((entry) => entry.code === code && !entry.subject)) {
2791
+ result.diagnostics.push({ code, severity: 'error', message: interruption.cleanupFailed
2792
+ ? 'Process cleanup could not be confirmed.'
2793
+ : 'The command was interrupted. Completed changes are retained in the result.' });
3282
2794
  }
3283
- else if (jsonAuthoringCommand === 'plugin:remove') {
3284
- writeJsonReceipt(io.stdout, {
3285
- schemaVersion: 1,
3286
- command: 'plugin:remove',
3287
- ok: false,
3288
- workspaceRoot: null,
3289
- workspaceRootResolvedFrom: null,
3290
- baseCommit: null,
3291
- plugin: null,
3292
- removed: false,
3293
- errors: [{ code: 'workspaceResolutionFailed', message }],
3294
- });
2795
+ }
2796
+ io.stdout(json ? `${JSON.stringify(result)}\n` : renderPublicResult(result, awArgs.includes('--verbose') || awArgs.includes('-v')));
2797
+ for (const diagnostic of result.diagnostics)
2798
+ if (json || diagnostic.code !== SKILL_INVOCATION_NOTICE)
2799
+ io.stderr(`${diagnostic.code}: ${diagnostic.message}\n`);
2800
+ if (options.diagnostics?.verbose || awArgs.includes('--verbose'))
2801
+ for (const line of stderr)
2802
+ io.stderr(`${safePublicMessage(line.trim())}\n`);
2803
+ return interruption.cleanupFailed ? 1 : interruption.exitCode ?? publicExitCode(result, invalid);
2804
+ };
2805
+ if (presentation.version)
2806
+ return emit(commandResult('version', { version: resolveCliVersion(), resultSchemaVersion: CLI_OUTPUT_SCHEMA_VERSION }));
2807
+ if (selected && presentation.help || argv.length === 0 && !context.interactive || selected === program && json) {
2808
+ const target = selected ?? program;
2809
+ if (!json) {
2810
+ target.configureOutput({ writeOut: io.stdout });
2811
+ target.outputHelp();
2812
+ return 0;
2813
+ }
2814
+ return emit(helpResult(program, target));
2815
+ }
2816
+ let bareOptions;
2817
+ try {
2818
+ bareOptions = parseBareConsoleOptions(argv);
2819
+ }
2820
+ catch {
2821
+ return emit(commandResult(null, {}, { status: 'failed', diagnostics: [{ code: 'invalidArguments', severity: 'error', message: 'A diagnostic option requires a value.' }] }), true);
2822
+ }
2823
+ if (bareOptions !== null || id === 'tui') {
2824
+ if (id === 'tui') {
2825
+ try {
2826
+ await program.parseAsync(['node', 'aw', ...argv]);
3295
2827
  }
3296
- else {
3297
- writeJsonReceipt(io.stdout, {
3298
- command: jsonAuthoringCommand,
3299
- ok: false,
3300
- errors: [{ code: 'workspaceResolutionFailed', message }],
3301
- });
2828
+ catch {
2829
+ return emit(commandResult('tui', {}, { status: 'failed', diagnostics: [{ code: 'invalidArguments', severity: 'error', message: 'Invalid TUI arguments.' }] }), true);
3302
2830
  }
3303
- return 1;
3304
2831
  }
3305
- if (jsonAuthoringCommand && error instanceof CommanderError) {
3306
- writeJsonReceipt(io.stdout, {
3307
- command: jsonAuthoringCommand,
3308
- ok: false,
3309
- errors: [{ code: 'invalidArguments', message: error.message }],
2832
+ if (json)
2833
+ return emit(commandResult('tui', {}, { status: 'failed', diagnostics: [{ code: 'invalidOptionCombination', severity: 'error', message: 'tui cannot use --json.' }] }), true);
2834
+ if (!context.interactive)
2835
+ return emit(commandResult('tui', {}, { status: 'blocked', diagnostics: [{ code: 'interactiveTerminalRequired', severity: 'error', message: 'The TUI requires an interactive terminal.' }] }));
2836
+ const tuiContext = createCliExecutionContext({ ...options, io, interruption,
2837
+ signal: options.signal ? AbortSignal.any([options.signal, interruption.signal]) : interruption.signal, diagnostics: toCliDiagnosticsOptions('console', bareOptions ?? {}, options.diagnostics) });
2838
+ const stopListening = interruption.listen();
2839
+ try {
2840
+ return await runActionWithContext(tuiContext, async () => {
2841
+ const { runConsoleController } = await import('./commands/console.js');
2842
+ const code = await runConsoleController(tuiContext);
2843
+ if (interruption.cleanupFailed) {
2844
+ io.stderr('processCleanupUnconfirmed: Process cleanup could not be confirmed.\n');
2845
+ return 1;
2846
+ }
2847
+ return interruption.exitCode ?? code;
3310
2848
  });
3311
2849
  }
3312
- return handleCliError(error, io.stderr);
2850
+ catch (error) {
2851
+ return emit(commandResult('tui', {}, { status: 'failed', diagnostics: [{ code: 'tuiFailed', severity: 'error', message: safePublicMessage(error instanceof Error ? error.message : String(error)) }] }));
2852
+ }
2853
+ finally {
2854
+ stopListening();
2855
+ }
2856
+ }
2857
+ // Only these adapters carry cancellation through every long-running child.
2858
+ // Other routes retain Node's normal signal termination until their domain
2859
+ // runner provides the same cleanup contract. Managed run and TUI exited above.
2860
+ const stopListening = controlledInterrupt ? interruption.listen() : () => undefined;
2861
+ try {
2862
+ program.hook('preAction', (_root, command) => {
2863
+ interruption.signal.throwIfAborted();
2864
+ const raw = command.opts();
2865
+ const current = commandId(command);
2866
+ if (current === 'dev.eval.prepare')
2867
+ for (const field of ['runs', 'timeoutMs'])
2868
+ if (raw[field] !== undefined && (!/^[1-9][0-9]*$/u.test(raw[field]) || !Number.isSafeInteger(Number(raw[field]))))
2869
+ throw new WriteCommandRequestError(`${field} must be a positive safe integer.`);
2870
+ if (current === 'dev.plugin.capabilities' && raw.surface !== undefined)
2871
+ normalizeWriteRequest(() => parsePluginCapabilitySurface(raw.surface));
2872
+ if (current === 'dev.catalog.version') {
2873
+ const version = command.args[0];
2874
+ if (version && raw.bump)
2875
+ throw new WriteCommandRequestError('Choose an exact version or --bump, not both.');
2876
+ if (raw.bump && !['patch', 'minor', 'major'].includes(raw.bump))
2877
+ throw new WriteCommandRequestError('--bump must be patch, minor, or major.');
2878
+ if (version && !/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-beta\.(0|[1-9][0-9]*))?$/u.test(version))
2879
+ throw new WriteCommandRequestError('Use a stable version or x.y.z-beta.N.');
2880
+ }
2881
+ if (current === 'source.add' && ((raw.git === undefined) === (raw.path === undefined)))
2882
+ throw new WriteCommandRequestError('Choose exactly one of --git or --path.');
2883
+ if (current === 'source.update' && awArgs.includes('--auto-check') && awArgs.includes('--no-auto-check'))
2884
+ throw new WriteCommandRequestError('--auto-check cannot use --no-auto-check.');
2885
+ if (current === 'source.update' && raw.subdir !== undefined && awArgs.includes('--no-subdir') && awArgs.some((arg) => arg === '--subdir' || arg.startsWith('--subdir=')))
2886
+ throw new WriteCommandRequestError('--subdir cannot use --no-subdir.');
2887
+ if (current === 'plugin.config.set' && [raw.valueJson !== undefined, raw.valueStdin === true, raw.preset !== undefined].filter(Boolean).length !== 1)
2888
+ throw new WriteCommandRequestError('Choose exactly one of --value-json, --value-stdin, or --preset.');
2889
+ let effect;
2890
+ if (current === 'plugin.config.reset')
2891
+ effect = { code: 'deletePluginConfig', message: 'Delete the selected local plugin configuration.', subject: { pluginId: command.args[0], scope: 'user' }, impact: 'user-wide' };
2892
+ if (current === 'dev.plugin.remove')
2893
+ effect = { code: 'deletePluginSource', message: 'Delete the selected plugin source tree.', subject: { pluginId: command.args[0] }, impact: 'selected-scope' };
2894
+ if (current === 'dev.catalog.publish.apply' && !/^sha256:[0-9a-f]{64}$/u.test(raw.expectedPlanDigest ?? ''))
2895
+ throw new WriteCommandRequestError('Use the exact --expected-plan-digest returned by dev catalog publish plan.');
2896
+ if (current === 'dev.catalog.publish.apply')
2897
+ effect = { code: 'publishRemote', message: 'Publish the prepared Catalog to the remote.', impact: 'shared' };
2898
+ if ((current === 'dev.catalog.build' || current === 'dev.plugin.build') && raw.force)
2899
+ effect = { code: 'removeOwnedOutput', message: 'Replace existing generated output.', impact: 'selected-scope' };
2900
+ if (effect) {
2901
+ confirmation = { required: true, provided: raw.yes === true, effects: [effect] };
2902
+ if (!raw.yes)
2903
+ throw Object.assign(new Error('Repeat the command with --yes to confirm the listed effects.'), { code: 'confirmationRequired' });
2904
+ }
2905
+ });
2906
+ await program.parseAsync(['node', 'aw', ...argv]);
2907
+ const exitCode = program.__awCommandExitState.exitCode;
2908
+ if (receipt === undefined) {
2909
+ if (selected?.commands.length)
2910
+ return emit(helpResult(program, selected));
2911
+ throw new Error('The command did not return a result.');
2912
+ }
2913
+ if (id === 'dev.plugin.test' && receipt && typeof receipt === 'object') {
2914
+ const logs = receipt;
2915
+ if (typeof logs.stdout === 'string')
2916
+ io.stderr(redactString(logs.stdout));
2917
+ if (typeof logs.stderr === 'string')
2918
+ io.stderr(redactString(logs.stderr));
2919
+ }
2920
+ const result = projectReceipt(id, receipt, { yes: awArgs.includes('--yes') || awArgs.includes('-y'), exitCode, confirmation });
2921
+ if (result.status === 'success' && ['dev.plugin.create', 'dev.skill.create'].includes(id)) {
2922
+ const data = result.data;
2923
+ const name = typeof data.pluginName === 'string' ? data.pluginName : selected?.args[0];
2924
+ if (name)
2925
+ for (const action of ['validate', 'test', 'build'])
2926
+ result.nextActions.push({ kind: 'command', argv: ['aw', 'dev', 'plugin', action, `plugins/${name}`], reason: 'Check and build the new source.', requiresConfirmation: false });
2927
+ result.nextActions.push({ kind: 'command', argv: ['aw', 'dev', 'catalog', 'build'], reason: 'Build the Catalog after checking the source.', requiresConfirmation: false });
2928
+ }
2929
+ const invalid = id === 'plugin.config.suggestions' ? exitCode === 2
2930
+ : result.diagnostics.some((diagnostic) => /invalidArguments|invalidOption|missingArgument|sensitiveConfigInputUnsupported/u.test(diagnostic.code));
2931
+ if (invalid && result.status !== 'partial') {
2932
+ result.status = 'failed';
2933
+ result.data = {};
2934
+ }
2935
+ return emit(result, invalid);
2936
+ }
2937
+ catch (error) {
2938
+ if (error instanceof CommanderError && error.exitCode === 0)
2939
+ return emit(helpResult(program, selected ?? program));
2940
+ const argumentError = error instanceof CommanderError || error instanceof WriteCommandRequestError;
2941
+ const raw = id?.startsWith('plugin.config.') && !(error instanceof CommanderError) && !(error instanceof WriteCommandRequestError)
2942
+ ? configMutationFailure(error, options.env ?? process.env, options.cwd ?? process.cwd())
2943
+ : error;
2944
+ const invalidOption = id !== 'plugin.config.suggestions'
2945
+ && (error instanceof InvalidArgumentError || error instanceof CommanderError && error.code === 'commander.invalidArgument');
2946
+ const code = argumentError ? invalidOption ? 'invalidOptionValue' : 'invalidArguments' : raw.code ?? catalogGenerationErrorCode(error);
2947
+ const blocked = code === 'confirmationRequired' || /unavailable|missing|stale|conflict|unsupported|identityMismatch/iu.test(code);
2948
+ let message = raw.message ?? 'The operation failed.';
2949
+ if (error instanceof CommanderError) {
2950
+ const field = raw.message?.match(/--([a-z][a-z-]*)/u)?.[1];
2951
+ if (error.code === 'commander.unknownOption')
2952
+ message = field ? `Unknown option --${field}.` : 'Unknown option.';
2953
+ else if (error.code === 'commander.unknownCommand')
2954
+ message = 'Unknown command.';
2955
+ else if (error.code === 'commander.invalidArgument')
2956
+ message = field ? `Invalid value for --${field}.` : 'Invalid argument value.';
2957
+ else if (error.code === 'commander.excessArguments')
2958
+ message = 'Too many positional arguments.';
2959
+ }
2960
+ const preparedConfirmation = error?.confirmation ?? confirmation;
2961
+ const unknownAuthoringChanges = error?.authoringChanges === 'unknown';
2962
+ const data = { ...(preparedConfirmation ? { confirmation: preparedConfirmation } : {}), ...(unknownAuthoringChanges ? { changes: 'unknown' } : {}) };
2963
+ return emit(commandResult(id, data, { status: unknownAuthoringChanges ? 'partial' : blocked ? 'blocked' : 'failed', diagnostics: [{ code, severity: 'error', message: safePublicMessage(message, code), ...(code === 'invalidOptionValue' ? { subject: { field: raw.message?.match(/--([a-z][a-z-]*)/u)?.[1] ?? 'option' } } : {}) }], nextActions: code === 'confirmationRequired' ? [{ kind: 'manual', message: 'Review the effects and repeat the command with --yes.' }] : [] }), argumentError);
2964
+ }
2965
+ finally {
2966
+ stopListening();
3313
2967
  }
3314
2968
  }
3315
2969
  export async function main(argv = process.argv.slice(2), options = {}) {
3316
2970
  return runCli(argv, options);
3317
2971
  }
3318
- const currentEntryPath = fileURLToPath(import.meta.url);
3319
- const invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : null;
3320
- if (invokedPath === currentEntryPath) {
3321
- void main().then((exitCode) => {
2972
+ export function runExecutableCli() {
2973
+ void withNativeCliInterruption(() => main()).then((exitCode) => {
3322
2974
  if (exitCode !== 0) {
3323
2975
  process.exitCode = exitCode;
3324
2976
  }
3325
2977
  });
3326
2978
  }
2979
+ const currentEntryPath = fileURLToPath(import.meta.url);
2980
+ const invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : null;
2981
+ if (invokedPath === currentEntryPath)
2982
+ runExecutableCli();
3327
2983
  //# sourceMappingURL=index.js.map