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

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