@outputai/cli 0.16.1-next.ac69246.0 → 0.16.1-next.b04d8e2.0

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.
@@ -80,7 +80,7 @@ services:
80
80
  condition: service_healthy
81
81
  worker:
82
82
  condition: service_healthy
83
- image: outputai/api:${OUTPUT_API_VERSION:-0.16.1-next.ac69246.0}
83
+ image: outputai/api:${OUTPUT_API_VERSION:-0.16.1-next.b04d8e2.0}
84
84
  init: true
85
85
  networks:
86
86
  - main
@@ -4,7 +4,7 @@ import { calculateCost, loadPricingConfig } from '#services/cost_calculator.js';
4
4
  import { getTrace } from '#services/trace_reader.js';
5
5
  import { formatCostReport } from '#utils/cost_formatter.js';
6
6
  import { getErrorCode } from '#utils/error_utils.js';
7
- import { handleApiError } from '#utils/error_handler.js';
7
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
8
8
  export default class WorkflowCost extends Command {
9
9
  static description = 'Calculate the cost of a workflow execution';
10
10
  static enableJsonFlag = true;
@@ -57,7 +57,7 @@ export default class WorkflowCost extends Command {
57
57
  }
58
58
  }
59
59
  async catch(error) {
60
- return handleApiError(error, (...args) => this.error(...args), {
60
+ return handleApiError(error, createErrorFn(this), {
61
61
  404: 'Workflow not found. Check the workflow ID and try again.'
62
62
  });
63
63
  }
@@ -7,7 +7,7 @@ import { getTrace } from '#services/trace_reader.js';
7
7
  import { extractDatasetFromTrace } from '#utils/trace_extractor.js';
8
8
  import { resolveScenarioPath, getScenarioNotFoundMessage } from '#utils/scenario_resolver.js';
9
9
  import { parseInputFlag } from '#utils/input_parser.js';
10
- import { handleApiError } from '#utils/error_handler.js';
10
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
11
11
  export default class DatasetGenerate extends Command {
12
12
  static description = 'Generate a dataset for a workflow from a scenario, trace file, or recent runs';
13
13
  static examples = [
@@ -165,7 +165,7 @@ export default class DatasetGenerate extends Command {
165
165
  ' - An input flag: output workflow dataset generate <workflow> --input <json>', { exit: 1 });
166
166
  }
167
167
  async catch(error) {
168
- return handleApiError(error, (...args) => this.error(...args), {
168
+ return handleApiError(error, createErrorFn(this), {
169
169
  404: 'Workflow not found. Check the workflow name.',
170
170
  500: 'Workflow execution failed.'
171
171
  });
@@ -11,4 +11,5 @@ export default class DatasetList extends Command {
11
11
  format: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
12
12
  };
13
13
  run(): Promise<DatasetInfo[]>;
14
+ catch(error: Error): Promise<void>;
14
15
  }
@@ -1,6 +1,7 @@
1
1
  import { Args, Command, Flags } from '@oclif/core';
2
2
  import Table from 'cli-table3';
3
3
  import { listDatasets } from '#services/datasets.js';
4
+ import { createErrorFn, handleCommandError } from '#utils/error_handler.js';
4
5
  const OutputFormat = {
5
6
  TABLE: 'table',
6
7
  TEXT: 'text'
@@ -80,4 +81,7 @@ export default class DatasetList extends Command {
80
81
  this.log(`\nFound ${datasets.length} dataset(s) for "${args.workflowName}"`);
81
82
  return datasets;
82
83
  }
84
+ async catch(error) {
85
+ return handleCommandError(error, createErrorFn(this));
86
+ }
83
87
  }
@@ -1,7 +1,7 @@
1
1
  import { Args, Command } from '@oclif/core';
2
2
  import { displayDebugTree } from '#utils/trace_formatter.js';
3
3
  import { getTrace } from '#services/trace_reader.js';
4
- import { handleApiError } from '#utils/error_handler.js';
4
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
5
5
  export default class WorkflowDebug extends Command {
6
6
  static description = 'Get and display workflow execution trace for debugging';
7
7
  static enableJsonFlag = true;
@@ -34,7 +34,7 @@ export default class WorkflowDebug extends Command {
34
34
  this.log('Tip: Use --json for the full untruncated trace');
35
35
  }
36
36
  async catch(error) {
37
- return handleApiError(error, (...args) => this.error(...args), {
37
+ return handleApiError(error, createErrorFn(this), {
38
38
  404: 'Workflow not found or trace not available. Check the workflow ID.'
39
39
  });
40
40
  }
@@ -2,7 +2,7 @@ import { Args, Command, Flags } from '@oclif/core';
2
2
  import { fetchWorkflowHistory } from '#services/workflow_history.js';
3
3
  import buildSpanLabels from '#utils/span_labels.js';
4
4
  import renderWaterfall, { formatDurationLabel } from '#utils/waterfall.js';
5
- import { handleApiError } from '#utils/error_handler.js';
5
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
6
6
  import { shouldColorize } from '#utils/color.js';
7
7
  const DEFAULT_WIDTH = 80;
8
8
  const OUTPUT_FORMAT = { JSON: 'json', TEXT: 'text' };
@@ -92,7 +92,7 @@ export default class WorkflowHistory extends Command {
92
92
  return `${workflowId} · run ${shortRun} · ${status ?? 'unknown'} · ${formatDurationLabel(totalDurationMs)}`;
93
93
  }
94
94
  async catch(error) {
95
- return handleApiError(error, (...args) => this.error(...args), {
95
+ return handleApiError(error, createErrorFn(this), {
96
96
  404: 'Workflow not found. Check the workflow ID.'
97
97
  });
98
98
  }
@@ -2,7 +2,7 @@ import { Args, Command, Flags } from '@oclif/core';
2
2
  import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { getWorkflowIdInput, getWorkflowIdRunsRidInput } from '#api/generated/api.js';
5
- import { handleApiError } from '#utils/error_handler.js';
5
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
6
6
  export default class WorkflowInput extends Command {
7
7
  static description = 'Get the original input a workflow run was started with';
8
8
  static enableJsonFlag = true;
@@ -67,7 +67,7 @@ export default class WorkflowInput extends Command {
67
67
  return input;
68
68
  }
69
69
  async catch(error) {
70
- return handleApiError(error, (...args) => this.error(...args), {
70
+ return handleApiError(error, createErrorFn(this), {
71
71
  404: 'Workflow not found. Check the workflow ID.'
72
72
  });
73
73
  }
@@ -2,7 +2,7 @@ import { Command, Flags } from '@oclif/core';
2
2
  import Table from 'cli-table3';
3
3
  import { fetchWorkflowCatalog } from '#api/workflow_catalog.js';
4
4
  import { parseWorkflowDefinition, formatParameters } from '#api/parser.js';
5
- import { handleApiError } from '#utils/error_handler.js';
5
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
6
6
  import { listScenariosForWorkflow } from '#utils/scenario_resolver.js';
7
7
  const OUTPUT_FORMAT = {
8
8
  LIST: 'list',
@@ -149,7 +149,7 @@ export default class WorkflowList extends Command {
149
149
  return formatWorkflowsAsJson(workflows);
150
150
  }
151
151
  async catch(error) {
152
- return handleApiError(error, (...args) => this.error(...args), {
152
+ return handleApiError(error, createErrorFn(this), {
153
153
  404: 'Catalog not found.'
154
154
  });
155
155
  }
@@ -1,6 +1,6 @@
1
1
  import { Args, Command, Flags } from '@oclif/core';
2
2
  import { commandStreamIo, monitorErrorOverrides, streamWorkflowUpdates } from '#services/monitor_stream.js';
3
- import { handleCommandError } from '#utils/error_handler.js';
3
+ import { createErrorFn, handleCommandError } from '#utils/error_handler.js';
4
4
  import { monitorStreamFlags } from '#utils/monitor_flags.js';
5
5
  const OUTPUT_FORMAT = { JSON: 'json', TEXT: 'text' };
6
6
  /**
@@ -58,7 +58,7 @@ export default class WorkflowMonitor extends Command {
58
58
  }, commandStreamIo(this));
59
59
  }
60
60
  async catch(error) {
61
- return handleCommandError(error, (...args) => this.error(...args), {
61
+ return handleCommandError(error, createErrorFn(this), {
62
62
  ...monitorErrorOverrides(error),
63
63
  // Owned by this command rather than the shared overrides: here the id is the
64
64
  // argument the user typed, so pointing at it is actionable advice.
@@ -1,6 +1,6 @@
1
1
  import { Args, Command, Flags } from '@oclif/core';
2
2
  import { postWorkflowIdReset } from '#api/generated/api.js';
3
- import { handleApiError } from '#utils/error_handler.js';
3
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
4
4
  export default class WorkflowReset extends Command {
5
5
  static description = 'Reset a workflow to re-run from after a specific step';
6
6
  static examples = [
@@ -43,7 +43,7 @@ export default class WorkflowReset extends Command {
43
43
  this.log(`\n${output}`);
44
44
  }
45
45
  async catch(error) {
46
- return handleApiError(error, (...args) => this.error(...args), {
46
+ return handleApiError(error, createErrorFn(this), {
47
47
  404: 'Workflow or step not found. Check the workflow ID and step name.',
48
48
  409: 'Step has not completed yet. Cannot reset to an incomplete step.'
49
49
  });
@@ -1,7 +1,7 @@
1
1
  import { Args, Command } from '@oclif/core';
2
2
  import { getWorkflowIdResult } from '#api/generated/api.js';
3
3
  import { formatWorkflowResult, isErrorStatus } from '#utils/format_workflow_result.js';
4
- import { handleApiError } from '#utils/error_handler.js';
4
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
5
5
  export default class WorkflowResult extends Command {
6
6
  static description = 'Get workflow execution result';
7
7
  static enableJsonFlag = true;
@@ -30,7 +30,7 @@ export default class WorkflowResult extends Command {
30
30
  return data;
31
31
  }
32
32
  async catch(error) {
33
- return handleApiError(error, (...args) => this.error(...args), {
33
+ return handleApiError(error, createErrorFn(this), {
34
34
  404: 'Workflow not found. Check the workflow ID.'
35
35
  });
36
36
  }
@@ -1,7 +1,7 @@
1
1
  import { Args, Command, Flags } from '@oclif/core';
2
2
  import { postWorkflowRun } from '#api/generated/api.js';
3
3
  import { formatWorkflowResult, isErrorStatus } from '#utils/format_workflow_result.js';
4
- import { handleApiError } from '#utils/error_handler.js';
4
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
5
5
  import { resolveInput } from '#utils/resolve_input.js';
6
6
  import { parseSearchAttributesFlag } from '#utils/search_attributes_flag.js';
7
7
  import { getRetryDelayFromResponse } from '#utils/header_utils.js';
@@ -102,7 +102,7 @@ export default class WorkflowRun extends Command {
102
102
  return data;
103
103
  }
104
104
  async catch(error) {
105
- return handleApiError(error, (...args) => this.error(...args), {
105
+ return handleApiError(error, createErrorFn(this), {
106
106
  404: 'Workflow not found. Check the workflow name.',
107
107
  500: 'Workflow execution failed.',
108
108
  503: 'Workflow service temporarily unavailable.'
@@ -2,7 +2,7 @@ import { Args, Command, Flags } from '@oclif/core';
2
2
  import Table from 'cli-table3';
3
3
  import { fetchWorkflowRuns } from '#services/workflow_runs.js';
4
4
  import { formatDate, formatDurationFromTimestamps } from '#utils/date_formatter.js';
5
- import { handleApiError } from '#utils/error_handler.js';
5
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
6
6
  const OUTPUT_FORMAT = {
7
7
  TABLE: 'table',
8
8
  TEXT: 'text'
@@ -102,7 +102,7 @@ export default class WorkflowRunsList extends Command {
102
102
  return runs;
103
103
  }
104
104
  async catch(error) {
105
- return handleApiError(error, (...args) => this.error(...args), {
105
+ return handleApiError(error, createErrorFn(this), {
106
106
  400: 'Invalid parameters provided.',
107
107
  503: 'Workflow service temporarily unavailable.'
108
108
  });
@@ -1,7 +1,7 @@
1
1
  import { Args, Command, Flags } from '@oclif/core';
2
2
  import { postWorkflowStart } from '#api/generated/api.js';
3
3
  import { commandStreamIo, monitorErrorOverrides, streamWorkflowUpdates } from '#services/monitor_stream.js';
4
- import { handleApiError, handleCommandError } from '#utils/error_handler.js';
4
+ import { createErrorFn, handleApiError, handleCommandError } from '#utils/error_handler.js';
5
5
  import { isErrorStatus } from '#utils/format_workflow_result.js';
6
6
  import { gatedMonitorStreamFlags, MONITOR_DEFAULTS } from '#utils/monitor_flags.js';
7
7
  import { resolveInput } from '#utils/resolve_input.js';
@@ -164,7 +164,7 @@ export default class WorkflowStart extends Command {
164
164
  return result;
165
165
  }
166
166
  async catch(error) {
167
- return handleCommandError(error, (...args) => this.error(...args), {
167
+ return handleCommandError(error, createErrorFn(this), {
168
168
  404: 'Workflow not found. Check the workflow name.'
169
169
  });
170
170
  }
@@ -2,6 +2,7 @@
2
2
  import { describe, it, expect, vi, beforeEach } from 'vitest';
3
3
  import { Parser } from '@oclif/core';
4
4
  import { CLIError } from '@oclif/core/errors';
5
+ import { ux } from '@oclif/core/ux';
5
6
  vi.mock('#api/generated/api.js', () => ({
6
7
  postWorkflowStart: vi.fn()
7
8
  }));
@@ -379,6 +380,15 @@ describe('workflow start command', () => {
379
380
  await expect(cmd.catch(usageError)).rejects.toBe(usageError);
380
381
  expect(cmd.error).not.toHaveBeenCalled();
381
382
  });
383
+ it('writes oclif errors as JSON to stderr with their own exit code under --json', async () => {
384
+ const { cmd } = await createCommand();
385
+ vi.spyOn(cmd, 'jsonEnabled').mockReturnValue(true);
386
+ const stderr = vi.spyOn(ux, 'stderr').mockImplementation(() => { });
387
+ const usageError = new CLIError('Cannot combine --monitor with --json.', { exit: 2 });
388
+ await expect(cmd.catch(usageError)).rejects.toMatchObject({ oclif: { exit: 2 } });
389
+ expect(JSON.parse(String(stderr.mock.calls[0][0]))).toEqual({ error: { message: 'Cannot combine --monitor with --json.' } });
390
+ expect(cmd.error).not.toHaveBeenCalled();
391
+ });
382
392
  });
383
393
  });
384
394
  });
@@ -1,6 +1,6 @@
1
1
  import { Args, Command } from '@oclif/core';
2
2
  import { getWorkflowIdStatus } from '#api/generated/api.js';
3
- import { handleApiError } from '#utils/error_handler.js';
3
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
4
4
  import { normalizeWorkflowStatus } from '#utils/normalize_workflow_status.js';
5
5
  function formatStatusText(result) {
6
6
  const lines = [
@@ -45,7 +45,7 @@ export default class WorkflowStatus extends Command {
45
45
  return data;
46
46
  }
47
47
  async catch(error) {
48
- return handleApiError(error, (...args) => this.error(...args), {
48
+ return handleApiError(error, createErrorFn(this), {
49
49
  404: 'Workflow not found. Check the workflow ID.'
50
50
  });
51
51
  }
@@ -1,6 +1,6 @@
1
1
  import { Args, Command } from '@oclif/core';
2
2
  import { patchWorkflowIdStop } from '#api/generated/api.js';
3
- import { handleApiError } from '#utils/error_handler.js';
3
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
4
4
  export default class WorkflowStop extends Command {
5
5
  static description = 'Stop a workflow execution';
6
6
  static examples = [
@@ -24,7 +24,7 @@ export default class WorkflowStop extends Command {
24
24
  this.log(`\n${output}`);
25
25
  }
26
26
  async catch(error) {
27
- return handleApiError(error, (...args) => this.error(...args), {
27
+ return handleApiError(error, createErrorFn(this), {
28
28
  404: 'Workflow not found. Check the workflow ID.'
29
29
  });
30
30
  }
@@ -1,6 +1,6 @@
1
1
  import { Args, Command, Flags } from '@oclif/core';
2
2
  import { postWorkflowIdTerminate } from '#api/generated/api.js';
3
- import { handleApiError } from '#utils/error_handler.js';
3
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
4
4
  export default class WorkflowTerminate extends Command {
5
5
  static description = 'Terminate a workflow execution (force stop)';
6
6
  static examples = [
@@ -32,7 +32,7 @@ export default class WorkflowTerminate extends Command {
32
32
  this.log(`\n${output}`);
33
33
  }
34
34
  async catch(error) {
35
- return handleApiError(error, (...args) => this.error(...args), {
35
+ return handleApiError(error, createErrorFn(this), {
36
36
  404: 'Workflow not found. Check the workflow ID.'
37
37
  });
38
38
  }
@@ -4,7 +4,7 @@ import { postWorkflowRun } from '#api/generated/api.js';
4
4
  import { readAllDatasets, writeDataset } from '#services/datasets.js';
5
5
  import { fetchWorkflowCatalog } from '#api/workflow_catalog.js';
6
6
  import { diagnoseMissingEvalWorkflow } from '#utils/eval_diagnostics.js';
7
- import { handleApiError } from '#utils/error_handler.js';
7
+ import { createErrorFn, handleApiError } from '#utils/error_handler.js';
8
8
  import { getEvalWorkflowName } from '#utils/eval_naming.js';
9
9
  import { renderEvalOutput, computeExitCode } from '#utils/eval_render.js';
10
10
  import { EvalOutputSchema } from '@outputai/core/evals';
@@ -153,7 +153,7 @@ export default class WorkflowTest extends Command {
153
153
  }
154
154
  }
155
155
  async catch(error) {
156
- return handleApiError(error, (...args) => this.error(...args), {
156
+ return handleApiError(error, createErrorFn(this), {
157
157
  404: 'Workflow or eval workflow not found. Check the workflow name.',
158
158
  500: 'Workflow execution failed.'
159
159
  });
@@ -1,3 +1,3 @@
1
1
  {
2
- "framework": "0.16.1-next.ac69246.0"
2
+ "framework": "0.16.1-next.b04d8e2.0"
3
3
  }
@@ -1,18 +1,35 @@
1
+ import type { Command } from '@oclif/core';
2
+ import { CLIError } from '@oclif/core/errors';
3
+ type ErrorOptions = {
4
+ exit: number;
5
+ status?: number;
6
+ code?: string;
7
+ original?: CLIError;
8
+ };
9
+ type ErrorFn = (message: string, options: ErrorOptions) => never;
1
10
  type ErrorOverrides = {
2
11
  [statusCode: number]: string;
3
12
  ECONNREFUSED?: string;
4
13
  };
5
- export declare function handleApiError(error: unknown, errorFn: (...args: [message: string, options: {
6
- exit: number;
7
- }]) => never, overrides?: ErrorOverrides): never;
14
+ /**
15
+ * Builds the `errorFn` a `--json` capable command hands to `handleApiError` and `handleCommandError`.
16
+ * In text mode it fails through `command.error()`, or rethrows the original oclif error when one is given.
17
+ * Under `--json` it writes `{ error: { message, status?, code? } }` to stderr and throws an `ExitError`, which
18
+ * oclif exits on without printing anything else. Stdout stays reserved for results, so it is empty on failure and
19
+ * the exit code says which. `command.error()` alone cannot do this: it only throws a plain-text error, and oclif's
20
+ * own JSON error handling lives in its default `catch()`, which the commands override.
21
+ *
22
+ * @param command - The command whose `catch()` reports the error
23
+ * @returns The error reporter
24
+ */
25
+ export declare function createErrorFn(command: Command): ErrorFn;
26
+ export declare function handleApiError(error: unknown, errorFn: ErrorFn, overrides?: ErrorOverrides): never;
8
27
  /**
9
28
  * `catch()` handling for a command that raises oclif errors of its own. Flag
10
29
  * relationship failures and every `this.error( ..., { exit } )` already carry an
11
30
  * exit code and formatted output, and `handleApiError` would flatten all of it
12
- * to a bare exit 1 — so pass those straight through and only map what actually
13
- * came back from the API.
31
+ * to a bare exit 1 - so hand those to `errorFn` with their own exit code and the
32
+ * original error, and only map what actually came back from the API.
14
33
  */
15
- export declare function handleCommandError(error: Error, errorFn: (...args: [message: string, options: {
16
- exit: number;
17
- }]) => never, overrides?: ErrorOverrides): never;
34
+ export declare function handleCommandError(error: Error, errorFn: ErrorFn, overrides?: ErrorOverrides): never;
18
35
  export {};
@@ -1,4 +1,5 @@
1
- import { CLIError } from '@oclif/core/errors';
1
+ import { CLIError, ExitError } from '@oclif/core/errors';
2
+ import { ux } from '@oclif/core/ux';
2
3
  import { config } from '#config.js';
3
4
  function getDefaultMessages() {
4
5
  return {
@@ -50,46 +51,77 @@ function getDetailedErrorMessage(error) {
50
51
  }
51
52
  return parts.length > 0 ? parts.join(' | ') : 'Unknown error';
52
53
  }
54
+ /**
55
+ * Builds the `errorFn` a `--json` capable command hands to `handleApiError` and `handleCommandError`.
56
+ * In text mode it fails through `command.error()`, or rethrows the original oclif error when one is given.
57
+ * Under `--json` it writes `{ error: { message, status?, code? } }` to stderr and throws an `ExitError`, which
58
+ * oclif exits on without printing anything else. Stdout stays reserved for results, so it is empty on failure and
59
+ * the exit code says which. `command.error()` alone cannot do this: it only throws a plain-text error, and oclif's
60
+ * own JSON error handling lives in its default `catch()`, which the commands override.
61
+ *
62
+ * @param command - The command whose `catch()` reports the error
63
+ * @returns The error reporter
64
+ */
65
+ export function createErrorFn(command) {
66
+ return (message, { exit, status, code, original }) => {
67
+ if (!command.jsonEnabled()) {
68
+ if (original) {
69
+ throw original;
70
+ }
71
+ return command.error(message, { exit });
72
+ }
73
+ ux.stderr(JSON.stringify({
74
+ error: {
75
+ message,
76
+ ...(status === undefined ? {} : { status }),
77
+ ...(code === undefined ? {} : { code })
78
+ }
79
+ }, null, 2));
80
+ throw new ExitError(exit);
81
+ };
82
+ }
53
83
  export function handleApiError(error, errorFn, overrides = {}) {
54
84
  const apiError = error;
55
85
  const errorMessages = { ...getDefaultMessages(), ...overrides };
86
+ const status = apiError.response?.status;
87
+ const code = apiError.code ?? apiError.cause?.code;
88
+ const fail = (message) => errorFn(message, { exit: 1, status, code });
56
89
  if (apiError.code === 'ECONNREFUSED' || apiError.cause?.code === 'ECONNREFUSED') {
57
- errorFn(errorMessages.ECONNREFUSED, { exit: 1 });
90
+ fail(errorMessages.ECONNREFUSED);
58
91
  }
59
- if (apiError.response?.status) {
60
- const status = apiError.response.status;
92
+ if (status) {
61
93
  // A caller-supplied override for this exact status wins over the raw server body. The API's
62
94
  // 404 body is a bare "WorkflowNotFoundError: ..." that the friendly override is meant to
63
95
  // replace; without this, extractApiErrorDetails consumes the body first and every command's
64
96
  // per-status override is dead code. Defaults are not consulted here, so commands that pass no
65
97
  // override still get the rich server detail below.
66
98
  if (status in overrides) {
67
- errorFn(overrides[status], { exit: 1 });
99
+ fail(overrides[status]);
68
100
  }
69
101
  // Extract error details from response body
70
- const apiErrorDetails = extractApiErrorDetails(apiError.response.data);
102
+ const apiErrorDetails = extractApiErrorDetails(apiError.response?.data);
71
103
  if (apiErrorDetails) {
72
104
  const { errorType, errorMsg } = apiErrorDetails;
73
- errorFn(`${errorType}: ${errorMsg}`, { exit: 1 });
105
+ fail(`${errorType}: ${errorMsg}`);
74
106
  }
75
107
  const message = errorMessages[status];
76
108
  if (message) {
77
- errorFn(message, { exit: 1 });
109
+ fail(message);
78
110
  }
79
111
  }
80
- const detailedMessage = getDetailedErrorMessage(error);
81
- errorFn(detailedMessage, { exit: 1 });
112
+ return fail(getDetailedErrorMessage(error));
82
113
  }
83
114
  /**
84
115
  * `catch()` handling for a command that raises oclif errors of its own. Flag
85
116
  * relationship failures and every `this.error( ..., { exit } )` already carry an
86
117
  * exit code and formatted output, and `handleApiError` would flatten all of it
87
- * to a bare exit 1 — so pass those straight through and only map what actually
88
- * came back from the API.
118
+ * to a bare exit 1 - so hand those to `errorFn` with their own exit code and the
119
+ * original error, and only map what actually came back from the API.
89
120
  */
90
121
  export function handleCommandError(error, errorFn, overrides = {}) {
91
122
  if (error instanceof CLIError) {
92
- throw error;
123
+ const exit = typeof error.oclif?.exit === 'number' ? error.oclif.exit : 1;
124
+ return errorFn(error.message, { exit, original: error });
93
125
  }
94
126
  return handleApiError(error, errorFn, overrides);
95
127
  }
@@ -1,7 +1,8 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
- import { describe, it, expect, vi } from 'vitest';
3
- import { CLIError } from '@oclif/core/errors';
4
- import { handleApiError, handleCommandError } from './error_handler.js';
2
+ import { describe, it, expect, vi, afterEach } from 'vitest';
3
+ import { CLIError, ExitError } from '@oclif/core/errors';
4
+ import { ux } from '@oclif/core/ux';
5
+ import { createErrorFn, handleApiError, handleCommandError } from './error_handler.js';
5
6
  const errorFn = () => vi.fn((message) => {
6
7
  throw new Error(message);
7
8
  });
@@ -42,21 +43,66 @@ describe('handleApiError()', () => {
42
43
  it('always exits 1, leaving a command\'s own exit codes to the command', () => {
43
44
  const fn = errorFn();
44
45
  expect(() => handleApiError(apiError(500), fn)).toThrow();
45
- expect(fn).toHaveBeenCalledWith(expect.any(String), { exit: 1 });
46
+ expect(fn).toHaveBeenCalledWith(expect.any(String), { exit: 1, status: 500, code: undefined });
47
+ });
48
+ it('passes the HTTP status and the error code along for structured output', () => {
49
+ const fn = errorFn();
50
+ const error = Object.assign(new Error('fetch failed'), { cause: { code: 'ECONNREFUSED' } });
51
+ expect(() => handleApiError(error, fn)).toThrow();
52
+ expect(fn).toHaveBeenCalledWith(expect.any(String), { exit: 1, status: undefined, code: 'ECONNREFUSED' });
46
53
  });
47
54
  });
48
55
  describe('handleCommandError()', () => {
49
- it('rethrows an oclif error untouched so its exit code and formatting survive', () => {
56
+ it('hands an oclif error to errorFn with its own exit code and the original error', () => {
50
57
  const fn = errorFn();
51
58
  // `workflow start --monitor` raises exit 2 (bad flag combination) and exit 3
52
59
  // (started but unmonitorable); flattening those to exit 1 would let a CI job
53
60
  // retrying on a failed workflow re-submit one that is already running.
54
61
  const cliError = new CLIError('Cannot combine --monitor with --json', { exit: 2 });
55
- expect(() => handleCommandError(cliError, fn)).toThrow(cliError);
56
- expect(fn).not.toHaveBeenCalled();
62
+ expect(() => handleCommandError(cliError, fn)).toThrow();
63
+ expect(fn).toHaveBeenCalledWith('Cannot combine --monitor with --json', { exit: 2, original: cliError });
57
64
  });
58
65
  it('maps anything that came back from the API the same way handleApiError does', () => {
59
66
  const fn = errorFn();
60
67
  expect(() => handleCommandError(apiError(404), fn, { 404: 'Workflow not found. Check the workflow name.' })).toThrow('Workflow not found. Check the workflow name.');
61
68
  });
62
69
  });
70
+ describe('createErrorFn()', () => {
71
+ afterEach(() => {
72
+ vi.restoreAllMocks();
73
+ });
74
+ const command = (isJson) => ({
75
+ jsonEnabled: () => isJson,
76
+ error: vi.fn((message) => {
77
+ throw new Error(message);
78
+ })
79
+ });
80
+ const printedJson = (stderr) => JSON.parse(String(stderr.mock.calls[0][0]));
81
+ it('fails through command.error() with the exit code in text mode', () => {
82
+ const cmd = command(false);
83
+ expect(() => createErrorFn(cmd)('Workflow not found.', { exit: 1, status: 404 })).toThrow('Workflow not found.');
84
+ expect(cmd.error).toHaveBeenCalledWith('Workflow not found.', { exit: 1 });
85
+ });
86
+ it('rethrows the original oclif error in text mode', () => {
87
+ const cmd = command(false);
88
+ const original = new CLIError('bad flags', { exit: 2 });
89
+ expect(() => createErrorFn(cmd)(original.message, { exit: 2, original })).toThrow(original);
90
+ expect(cmd.error).not.toHaveBeenCalled();
91
+ });
92
+ it('writes the error as JSON to stderr, leaves stdout alone and exits without printing in json mode', () => {
93
+ const stderr = vi.spyOn(ux, 'stderr').mockImplementation(() => { });
94
+ const stdout = vi.spyOn(ux, 'stdout').mockImplementation(() => { });
95
+ const cmd = command(true);
96
+ const fail = createErrorFn(cmd);
97
+ expect(() => fail('Workflow not found.', { exit: 1, status: 404, code: undefined })).toThrow(ExitError);
98
+ expect(printedJson(stderr)).toEqual({ error: { message: 'Workflow not found.', status: 404 } });
99
+ expect(stdout).not.toHaveBeenCalled();
100
+ expect(cmd.error).not.toHaveBeenCalled();
101
+ });
102
+ it('keeps the exit code of an oclif error in json mode and includes the error code', () => {
103
+ const stderr = vi.spyOn(ux, 'stderr').mockImplementation(() => { });
104
+ const original = new CLIError('Cannot combine --monitor with --json', { exit: 2 });
105
+ expect(() => createErrorFn(command(true))(original.message, { exit: 2, code: 'ECONNREFUSED', original })).toThrow(expect.objectContaining({ oclif: { exit: 2 } }));
106
+ expect(printedJson(stderr)).toEqual({ error: { message: 'Cannot combine --monitor with --json', code: 'ECONNREFUSED' } });
107
+ });
108
+ });
@@ -1772,5 +1772,5 @@
1772
1772
  ]
1773
1773
  }
1774
1774
  },
1775
- "version": "0.16.1-next.ac69246.0"
1775
+ "version": "0.16.1-next.b04d8e2.0"
1776
1776
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outputai/cli",
3
- "version": "0.16.1-next.ac69246.0",
3
+ "version": "0.16.1-next.b04d8e2.0",
4
4
  "description": "CLI for Output.ai workflow generation",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -37,7 +37,7 @@
37
37
  "react": "19.3.0",
38
38
  "semver": "7.8.5",
39
39
  "undici": "8.12.3",
40
- "@outputai/core": "0.16.1-next.ac69246.0"
40
+ "@outputai/core": "0.16.1-next.b04d8e2.0"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/cli-progress": "3.11.6",