@lesliechan721/aw 0.1.0-beta.9 → 0.1.0-beta.91

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