@lesliechan721/aw 0.1.0-beta.69 → 0.1.0-beta.72

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 (121) hide show
  1. package/dist/authoring/assets/aw-config.mjs +1 -1
  2. package/dist/authoring/assets/aw-config.mjs.map +1 -1
  3. package/dist/authoring/assets/aw-runtime-config.mjs +1 -1
  4. package/dist/authoring/assets/aw-runtime-config.mjs.map +1 -1
  5. package/dist/authoring/scripts/add-skill.mjs +8 -8
  6. package/dist/authoring/scripts/add-skill.mjs.map +1 -1
  7. package/dist/authoring/scripts/init-plugin.mjs +8 -8
  8. package/dist/authoring/scripts/init-plugin.mjs.map +1 -1
  9. package/dist/authoring/scripts/lib/skill-scaffold.mjs +2 -2
  10. package/dist/authoring/scripts/lib/skill-scaffold.mjs.map +1 -1
  11. package/dist/authoring/scripts/validate-plugin.mjs +2 -2
  12. package/dist/authoring/scripts/validate-plugin.mjs.map +1 -1
  13. package/dist/authoring/scripts/validate-skill.mjs +1 -1
  14. package/dist/src/authoring/workspace-commands.d.ts +1 -0
  15. package/dist/src/authoring/workspace-commands.js +4 -1
  16. package/dist/src/authoring/workspace-commands.js.map +1 -1
  17. package/dist/src/commands/aw-capabilities.d.ts +1 -1
  18. package/dist/src/commands/aw-capabilities.js +14 -13
  19. package/dist/src/commands/aw-capabilities.js.map +1 -1
  20. package/dist/src/commands/catalog-dev-source.d.ts +3 -0
  21. package/dist/src/commands/catalog-dev-source.js +78 -8
  22. package/dist/src/commands/catalog-dev-source.js.map +1 -1
  23. package/dist/src/commands/catalog-publish.d.ts +16 -0
  24. package/dist/src/commands/catalog-publish.js +127 -90
  25. package/dist/src/commands/catalog-publish.js.map +1 -1
  26. package/dist/src/commands/catalog-source.d.ts +4 -0
  27. package/dist/src/commands/catalog-source.js +24 -8
  28. package/dist/src/commands/catalog-source.js.map +1 -1
  29. package/dist/src/commands/catalog-status.js +2 -2
  30. package/dist/src/commands/catalog-status.js.map +1 -1
  31. package/dist/src/commands/catalog-workspace-resolution.d.ts +4 -0
  32. package/dist/src/commands/catalog-workspace-resolution.js +18 -3
  33. package/dist/src/commands/catalog-workspace-resolution.js.map +1 -1
  34. package/dist/src/commands/console.js +1 -1
  35. package/dist/src/commands/console.js.map +1 -1
  36. package/dist/src/commands/init.js +1 -1
  37. package/dist/src/commands/init.js.map +1 -1
  38. package/dist/src/commands/intent-command.d.ts +2 -0
  39. package/dist/src/commands/intent-command.js +8 -1
  40. package/dist/src/commands/intent-command.js.map +1 -1
  41. package/dist/src/commands/managed-commands.d.ts +8 -1
  42. package/dist/src/commands/managed-commands.js +52 -8
  43. package/dist/src/commands/managed-commands.js.map +1 -1
  44. package/dist/src/commands/public-config-confirmation.d.ts +8 -0
  45. package/dist/src/commands/public-config-confirmation.js +56 -0
  46. package/dist/src/commands/public-config-confirmation.js.map +1 -0
  47. package/dist/src/commands/public-interruption.d.ts +9 -0
  48. package/dist/src/commands/public-interruption.js +23 -0
  49. package/dist/src/commands/public-interruption.js.map +1 -0
  50. package/dist/src/commands/public-lifecycle-result.d.ts +53 -0
  51. package/dist/src/commands/public-lifecycle-result.js +102 -0
  52. package/dist/src/commands/public-lifecycle-result.js.map +1 -0
  53. package/dist/src/commands/public-lifecycle.d.ts +26 -0
  54. package/dist/src/commands/public-lifecycle.js +469 -0
  55. package/dist/src/commands/public-lifecycle.js.map +1 -0
  56. package/dist/src/commands/public-plugin-query.d.ts +15 -0
  57. package/dist/src/commands/public-plugin-query.js +154 -0
  58. package/dist/src/commands/public-plugin-query.js.map +1 -0
  59. package/dist/src/commands/rebuild-command.js +4 -2
  60. package/dist/src/commands/rebuild-command.js.map +1 -1
  61. package/dist/src/commands/rebuild-integration.d.ts +1 -0
  62. package/dist/src/commands/rebuild-integration.js.map +1 -1
  63. package/dist/src/commands/runtime.d.ts +4 -0
  64. package/dist/src/commands/runtime.js +16 -2
  65. package/dist/src/commands/runtime.js.map +1 -1
  66. package/dist/src/commands/status-v6.js +2 -2
  67. package/dist/src/commands/status-v6.js.map +1 -1
  68. package/dist/src/commands/targets-command.d.ts +2 -0
  69. package/dist/src/commands/targets-command.js +55 -1
  70. package/dist/src/commands/targets-command.js.map +1 -1
  71. package/dist/src/commands/write-commands.js +1 -1
  72. package/dist/src/commands/write-commands.js.map +1 -1
  73. package/dist/src/index.js +664 -761
  74. package/dist/src/index.js.map +1 -1
  75. package/dist/src/intent/diagnostics.js +2 -2
  76. package/dist/src/intent/diagnostics.js.map +1 -1
  77. package/dist/src/output/command-receipt.js +1 -1
  78. package/dist/src/output/command-receipt.js.map +1 -1
  79. package/dist/src/output/public-result.d.ts +43 -0
  80. package/dist/src/output/public-result.js +139 -0
  81. package/dist/src/output/public-result.js.map +1 -0
  82. package/dist/src/output/receipt-projection.d.ts +7 -0
  83. package/dist/src/output/receipt-projection.js +575 -0
  84. package/dist/src/output/receipt-projection.js.map +1 -0
  85. package/dist/src/recovery/coordinator.d.ts +4 -0
  86. package/dist/src/recovery/coordinator.js +7 -7
  87. package/dist/src/recovery/coordinator.js.map +1 -1
  88. package/dist/src/recovery/joint-coordinator.js +19 -6
  89. package/dist/src/recovery/joint-coordinator.js.map +1 -1
  90. package/dist/src/recovery/retirement.d.ts +2 -0
  91. package/dist/src/recovery/retirement.js +9 -8
  92. package/dist/src/recovery/retirement.js.map +1 -1
  93. package/dist/src/review/review-selection.js +4 -1
  94. package/dist/src/review/review-selection.js.map +1 -1
  95. package/dist/src/review/review-types.d.ts +1 -1
  96. package/dist/src/review/review-types.js.map +1 -1
  97. package/dist/src/review/source-binding.js +2 -2
  98. package/dist/src/review/source-binding.js.map +1 -1
  99. package/dist/src/tui/catalog-generation.js +1 -1
  100. package/dist/src/tui/catalog-generation.js.map +1 -1
  101. package/dist/src/tui/model.js +1 -1
  102. package/dist/src/tui/model.js.map +1 -1
  103. package/dist/src/tui/operation-review-planner.js +3 -2
  104. package/dist/src/tui/operation-review-planner.js.map +1 -1
  105. package/dist/src/utils/catalog-generation-resolver.js +3 -3
  106. package/dist/src/utils/catalog-generation-resolver.js.map +1 -1
  107. package/dist/src/utils/catalog-generation-service.d.ts +12 -1
  108. package/dist/src/utils/catalog-generation-service.js +10 -0
  109. package/dist/src/utils/catalog-generation-service.js.map +1 -1
  110. package/dist/src/utils/catalog-generation-state.js +1 -1
  111. package/dist/src/utils/catalog-generation-state.js.map +1 -1
  112. package/dist/src/utils/catalog-generation-store.js +1 -1
  113. package/dist/src/utils/catalog-generation-store.js.map +1 -1
  114. package/dist/src/utils/catalog-operation-context.js +1 -1
  115. package/dist/src/utils/catalog-operation-context.js.map +1 -1
  116. package/dist/src/utils/catalog-sources.js +2 -2
  117. package/dist/src/utils/catalog-sources.js.map +1 -1
  118. package/dist/src/utils/plugin-scripts.d.ts +1 -1
  119. package/dist/src/utils/plugin-scripts.js +29 -7
  120. package/dist/src/utils/plugin-scripts.js.map +1 -1
  121. package/package.json +3 -3
package/dist/src/index.js CHANGED
@@ -1,27 +1,30 @@
1
1
  #!/usr/bin/env node
2
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 { commandResult, publicExitCode, renderPublicResult, safePublicMessage } from './output/public-result.js';
6
+ import { projectReceipt } from './output/receipt-projection.js';
7
+ import { runPublicLifecycle } from './commands/public-lifecycle.js';
8
+ import { runPublicPluginList, runPublicPluginShow, runPublicPluginStatus } from './commands/public-plugin-query.js';
3
9
  import fs from 'node:fs';
4
10
  import path from 'node:path';
5
- import { spawn } from 'node:child_process';
11
+ import { defaultPluginProcessRunner } from './utils/plugin-scripts.js';
6
12
  import { fileURLToPath } from 'node:url';
7
13
  import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';
8
14
  import { doctorEvalProviders } from '@lesliechan721/agent-skill-eval';
9
15
  import { compilePluginConfigDefinition, selectPluginConfigProfile, PLATFORM_TARGETS, PORTABLE_PLATFORM_TARGETS } from '@lesliechan721/aw-plugin-core/manifest';
10
- import { initCommand } from './commands/init.js';
11
- import { resolveCatalogWorkspaceRoot } from './commands/catalog-workspace-resolution.js';
12
- import { addCatalogSourceCommand, preflightCatalogSourceMutation, explicitRefPolicy, listCatalogSources, removeCatalogSourceCommand, setPrimaryCatalogSourceCommand, updateCatalogSourceCommand, } from './commands/catalog-source.js';
16
+ import { CatalogWorkspaceMissingError, resolveCatalogWorkspaceRoot } from './commands/catalog-workspace-resolution.js';
17
+ import { addCatalogSourceCommand, preflightCatalogSourceMutation, explicitRefPolicy, listCatalogSources, removeCatalogSourceCommand, updateCatalogSourceCommand, } from './commands/catalog-source.js';
13
18
  import { catalogSourceStatusCommand, syncCatalogSourceCommand, } from './commands/catalog-generation.js';
14
19
  import { catalogStoreErrorCode, catalogStorePrune, catalogStoreStatus, } from './commands/catalog-store.js';
15
- import { formatInteractiveConsoleUnavailableMessage, runConsoleController, } from './commands/console.js';
20
+ import { runConsoleController, } from './commands/console.js';
16
21
  import { WizardExecutionError, } from './commands/wizard.js';
17
22
  import { createCliExecutionContext, emitCommandEvent, } from './commands/runtime.js';
18
23
  import { parseContextValue, parsePlatformTargetValue, parseScopeValue, resolveScriptTimeoutMs, } from './commands/options.js';
19
- import { isCommandWarningError, } from './types.js';
20
- import { formatWarnings } from './output/reporter.js';
24
+ import { createNoopReporter, formatWarnings } from './output/reporter.js';
21
25
  import { redactString, redactValue } from './output/redact.js';
22
- import { buildInitReceiptJson, renderInitReceipt, } from './output/command-receipt.js';
23
26
  import { resolveCliPackageRoot } from './utils/paths.js';
24
- import { findConfigFieldEntry, formatPluginConfigSetRecoveryCommand, listNamespacedPluginConfigStores, readPluginConfigStore, renderPluginConfigValueForDisplay, resolveConfigRead, } from './utils/plugin-config.js';
27
+ import { coercePluginConfigUpdates, assertPluginConfigMutationCandidate, findConfigFieldEntry, formatPluginConfigSetRecoveryCommand, listNamespacedPluginConfigStores, readPluginConfigStore, renderPluginConfigValueForDisplay, resolveConfigRead, } from './utils/plugin-config.js';
25
28
  import { applyPluginConfigWrite, applyPluginConfig, buildConfigMutationReceipt, configWriteStateForError, resetPluginConfigWithHelper, } from './utils/plugin-config-write.js';
26
29
  import { assertStrictSemVer } from './utils/manifest.js';
27
30
  import { assertCatalogSourceReferencesSupported, inventoryLegacyConfigReferences, } from './utils/catalog-source-references.js';
@@ -34,21 +37,18 @@ import { materializePortableSkillsToDirectory, PortableCommandError } from './po
34
37
  import { createReviewInspectionFailure, getReviewInspectionExitCode, inspectReviewTarget, } from './commands/review-inspection.js';
35
38
  import { prepareReviewTarget, } from './commands/review-preparation.js';
36
39
  import { runCatalogBuildCommand, runCatalogInitCommand, runCatalogValidateCommand, runCatalogVersionCommand, runPluginBuildCommand, runPluginTestCommand, } from './authoring/workspace-commands.js';
37
- import { runCatalogPublishApplyCommand, runCatalogPublishPlanCommand, } from './commands/catalog-publish.js';
38
- import { catalogPublicationFailure, CatalogPublicationInspectionError, } from './commands/catalog-publication-inspection.js';
40
+ import { CatalogPublicationApplyFailure, runCatalogPublishApplyCommand, runCatalogPublishPlanCommand, } from './commands/catalog-publish.js';
41
+ import { catalogPublicationFailure, } from './commands/catalog-publication-inspection.js';
39
42
  import { getCatalogStatus, renderCatalogStatus } from './commands/catalog-status.js';
40
43
  import { activateCatalogDevSource, catalogDevSourceError, createCatalogDevFailureReceipt, deactivateCatalogDevSource, getCatalogDevSourceStatus, } from './commands/catalog-dev-source.js';
41
44
  import { getPluginCapabilitiesResult, parsePluginCapabilitySurface, renderPluginCapabilities, } from './commands/plugin-capabilities.js';
42
45
  import { AwCapabilityUnsupportedError, checkCurrentAw, describeCurrentAw, inspectPluginRequirements, } from './commands/aw-capabilities.js';
43
46
  import { prepareSkillEval } from './commands/skill-eval.js';
44
- import { readRecoveryStatus, checkRecovery } from './recovery/status.js';
45
- import { intentAdd, intentRemove, intentList } from './commands/intent-command.js';
46
47
  import { targetsSet, targetsList, targetsChangeExclusion } from './commands/targets-command.js';
47
- import { runRecovery } from './recovery/coordinator.js';
48
- import { runRetire } from './recovery/retirement.js';
49
48
  import { normalizeAgents } from './intent/deployment-preferences.js';
50
49
  import { resolveWorkContext } from './intent/work-context.js';
51
50
  import { registerManagedCommandCli, runManagedCommandCli } from './commands/managed-commands.js';
51
+ const receiptSinks = new WeakMap();
52
52
  function createDefaultIo() {
53
53
  return {
54
54
  stdout: (text) => process.stdout.write(text),
@@ -61,6 +61,8 @@ function writeLine(write, line) {
61
61
  function strictValueOption(flags, description, choices) {
62
62
  let seen = false;
63
63
  const option = new Option(flags, description);
64
+ if (choices)
65
+ option.choices([...choices]);
64
66
  return option.argParser((value) => {
65
67
  if (seen)
66
68
  throw new InvalidArgumentError(`${option.long} can be specified only once.`);
@@ -91,17 +93,6 @@ function renderReviewPreparation(write, receipt) {
91
93
  writeLine(write, `Source binding: ${receipt.sourceBindingPath}`);
92
94
  renderReviewSkills(write, receipt.skills, receipt.issues);
93
95
  }
94
- function createReviewPreparationFailure(message, code = 'invalidArguments') {
95
- return {
96
- schemaVersion: 1,
97
- command: 'review:prepare',
98
- ok: false,
99
- target: null,
100
- sourceBindingPath: null,
101
- skills: [],
102
- issues: [{ code, path: null, message }],
103
- };
104
- }
105
96
  function writeWarnings(write, warnings, options = {}) {
106
97
  for (const warning of formatWarnings(warnings, options)) {
107
98
  writeLine(write, warning);
@@ -123,142 +114,8 @@ function normalizeWriteRequest(normalize) {
123
114
  throw new WriteCommandRequestError(error instanceof Error ? error.message : String(error));
124
115
  }
125
116
  }
126
- function writeCommandFailure(error) {
127
- const message = redactString(error instanceof Error ? error.message : String(error));
128
- if (error instanceof CommanderError || error instanceof WriteCommandRequestError) {
129
- return { code: 'invalidArguments', message };
130
- }
131
- const explicitCode = error?.code;
132
- if (typeof explicitCode === 'string' && /^[A-Za-z][A-Za-z0-9]*$/u.test(explicitCode)) {
133
- return { code: explicitCode, message };
134
- }
135
- const separator = message.indexOf(':');
136
- const prefix = separator > 0 ? message.slice(0, separator) : '';
137
- return {
138
- code: /^[A-Za-z][A-Za-z0-9]*$/u.test(prefix) ? prefix : 'writeCommandFailed',
139
- message,
140
- };
141
- }
142
- function recoveryRequest(argv) {
143
- const nested = argv[0] === 'plugin';
144
- const args = nested ? argv.slice(1) : argv;
145
- const family = args[0] ?? '';
146
- if (nested && ['remove', 'status'].includes(family)
147
- && args.some((value) => value === '--workspace-root' || value.startsWith('--workspace-root=')))
148
- return null;
149
- if (!['intent', 'targets', 'sync', 'install', 'remove', 'reinstall', 'uninstall', 'cleanup', 'status', 'project'].includes(family))
150
- return null;
151
- let rawScope;
152
- let json = false;
153
- for (let index = 1; index < args.length; index++) {
154
- const value = args[index];
155
- if (value === '--')
156
- break;
157
- if (value === '--scope')
158
- rawScope = args[++index];
159
- else if (value.startsWith('--scope='))
160
- rawScope = value.slice('--scope='.length);
161
- else if (value === '--json' || (/^-[ajvyD]+$/u.test(value) && value.includes('j')))
162
- json = true;
163
- else if (['--target', '--context', '--script-timeout', '--log-file'].includes(value))
164
- index++;
165
- }
166
- return {
167
- command: ['intent', 'targets', 'project'].includes(family) ? `${family}:${args[1] ?? ''}` : family,
168
- scope: rawScope === 'user' || rawScope === 'project' ? rawScope : null,
169
- json,
170
- };
171
- }
172
- function recoveryFailureReceipt(command, scope, error) {
173
- const failure = writeCommandFailure(error);
174
- return {
175
- schemaVersion: 1, kind: 'aw-recovery', scope, command, ok: false,
176
- intent: { state: 'unreadable', roots: null }, requestedRoots: [], requestedTargets: [],
177
- selection: { agents: [], origin: 'none', preferences: 'unreadable' },
178
- blockers: [failure], errors: [failure], targetResults: [], remainingTargets: [], recoveryActions: [],
179
- declarationChanged: false, preferencesChanged: false, configChanged: false, outputsMayHaveChanged: false,
180
- };
181
- }
182
- function scanConfigMutationShortOptions(token) {
183
- if (!/^-[^-].*/u.test(token))
184
- return { json: false, consumesNextValue: false };
185
- let json = false;
186
- for (let index = 1; index < token.length; index += 1) {
187
- const option = token[index];
188
- if (option === 's') {
189
- return {
190
- json,
191
- consumesNextValue: index === token.length - 1,
192
- };
193
- }
194
- if (option === 'j') {
195
- json = true;
196
- continue;
197
- }
198
- if (option === 'v' || option === 'D' || option === 'y') {
199
- continue;
200
- }
201
- break;
202
- }
203
- return { json, consumesNextValue: false };
204
- }
205
- function jsonConfigMutationRequest(argv) {
206
- const args = argv[0] === 'plugin' ? argv.slice(1) : argv;
207
- if (args[0] !== 'config' || !['set', 'edit', 'unset', 'reset', 'apply'].includes(args[1] ?? '')) {
208
- return null;
209
- }
210
- const command = `config:${args[1]}`;
211
- let json = false;
212
- let plugin;
213
- const valueOptions = new Set(['--platform', '--context', '--target', '--value-json', '--preset', '--log-file', '--script-timeout']);
214
- for (let index = 2; index < args.length; index += 1) {
215
- const token = args[index];
216
- if (token === '--')
217
- break;
218
- if (valueOptions.has(token)) {
219
- index += 1;
220
- continue;
221
- }
222
- if (token === '--json') {
223
- json = true;
224
- continue;
225
- }
226
- const shortOptions = scanConfigMutationShortOptions(token);
227
- if (shortOptions.json)
228
- json = true;
229
- if (shortOptions.consumesNextValue)
230
- index += 1;
231
- if (token.startsWith('-'))
232
- continue;
233
- plugin ??= token;
234
- }
235
- if (!json)
236
- return null;
237
- return {
238
- command,
239
- ...(plugin ? { plugin } : {}),
240
- };
241
- }
242
- function jsonConfigReadRequested(argv) {
243
- if (argv[0] !== 'plugin' || argv[1] !== 'config'
244
- || !['schema', 'list', 'get'].includes(argv[2] ?? ''))
245
- return false;
246
- const values = new Set(['--platform', '--context', '--target', '--script-timeout', '--log-file']);
247
- for (let index = 3; index < argv.length; index++) {
248
- const token = argv[index];
249
- if (token === '--')
250
- break;
251
- if (values.has(token)) {
252
- index++;
253
- continue;
254
- }
255
- if (token === '--json' || /^-[jvD]+$/u.test(token) && token.includes('j'))
256
- return true;
257
- }
258
- return false;
259
- }
260
117
  function configMutationFailure(error, env, cwd) {
261
- const configWrite = configWriteStateForError(error);
118
+ const configWrite = error?.configWrite === 'succeeded' ? 'succeeded' : configWriteStateForError(error);
262
119
  if (error instanceof CommanderError) {
263
120
  return {
264
121
  code: 'invalidArguments',
@@ -317,23 +174,24 @@ function writeConfigMutationFailureReceipt(write, request, failure) {
317
174
  }
318
175
  async function runAuthoringScript(options) {
319
176
  const scriptPath = path.join(resolveCliPackageRoot(), 'dist', 'authoring', 'scripts', options.scriptName);
320
- return new Promise((resolve, reject) => {
321
- const child = spawn(process.execPath, [scriptPath, ...options.args], {
322
- cwd: options.cwd,
323
- env: options.env,
324
- stdio: ['ignore', 'pipe', 'pipe'],
325
- });
326
- child.stdout.on('data', (chunk) => options.io.stdout(String(chunk)));
327
- child.stderr.on('data', (chunk) => options.io.stderr(String(chunk)));
328
- child.once('error', reject);
329
- child.once('close', (code, signal) => {
330
- if (signal) {
331
- reject(new Error(`Plugin authoring command terminated by signal ${signal}.`));
332
- return;
333
- }
334
- resolve(code ?? 1);
177
+ try {
178
+ const result = await defaultPluginProcessRunner.run({ command: process.execPath, args: [scriptPath, ...options.args], cwd: options.cwd, env: options.env }, {
179
+ // Authoring has no CLI timeout option. Keep the largest Node timer while
180
+ // using the existing process-tree cleanup contract for interruption.
181
+ timeoutMs: 2_147_483_647, signal: options.interruption?.signal, maxStdoutBytes: 32 * 1024 * 1024,
335
182
  });
336
- });
183
+ options.io.stdout(result.stdout);
184
+ options.io.stderr(result.stderr);
185
+ return result.exitCode ?? 1;
186
+ }
187
+ catch (error) {
188
+ if (options.interruption?.signal.aborted && error !== options.interruption.signal.reason)
189
+ options.interruption.cleanupFailed = true;
190
+ if (options.interruption?.signal.aborted && ['init-plugin.mjs', 'add-skill.mjs', 'remove-plugin.mjs'].includes(options.scriptName)) {
191
+ throw Object.assign(new Error('The authoring command was interrupted after execution started.'), { code: 'operationInterrupted', authoringChanges: 'unknown' });
192
+ }
193
+ throw error;
194
+ }
337
195
  }
338
196
  function toCliDiagnosticsOptions(commandName, rawOptions, runtimeDiagnostics) {
339
197
  return {
@@ -516,16 +374,6 @@ function renderRecoveryReceipt(write, value) {
516
374
  for (const action of value.recoveryActions)
517
375
  writeLine(write, action);
518
376
  }
519
- function renderRecoveryStatus(write, value) {
520
- writeLine(write, `status [${value.scope}]: ${value.ok ? 'ok' : 'failed'}`);
521
- writeLine(write, `本机工具:${value.selection.agents.join('、') || '未配置'}`);
522
- writeLine(write, `全部满足:${value.allSatisfied === null ? '未知' : value.allSatisfied ? '是' : '否'}`);
523
- for (const root of value.inventory ?? []) {
524
- writeLine(write, `${root.pluginId}: ${root.targetResults.length ? root.targetResults.map((target) => `${target.agent}/${target.content ?? target.observation}`).join(', ') : 'localTargetsRequired'}`);
525
- }
526
- for (const error of value.errors)
527
- writeLine(write, `${error.code}: ${error.message}`);
528
- }
529
377
  function recoveryRuntime(context, rawOptions, directCli) {
530
378
  return {
531
379
  ...context,
@@ -590,7 +438,7 @@ async function runActionWithContext(context, action) {
590
438
  Promise.resolve().then(() => context.debugLogger.flush?.()),
591
439
  ]);
592
440
  if (context.diagnostics.debug && context.debugLogger.logFile) {
593
- writeLine(context.io.stderr, `调试日志:${context.debugLogger.logFile}`);
441
+ writeLine(context.io.stderr, `Debug log: ${context.debugLogger.logFile}`);
594
442
  }
595
443
  return result;
596
444
  }
@@ -630,13 +478,17 @@ async function runActionWithContext(context, action) {
630
478
  Promise.resolve().then(() => context.debugLogger.flush?.()),
631
479
  ]);
632
480
  if (context.diagnostics.debug && context.debugLogger.logFile) {
633
- writeLine(context.io.stderr, `调试日志:${context.debugLogger.logFile}`);
481
+ writeLine(context.io.stderr, `Debug log: ${context.debugLogger.logFile}`);
634
482
  }
635
483
  throw error;
636
484
  }
637
485
  }
638
486
  function writeJsonReceipt(write, payload) {
639
- writeLine(write, JSON.stringify(payload, null, 2));
487
+ const sink = receiptSinks.get(write);
488
+ if (sink)
489
+ sink(payload);
490
+ else
491
+ writeLine(write, JSON.stringify(payload, null, 2));
640
492
  }
641
493
  function writeConfigApplyNotice(write, receipt) {
642
494
  const sanitizeMessage = (message) => redactString(message)
@@ -746,10 +598,13 @@ export function buildProgram(options = {}) {
746
598
  cwd,
747
599
  env,
748
600
  io,
749
- interactive: options.interactive,
601
+ interactive: false,
602
+ reporter: options.reporter ?? createNoopReporter(),
750
603
  diagnostics: toCliDiagnosticsOptions(commandName, rawOptions, options.diagnostics),
751
604
  });
752
- const program = new Command();
605
+ if (io.result)
606
+ receiptSinks.set(io.stdout, io.result);
607
+ const program = new Command().enablePositionalOptions();
753
608
  program
754
609
  .name('aw')
755
610
  .description('Agent workflow marketplace installer')
@@ -760,10 +615,12 @@ export function buildProgram(options = {}) {
760
615
  writeErr: (text) => io.stderr(text),
761
616
  outputError: (text, write) => write(text),
762
617
  });
618
+ const dev = program.command('dev').description('Create, validate, build, and publish author sources');
619
+ const devPlugin = dev.command('plugin').description('Manage plugin source code');
763
620
  const plugin = program
764
621
  .command('plugin')
765
622
  .description('Manage plugin demand, outputs, configuration, and author sources');
766
- registerManagedCommandCli(program, () => createActionContext('command', {}), {
623
+ registerManagedCommandCli(program, (rawOptions = {}) => createActionContext('command', rawOptions), {
767
624
  cliEntry: fileURLToPath(import.meta.url),
768
625
  cliVersion: resolveCliVersion(),
769
626
  }, (code) => { commandExitState.exitCode = code; });
@@ -790,7 +647,7 @@ export function buildProgram(options = {}) {
790
647
  writeJsonReceipt(io.stdout, result);
791
648
  commandExitState.exitCode = result.ok ? 0 : 1;
792
649
  });
793
- plugin
650
+ devPlugin
794
651
  .command('capabilities')
795
652
  .description('Show the current plugin manifest authoring surface')
796
653
  .option('--surface <surface>', 'manifest | build-config | extensions | slash-commands | mcp-apps | config | pre-apply | artifacts')
@@ -815,7 +672,7 @@ export function buildProgram(options = {}) {
815
672
  commandExitState.exitCode = 1;
816
673
  }
817
674
  });
818
- plugin
675
+ devPlugin
819
676
  .command('requirements')
820
677
  .description('Inspect or update effective AW capabilities required by a plugin')
821
678
  .argument('<plugin-directory>', 'plugin source directory')
@@ -838,6 +695,8 @@ export function buildProgram(options = {}) {
838
695
  }
839
696
  }
840
697
  catch (error) {
698
+ if (error instanceof CatalogWorkspaceMissingError)
699
+ throw error;
841
700
  writeJsonReceipt(io.stdout, {
842
701
  schemaVersion: 1,
843
702
  command: 'plugin:requirements',
@@ -847,14 +706,14 @@ export function buildProgram(options = {}) {
847
706
  commandExitState.exitCode = 1;
848
707
  }
849
708
  });
850
- const skill = program
709
+ const skill = dev
851
710
  .command('skill')
852
711
  .description('Install, materialize, or validate Agent Skills');
853
- const skillEval = skill
712
+ const skillEval = dev
854
713
  .command('eval')
855
714
  .description('Prepare or diagnose deterministic Agent Skill Eval inputs');
856
715
  skillEval
857
- .command('doctor')
716
+ .command('check')
858
717
  .description('Inspect Agent Skill Eval provider readiness without model execution')
859
718
  .requiredOption('--json', 'emit one provider doctor JSON object')
860
719
  .action(async () => {
@@ -929,6 +788,8 @@ export function buildProgram(options = {}) {
929
788
  writeJsonReceipt(io.stdout, receipt);
930
789
  }
931
790
  catch (error) {
791
+ if (error instanceof CatalogWorkspaceMissingError)
792
+ throw error;
932
793
  writeJsonReceipt(io.stdout, {
933
794
  schemaVersion: 1,
934
795
  command: 'skill:eval:prepare',
@@ -941,7 +802,7 @@ export function buildProgram(options = {}) {
941
802
  commandExitState.exitCode = 1;
942
803
  }
943
804
  });
944
- const review = program
805
+ const review = dev
945
806
  .command('review')
946
807
  .description('Inspect and prepare Skill review materializations');
947
808
  review
@@ -1020,7 +881,7 @@ export function buildProgram(options = {}) {
1020
881
  commandExitState.exitCode = result.exitCode;
1021
882
  });
1022
883
  skill
1023
- .command('materialize')
884
+ .command('export')
1024
885
  .description('Write portable Skills to a safe output directory')
1025
886
  .argument('<plugin>', 'plugin or source/plugin selector')
1026
887
  .addOption(strictValueOption('--platform <target>', 'Portable platform target', PORTABLE_PLATFORM_TARGETS).makeOptionMandatory())
@@ -1081,14 +942,14 @@ export function buildProgram(options = {}) {
1081
942
  commandExitState.exitCode = 1;
1082
943
  }
1083
944
  });
1084
- plugin
1085
- .command('init')
945
+ devPlugin
946
+ .command('create')
1086
947
  .description('Create a new deterministic plugin scaffold')
1087
948
  .addHelpText('after', [
1088
949
  '',
1089
950
  'During development, keep the current stable target when production content changes.',
1090
- 'Next, run `aw plugin validate`, `aw plugin test`, `aw plugin build`, and `aw catalog build`.',
1091
- 'Publish only as an explicit later step; inspect `aw catalog publish plan --help` first.',
951
+ 'Next, run `aw dev plugin validate`, `aw dev plugin test`, `aw dev plugin build`, and `aw dev catalog build`.',
952
+ 'Publish only as an explicit later step; inspect `aw dev catalog publish plan --help` first.',
1092
953
  '',
1093
954
  ].join('\n'))
1094
955
  .argument('<plugin-name>', 'lowercase hyphen-case plugin name')
@@ -1106,23 +967,23 @@ export function buildProgram(options = {}) {
1106
967
  .option('--with-apps', 'add a minimal .app.json', false)
1107
968
  .option('--with-config-api', 'add AW config schema and helper', false)
1108
969
  .option('--with-pre-apply', 'add an idempotent Node preApply environment check', false);
1109
- plugin
1110
- .command('add-skill')
970
+ skill
971
+ .command('create')
1111
972
  .description('Add one static Skill scaffold to an existing plugin')
1112
973
  .addHelpText('after', [
1113
974
  '',
1114
975
  'During development, keep the current stable target when production content changes.',
1115
- 'Next, run `aw plugin validate`, `aw plugin test`, `aw plugin build`, and `aw catalog build`.',
1116
- 'Publish only as an explicit later step; inspect `aw catalog publish plan --help` first.',
976
+ 'Next, run `aw dev plugin validate`, `aw dev plugin test`, `aw dev plugin build`, and `aw dev catalog build`.',
977
+ 'Publish only as an explicit later step; inspect `aw dev catalog publish plan --help` first.',
1117
978
  '',
1118
979
  ].join('\n'))
1119
- .argument('<plugin-name>', 'existing lowercase hyphen-case plugin name')
980
+ .requiredOption('--plugin <name>', 'Plugin that owns the Skill')
1120
981
  .option('--skill-name <name>', 'new static Skill name (required)')
1121
982
  .option('--skill-description <text>', 'Skill goal and discovery description (required)')
1122
983
  .option('--skill-short-description <text>', 'Skill UI summary (25-64 characters)')
1123
984
  .option('--skill-invocation <mode>', 'model | manual | claude-model-only (default: model)')
1124
985
  .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from current directory)');
1125
- plugin
986
+ devPlugin
1126
987
  .command('validate')
1127
988
  .description('Validate one source plugin directory')
1128
989
  .argument('<plugin-directory>', 'source plugin directory')
@@ -1131,7 +992,7 @@ export function buildProgram(options = {}) {
1131
992
  .option('--version-base <git-ref>', 'production bundle comparison base (default: HEAD)')
1132
993
  .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from plugin directory)')
1133
994
  .option('--json', 'emit one machine-readable JSON result', false);
1134
- plugin
995
+ devPlugin
1135
996
  .command('test')
1136
997
  .description('Run deterministic Node tests declared by one source plugin')
1137
998
  .argument('<plugin-directory>', 'source plugin directory')
@@ -1156,6 +1017,8 @@ export function buildProgram(options = {}) {
1156
1017
  });
1157
1018
  }
1158
1019
  catch (error) {
1020
+ if (error instanceof CatalogWorkspaceMissingError)
1021
+ throw error;
1159
1022
  const message = error instanceof Error ? error.message : String(error);
1160
1023
  if (rawOptions.json)
1161
1024
  writeJsonReceipt(io.stdout, { command: 'plugin:test', ok: false, errors: [{ message }] });
@@ -1163,7 +1026,7 @@ export function buildProgram(options = {}) {
1163
1026
  commandExitState.exitCode = 1;
1164
1027
  }
1165
1028
  });
1166
- plugin
1029
+ devPlugin
1167
1030
  .command('build')
1168
1031
  .description('Build and inspect one source plugin bundle')
1169
1032
  .argument('<plugin-directory>', 'source plugin directory')
@@ -1188,6 +1051,8 @@ export function buildProgram(options = {}) {
1188
1051
  });
1189
1052
  }
1190
1053
  catch (error) {
1054
+ if (error instanceof CatalogWorkspaceMissingError)
1055
+ throw error;
1191
1056
  const message = error instanceof Error ? error.message : String(error);
1192
1057
  if (rawOptions.json)
1193
1058
  writeJsonReceipt(io.stdout, { command: 'plugin:build', ok: false, errors: [{ message }] });
@@ -1202,11 +1067,11 @@ export function buildProgram(options = {}) {
1202
1067
  .option('--frontmatter-profile <profile>', 'portable-agent-skills | claude-2.1.88 | claude-current (default: portable-agent-skills)')
1203
1068
  .option('--codex-metadata <policy>', 'required | optional | ignore (default: optional)')
1204
1069
  .option('--json', 'emit one machine-readable JSON result', false);
1205
- const catalog = program
1070
+ const catalog = dev
1206
1071
  .command('catalog')
1207
1072
  .description('Build and manage catalogs');
1208
1073
  catalog
1209
- .command('init')
1074
+ .command('create')
1210
1075
  .description('Initialize a local AW Catalog Workspace')
1211
1076
  .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor, then Git worktree root, then current directory)')
1212
1077
  .option('--owner-name <name>', 'catalog owner name')
@@ -1260,6 +1125,8 @@ export function buildProgram(options = {}) {
1260
1125
  });
1261
1126
  }
1262
1127
  catch (error) {
1128
+ if (error instanceof CatalogWorkspaceMissingError)
1129
+ throw error;
1263
1130
  const message = error instanceof Error ? error.message : String(error);
1264
1131
  if (rawOptions.json)
1265
1132
  writeJsonReceipt(io.stdout, { command: 'catalog:version', ok: false, errors: [{ message }] });
@@ -1290,6 +1157,8 @@ export function buildProgram(options = {}) {
1290
1157
  });
1291
1158
  }
1292
1159
  catch (error) {
1160
+ if (error instanceof CatalogWorkspaceMissingError)
1161
+ throw error;
1293
1162
  const message = error instanceof Error ? error.message : String(error);
1294
1163
  if (rawOptions.json)
1295
1164
  writeJsonReceipt(io.stdout, { command: 'catalog:build', ok: false, errors: [{ message }] });
@@ -1371,6 +1240,8 @@ export function buildProgram(options = {}) {
1371
1240
  }
1372
1241
  }
1373
1242
  catch (error) {
1243
+ if (error instanceof CatalogWorkspaceMissingError)
1244
+ throw error;
1374
1245
  const failure = catalogPublicationFailure({
1375
1246
  error,
1376
1247
  env,
@@ -1424,10 +1295,12 @@ export function buildProgram(options = {}) {
1424
1295
  writeLine(io.stdout, `Branch: refs/heads/${result.branch}`);
1425
1296
  writeLine(io.stdout, `Tag: refs/tags/${result.tag}`);
1426
1297
  writeLine(io.stdout, `Commit: ${result.commit}`);
1427
- writeLine(io.stdout, `Add it as a source: aw catalog source add <id> --git ${result.fetchUrl} --ref refs/heads/${result.branch}`);
1298
+ writeLine(io.stdout, `Add it as a source: aw source add <id> --git ${result.fetchUrl} --ref refs/heads/${result.branch}`);
1428
1299
  }
1429
1300
  }
1430
1301
  catch (error) {
1302
+ if (error instanceof CatalogWorkspaceMissingError)
1303
+ throw error;
1431
1304
  const failure = catalogPublicationFailure({
1432
1305
  error,
1433
1306
  env,
@@ -1437,13 +1310,13 @@ export function buildProgram(options = {}) {
1437
1310
  ],
1438
1311
  });
1439
1312
  if (rawOptions.json)
1440
- writeJsonReceipt(io.stdout, failure);
1313
+ writeJsonReceipt(io.stdout, { ...failure, ...(error instanceof CatalogPublicationApplyFailure ? { overallState: 'partial', ...error.outcome } : {}) });
1441
1314
  writeLine(io.stderr, failure.message);
1442
1315
  commandExitState.exitCode = 1;
1443
1316
  }
1444
1317
  });
1445
- const catalogDev = catalog
1446
- .command('dev')
1318
+ const catalogDev = dev
1319
+ .command('source')
1447
1320
  .description('Manage the current Catalog Workspace development source');
1448
1321
  catalogDev
1449
1322
  .command('activate')
@@ -1469,6 +1342,8 @@ export function buildProgram(options = {}) {
1469
1342
  commandExitState.exitCode = receipt.ok ? 0 : 1;
1470
1343
  }
1471
1344
  catch (error) {
1345
+ if (error instanceof CatalogWorkspaceMissingError)
1346
+ throw error;
1472
1347
  const failure = catalogDevSourceError(error);
1473
1348
  writeJsonReceipt(io.stdout, createCatalogDevFailureReceipt({
1474
1349
  command: 'activate', cwd, workspaceRoot: rawOptions.workspaceRoot,
@@ -1512,6 +1387,8 @@ export function buildProgram(options = {}) {
1512
1387
  commandExitState.exitCode = receipt.ok ? 0 : 1;
1513
1388
  }
1514
1389
  catch (error) {
1390
+ if (error instanceof CatalogWorkspaceMissingError)
1391
+ throw error;
1515
1392
  const failure = catalogDevSourceError(error);
1516
1393
  writeJsonReceipt(io.stdout, createCatalogDevFailureReceipt({
1517
1394
  command: 'deactivate', cwd, workspaceRoot: rawOptions.workspaceRoot,
@@ -1520,7 +1397,7 @@ export function buildProgram(options = {}) {
1520
1397
  commandExitState.exitCode = 1;
1521
1398
  }
1522
1399
  });
1523
- const catalogSource = catalog
1400
+ const catalogSource = program
1524
1401
  .command('source')
1525
1402
  .description('Manage catalog sources');
1526
1403
  const writeCatalogSourceFailure = async (command, sourceId, json, error, sensitiveRoots = []) => {
@@ -1535,6 +1412,7 @@ export function buildProgram(options = {}) {
1535
1412
  sourceId,
1536
1413
  primaryChange: failure.impact?.primaryChange ?? null,
1537
1414
  references: failure.impact?.references ?? failure.inventory?.references ?? [],
1415
+ impact: failure.impact ?? failure.inventory ?? null,
1538
1416
  errors: [{ code: failure.code ?? failure.name ?? 'catalogSourceMutationFailed', message }],
1539
1417
  });
1540
1418
  }
@@ -1561,6 +1439,12 @@ export function buildProgram(options = {}) {
1561
1439
  };
1562
1440
  const writeConfigMutationFailure = (command, plugin, json, error) => {
1563
1441
  const failure = configMutationFailure(error, env, cwd);
1442
+ const confirmation = error?.confirmation;
1443
+ if (confirmation) {
1444
+ writeJsonReceipt(io.stdout, { command, ok: false, pluginId: plugin, configWrite: 'notStarted', confirmation, errors: [failure] });
1445
+ commandExitState.exitCode = 3;
1446
+ return;
1447
+ }
1564
1448
  if (json) {
1565
1449
  writeConfigMutationFailureReceipt(io.stdout, {
1566
1450
  command,
@@ -1592,24 +1476,9 @@ export function buildProgram(options = {}) {
1592
1476
  },
1593
1477
  });
1594
1478
  })();
1595
- catalogSource
1596
- .command('list')
1597
- .option('-j, --json', 'print catalog sources as JSON', false)
1598
- .action(async (rawOptions) => {
1599
- const payload = await listCatalogSources({ env });
1600
- if (rawOptions.json) {
1601
- writeJsonReceipt(io.stdout, payload);
1602
- return;
1603
- }
1604
- writeLine(io.stdout, `Primary source: ${payload.primarySourceId}`);
1605
- for (const source of payload.sources) {
1606
- writeLine(io.stdout, `${source.primary ? '*' : '-'} ${source.id} ${source.type} ${source.sourceIdentity}`);
1607
- }
1608
- });
1609
1479
  catalogSource
1610
1480
  .command('sync')
1611
1481
  .argument('<id>')
1612
- .option('--check', 'fetch and validate without changing the Catalog store or Active state', false)
1613
1482
  .option('--replace-damaged', 'replace a damaged Active entry with the current candidate', false)
1614
1483
  .option('-y, --yes', 'confirm affected, unknown, or damaged Active replacement impact', false)
1615
1484
  .option('-j, --json', 'print the source sync result as JSON', false)
@@ -1685,13 +1554,13 @@ export function buildProgram(options = {}) {
1685
1554
  .action(async (id, rawOptions) => {
1686
1555
  try {
1687
1556
  if ((rawOptions.git === undefined) === (rawOptions.path === undefined)) {
1688
- throw new Error('catalog source add requires exactly one of `--git` or `--path`.');
1557
+ throw new WriteCommandRequestError('catalog source add requires exactly one of `--git` or `--path`.');
1689
1558
  }
1690
1559
  if (rawOptions.git !== undefined && ((rawOptions.ref === undefined) === (rawOptions.defaultRef !== true))) {
1691
- throw new Error('Git catalog source add requires exactly one of `--ref` or `--default-ref`.');
1560
+ throw new WriteCommandRequestError('Git catalog source add requires exactly one of `--ref` or `--default-ref`.');
1692
1561
  }
1693
1562
  if (rawOptions.path !== undefined && (rawOptions.ref !== undefined || rawOptions.defaultRef === true || rawOptions.subdir !== undefined)) {
1694
- throw new Error('Path catalog source add only accepts `--path`, `--primary`, `--no-auto-check`, and `--yes`.');
1563
+ throw new WriteCommandRequestError('Path catalog source add only accepts `--path`, `--primary`, `--no-auto-check`, and `--yes`.');
1695
1564
  }
1696
1565
  const source = rawOptions.git !== undefined
1697
1566
  ? {
@@ -1729,7 +1598,7 @@ export function buildProgram(options = {}) {
1729
1598
  confirmImpact: rawOptions.yes === true,
1730
1599
  });
1731
1600
  if (rawOptions.json)
1732
- writeJsonReceipt(io.stdout, receipt);
1601
+ writeJsonReceipt(io.stdout, { ...receipt, impact: preview?.references ?? null, confirmation: sourceConfirmation(id, rawOptions.yes, preview) });
1733
1602
  else
1734
1603
  writeLine(io.stdout, `Catalog source ${id} added.`);
1735
1604
  for (const diagnostic of receipt.errors)
@@ -1755,26 +1624,26 @@ export function buildProgram(options = {}) {
1755
1624
  .action(async (id, rawOptions) => {
1756
1625
  try {
1757
1626
  if (rawOptions.git !== undefined && rawOptions.path !== undefined) {
1758
- throw new Error('catalog source update cannot combine `--git` and `--path`.');
1627
+ throw new WriteCommandRequestError('catalog source update cannot combine `--git` and `--path`.');
1759
1628
  }
1760
1629
  if (rawOptions.ref !== undefined && rawOptions.defaultRef === true) {
1761
- throw new Error('catalog source update cannot combine `--ref` and `--default-ref`.');
1630
+ throw new WriteCommandRequestError('catalog source update cannot combine `--ref` and `--default-ref`.');
1762
1631
  }
1763
- const hasUpdate = rawOptions.git !== undefined
1632
+ const hasUpdate = rawOptions.primary === true || rawOptions.git !== undefined
1764
1633
  || rawOptions.path !== undefined
1765
1634
  || rawOptions.ref !== undefined
1766
1635
  || rawOptions.defaultRef === true
1767
1636
  || rawOptions.subdir !== undefined
1768
1637
  || rawOptions.autoCheck !== undefined;
1769
1638
  if (!hasUpdate)
1770
- throw new Error('catalog source update requires at least one update option.');
1639
+ throw new WriteCommandRequestError('catalog source update requires at least one update option.');
1771
1640
  if (rawOptions.path !== undefined && (rawOptions.ref !== undefined || rawOptions.defaultRef === true || rawOptions.subdir !== undefined))
1772
- throw new Error('Path catalog source update only accepts `--path` and auto-check options.');
1641
+ throw new WriteCommandRequestError('Path catalog source update only accepts `--path` and auto-check options.');
1773
1642
  const hasGitUpdate = rawOptions.git !== undefined
1774
1643
  || rawOptions.ref !== undefined
1775
1644
  || rawOptions.defaultRef === true
1776
1645
  || rawOptions.subdir !== undefined;
1777
- const update = rawOptions.path !== undefined
1646
+ const transportUpdate = rawOptions.path !== undefined
1778
1647
  ? {
1779
1648
  type: 'path',
1780
1649
  path: rawOptions.path,
@@ -1792,12 +1661,16 @@ export function buildProgram(options = {}) {
1792
1661
  : {}),
1793
1662
  }
1794
1663
  : { autoCheck: rawOptions.autoCheck };
1664
+ const update = transportUpdate;
1795
1665
  const preview = await preflightCatalogSourceMutation({
1796
- request: { action: 'update', sourceId: id, update }, cwd, env,
1666
+ request: { action: 'update', sourceId: id, update, ...(rawOptions.primary ? { primary: true } : {}) }, cwd, env,
1797
1667
  });
1798
1668
  const receipt = await updateCatalogSourceCommand({
1799
1669
  sourceId: id,
1800
1670
  update,
1671
+ ...(rawOptions.primary ? { primary: true } : {}),
1672
+ requireImpactConfirmation: true,
1673
+ confirmImpact: rawOptions.yes === true,
1801
1674
  cliVersion: resolveCliVersion(),
1802
1675
  cwd,
1803
1676
  env,
@@ -1808,7 +1681,7 @@ export function buildProgram(options = {}) {
1808
1681
  confirmIdentityChange: rawOptions.yes === true,
1809
1682
  });
1810
1683
  if (rawOptions.json)
1811
- writeJsonReceipt(io.stdout, receipt);
1684
+ writeJsonReceipt(io.stdout, { ...receipt, impact: preview.references, confirmation: sourceConfirmation(id, rawOptions.yes, preview) });
1812
1685
  else
1813
1686
  writeLine(io.stdout, `Catalog source ${id} updated.`);
1814
1687
  for (const diagnostic of receipt.errors)
@@ -1818,29 +1691,6 @@ export function buildProgram(options = {}) {
1818
1691
  await writeCatalogSourceFailure('catalog:source:update', id, rawOptions.json === true, error, rawOptions.path === undefined ? [] : [rawOptions.path, path.resolve(cwd, rawOptions.path)]);
1819
1692
  }
1820
1693
  });
1821
- catalogSource
1822
- .command('set-primary')
1823
- .argument('<id>')
1824
- .option('-y, --yes', 'confirm affected or unknown primary source references', false)
1825
- .option('-j, --json', 'print mutation receipt as JSON', false)
1826
- .action(async (id, rawOptions) => {
1827
- try {
1828
- const receipt = await setPrimaryCatalogSourceCommand({
1829
- sourceId: id,
1830
- cwd,
1831
- env,
1832
- requireImpactConfirmation: true,
1833
- confirmImpact: rawOptions.yes === true,
1834
- });
1835
- if (rawOptions.json)
1836
- writeJsonReceipt(io.stdout, receipt);
1837
- else
1838
- writeLine(io.stdout, `Primary catalog source set to ${id}.`);
1839
- }
1840
- catch (error) {
1841
- await writeCatalogSourceFailure('catalog:source:set-primary', id, rawOptions.json === true, error);
1842
- }
1843
- });
1844
1694
  catalogSource
1845
1695
  .command('remove')
1846
1696
  .argument('<id>')
@@ -1848,6 +1698,7 @@ export function buildProgram(options = {}) {
1848
1698
  .option('-j, --json', 'print mutation receipt as JSON', false)
1849
1699
  .action(async (id, rawOptions) => {
1850
1700
  try {
1701
+ const preview = await preflightCatalogSourceMutation({ request: { action: 'remove', sourceId: id }, cwd, env });
1851
1702
  const receipt = await removeCatalogSourceCommand({
1852
1703
  sourceId: id,
1853
1704
  cwd,
@@ -1856,7 +1707,7 @@ export function buildProgram(options = {}) {
1856
1707
  confirmImpact: rawOptions.yes === true,
1857
1708
  });
1858
1709
  if (rawOptions.json)
1859
- writeJsonReceipt(io.stdout, receipt);
1710
+ writeJsonReceipt(io.stdout, { ...receipt, impact: preview.references, confirmation: sourceConfirmation(id, rawOptions.yes, preview) });
1860
1711
  else
1861
1712
  writeLine(io.stdout, `Catalog source ${id} removed.`);
1862
1713
  }
@@ -1864,8 +1715,8 @@ export function buildProgram(options = {}) {
1864
1715
  await writeCatalogSourceFailure('catalog:source:remove', id, rawOptions.json === true, error);
1865
1716
  }
1866
1717
  });
1867
- const catalogStore = catalog
1868
- .command('store')
1718
+ const catalogStore = program
1719
+ .command('cache')
1869
1720
  .description('Inspect or prune the immutable Catalog store');
1870
1721
  catalogStore
1871
1722
  .command('status')
@@ -1925,7 +1776,7 @@ export function buildProgram(options = {}) {
1925
1776
  }
1926
1777
  else if (dryRun) {
1927
1778
  writeLine(io.stdout, `Dry run: ${result.entries.filter((entry) => entry.status === 'reclaimable').length} item(s) are reclaimable.`);
1928
- writeLine(io.stdout, 'Run `aw catalog store prune --yes` to delete them.');
1779
+ writeLine(io.stdout, 'Run `aw cache prune --yes` to delete them.');
1929
1780
  if (result.errors.length > 0)
1930
1781
  writeLine(io.stderr, `${result.errors.length} item(s) could not be fully inspected and were retained.`);
1931
1782
  }
@@ -1958,43 +1809,14 @@ export function buildProgram(options = {}) {
1958
1809
  commandExitState.exitCode = 1;
1959
1810
  }
1960
1811
  });
1961
- program
1962
- .command('init')
1963
- .option('-j, --json', 'print receipt as JSON', false)
1964
- .option('-v, --verbose', 'show command diagnostics', false)
1965
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
1966
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
1967
- .action(async (rawOptions) => {
1968
- const context = createActionContext('init', rawOptions);
1969
- const result = await runActionWithContext(context, () => initCommand({
1970
- env: context.env,
1971
- }));
1972
- if (rawOptions.json) {
1973
- writeJsonReceipt(io.stdout, buildInitReceiptJson(result));
1974
- }
1975
- else {
1976
- for (const line of renderInitReceipt(result)) {
1977
- writeLine(io.stdout, line);
1978
- }
1979
- }
1980
- for (const source of result.sources) {
1981
- if (!source.ok && source.error)
1982
- writeLine(io.stderr, `${source.id}: ${source.error}`);
1983
- }
1984
- commandExitState.exitCode = result.ok ? 0 : 1;
1985
- });
1986
1812
  const recoveryCommand = (command) => command
1987
1813
  .option('-j, --json', 'print one recovery receipt as JSON', false)
1988
1814
  .option('-v, --verbose', 'show command diagnostics', false)
1989
1815
  .option('-D, --debug', 'write debug diagnostics to a log file', false)
1990
1816
  .option('--log-file <path>', 'write debug diagnostics to the specified file');
1991
- const scopedCommand = (command) => recoveryCommand(command)
1992
- .addOption(strictValueOption('--scope <scope>', 'requirement or physical scope', ['user', 'project']).makeOptionMandatory());
1993
1817
  const contextualCommand = (command) => recoveryCommand(command)
1994
1818
  .addOption(strictValueOption('--context <context>', 'user only, or user and current project', ['user', 'project']));
1995
1819
  const recoveryScope = (rawOptions) => normalizeWriteRequest(() => parseScopeValue(rawOptions.scope));
1996
- const recoveryTargets = (rawOptions) => rawOptions.target === undefined
1997
- ? undefined : normalizeWriteRequest(() => normalizeAgents(typeof rawOptions.target === 'string' ? [rawOptions.target] : rawOptions.target));
1998
1820
  const recoveryContext = (rawOptions) => rawOptions.context === undefined
1999
1821
  ? undefined : normalizeWriteRequest(() => parseContextValue(rawOptions.context));
2000
1822
  const runRecoveryAction = async (command, rawOptions, action) => {
@@ -2018,24 +1840,7 @@ export function buildProgram(options = {}) {
2018
1840
  ? `工作上下文:用户与当前项目 ${work.projectRoot}` : '工作上下文:仅用户');
2019
1841
  return work;
2020
1842
  };
2021
- const intent = plugin.command('intent').description('Manage user or project plugin requirements');
2022
- scopedCommand(intent.command('add').argument('<plugins...>'))
2023
- .action(async (plugins, rawOptions) => runRecoveryAction('intent:add', rawOptions, (context) => intentAdd({ scope: recoveryScope(rawOptions), cwd: context.cwd, env: context.env, selectors: plugins })));
2024
- scopedCommand(intent.command('remove').argument('<plugins...>'))
2025
- .action(async (plugins, rawOptions) => runRecoveryAction('intent:remove', rawOptions, (context) => intentRemove({ scope: recoveryScope(rawOptions), cwd: context.cwd, env: context.env, selectors: plugins })));
2026
- scopedCommand(intent.command('list'))
2027
- .action(async (rawOptions) => runRecoveryAction('intent:list', rawOptions, (context) => intentList({ scope: recoveryScope(rawOptions), cwd: context.cwd, env: context.env })));
2028
- scopedCommand(intent.command('retire').argument('<plugin>'))
2029
- .description('Retire a plugin proven absent from its healthy Catalog')
2030
- .option('--target <target>', 'limit output changes to a platform target', collectUniqueOption)
2031
- .option('--delete-config', 'also delete saved user plugin configuration', false)
2032
- .option('-y, --yes', 'confirm the reviewed retirement changes', false)
2033
- .action(async (selector, rawOptions) => runRecoveryAction('intent:retire', rawOptions, (context) => runRetire({ scope: recoveryScope(rawOptions), cwd: context.cwd, env: context.env, selector,
2034
- cliVersion: resolveCliVersion(), targets: recoveryTargets(rawOptions),
2035
- deleteConfig: rawOptions.deleteConfig, yes: rawOptions.yes,
2036
- interactive: isWizardAvailable(context, rawOptions), prompt: context.prompt,
2037
- }, recoveryRuntime(context, rawOptions, true))));
2038
- const targets = plugin.command('targets').description('Manage the local platform policy');
1843
+ const targets = program.command('target').description('Manage the local platform policy');
2039
1844
  contextualCommand(targets.command('set').argument('[targets...]'))
2040
1845
  .option('--none', 'save an empty target set', false)
2041
1846
  .option('--apply', 'apply the saved target policy in this work context', false)
@@ -2068,54 +1873,6 @@ export function buildProgram(options = {}) {
2068
1873
  });
2069
1874
  });
2070
1875
  }
2071
- for (const command of ['sync', 'install', 'remove', 'cleanup']) {
2072
- const entry = command === 'cleanup'
2073
- ? scopedCommand(plugin.command(command).argument('[plugins...]'))
2074
- : contextualCommand(plugin.command(command).argument(command === 'sync' ? '[plugins...]' : '<plugins...>'));
2075
- entry.option('-y, --yes', 'authorize reviewed scripts or output changes', false);
2076
- if (command === 'install' || command === 'remove')
2077
- entry
2078
- .addOption(strictValueOption('--scope <scope>', 'requirement document to edit', ['user', 'project']));
2079
- if (command === 'remove')
2080
- entry.option('--workspace-root <path>', 'delete plugin source from this explicit Catalog Workspace');
2081
- if (command === 'sync')
2082
- entry
2083
- .option('--target <target>', 'limit execution to a canonical platform target', collectUniqueOption)
2084
- .option('--rebuild', 'rebuild selected desired outputs', false)
2085
- .option('--check', 'observe without preparing or writing', false)
2086
- .option('--refresh', 'refresh required Catalog sources before review', false);
2087
- if (command === 'cleanup')
2088
- entry
2089
- .addOption(strictValueOption('--target <target>', 'physical platform target to clean', PLATFORM_TARGETS).makeOptionMandatory())
2090
- .option('--force', 'clean provably owned output despite damaged weak state', false);
2091
- if (command === 'install' || command === 'sync')
2092
- entry
2093
- .option('--script-timeout <ms>', 'override plugin preApply timeout in milliseconds');
2094
- entry.action(async (plugins, rawOptions) => {
2095
- if (rawOptions.check && (rawOptions.refresh || rawOptions.rebuild)) {
2096
- throw new WriteCommandRequestError('--check cannot be combined with --refresh or --rebuild.');
2097
- }
2098
- await runRecoveryAction(command, rawOptions, async (context) => {
2099
- if (command !== 'cleanup')
2100
- await showWorkContext(context, rawOptions);
2101
- const targetValues = typeof rawOptions.target === 'string' ? [rawOptions.target] : rawOptions.target;
2102
- const options = {
2103
- ...(rawOptions.scope === undefined ? {} : { scope: recoveryScope(rawOptions) }),
2104
- context: recoveryContext(rawOptions), cwd: context.cwd, env: context.env, cliVersion: resolveCliVersion(),
2105
- targets: targetValues === undefined ? undefined : normalizeWriteRequest(() => normalizeAgents(targetValues)),
2106
- all: command === 'sync' && plugins.length === 0,
2107
- yes: rawOptions.yes, force: rawOptions.force, refresh: rawOptions.refresh,
2108
- scriptTimeoutMs: normalizeWriteRequest(() => resolveScriptTimeoutMs(rawOptions)),
2109
- interactive: isWizardAvailable(context, rawOptions), prompt: context.prompt,
2110
- };
2111
- const backendCommand = command === 'remove' ? 'uninstall'
2112
- : command === 'sync' && rawOptions.rebuild ? 'reinstall' : command;
2113
- const result = rawOptions.check ? await checkRecovery(plugins, options)
2114
- : await runRecovery(backendCommand, plugins, options, recoveryRuntime(context, rawOptions, true));
2115
- return { ...result, command };
2116
- });
2117
- });
2118
- }
2119
1876
  const config = plugin.command('config').description('Manage user common and platform configuration');
2120
1877
  const configCommand = (command) => command
2121
1878
  .addOption(strictValueOption('--platform <target>', 'configuration platform; omitted means common', PLATFORM_TARGETS))
@@ -2140,7 +1897,7 @@ export function buildProgram(options = {}) {
2140
1897
  const configPlatform = (rawOptions) => rawOptions.platform === undefined
2141
1898
  ? undefined : normalizeWriteRequest(() => parsePlatformTargetValue(rawOptions.platform));
2142
1899
  for (const command of ['schema', 'list', 'get']) {
2143
- const entry = configCommand(config.command(command).argument('<plugin>'));
1900
+ const entry = configCommand((command === 'list' ? new Command(command) : config.command(command)).argument('<plugin>'));
2144
1901
  if (command === 'get')
2145
1902
  entry.argument('[key]');
2146
1903
  entry.action(async (...args) => {
@@ -2152,8 +1909,8 @@ export function buildProgram(options = {}) {
2152
1909
  const resolved = await runActionWithContext(context, () => resolveMultiSourceConfigRead({
2153
1910
  selector, key, rawOptions: { ...rawOptions, context: work.context }, context,
2154
1911
  }));
2155
- if (rawOptions.json)
2156
- writeJsonReceipt(io.stdout, {
1912
+ if (rawOptions.json) {
1913
+ const result = projectReceipt(`plugin.config.${command}`, {
2157
1914
  ok: true, configSchemaVersion: 5, command: `config:${command}`,
2158
1915
  plugin: resolved.pluginName, pluginName: resolved.pluginName, pluginId: resolved.pluginId,
2159
1916
  sourceId: resolved.sourceId, sourceIdentity: resolved.sourceIdentity,
@@ -2162,6 +1919,18 @@ export function buildProgram(options = {}) {
2162
1919
  fields: command === 'schema' ? resolved.result.fieldDefinitions ?? {} : resolved.result.fields,
2163
1920
  ...(key === undefined ? {} : { key }),
2164
1921
  });
1922
+ if (command === 'get')
1923
+ for (const field of resolved.result.fields) {
1924
+ const definition = resolved.result.fieldDefinitions?.[field.key];
1925
+ if (field.kind !== 'manifest' || field.valueState !== 'invalid' || !definition?.sensitive)
1926
+ continue;
1927
+ result.nextActions.push({ kind: 'command',
1928
+ argv: ['aw', 'plugin', 'config', 'set', resolved.pluginId, field.key,
1929
+ '--context', work.context, ...(resolved.result.platform ? ['--platform', resolved.result.platform] : []), '--value-stdin'],
1930
+ reason: 'Replace the invalid sensitive configuration value through stdin.', requiresConfirmation: false });
1931
+ }
1932
+ writeJsonReceipt(io.stdout, result);
1933
+ }
2165
1934
  else if (command === 'schema')
2166
1935
  writeJsonReceipt(io.stdout, resolved.result.fieldDefinitions ?? {});
2167
1936
  else
@@ -2169,7 +1938,7 @@ export function buildProgram(options = {}) {
2169
1938
  });
2170
1939
  }
2171
1940
  for (const command of ['set', 'edit', 'unset']) {
2172
- const entry = configMutation(config.command(command).argument('<plugin>'));
1941
+ const entry = configMutation((command === 'edit' ? new Command(command) : config.command(command)).argument('<plugin>'));
2173
1942
  if (command !== 'edit')
2174
1943
  entry.argument('<field>');
2175
1944
  if (command === 'set')
@@ -2221,7 +1990,7 @@ export function buildProgram(options = {}) {
2221
1990
  if (command !== 'unset') {
2222
1991
  const sensitive = field.sensitive === true;
2223
1992
  if (sensitive && (rawOptions.valueJson !== undefined || rawOptions.preset !== undefined)) {
2224
- throw new Error('sensitiveConfigInputUnsupported: Sensitive config requires --value-stdin.');
1993
+ throw Object.assign(new WriteCommandRequestError('Sensitive config requires --value-stdin.'), { code: 'sensitiveConfigInputUnsupported' });
2225
1994
  }
2226
1995
  if (rawOptions.valueStdin)
2227
1996
  inputValue = await readUtf8Stdin(context.stdin);
@@ -2263,6 +2032,32 @@ export function buildProgram(options = {}) {
2263
2032
  inputValue = structuredClone(preset.value);
2264
2033
  }
2265
2034
  }
2035
+ if (command !== 'unset') {
2036
+ try {
2037
+ inputValue = (await coercePluginConfigUpdates({ schema: fields, updates: { [key]: inputValue }, cwd: context.cwd }))[key];
2038
+ }
2039
+ catch {
2040
+ throw new WriteCommandRequestError(`Invalid value for configuration field "${key}".`);
2041
+ }
2042
+ }
2043
+ try {
2044
+ await assertPluginConfigMutationCandidate({ sourceId: source.sourceId, sourceIdentity: source.sourceIdentity,
2045
+ logicalIdentity: source.logicalIdentity, pluginName: plugin.manifest.name, manifest: plugin.manifest,
2046
+ scope: work.context, platform, cwd: context.cwd, env: context.env,
2047
+ updates: command === 'unset' ? {} : { [key]: inputValue }, removeKeys: command === 'unset' ? [key] : [] });
2048
+ }
2049
+ catch (error) {
2050
+ if (error?.code === 'configReferenceInvalid')
2051
+ throw new WriteCommandRequestError(`Invalid value or reference for configuration field "${key}".`);
2052
+ throw error;
2053
+ }
2054
+ const mutation = command === 'unset' ? { kind: 'patch', removeKeys: [key] } : { kind: 'patch', updates: { [key]: inputValue } };
2055
+ const confirmation = rawOptions.apply ? await preparePublicConfigConfirmation({ plugin, scope: work.context,
2056
+ context: work.context, platform, cwd: context.cwd, env: context.env, cliVersion: resolveCliVersion(),
2057
+ nativeCliRunner: context.nativeCliRunner, awHomeMutationToken, yes: rawOptions.yes, mutation,
2058
+ rebuildRuntime: { ...context, awHomeMutationToken, catalogOperationContext,
2059
+ expectedGenerationSetDigest: catalogOperationContext.generationSetDigest } })
2060
+ : { required: false, provided: rawOptions.yes === true, effects: [] };
2266
2061
  const writeReceipt = await applyPluginConfigWrite({ plugin, pluginName: plugin.manifest.name,
2267
2062
  scope: work.context, context: work.context, platform, cliVersion: resolveCliVersion(),
2268
2063
  cwd: context.cwd, env: context.env, nativeCliRunner: context.nativeCliRunner,
@@ -2273,7 +2068,7 @@ export function buildProgram(options = {}) {
2273
2068
  apply: rawOptions.apply === true, sharedNativeApplyConfirmed: rawOptions.yes === true,
2274
2069
  preApplyConfirmed: rawOptions.yes === true });
2275
2070
  return buildConfigMutationReceipt(`config:${command}`, {
2276
- ...writeReceipt, ok: writeReceipt.overallState === 'succeeded', plugin: plugin.manifest.name,
2071
+ ...writeReceipt, confirmation, ok: writeReceipt.overallState === 'succeeded', plugin: plugin.manifest.name,
2277
2072
  pluginName: plugin.manifest.name, pluginId, sourceId: source.sourceId, sourceIdentity: source.sourceIdentity,
2278
2073
  context: work, platform: platform ?? 'common',
2279
2074
  ...(command === 'unset' ? { removedKey: key, existed: true } : {}),
@@ -2311,11 +2106,18 @@ export function buildProgram(options = {}) {
2311
2106
  return;
2312
2107
  }
2313
2108
  const located = await resolveStoredConfigResetIdentity({ selector, context, scope: 'user' });
2314
- const resetStore = async (plugin, pluginError) => resetPluginConfigWithHelper({ ...located, plugin, pluginError, platform, scope: work.context,
2315
- context: work.context, cliVersion: resolveCliVersion(), cwd: context.cwd, env: context.env,
2316
- nativeCliRunner: context.nativeCliRunner, apply: rawOptions.apply === true,
2317
- rebuildRuntime: { ...context, scriptTimeoutMs: resolveScriptTimeoutMs(rawOptions) },
2318
- sharedNativeApplyConfirmed: true, preApplyConfirmed: rawOptions.yes === true });
2109
+ const resetStore = async (plugin, pluginError) => withAwHomeMutationLock({ env: context.env, action: async (awHomeMutationToken) => {
2110
+ const confirmation = plugin && rawOptions.apply ? await preparePublicConfigConfirmation({ plugin,
2111
+ scope: work.context, context: work.context, platform, cwd: context.cwd, env: context.env,
2112
+ cliVersion: resolveCliVersion(), nativeCliRunner: context.nativeCliRunner, awHomeMutationToken,
2113
+ yes: rawOptions.yes, mutation: { kind: 'reset' }, rebuildRuntime: context }) : null;
2114
+ const receipt = await resetPluginConfigWithHelper({ ...located, plugin, pluginError, platform, scope: work.context,
2115
+ context: work.context, cliVersion: resolveCliVersion(), cwd: context.cwd, env: context.env, awHomeMutationToken,
2116
+ nativeCliRunner: context.nativeCliRunner, apply: rawOptions.apply === true,
2117
+ rebuildRuntime: { ...context, awHomeMutationToken, scriptTimeoutMs: resolveScriptTimeoutMs(rawOptions) },
2118
+ sharedNativeApplyConfirmed: true, preApplyConfirmed: rawOptions.yes === true });
2119
+ return { ...receipt, confirmation };
2120
+ } });
2319
2121
  let started = false;
2320
2122
  const resetReceipt = await runActionWithContext(context, async () => {
2321
2123
  try {
@@ -2351,14 +2153,16 @@ export function buildProgram(options = {}) {
2351
2153
  const context = createActionContext('config:apply', rawOptions);
2352
2154
  const work = await configContext(context, rawOptions, true);
2353
2155
  const targets = rawOptions.target?.map((target) => normalizeWriteRequest(() => parsePlatformTargetValue(target)));
2354
- const receipt = await runActionWithContext(context, () => withResolvedConfigMutationPlugin(context, selector, async ({ plugin, pluginId, source }, awHomeMutationToken) => ({
2355
- ...await applyPluginConfig({ plugin, scope: work.context, context: work.context, targets,
2356
- cliVersion: resolveCliVersion(), cwd: context.cwd, env: context.env, awHomeMutationToken,
2357
- nativeCliRunner: context.nativeCliRunner, sharedNativeApplyConfirmed: rawOptions.yes === true,
2358
- preApplyConfirmed: rawOptions.yes === true, rebuildRuntime: { ...context, scriptTimeoutMs: resolveScriptTimeoutMs(rawOptions) } }),
2359
- command: 'config:apply', plugin: plugin.manifest.name, pluginId, sourceId: source.sourceId,
2360
- context: work,
2361
- }), true));
2156
+ const receipt = await runActionWithContext(context, () => withResolvedConfigMutationPlugin(context, selector, async ({ plugin, pluginId, source }, awHomeMutationToken) => {
2157
+ const confirmation = await preparePublicConfigConfirmation({ plugin, scope: work.context, context: work.context, targets, cwd: context.cwd, env: context.env, cliVersion: resolveCliVersion(), nativeCliRunner: context.nativeCliRunner, awHomeMutationToken, yes: rawOptions.yes, rebuildRuntime: context });
2158
+ return { confirmation, ...await applyPluginConfig({ plugin, scope: work.context, context: work.context, targets,
2159
+ cliVersion: resolveCliVersion(), cwd: context.cwd, env: context.env, awHomeMutationToken,
2160
+ nativeCliRunner: context.nativeCliRunner, sharedNativeApplyConfirmed: rawOptions.yes === true,
2161
+ preApplyConfirmed: rawOptions.yes === true, rebuildRuntime: { ...context, scriptTimeoutMs: resolveScriptTimeoutMs(rawOptions) } }),
2162
+ command: 'config:apply', plugin: plugin.manifest.name, pluginId, sourceId: source.sourceId,
2163
+ context: work,
2164
+ };
2165
+ }, true));
2362
2166
  const result = buildConfigMutationReceipt('config:apply', { ...receipt,
2363
2167
  ok: receipt.overallState === 'succeeded' });
2364
2168
  if (rawOptions.json)
@@ -2369,407 +2173,506 @@ export function buildProgram(options = {}) {
2369
2173
  }
2370
2174
  commandExitState.exitCode = result.ok ? 0 : 1;
2371
2175
  });
2372
- contextualCommand(plugin.command('status'))
2373
- .description('Observe user and current project demand and output state')
2374
- .action(async (rawOptions) => {
2375
- const context = createActionContext('status', rawOptions);
2376
- await showWorkContext(context, rawOptions);
2377
- const result = await runActionWithContext(context, () => readRecoveryStatus({
2378
- context: recoveryContext(rawOptions), cwd: context.cwd, env: context.env, cliVersion: resolveCliVersion(),
2379
- nativeCliRunner: context.nativeCliRunner,
2380
- }));
2381
- if (rawOptions.json)
2382
- writeJsonReceipt(io.stdout, result);
2383
- else
2384
- renderRecoveryStatus(io.stdout, result);
2385
- commandExitState.exitCode = result.errors.length ? 1 : 0;
2386
- });
2176
+ configurePublicCommands(program, options, io, commandExitState);
2387
2177
  Object.assign(program, { __awCommandExitState: commandExitState });
2388
2178
  return program;
2389
2179
  }
2390
- function handleCliError(error, writeError) {
2391
- if (error instanceof CommanderError) {
2392
- return error.exitCode;
2393
- }
2394
- if (isCommandWarningError(error)) {
2395
- writeWarnings(writeError, error.warnings);
2396
- writeLine(writeError, error.message);
2397
- return error.exitCode;
2180
+ /** Invoke the packaged author tool. Its JSON remains an internal child-process protocol. */
2181
+ async function runAuthoringCliAdapter(argv, options) {
2182
+ const io = { ...createDefaultIo(), ...options.io };
2183
+ const authoringPluginCommand = argv[0] === 'plugin';
2184
+ const explicitWorkspace = argv.some((token) => token === '--workspace-root' || token.startsWith('--workspace-root='));
2185
+ const authoringScriptByCommand = {
2186
+ init: 'init-plugin.mjs',
2187
+ 'add-skill': 'add-skill.mjs',
2188
+ remove: 'remove-plugin.mjs',
2189
+ validate: 'validate-plugin.mjs',
2190
+ status: 'plugin-status.mjs',
2191
+ };
2192
+ const authoringScript = authoringPluginCommand
2193
+ ? authoringScriptByCommand[argv[1] ?? '']
2194
+ : argv[0] === 'skill' && argv[1] === 'validate'
2195
+ ? 'validate-skill.mjs'
2196
+ : undefined;
2197
+ if (authoringScript && ((!argv.includes('--help') && !argv.includes('-h'))
2198
+ || explicitWorkspace && ['remove', 'status'].includes(argv[1] ?? ''))) {
2199
+ const authoringArgs = argv.slice(2);
2200
+ let authoringEnv = options.env ?? process.env;
2201
+ if (argv[0] === 'plugin'
2202
+ && !authoringArgs.some((token) => token === '--plugin-root' || token.startsWith('--plugin-root='))) {
2203
+ let explicitRoot;
2204
+ for (let index = 0; index < authoringArgs.length; index += 1) {
2205
+ const token = authoringArgs[index];
2206
+ if (token.startsWith('--workspace-root='))
2207
+ explicitRoot = token.slice('--workspace-root='.length);
2208
+ if (token === '--workspace-root')
2209
+ explicitRoot = authoringArgs[index + 1];
2210
+ }
2211
+ const originalCwd = options.cwd ?? process.cwd();
2212
+ let discoveryCwd = originalCwd;
2213
+ if (argv[1] === 'validate') {
2214
+ const valueOptions = new Set(['--workspace-root', '--claude-skill-profile', '--version-base']);
2215
+ for (let index = 0; index < authoringArgs.length; index += 1) {
2216
+ const token = authoringArgs[index];
2217
+ if (valueOptions.has(token)) {
2218
+ index += 1;
2219
+ continue;
2220
+ }
2221
+ if (!token.startsWith('-')) {
2222
+ discoveryCwd = path.resolve(originalCwd, token);
2223
+ authoringArgs[index] = discoveryCwd;
2224
+ break;
2225
+ }
2226
+ }
2227
+ }
2228
+ const workspace = await resolveCatalogWorkspaceRoot({
2229
+ cwd: discoveryCwd,
2230
+ ...(explicitRoot === undefined ? {} : { explicitRoot: path.resolve(options.cwd ?? process.cwd(), explicitRoot) }),
2231
+ mode: 'existing',
2232
+ });
2233
+ authoringEnv = {
2234
+ ...authoringEnv,
2235
+ AW_AUTHORING_WORKSPACE_ROOT: workspace.workspaceRoot,
2236
+ AW_AUTHORING_WORKSPACE_ROOT_RESOLVED_FROM: workspace.workspaceRootResolvedFrom,
2237
+ };
2238
+ if (explicitRoot === undefined)
2239
+ authoringArgs.push('--workspace-root', workspace.workspaceRoot);
2240
+ }
2241
+ return runAuthoringScript({
2242
+ scriptName: authoringScript,
2243
+ args: authoringArgs,
2244
+ cwd: options.cwd ?? process.cwd(),
2245
+ env: authoringEnv,
2246
+ io,
2247
+ interruption: options.interruption,
2248
+ });
2398
2249
  }
2399
- writeLine(writeError, error instanceof Error ? error.message : String(error));
2400
- return 1;
2250
+ throw new Error('No authoring script is registered for this operation.');
2401
2251
  }
2402
- export async function runCli(argv, options = {}) {
2403
- const io = {
2404
- ...createDefaultIo(),
2405
- ...options.io,
2252
+ function sourceConfirmation(sourceId, yes, preview) {
2253
+ const required = preview !== undefined && (preview.identityChanged || !preview.references.inventoryComplete || preview.references.references.length > 0);
2254
+ return { required, provided: yes === true, effects: required ? [{ code: 'changeSource', message: 'Change the source used by the affected or unobserved plugin references.', subject: { sourceId }, impact: preview?.references.inventoryComplete ? 'shared' : 'unknown' }] : [] };
2255
+ }
2256
+ function commandId(command) {
2257
+ const names = [];
2258
+ for (let current = command; current?.parent; current = current.parent)
2259
+ names.unshift(current.name());
2260
+ return names.join('.');
2261
+ }
2262
+ function configurePublicCommands(program, options, io, exit) {
2263
+ const find = (parent, name) => {
2264
+ const result = parent.commands.find((entry) => entry.name() === name);
2265
+ if (!result)
2266
+ throw new Error(`Missing registered command: ${name}`);
2267
+ return result;
2406
2268
  };
2407
- if (argv[0] === 'command') {
2408
- return runManagedCommandCli(argv.slice(1), createCliExecutionContext({ ...options, io }), {
2409
- cliEntry: fileURLToPath(import.meta.url),
2410
- cliVersion: resolveCliVersion(),
2269
+ const plugin = find(program, 'plugin');
2270
+ const dev = find(program, 'dev');
2271
+ const devPlugin = find(dev, 'plugin');
2272
+ const catalog = find(dev, 'catalog');
2273
+ const source = find(program, 'source');
2274
+ const sourceUpdate = find(source, 'update');
2275
+ sourceUpdate.option('--primary', 'Make this source primary');
2276
+ const sourceStatus = find(source, 'status');
2277
+ sourceStatus.option('--remote', 'Check remote candidates without changing stored state');
2278
+ sourceStatus.action(async (id, raw) => {
2279
+ const env = options.env ?? process.env;
2280
+ const [observed, configured] = await Promise.all([catalogSourceStatusCommand({ sourceId: id, env }), listCatalogSources({ env })]);
2281
+ const result = { ...observed, primarySourceId: configured.primarySourceId, sources: observed.sources.map((source) => ({ ...source, configuration: configured.sources.find((entry) => entry.id === source.sourceId) ?? null })) };
2282
+ if (!raw.remote) {
2283
+ io.result?.(result);
2284
+ return;
2285
+ }
2286
+ const remote = await Promise.all(result.sources.map(async (source) => {
2287
+ try {
2288
+ const probe = await syncCatalogSourceCommand({ sourceId: source.sourceId, cliVersion: resolveCliVersion(), cwd: options.cwd, check: true, env });
2289
+ return { sourceId: source.sourceId, checked: true, candidate: probe.resolution, outcome: probe.outcome };
2290
+ }
2291
+ catch (error) {
2292
+ const safe = sanitizeCatalogSourceError(error, env);
2293
+ return { sourceId: source.sourceId, checked: false, error: { code: catalogGenerationErrorCode(error), message: safe.message } };
2294
+ }
2295
+ }));
2296
+ const failures = remote.filter((entry) => !entry.checked);
2297
+ const projected = projectReceipt('source.status', { ...result, remote, complete: failures.length === 0 });
2298
+ projected.diagnostics.push(...failures.map((entry) => ({ code: entry.error.code, severity: 'error', message: safePublicMessage(entry.error.message), subject: { sourceId: entry.sourceId } })));
2299
+ io.result?.(projected);
2300
+ });
2301
+ const context = (name, raw = {}) => createCliExecutionContext({ ...options, io, interactive: false, reporter: options.reporter ?? createNoopReporter(), diagnostics: toCliDiagnosticsOptions(name, raw, options.diagnostics) });
2302
+ for (const name of ['install', 'remove', 'sync']) {
2303
+ const cmd = plugin.command(name).argument(name === 'sync' ? '[plugins...]' : '<plugins...>');
2304
+ if (name !== 'sync')
2305
+ cmd.addOption(strictValueOption('--scope <scope>', 'Requirement or physical scope', ['user', 'project']).makeOptionMandatory());
2306
+ cmd.addOption(strictValueOption('--context <context>', 'User or current project context', ['user', 'project']))
2307
+ .option('--target <target>', 'Select an execution target', collectUniqueOption)
2308
+ .option('-y, --yes', 'Confirm the listed effects');
2309
+ if (name !== 'sync')
2310
+ cmd.addOption(strictValueOption('--only <mode>', 'Limit the effects', name === 'install' ? ['requirements'] : ['requirements', 'outputs']));
2311
+ if (name === 'remove')
2312
+ cmd.option('--delete-config', 'Delete all local plugin configuration').option('--force', 'Recover provably owned damaged output');
2313
+ if (name !== 'remove')
2314
+ cmd.option('--script-timeout <ms>', 'Plugin script timeout');
2315
+ if (name === 'sync')
2316
+ cmd.option('--rebuild', 'Rebuild selected owned output').option('--refresh', 'Refresh required Catalog sources');
2317
+ cmd.action(async (plugins, raw) => {
2318
+ io.result?.(await runPublicLifecycle(name, plugins, { ...raw, cwd: options.cwd ?? process.cwd(), env: options.env, cliVersion: resolveCliVersion() }, context(`plugin.${name}`, raw)));
2411
2319
  });
2412
2320
  }
2413
- const reviewCommand = argv[0] === 'review' && ['inspect', 'prepare'].includes(argv[1] ?? '')
2414
- ? argv[1]
2415
- : null;
2416
- const jsonReviewCommand = reviewCommand !== null && argv.includes('--json');
2417
- const jsonMaterialize = argv[0] === 'skill' && argv[1] === 'materialize'
2418
- && (argv.includes('--json') || argv.includes('-j'));
2419
- const jsonConfigCommand = jsonConfigReadRequested(argv);
2420
- const explicitWorkspace = argv.some((token) => token === '--workspace-root' || token.startsWith('--workspace-root='));
2421
- const authoringPluginCommand = argv[0] === 'plugin'
2422
- && (['build', 'test', 'validate', 'init', 'add-skill'].includes(argv[1] ?? '')
2423
- || ['remove', 'status'].includes(argv[1] ?? '') && explicitWorkspace);
2424
- const jsonAuthoringCommand = argv.includes('--json')
2425
- && ((argv[0] === 'catalog' && ['init', 'context', 'version', 'build', 'validate', 'status', 'publish'].includes(argv[1] ?? ''))
2426
- || authoringPluginCommand
2427
- || reviewCommand !== null)
2428
- ? `${argv[0]}:${argv[1]}`
2429
- : null;
2430
- const jsonCatalogDevCommand = argv.includes('--json')
2431
- && argv[0] === 'catalog'
2432
- && argv[1] === 'dev'
2433
- && ['activate', 'status', 'deactivate'].includes(argv[2] ?? '')
2434
- ? argv[2]
2435
- : null;
2436
- const recovery = recoveryRequest(argv);
2437
- const jsonRecoveryRequest = recovery?.json ? recovery : null;
2438
- const jsonConfigMutation = jsonConfigMutationRequest(argv);
2439
- try {
2440
- const authoringScriptByCommand = {
2441
- init: 'init-plugin.mjs',
2442
- 'add-skill': 'add-skill.mjs',
2443
- remove: 'remove-plugin.mjs',
2444
- validate: 'validate-plugin.mjs',
2445
- status: 'plugin-status.mjs',
2446
- };
2447
- const authoringScript = authoringPluginCommand
2448
- ? authoringScriptByCommand[argv[1] ?? '']
2449
- : argv[0] === 'skill' && argv[1] === 'validate'
2450
- ? 'validate-skill.mjs'
2451
- : undefined;
2452
- if (authoringScript && ((!argv.includes('--help') && !argv.includes('-h'))
2453
- || explicitWorkspace && ['remove', 'status'].includes(argv[1] ?? ''))) {
2454
- const authoringArgs = argv.slice(2);
2455
- let authoringEnv = options.env ?? process.env;
2456
- if (argv[0] === 'plugin'
2457
- && !authoringArgs.some((token) => token === '--plugin-root' || token.startsWith('--plugin-root='))) {
2458
- let explicitRoot;
2459
- for (let index = 0; index < authoringArgs.length; index += 1) {
2460
- const token = authoringArgs[index];
2461
- if (token.startsWith('--workspace-root='))
2462
- explicitRoot = token.slice('--workspace-root='.length);
2463
- if (token === '--workspace-root')
2464
- explicitRoot = authoringArgs[index + 1];
2465
- }
2466
- const originalCwd = options.cwd ?? process.cwd();
2467
- let discoveryCwd = originalCwd;
2468
- if (argv[1] === 'validate') {
2469
- const valueOptions = new Set(['--workspace-root', '--claude-skill-profile', '--version-base']);
2470
- for (let index = 0; index < authoringArgs.length; index += 1) {
2471
- const token = authoringArgs[index];
2472
- if (valueOptions.has(token)) {
2473
- index += 1;
2321
+ plugin.command('list').description('List available plugins or direct requirements')
2322
+ .option('--requested', 'List direct requirement roots')
2323
+ .addOption(strictValueOption('--scope <scope>', 'Requirement scope', ['user', 'project']))
2324
+ .action(async (raw) => { io.result?.(await runPublicPluginList({ ...raw, cwd: options.cwd ?? process.cwd(), env: options.env, cliVersion: resolveCliVersion() }, context('plugin.list', raw))); });
2325
+ plugin.command('show').description('Show one plugin').argument('<plugin>')
2326
+ .action(async (selector) => { io.result?.(await runPublicPluginShow(selector, { cwd: options.cwd ?? process.cwd(), env: options.env, cliVersion: resolveCliVersion() }, context('plugin.show'))); });
2327
+ plugin.command('status').description('Inspect requirements, outputs, and coverage').argument('[plugins...]')
2328
+ .addOption(strictValueOption('--context <context>', 'Observation context', ['user', 'project']))
2329
+ .action(async (plugins, raw) => { io.result?.(await runPublicPluginStatus(plugins, { ...raw, cwd: options.cwd ?? process.cwd(), env: options.env, cliVersion: resolveCliVersion() }, context('plugin.status', raw))); });
2330
+ devPlugin.command('remove').description('Delete one owned plugin source tree').argument('<plugin>')
2331
+ .option('--workspace-root <path>', 'Catalog Workspace root').option('-y, --yes', 'Confirm source deletion');
2332
+ devPlugin.command('status').description('Check source plugin version policy').argument('[plugin]')
2333
+ .option('--all', 'Check all source plugins').option('--base <ref>', 'Git comparison base').option('--workspace-root <path>', 'Catalog Workspace root');
2334
+ find(devPlugin, 'build').option('-y, --yes', 'Confirm replacement of generated output');
2335
+ find(catalog, 'build').option('-y, --yes', 'Confirm replacement of generated output');
2336
+ const scriptRoutes = {
2337
+ 'dev.plugin.create': ['plugin', 'init'], 'dev.plugin.validate': ['plugin', 'validate'],
2338
+ 'dev.plugin.remove': ['plugin', 'remove'], 'dev.plugin.status': ['plugin', 'status'],
2339
+ 'dev.skill.create': ['plugin', 'add-skill'], 'dev.skill.validate': ['skill', 'validate'],
2340
+ };
2341
+ const attach = (parent) => {
2342
+ for (const cmd of parent.commands) {
2343
+ const id = commandId(cmd);
2344
+ if (scriptRoutes[id])
2345
+ cmd.action(async (...args) => {
2346
+ const selected = args.at(-1);
2347
+ const raw = selected.opts();
2348
+ const tokens = [...scriptRoutes[id], ...(id === 'dev.skill.create' ? [String(raw.plugin)] : selected.args)];
2349
+ for (const option of selected.options) {
2350
+ const value = selected.getOptionValue(option.attributeName());
2351
+ if (['json', 'plugin', 'verbose', 'debug', 'logFile'].includes(option.attributeName()) || value === undefined || value === false && !option.negate || value === true && option.negate)
2474
2352
  continue;
2353
+ tokens.push(option.long);
2354
+ if (value !== true && !option.negate)
2355
+ tokens.push(String(value));
2356
+ }
2357
+ const hasProtocol = !['dev.plugin.create', 'dev.skill.create'].includes(id);
2358
+ if (hasProtocol)
2359
+ tokens.push('--json');
2360
+ if (['dev.plugin.remove', 'dev.plugin.status'].includes(id) && !raw.workspaceRoot) {
2361
+ const workspace = await resolveCatalogWorkspaceRoot({ cwd: options.cwd ?? process.cwd(), mode: 'existing', env: options.env });
2362
+ tokens.push('--workspace-root', workspace.workspaceRoot);
2363
+ }
2364
+ let protocol = '';
2365
+ let scriptDiagnostics = '';
2366
+ exit.exitCode = await runAuthoringCliAdapter(tokens, { ...options, interactive: false, io: { stdout: (text) => { if (hasProtocol)
2367
+ protocol += text;
2368
+ else
2369
+ io.stderr(text); }, stderr: (text) => { scriptDiagnostics += text; io.stderr(text); } } });
2370
+ if (hasProtocol && protocol.trim()) {
2371
+ let value;
2372
+ try {
2373
+ value = JSON.parse(protocol);
2475
2374
  }
2476
- if (!token.startsWith('-')) {
2477
- discoveryCwd = path.resolve(originalCwd, token);
2478
- authoringArgs[index] = discoveryCwd;
2479
- break;
2375
+ catch {
2376
+ throw new Error('The authoring tool returned invalid structured output.');
2480
2377
  }
2378
+ io.result?.(value);
2481
2379
  }
2482
- }
2483
- const workspace = await resolveCatalogWorkspaceRoot({
2484
- cwd: discoveryCwd,
2485
- ...(explicitRoot === undefined ? {} : { explicitRoot: path.resolve(options.cwd ?? process.cwd(), explicitRoot) }),
2486
- mode: 'existing',
2380
+ else
2381
+ io.result?.({ ok: exit.exitCode === 0, pluginName: raw.plugin ?? selected.args[0], workspaceRoot: raw.workspaceRoot ?? options.cwd, ...(exit.exitCode ? { errors: [{ code: 'authoringFailed', message: scriptDiagnostics.trim() || 'The authoring tool did not complete.' }] } : {}) });
2487
2382
  });
2488
- authoringEnv = {
2489
- ...authoringEnv,
2490
- AW_AUTHORING_WORKSPACE_ROOT: workspace.workspaceRoot,
2491
- AW_AUTHORING_WORKSPACE_ROOT_RESOLVED_FROM: workspace.workspaceRootResolvedFrom,
2492
- };
2493
- if (explicitRoot === undefined)
2494
- authoringArgs.push('--workspace-root', workspace.workspaceRoot);
2495
- }
2496
- return runAuthoringScript({
2497
- scriptName: authoringScript,
2498
- args: authoringArgs,
2499
- cwd: options.cwd ?? process.cwd(),
2500
- env: authoringEnv,
2501
- io,
2502
- });
2383
+ if (!cmd.options.some((option) => option.long === '--json'))
2384
+ cmd.option('-j, --json', 'Output one JSON result');
2385
+ const json = cmd.options.find((option) => option.long === '--json');
2386
+ json.makeOptionMandatory(false);
2387
+ if (!json.short)
2388
+ json.short = '-j';
2389
+ if (!cmd.options.some((option) => option.long === '--verbose'))
2390
+ cmd.option('-v, --verbose', 'Show additional details');
2391
+ if (!cmd.options.some((option) => option.long === '--debug'))
2392
+ cmd.option('-D, --debug', 'Write diagnostic logs');
2393
+ if (!cmd.options.some((option) => option.long === '--log-file'))
2394
+ cmd.option('--log-file <path>', 'Diagnostic log path');
2395
+ attach(cmd);
2503
2396
  }
2504
- if (!jsonConfigMutation
2505
- && argv.some((token) => token === '--subdir' || token.startsWith('--subdir='))
2506
- && argv.includes('--no-subdir')) {
2507
- const message = 'option --subdir cannot be used with option --no-subdir';
2508
- if (argv.includes('--json') && argv[0] === 'catalog' && argv[1] === 'source' && argv[2] === 'update') {
2509
- writeJsonReceipt(io.stdout, {
2510
- receiptSchemaVersion: 6,
2511
- command: 'catalog:source:update',
2512
- ok: false,
2513
- changed: false,
2514
- sourceId: argv[3] ?? '',
2515
- primaryChange: null,
2516
- references: [],
2517
- errors: [{ code: 'catalogSourceOptionConflict', message }],
2518
- });
2519
- }
2520
- writeLine(io.stderr, `error: ${message}`);
2521
- return 1;
2397
+ };
2398
+ 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');
2399
+ program.command('tui').description('Open the interactive console').action(() => undefined);
2400
+ attach(program);
2401
+ program.hook('preAction', (_root, action) => { action.setOptionValue('json', true); });
2402
+ }
2403
+ function resolveRegisteredCommand(program, argv) {
2404
+ let current = program;
2405
+ let commandIndex = -1;
2406
+ for (let index = 0; index < argv.length; index++) {
2407
+ const token = argv[index];
2408
+ if (token === '--')
2409
+ break;
2410
+ if (token.startsWith('-')) {
2411
+ const option = [...current.options, ...program.options].find((candidate) => candidate.long === token.split('=')[0] || candidate.short === token);
2412
+ if (option?.required && !token.includes('='))
2413
+ index++;
2414
+ continue;
2522
2415
  }
2523
- if (argv[0] === 'catalog' && argv[1] === 'source' && argv[2] === 'update'
2524
- && argv.includes('--auto-check') && argv.includes('--no-auto-check')) {
2525
- const message = 'option --auto-check cannot be used with option --no-auto-check';
2526
- if (argv.includes('--json') || argv.includes('-j')) {
2527
- writeJsonReceipt(io.stdout, {
2528
- receiptSchemaVersion: 6,
2529
- command: 'catalog:source:update',
2530
- ok: false,
2531
- changed: false,
2532
- sourceId: argv[3] ?? '',
2533
- primaryChange: null,
2534
- references: [],
2535
- errors: [{ code: 'catalogSourceOptionConflict', message }],
2536
- });
2537
- }
2538
- writeLine(io.stderr, `error: ${message}`);
2539
- return 1;
2416
+ const child = current.commands.find((entry) => entry.name() === token);
2417
+ if (child) {
2418
+ current = child;
2419
+ commandIndex = index;
2540
2420
  }
2541
- const bareConsoleOptions = parseBareConsoleOptions(argv);
2542
- if (bareConsoleOptions) {
2543
- const context = createCliExecutionContext({
2544
- ...options,
2545
- io,
2546
- env: options.env ?? process.env,
2547
- diagnostics: {
2548
- ...toCliDiagnosticsOptions('console', bareConsoleOptions, options.diagnostics),
2549
- metadata: {
2550
- ...options.diagnostics?.metadata,
2551
- argCount: argv.length,
2552
- },
2553
- },
2554
- });
2555
- if (!context.interactive) {
2556
- writeLine(io.stderr, formatInteractiveConsoleUnavailableMessage(context));
2557
- return 1;
2558
- }
2559
- return await runActionWithContext(context, () => runConsoleController(context));
2421
+ else if (current.commands.length === 0 || current.registeredArguments.length > 0)
2422
+ break;
2423
+ else
2424
+ return { command: null, index: commandIndex };
2425
+ }
2426
+ return { command: current, index: commandIndex };
2427
+ }
2428
+ function helpResult(program, selected) {
2429
+ return commandResult('help', {
2430
+ command: commandId(selected) || 'aw', description: selected.description(),
2431
+ arguments: selected.registeredArguments.map((argument) => ({ name: argument.name(), required: argument.required, variadic: argument.variadic, description: argument.description })),
2432
+ options: [...selected.options, ...(selected === program ? [] : program.options)].map((option) => ({ flags: option.flags, description: option.description, required: option.mandatory, choices: option.argChoices ?? null, conflicts: [] })),
2433
+ commands: selected.commands.map((command) => ({ command: commandId(command), description: command.description() })),
2434
+ resultSchema: { schemaVersion: 1, statuses: ['success', 'partial', 'blocked', 'failed'] },
2435
+ 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 requires --only outputs.', '--delete-config cannot use --only.'] : [],
2436
+ effects: selected.options.some((option) => option.long === '--yes') ? ['Important effects require --yes.'] : [],
2437
+ examples: [selected === program ? ['aw', 'plugin', 'list'] : ['aw', ...commandId(selected).split('.'), '--help']],
2438
+ });
2439
+ }
2440
+ function scanPresentation(program, argv) {
2441
+ const result = { json: false, help: false, version: false };
2442
+ let command = program;
2443
+ for (let index = 0; index < argv.length; index++) {
2444
+ const token = argv[index];
2445
+ if (token === '--')
2446
+ break;
2447
+ if (!token.startsWith('-')) {
2448
+ command = command.commands.find((entry) => entry.name() === token) ?? command;
2449
+ continue;
2560
2450
  }
2561
- let catalogPublicationActionStarted = false;
2562
- let configMutationActionStarted = false;
2563
- const programIo = jsonCatalogDevCommand || jsonRecoveryRequest || jsonReviewCommand || jsonMaterialize || jsonConfigCommand
2564
- ? { ...io, stderr: () => undefined }
2565
- : jsonConfigMutation
2566
- ? {
2567
- ...io,
2568
- stderr: (text) => {
2569
- if (configMutationActionStarted)
2570
- io.stderr(text);
2571
- },
2572
- }
2573
- : jsonAuthoringCommand === 'catalog:publish'
2574
- ? {
2575
- ...io,
2576
- stderr: (text) => {
2577
- if (catalogPublicationActionStarted)
2578
- io.stderr(text);
2579
- },
2580
- }
2581
- : io;
2582
- const program = buildProgram({
2583
- ...options,
2584
- io: programIo,
2585
- diagnostics: {
2586
- ...options.diagnostics,
2587
- metadata: {
2588
- ...options.diagnostics?.metadata,
2589
- argCount: argv.length,
2590
- },
2591
- },
2592
- });
2593
- if (jsonAuthoringCommand === 'catalog:publish') {
2594
- program.hook('preAction', () => {
2595
- catalogPublicationActionStarted = true;
2596
- });
2451
+ const available = [...command.options, ...program.options];
2452
+ if (token.startsWith('--')) {
2453
+ const flag = token.split('=')[0];
2454
+ const option = available.find((entry) => entry.long === flag);
2455
+ if (flag === '--json')
2456
+ result.json = true;
2457
+ if (flag === '--help')
2458
+ result.help = true;
2459
+ if (flag === '--version' && !option?.required)
2460
+ result.version = true;
2461
+ if (option?.required && !token.includes('='))
2462
+ index++;
2597
2463
  }
2598
- if (jsonConfigMutation) {
2599
- program.hook('preAction', () => {
2600
- configMutationActionStarted = true;
2601
- });
2464
+ else {
2465
+ for (let offset = 1; offset < token.length; offset++) {
2466
+ const flag = `-${token[offset]}`;
2467
+ const option = available.find((entry) => entry.short === flag);
2468
+ if (flag === '-j')
2469
+ result.json = true;
2470
+ if (flag === '-h')
2471
+ result.help = true;
2472
+ if (flag === '-V')
2473
+ result.version = true;
2474
+ if (option?.required) {
2475
+ if (offset === token.length - 1)
2476
+ index++;
2477
+ break;
2478
+ }
2479
+ }
2602
2480
  }
2603
- await program.parseAsync(['node', 'aw', ...argv]);
2604
- return program.__awCommandExitState?.exitCode ?? 0;
2605
2481
  }
2606
- catch (error) {
2607
- if (jsonMaterialize && error instanceof CommanderError) {
2608
- if (error.exitCode === 0)
2609
- return 0;
2610
- writeJsonReceipt(io.stdout, {
2611
- receiptSchemaVersion: 5, command: 'skill:materialize', ok: false,
2612
- selectedSkills: [], dependencies: [], configDigest: null, materializationDigest: null,
2613
- outputDigest: null, errors: [{ code: 'invalidArguments', message: error.message }],
2614
- });
2615
- return 2;
2616
- }
2617
- if (reviewCommand && error instanceof CommanderError) {
2618
- if (error.exitCode === 0)
2619
- return 0;
2620
- if (jsonReviewCommand) {
2621
- const receipt = reviewCommand === 'inspect'
2622
- ? createReviewInspectionFailure(new Error(error.message), 'invalidArguments')
2623
- : createReviewPreparationFailure(error.message);
2624
- writeJsonReceipt(io.stdout, receipt);
2625
- }
2626
- return 2;
2627
- }
2628
- if (jsonCatalogDevCommand) {
2629
- const workspaceRootIndex = argv.findIndex((token) => token === '--workspace-root');
2630
- const workspaceRootOption = argv.find((token) => token.startsWith('--workspace-root='));
2631
- const workspaceRoot = workspaceRootOption?.slice('--workspace-root='.length)
2632
- ?? (workspaceRootIndex >= 0 ? argv[workspaceRootIndex + 1] : undefined);
2633
- const sourceIdIndex = argv.findIndex((token) => token === '--source-id');
2634
- const sourceIdOption = argv.find((token) => token.startsWith('--source-id='));
2635
- const sourceId = sourceIdOption?.slice('--source-id='.length)
2636
- ?? (sourceIdIndex >= 0 ? argv[sourceIdIndex + 1] : undefined);
2637
- const failure = error instanceof CommanderError
2638
- ? { code: 'invalidArguments', message: error.message }
2639
- : catalogDevSourceError(error);
2640
- writeJsonReceipt(io.stdout, createCatalogDevFailureReceipt({
2641
- command: jsonCatalogDevCommand,
2642
- cwd: options.cwd ?? process.cwd(),
2643
- workspaceRoot,
2644
- sourceId,
2645
- ...failure,
2646
- }));
2647
- return 1;
2648
- }
2649
- if (jsonConfigCommand && !jsonConfigMutation) {
2650
- if (error instanceof CommanderError && error.exitCode === 0)
2651
- return 0;
2652
- const failure = configMutationFailure(error, options.env ?? process.env, options.cwd ?? process.cwd());
2653
- writeJsonReceipt(io.stdout, { ok: false, command: `config:${argv[2] ?? ''}`, errors: [failure] });
2654
- return failure.code === 'invalidArguments' ? 2 : 1;
2655
- }
2656
- if (recovery) {
2657
- if (error instanceof CommanderError && error.exitCode === 0)
2658
- return 0;
2659
- const failure = writeCommandFailure(error);
2660
- if (argv[0] === 'project' || argv.some((value) => value === '-p' || value === '--platform' || value.startsWith('--platform='))) {
2661
- failure.message += '\n使用 aw plugin intent、aw plugin targets 或 aw plugin install/remove/sync/cleanup/status。安装归属使用 --scope;工作上下文使用 --context。';
2482
+ return result;
2483
+ }
2484
+ export async function runCli(argv, options = {}) {
2485
+ const interruption = createPublicCommandInterruption();
2486
+ const io = { ...createDefaultIo(), ...options.io };
2487
+ const delimiter = argv.indexOf('--');
2488
+ const awArgs = delimiter < 0 ? argv : argv.slice(0, delimiter);
2489
+ const context = createCliExecutionContext({ ...options, io });
2490
+ let receipt;
2491
+ const stderr = [];
2492
+ const commandOptions = { ...options, interactive: false, io: {
2493
+ stdout: (text) => { stderr.push(text); }, stderr: (text) => { stderr.push(text); }, result: (value) => { receipt = value; },
2494
+ } };
2495
+ const program = buildProgram(commandOptions);
2496
+ const presentation = scanPresentation(program, awArgs);
2497
+ const json = presentation.json;
2498
+ const resolvedCommand = resolveRegisteredCommand(program, awArgs);
2499
+ const selected = resolvedCommand.command;
2500
+ const id = selected && selected !== program ? commandId(selected) : null;
2501
+ const controlledInterrupt = ['plugin.install', 'plugin.remove', 'plugin.sync',
2502
+ 'dev.plugin.create', 'dev.plugin.validate', 'dev.plugin.remove', 'dev.plugin.status',
2503
+ 'dev.skill.create', 'dev.skill.validate'].includes(id ?? '');
2504
+ if (controlledInterrupt) {
2505
+ commandOptions.interruption = interruption;
2506
+ commandOptions.signal = interruption.signal;
2507
+ }
2508
+ if (id === 'command.run' && !presentation.help)
2509
+ return runManagedCommandCli(['run', ...argv.slice(resolvedCommand.index + 1)], { ...context, interactive: false }, { cliEntry: fileURLToPath(import.meta.url), cliVersion: resolveCliVersion() });
2510
+ let confirmation = null;
2511
+ const emit = (result, invalid = false) => {
2512
+ if (result.diagnostics.some((diagnostic) => diagnostic.code === 'catalogWorkspaceMissing')) {
2513
+ const workspaceRoot = selected?.getOptionValue('workspaceRoot');
2514
+ result.nextActions = result.nextActions.filter((action) => action.kind !== 'command'
2515
+ || action.argv.slice(0, 4).join(' ') !== 'aw dev catalog create');
2516
+ result.nextActions.push({ kind: 'command',
2517
+ argv: ['aw', 'dev', 'catalog', 'create', ...(typeof workspaceRoot === 'string' ? ['--workspace-root', workspaceRoot] : [])],
2518
+ reason: 'Create a Catalog Workspace explicitly before running authoring commands.', requiresConfirmation: false });
2519
+ }
2520
+ io.stdout(json ? `${JSON.stringify(result)}\n` : renderPublicResult(result, awArgs.includes('--verbose') || awArgs.includes('-v')));
2521
+ for (const diagnostic of result.diagnostics)
2522
+ io.stderr(`${diagnostic.code}: ${diagnostic.message}\n`);
2523
+ if (options.diagnostics?.verbose || awArgs.includes('--verbose'))
2524
+ for (const line of stderr)
2525
+ io.stderr(`${safePublicMessage(line.trim())}\n`);
2526
+ return interruption.exitCode ? interruption.cleanupFailed ? 1 : interruption.exitCode : publicExitCode(result, invalid);
2527
+ };
2528
+ if (presentation.version)
2529
+ return emit(commandResult('version', { version: resolveCliVersion(), resultSchemaVersion: 1 }));
2530
+ if (selected && presentation.help || argv.length === 0 && !context.interactive || selected === program && json) {
2531
+ const target = selected ?? program;
2532
+ if (!json) {
2533
+ target.configureOutput({ writeOut: io.stdout });
2534
+ target.outputHelp();
2535
+ return 0;
2536
+ }
2537
+ return emit(helpResult(program, target));
2538
+ }
2539
+ let bareOptions;
2540
+ try {
2541
+ bareOptions = parseBareConsoleOptions(argv);
2542
+ }
2543
+ catch {
2544
+ return emit(commandResult(null, {}, { status: 'failed', diagnostics: [{ code: 'invalidArguments', severity: 'error', message: 'A diagnostic option requires a value.' }] }), true);
2545
+ }
2546
+ if (bareOptions !== null || id === 'tui') {
2547
+ if (id === 'tui') {
2548
+ try {
2549
+ await program.parseAsync(['node', 'aw', ...argv]);
2662
2550
  }
2663
- if (jsonRecoveryRequest) {
2664
- if (recovery.command === 'status')
2665
- writeJsonReceipt(io.stdout, {
2666
- schemaVersion: 1, kind: 'aw-recovery-status', scope: recovery.scope, ok: false,
2667
- intent: { state: 'unreadable', roots: null },
2668
- selection: { agents: [], origin: 'none', preferences: 'unreadable' },
2669
- inventory: null, extraObserved: [], coverage: null, counts: null, allSatisfied: null,
2670
- errors: [failure],
2671
- });
2672
- else
2673
- writeJsonReceipt(io.stdout, { ...recoveryFailureReceipt(recovery.command, recovery.scope, error),
2674
- blockers: [failure], errors: [failure] });
2551
+ catch {
2552
+ return emit(commandResult('tui', {}, { status: 'failed', diagnostics: [{ code: 'invalidArguments', severity: 'error', message: 'Invalid TUI arguments.' }] }), true);
2675
2553
  }
2676
- else
2677
- writeLine(io.stderr, failure.message);
2678
- return failure.code === 'invalidArguments' ? 2 : 1;
2679
- }
2680
- if (jsonConfigMutation) {
2681
- if (error instanceof CommanderError && error.exitCode === 0)
2682
- return 0;
2683
- const failure = configMutationFailure(error, options.env ?? process.env, options.cwd ?? process.cwd());
2684
- writeConfigMutationFailureReceipt(io.stdout, error instanceof CommanderError
2685
- ? { command: jsonConfigMutation.command }
2686
- : jsonConfigMutation, failure);
2687
- writeLine(io.stderr, failure.message);
2688
- return failure.code === 'invalidArguments' ? 2 : 1;
2689
2554
  }
2690
- if ((argv[0] === 'plugin' && argv[1] === 'config'
2691
- || argv[0] === 'skill' && argv[1] === 'materialize')
2692
- && (error instanceof CommanderError || error instanceof WriteCommandRequestError)) {
2693
- if (error instanceof CommanderError)
2694
- return error.exitCode === 0 ? 0 : 2;
2695
- writeLine(io.stderr, error.message);
2696
- return 2;
2555
+ if (json)
2556
+ return emit(commandResult('tui', {}, { status: 'failed', diagnostics: [{ code: 'invalidOptionCombination', severity: 'error', message: 'tui cannot use --json.' }] }), true);
2557
+ if (!context.interactive)
2558
+ return emit(commandResult('tui', {}, { status: 'blocked', diagnostics: [{ code: 'interactiveTerminalRequired', severity: 'error', message: 'The TUI requires an interactive terminal.' }] }));
2559
+ const tuiContext = createCliExecutionContext({ ...options, io, diagnostics: toCliDiagnosticsOptions('console', bareOptions ?? {}, options.diagnostics) });
2560
+ try {
2561
+ return await runActionWithContext(tuiContext, () => runConsoleController(tuiContext));
2697
2562
  }
2698
- if (jsonAuthoringCommand === 'catalog:publish' && error instanceof CommanderError) {
2699
- const failure = catalogPublicationFailure({
2700
- error: new CatalogPublicationInspectionError('invalidArguments', error.message),
2701
- env: options.env,
2702
- sensitiveRoots: [options.cwd ?? process.cwd()],
2703
- });
2704
- writeJsonReceipt(io.stdout, failure);
2705
- writeLine(io.stderr, failure.message);
2706
- return 1;
2563
+ catch (error) {
2564
+ return emit(commandResult('tui', {}, { status: 'failed', diagnostics: [{ code: 'tuiFailed', severity: 'error', message: safePublicMessage(error instanceof Error ? error.message : String(error)) }] }));
2707
2565
  }
2708
- if (jsonAuthoringCommand && !(error instanceof CommanderError)) {
2709
- const message = error instanceof Error ? error.message : String(error);
2710
- if (jsonAuthoringCommand === 'plugin:validate') {
2711
- writeJsonReceipt(io.stdout, {
2712
- ok: false,
2713
- profile: 'unknown',
2714
- warnings: [],
2715
- errors: [message],
2716
- });
2717
- }
2718
- else if (jsonAuthoringCommand === 'plugin:status') {
2719
- writeJsonReceipt(io.stdout, {
2720
- schemaVersion: 3,
2721
- policy: 'development',
2722
- ok: false,
2723
- base: null,
2724
- requestedBase: null,
2725
- baseCommit: null,
2726
- checkedPlugins: 0,
2727
- checks: [],
2728
- workspaceRoot: null,
2729
- workspaceRootResolvedFrom: null,
2730
- errors: [{ code: 'workspaceResolutionFailed', message }],
2731
- });
2732
- }
2733
- else if (jsonAuthoringCommand === 'plugin:remove') {
2734
- writeJsonReceipt(io.stdout, {
2735
- schemaVersion: 1,
2736
- command: 'plugin:remove',
2737
- ok: false,
2738
- workspaceRoot: null,
2739
- workspaceRootResolvedFrom: null,
2740
- baseCommit: null,
2741
- plugin: null,
2742
- removed: false,
2743
- errors: [{ code: 'workspaceResolutionFailed', message }],
2744
- });
2745
- }
2746
- else if (jsonAuthoringCommand === 'review:inspect') {
2747
- writeJsonReceipt(io.stdout, createReviewInspectionFailure(error));
2748
- }
2749
- else if (jsonAuthoringCommand === 'review:prepare') {
2750
- writeJsonReceipt(io.stdout, createReviewPreparationFailure(message, 'reviewPreparationFailed'));
2566
+ }
2567
+ // Only these adapters carry cancellation through every long-running child.
2568
+ // Other routes retain Node's normal signal termination until their domain
2569
+ // runner provides the same cleanup contract. Managed run and TUI exited above.
2570
+ const stopListening = controlledInterrupt ? interruption.listen() : () => undefined;
2571
+ try {
2572
+ program.hook('preAction', (_root, command) => {
2573
+ interruption.signal.throwIfAborted();
2574
+ const raw = command.opts();
2575
+ const current = commandId(command);
2576
+ if (current === 'dev.eval.prepare')
2577
+ for (const field of ['runs', 'timeoutMs'])
2578
+ if (raw[field] !== undefined && (!/^[1-9][0-9]*$/u.test(raw[field]) || !Number.isSafeInteger(Number(raw[field]))))
2579
+ throw new WriteCommandRequestError(`${field} must be a positive safe integer.`);
2580
+ if (current === 'dev.plugin.capabilities' && raw.surface !== undefined)
2581
+ normalizeWriteRequest(() => parsePluginCapabilitySurface(raw.surface));
2582
+ if (current === 'dev.catalog.version') {
2583
+ const version = command.args[0];
2584
+ if (version && raw.bump)
2585
+ throw new WriteCommandRequestError('Choose an exact version or --bump, not both.');
2586
+ if (raw.bump && !['patch', 'minor', 'major'].includes(raw.bump))
2587
+ throw new WriteCommandRequestError('--bump must be patch, minor, or major.');
2588
+ 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))
2589
+ throw new WriteCommandRequestError('Use a stable version or x.y.z-beta.N.');
2751
2590
  }
2752
- else {
2753
- writeJsonReceipt(io.stdout, {
2754
- command: jsonAuthoringCommand,
2755
- ok: false,
2756
- errors: [{ code: 'workspaceResolutionFailed', message }],
2757
- });
2591
+ if (current === 'source.add' && ((raw.git === undefined) === (raw.path === undefined)))
2592
+ throw new WriteCommandRequestError('Choose exactly one of --git or --path.');
2593
+ if (current === 'source.update' && awArgs.includes('--auto-check') && awArgs.includes('--no-auto-check'))
2594
+ throw new WriteCommandRequestError('--auto-check cannot use --no-auto-check.');
2595
+ if (current === 'source.update' && raw.subdir !== undefined && awArgs.includes('--no-subdir') && awArgs.some((arg) => arg === '--subdir' || arg.startsWith('--subdir=')))
2596
+ throw new WriteCommandRequestError('--subdir cannot use --no-subdir.');
2597
+ if (current === 'plugin.config.set' && [raw.valueJson !== undefined, raw.valueStdin === true, raw.preset !== undefined].filter(Boolean).length !== 1)
2598
+ throw new WriteCommandRequestError('Choose exactly one of --value-json, --value-stdin, or --preset.');
2599
+ let effect;
2600
+ if (current === 'plugin.config.reset')
2601
+ effect = { code: 'deletePluginConfig', message: 'Delete the selected local plugin configuration.', subject: { pluginId: command.args[0], scope: 'user' }, impact: 'user-wide' };
2602
+ if (current === 'dev.plugin.remove')
2603
+ effect = { code: 'deletePluginSource', message: 'Delete the selected plugin source tree.', subject: { pluginId: command.args[0] }, impact: 'selected-scope' };
2604
+ if (current === 'dev.catalog.publish.apply' && !/^sha256:[0-9a-f]{64}$/u.test(raw.expectedPlanDigest ?? ''))
2605
+ throw new WriteCommandRequestError('Use the exact --expected-plan-digest returned by dev catalog publish plan.');
2606
+ if (current === 'dev.catalog.publish.apply')
2607
+ effect = { code: 'publishRemote', message: 'Publish the prepared Catalog to the remote.', impact: 'shared' };
2608
+ if ((current === 'dev.catalog.build' || current === 'dev.plugin.build') && raw.force)
2609
+ effect = { code: 'removeOwnedOutput', message: 'Replace existing generated output.', impact: 'selected-scope' };
2610
+ if (effect) {
2611
+ confirmation = { required: true, provided: raw.yes === true, effects: [effect] };
2612
+ if (!raw.yes)
2613
+ throw Object.assign(new Error('Repeat the command with --yes to confirm the listed effects.'), { code: 'confirmationRequired' });
2758
2614
  }
2759
- return 1;
2760
- }
2761
- if (jsonAuthoringCommand && error instanceof CommanderError) {
2762
- writeJsonReceipt(io.stdout, jsonAuthoringCommand === 'review:inspect'
2763
- ? createReviewInspectionFailure(new Error(error.message), 'invalidArguments')
2764
- : jsonAuthoringCommand === 'review:prepare'
2765
- ? createReviewPreparationFailure(error.message)
2766
- : {
2767
- command: jsonAuthoringCommand,
2768
- ok: false,
2769
- errors: [{ code: 'invalidArguments', message: error.message }],
2770
- });
2771
- }
2772
- return handleCliError(error, io.stderr);
2615
+ });
2616
+ await program.parseAsync(['node', 'aw', ...argv]);
2617
+ const exitCode = program.__awCommandExitState.exitCode;
2618
+ if (receipt === undefined) {
2619
+ if (selected?.commands.length)
2620
+ return emit(helpResult(program, selected));
2621
+ throw new Error('The command did not return a result.');
2622
+ }
2623
+ if (id === 'dev.plugin.test' && receipt && typeof receipt === 'object') {
2624
+ const logs = receipt;
2625
+ if (typeof logs.stdout === 'string')
2626
+ io.stderr(redactString(logs.stdout));
2627
+ if (typeof logs.stderr === 'string')
2628
+ io.stderr(redactString(logs.stderr));
2629
+ }
2630
+ const result = projectReceipt(id, receipt, { yes: awArgs.includes('--yes') || awArgs.includes('-y'), exitCode, confirmation });
2631
+ if (interruption.exitCode)
2632
+ result.diagnostics.push({ code: interruption.cleanupFailed ? 'processCleanupUnconfirmed' : 'operationInterrupted', severity: 'error', message: interruption.cleanupFailed ? 'Process cleanup could not be confirmed after interruption.' : 'The command was interrupted. Completed changes are retained in the result.' });
2633
+ if (result.status === 'success' && ['dev.plugin.create', 'dev.skill.create'].includes(id)) {
2634
+ const data = result.data;
2635
+ const name = typeof data.pluginName === 'string' ? data.pluginName : selected?.args[0];
2636
+ if (name)
2637
+ for (const action of ['validate', 'test', 'build'])
2638
+ result.nextActions.push({ kind: 'command', argv: ['aw', 'dev', 'plugin', action, `plugins/${name}`], reason: 'Check and build the new source.', requiresConfirmation: false });
2639
+ result.nextActions.push({ kind: 'command', argv: ['aw', 'dev', 'catalog', 'build'], reason: 'Build the Catalog after checking the source.', requiresConfirmation: false });
2640
+ }
2641
+ const invalid = result.diagnostics.some((diagnostic) => /invalidArguments|invalidOption|missingArgument|sensitiveConfigInputUnsupported/u.test(diagnostic.code));
2642
+ if (invalid && result.status !== 'partial') {
2643
+ result.status = 'failed';
2644
+ result.data = {};
2645
+ }
2646
+ return emit(result, invalid);
2647
+ }
2648
+ catch (error) {
2649
+ if (error instanceof CommanderError && error.exitCode === 0)
2650
+ return emit(helpResult(program, selected ?? program));
2651
+ const argumentError = error instanceof CommanderError || error instanceof WriteCommandRequestError;
2652
+ const raw = id?.startsWith('plugin.config.') && !(error instanceof CommanderError) && !(error instanceof WriteCommandRequestError)
2653
+ ? configMutationFailure(error, options.env ?? process.env, options.cwd ?? process.cwd())
2654
+ : error;
2655
+ const code = argumentError ? error instanceof InvalidArgumentError || error instanceof CommanderError && error.code === 'commander.invalidArgument' ? 'invalidOptionValue' : 'invalidArguments' : raw.code ?? catalogGenerationErrorCode(error);
2656
+ const blocked = code === 'confirmationRequired' || /unavailable|missing|stale|conflict|unsupported|identityMismatch/iu.test(code);
2657
+ let message = raw.message ?? 'The operation failed.';
2658
+ if (error instanceof CommanderError) {
2659
+ const field = raw.message?.match(/--([a-z][a-z-]*)/u)?.[1];
2660
+ if (error.code === 'commander.unknownOption')
2661
+ message = field ? `Unknown option --${field}.` : 'Unknown option.';
2662
+ else if (error.code === 'commander.unknownCommand')
2663
+ message = 'Unknown command.';
2664
+ else if (error.code === 'commander.invalidArgument')
2665
+ message = field ? `Invalid value for --${field}.` : 'Invalid argument value.';
2666
+ else if (error.code === 'commander.excessArguments')
2667
+ message = 'Too many positional arguments.';
2668
+ }
2669
+ const preparedConfirmation = error?.confirmation ?? confirmation;
2670
+ const unknownAuthoringChanges = error?.authoringChanges === 'unknown';
2671
+ const data = { ...(preparedConfirmation ? { confirmation: preparedConfirmation } : {}), ...(unknownAuthoringChanges ? { changes: 'unknown' } : {}) };
2672
+ return emit(commandResult(id, data, { status: unknownAuthoringChanges ? 'partial' : blocked ? 'blocked' : 'failed', diagnostics: [{ code, severity: 'error', message: safePublicMessage(message, code), ...(code === 'invalidOptionValue' ? { subject: { field: raw.message?.match(/--([a-z][a-z-]*)/u)?.[1] ?? 'option' } } : {}) }], nextActions: code === 'confirmationRequired' ? [{ kind: 'manual', message: 'Review the effects and repeat the command with --yes.' }] : [] }), argumentError);
2673
+ }
2674
+ finally {
2675
+ stopListening();
2773
2676
  }
2774
2677
  }
2775
2678
  export async function main(argv = process.argv.slice(2), options = {}) {