diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 171fccd38e6..8d03a2a75cf 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8518,9 +8518,9 @@ sim workflows run [options] | `--draft` | No | Run the saved draft instead of the active deployment, sending its writes. | | `--deployment-version ` | No | Run this deployed version instead of the active one (a version number from `sim workflows versions list`); a Workflow block in it still runs its child workflow's active deployment. Needs workspace write access, through a full-access API key or an OAuth token with api:write. Not with --draft or any flag that runs the draft. | | `--dry` | No | Dry run of the saved draft (implies --draft): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | -| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | -| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock <block> takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only (the API reference lists the fields a mock cannot set). The run records only which blocks were mocked, not the outputs, so a rerun reads them again with --mock-from; repeatable. | -| `--mock-from ` | No | Answer each block a bare --mock <block> names with the output it recorded in this earlier run of the workflow, redacted as the run shows it: this workflow's blocks (not a child's; not inside a loop or parallel unless that run mocked it); fields a mock cannot set, such as cost or model, are left out (requires --dry). | +| `--allow ` | No | Send this block's writes for real during a dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls.; repeatable. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it during a dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock <block> takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only (the API reference lists the fields a mock cannot set). The run records only which blocks were mocked, not the outputs, so a rerun reads them again with --mock-from; repeatable. | +| `--mock-from ` | No | Answer each block a bare --mock <block> names with the output it recorded in this earlier run of the workflow, redacted as the run shows it: this workflow's blocks (not a child's; not inside a loop or parallel unless that run mocked it); fields a mock cannot set, such as cost or model, are left out. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the saved draft (implies --draft). | | `--sample` | No | Run with the selected trigger's sample payload instead of --input; runs the saved draft (implies --draft), whose writes are sent unless --dry. | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -8536,7 +8536,7 @@ sim workflows run [options] Without --draft (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --deployment-version <n> runs that deployed version instead (it needs workspace write access, through a full-access API key or an OAuth token with api:write); the child workflows it calls still run their own active deployment. --draft runs the saved draft, as the source loop leaves it, sending its writes. ---dry runs the saved draft without its writes: each call that could change something (a write tool, any MCP call, an HTTP request other than GET/HEAD/OPTIONS, code's other fetches) gets a placeholder (ids like dry_run_row_1, numbers above 900000000) and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. A read that would send a placeholder is held back too (reason placeholder), and an MCP call its server calls read-only says so (reason mcp-read-only). Reads, model calls and code run for real; code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. --allow <block> sends that block's writes for real (use a test resource). --mock <block>=<json> answers a block with fixed output, to steer a branch; --mock-from <runId> with a bare --mock <block> answers it with the output that run recorded. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block>. Overrides the run never reached are listed in sideEffects.unreached, and mock fields a block never gets in sideEffects.mockFields. The API reference describes each list and refusal. +--dry runs the saved draft without its writes: each call that could change something (a write tool, any MCP call, an HTTP request other than GET/HEAD/OPTIONS, code's other fetches) gets a placeholder (ids like dry_run_row_1, numbers above 900000000) and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. A read that would send a placeholder is held back too (reason placeholder), and an MCP call its server calls read-only says so (reason mcp-read-only). Reads, model calls and code run for real; code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. --allow <block> sends that block's writes for real (use a test resource). --mock <block>=<json> answers a block with fixed output, to steer a branch; --mock-from <runId> with a bare --mock <block> answers it with the output that run recorded. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block>. --allow, --mock and --mock-from imply --dry; --draft sends every write, so it refuses them. Overrides the run never reached are listed in sideEffects.unreached, and mock fields a block never gets in sideEffects.mockFields. The API reference describes each list and refusal. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index e11f158af59..db507500e8c 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -835,9 +835,9 @@ sim workflows run [options] | `--draft` | No | Run the saved draft instead of the active deployment, sending its writes. | | `--deployment-version ` | No | Run this deployed version instead of the active one (a version number from `sim workflows versions list`); a Workflow block in it still runs its child workflow's active deployment. Needs workspace write access, through a full-access API key or an OAuth token with api:write. Not with --draft or any flag that runs the draft. | | `--dry` | No | Dry run of the saved draft (implies --draft): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | -| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | -| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock <block> takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only (the API reference lists the fields a mock cannot set). The run records only which blocks were mocked, not the outputs, so a rerun reads them again with --mock-from; repeatable. | -| `--mock-from ` | No | Answer each block a bare --mock <block> names with the output it recorded in this earlier run of the workflow, redacted as the run shows it: this workflow's blocks (not a child's; not inside a loop or parallel unless that run mocked it); fields a mock cannot set, such as cost or model, are left out (requires --dry). | +| `--allow ` | No | Send this block's writes for real during a dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls.; repeatable. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it during a dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock <block> takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only (the API reference lists the fields a mock cannot set). The run records only which blocks were mocked, not the outputs, so a rerun reads them again with --mock-from; repeatable. | +| `--mock-from ` | No | Answer each block a bare --mock <block> names with the output it recorded in this earlier run of the workflow, redacted as the run shows it: this workflow's blocks (not a child's; not inside a loop or parallel unless that run mocked it); fields a mock cannot set, such as cost or model, are left out. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the saved draft (implies --draft). | | `--sample` | No | Run with the selected trigger's sample payload instead of --input; runs the saved draft (implies --draft), whose writes are sent unless --dry. | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -853,7 +853,7 @@ sim workflows run [options] Without --draft (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --deployment-version <n> runs that deployed version instead (it needs workspace write access, through a full-access API key or an OAuth token with api:write); the child workflows it calls still run their own active deployment. --draft runs the saved draft, as the source loop leaves it, sending its writes. ---dry runs the saved draft without its writes: each call that could change something (a write tool, any MCP call, an HTTP request other than GET/HEAD/OPTIONS, code's other fetches) gets a placeholder (ids like dry_run_row_1, numbers above 900000000) and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. A read that would send a placeholder is held back too (reason placeholder), and an MCP call its server calls read-only says so (reason mcp-read-only). Reads, model calls and code run for real; code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. --allow <block> sends that block's writes for real (use a test resource). --mock <block>=<json> answers a block with fixed output, to steer a branch; --mock-from <runId> with a bare --mock <block> answers it with the output that run recorded. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block>. Overrides the run never reached are listed in sideEffects.unreached, and mock fields a block never gets in sideEffects.mockFields. The API reference describes each list and refusal. +--dry runs the saved draft without its writes: each call that could change something (a write tool, any MCP call, an HTTP request other than GET/HEAD/OPTIONS, code's other fetches) gets a placeholder (ids like dry_run_row_1, numbers above 900000000) and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. A read that would send a placeholder is held back too (reason placeholder), and an MCP call its server calls read-only says so (reason mcp-read-only). Reads, model calls and code run for real; code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. --allow <block> sends that block's writes for real (use a test resource). --mock <block>=<json> answers a block with fixed output, to steer a branch; --mock-from <runId> with a bare --mock <block> answers it with the output that run recorded. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block>. --allow, --mock and --mock-from imply --dry; --draft sends every write, so it refuses them. Overrides the run never reached are listed in sideEffects.unreached, and mock fields a block never gets in sideEffects.mockFields. The API reference describes each list and refusal. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 8a3a8fa5544..06b4f99be60 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -68,7 +68,7 @@ ${PATTERNS_HEADING} (\`.sim/examples/\`, indexed atop \`cookbook.ts\`; any build - Tables: \`table.queryRows\` outputs \`rows\` (\`recent.rows[0].data.status\`), not \`row\`; \`table.upsertRow\` takes \`conflictColumn: 'orderId'\`. - Rejoin: before one \`response\`, a Function picks the branch that ran with \`??\`.${extra.patterns ?? ''} - **Credentials**: \`sim credentials connect --name ""\`, send the owner its link, then \`credential('')\`. -- **Run**: \`sim workflows run \` runs the active deployment; \`--draft\` runs the draft for real and \`--allow \` sends that block's writes (use test resources); \`--dry\` runs it stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. \`--mock ='{…}'\` fixes its output (bare, with \`--mock-from \`: that run's); a child's block: \`.\`. +- **Run**: \`sim workflows run \` runs the active deployment; \`--dry\` runs the draft stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. With \`--dry\`, \`--allow \` sends its writes; \`--draft\` sends all (use test resources). \`--mock ='{…}'\` fixes its output (bare, with \`--mock-from \`: that run's); a child's block: \`.\`. - **Debug**: \`--dir \` maps a failure to file:line; \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list \`; rerun: \`--from-block --source-run \`; \`--stop-after \`.${extra.debug ?? ''} - **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo in a fresh get), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed.` } diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index cf23a27fca7..4d9c3df00f2 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -798,9 +798,11 @@ describe('sim workflows run --dry', () => { }) it('refuses combinations a dry run cannot honour before sending anything', async () => { - await expect(run(WORKFLOW_ID, '--allow', 'Save lead')).rejects.toThrow('add --dry') - await expect(run(WORKFLOW_ID, '--mock', 'Score={"content":"spam"}')).rejects.toThrow( - 'add --dry' + await expect(run(WORKFLOW_ID, '--draft', '--allow', 'Save lead')).rejects.toThrow( + 'use --dry in place of --draft' + ) + await expect(run(WORKFLOW_ID, '--draft', '--mock', 'Score={"content":"spam"}')).rejects.toThrow( + 'use --dry in place of --draft' ) await expect(run(WORKFLOW_ID, '--dry', '--follow')).rejects.toThrow('drop --follow') await expect(run(WORKFLOW_ID, '--dry', '--wait-timeout', '30')).rejects.toThrow( @@ -816,9 +818,9 @@ describe('sim workflows run --dry', () => { await expect(run(WORKFLOW_ID, '--dry', '--mock-from', 'run_1')).rejects.toThrow( 'name at least one' ) - await expect(run(WORKFLOW_ID, '--mock-from', 'run_1', '--mock', 'Score')).rejects.toThrow( - '--mock-from answers a block during a dry run' - ) + await expect( + run(WORKFLOW_ID, '--draft', '--mock-from', 'run_1', '--mock', 'Score') + ).rejects.toThrow('use --dry in place of --draft') await expect(run(WORKFLOW_ID, '--dry', '--mock', 'Score=spam')).rejects.toThrow( 'is not valid JSON' ) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index e6a59a9e57f..0f4cd3c0d9c 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -16,7 +16,7 @@ import { retypeApiError } from '../../runtime/naming' import { collectRepeated } from '../../runtime/options' import { buildRequest, readArgumentSource } from '../../runtime/request' import { renderResult } from '../../runtime/result' -import { selectorOf, shellArgument, withRunNext } from '../../runtime/run-next' +import { selectorOf, shellArgument, typedCommandLine, withRunNext } from '../../runtime/run-next' import type { OperationSpec } from '../../runtime/types' import { printRunFailureSite } from './run-source-location' import { BLOCK_ID } from './workflow-run-get' @@ -167,8 +167,17 @@ async function readBlockMocks( return { mocks, recorded } } -/** Projects friendly CLI flags into the API's strict nested run selector. */ +/** The draft and dry flags a corrected dry run leaves out of the caller's command line. */ +const DRAFT_AND_DRY = new Set(['draft', 'dry']) + +/** + * Projects friendly CLI flags into the API's strict nested run selector. `--allow`, `--mock` and + * `--mock-from` mean something only on a dry run, so they imply `--dry`, and beside `--draft`, + * which sends every write, they are refused with the dry run they meant. + */ async function resolveWorkflowRunSelection( + workflowId: string, + command: Command, flags: Record ): Promise { const pinned = pinnedDeployment(flags) @@ -176,25 +185,24 @@ async function resolveWorkflowRunSelection( const trigger = typeof flags.trigger === 'string' ? flags.trigger : undefined const sample = flags.sample === true const stopAfter = typeof flags.stopAfter === 'string' ? flags.stopAfter : undefined - const dry = flags.dry === true const allow = toArray(flags.allow) const mockValues = toArray(flags.mock) const mockFrom = typeof flags.mockFrom === 'string' ? flags.mockFrom : undefined + /** These flags mean something only on a dry run, so they imply `--dry`. */ + const overrides = allow.length > 0 || mockValues.length > 0 || mockFrom !== undefined + if (overrides && flags.draft === true && flags.dry !== true) { + throw new SimApiError( + `--allow picks the writes a --dry run sends and --mock answers a block in one, but --draft runs every block and sends every write: use --dry in place of --draft. Next: ${typedCommandLine(command, [workflowId, '--dry'], DRAFT_AND_DRY)}`, + 0 + ) + } + const dry = flags.dry === true || overrides /** These flags only apply to the draft, so each implies `--draft`. */ const draft = flags.draft === true || trigger !== undefined || sample || stopAfter !== undefined || dry const fromBlock = typeof flags.fromBlock === 'string' ? flags.fromBlock : undefined const sourceRun = typeof flags.sourceRun === 'string' ? flags.sourceRun : undefined - if (allow.length > 0 && !dry) { - throw new SimApiError("--allow sends one block's writes during a dry run; add --dry", 0) - } - if ((mockValues.length > 0 || mockFrom !== undefined) && !dry) { - throw new SimApiError( - `${mockFrom !== undefined ? '--mock-from' : '--mock'} answers a block during a dry run, so its output never drives real writes; add --dry`, - 0 - ) - } if (mockFrom !== undefined && mockFrom.trim() === '') { throw new SimApiError('--mock-from requires a run id', 0) } @@ -203,13 +211,13 @@ async function resolveWorkflowRunSelection( } if (dry && flags.follow === true) { throw new SimApiError( - '--dry reports its side effects with the run result, which --follow does not return; drop --follow', + 'A dry run reports its side effects with the run result, which --follow does not return; drop --follow', 0 ) } if (dry && (flags.waitTimeout !== undefined || flags.async === true)) { throw new SimApiError( - `--dry reports its side effects with the run result, so the command waits for it; drop ${flags.async === true ? '--async' : '--wait-timeout'}`, + `A dry run reports its side effects with the run result, so the command waits for it; drop ${flags.async === true ? '--async' : '--wait-timeout'}`, 0 ) } @@ -889,7 +897,7 @@ async function runWorkflow(workflowId: string, _options: unknown, command: Comma 0 ) } - const selection = await resolveWorkflowRunSelection(initialFlags) + const selection = await resolveWorkflowRunSelection(workflowId, command, initialFlags) const stopBlock = stopBlockSelection(selection, initialFlags) if (stopBlock) command.setOptionValue('selectOutput', stopBlock) const flags = command.optsWithGlobals() as Record @@ -944,7 +952,8 @@ dry too; custom, Human in the loop and Wait blocks are answered whole, so the ru --allow sends that block's writes for real (use a test resource). --mock = answers a block with fixed output, to steer a branch; --mock-from with a bare --mock answers it with the output that run recorded. --allow and --mock also name a -block of a workflow this one calls as .. Overrides the run never reached are +block of a workflow this one calls as .. --allow, --mock and --mock-from imply +--dry; --draft sends every write, so it refuses them. Overrides the run never reached are listed in sideEffects.unreached, and mock fields a block never gets in sideEffects.mockFields. The API reference describes each list and refusal. @@ -998,17 +1007,17 @@ export function attachWorkflowRunFollow(workflows: Command): void { ) .option( '--allow ', - "Send this block's writes for real during a --dry run (its id, display name or key, or . for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable", + "Send this block's writes for real during a dry run (its id, display name or key, or . for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls.; repeatable", collectRepeated ) .option( '--mock =', - 'Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key, or . for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only (the API reference lists the fields a mock cannot set). The run records only which blocks were mocked, not the outputs, so a rerun reads them again with --mock-from; repeatable', + 'Answer this block with the given JSON object instead of running it during a dry run (its id, display name or key, or . for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only (the API reference lists the fields a mock cannot set). The run records only which blocks were mocked, not the outputs, so a rerun reads them again with --mock-from; repeatable', collectRepeated ) .option( '--mock-from ', - "Answer each block a bare --mock names with the output it recorded in this earlier run of the workflow, redacted as the run shows it: this workflow's blocks (not a child's; not inside a loop or parallel unless that run mocked it); fields a mock cannot set, such as cost or model, are left out (requires --dry)" + "Answer each block a bare --mock names with the output it recorded in this earlier run of the workflow, redacted as the run shows it: this workflow's blocks (not a child's; not inside a loop or parallel unless that run mocked it); fields a mock cannot set, such as cost or model, are left out" ) .option( '--trigger ', diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index 888b7331202..57cbe7aded9 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -760,7 +760,11 @@ export const CLI_CONTRACT: CliContract = { confirm: 'This edits the draft graph: the batch adds, edits, or deletes blocks and their edges as written.', flags: { - operations: { json: true, describe: WORKFLOW_OPERATIONS_HELP }, + operations: { + json: true, + describe: WORKFLOW_OPERATIONS_HELP, + example: `'[{"operation_type":"edit","block_id":"","params":{"name":"New name"}}]'`, + }, setBlockEnabled: { json: true, describe: WORKFLOW_SET_BLOCK_ENABLED_HELP }, }, }, diff --git a/packages/sim-cli/src/contract/types.ts b/packages/sim-cli/src/contract/types.ts index 698fad3954d..28979433fbb 100644 --- a/packages/sim-cli/src/contract/types.ts +++ b/packages/sim-cli/src/contract/types.ts @@ -111,6 +111,11 @@ export interface FlagSpec { rowCap?: true /** Overrides the help text otherwise taken from the OpenAPI description. */ describe?: string + /** + * A minimal valid value of a JSON flag, quoted for a shell, which the refusal of a value of the + * wrong shape shows in place of a generic `'[{"key":"value"}]'`. + */ + example?: string /** * Value sent when the caller passes nothing, in place of the server's default. * diff --git a/packages/sim-cli/src/embed-isolation.test.ts b/packages/sim-cli/src/embed-isolation.test.ts index 1769c75baed..7dd0175beca 100644 --- a/packages/sim-cli/src/embed-isolation.test.ts +++ b/packages/sim-cli/src/embed-isolation.test.ts @@ -174,6 +174,174 @@ describe('embedded CLI output ownership', () => { expect(handWritten.stderr).toContain('Options for sim files upload:') }) + it('answers a JSON positional with its flag, and an option that took another flag as its value', async () => { + const transport = async () => { + throw new Error('a parse error must not reach the API') + } + const [positionalInput, swallowed, rootSwallowed, negated, fromFile] = await Promise.all([ + runEmbeddedCli(['workflows', 'run', 'wf_1', '--dry', '{"email":"a@b.co"}'], { + ...identity, + transport, + }), + runEmbeddedCli( + ['workflows', 'run', 'wf_1', '--draft', '--allow', '--input', '{"email":"a@b.co"}'], + { ...identity, transport } + ), + runEmbeddedCli(['workflows', 'run', 'wf_1', '--workspace', '--input', '{"a":1}'], { + ...identity, + transport, + }), + runEmbeddedCli(['workflows', 'run', 'wf_1', '--dry', '--include-file-base64', '{"a":1}'], { + ...identity, + transport, + }), + runEmbeddedCli(['workflows', 'run', 'wf_1', '@input.json'], { ...identity, transport }), + ]) + expect(positionalInput.exitCode).toBe(1) + expect(positionalInput.stderr).toContain( + `Example: sim workflows run wf_1 --dry --input '{"email":"a@b.co"}'` + ) + expect(swallowed.exitCode).toBe(1) + expect(swallowed.stderr).toContain('--allow took --input as its value; write --allow :') + expect(swallowed.stderr).not.toContain('--input \'{"email"') + expect(rootSwallowed.stderr).toContain('--workspace took --input as its value') + expect(fromFile.stderr).toContain("Example: sim workflows run wf_1 --input '@input.json'") + expect(negated.stderr).toContain( + `Example: sim workflows run wf_1 --include-file-base64 --dry --input '{"a":1}'` + ) + }) + + it('refuses --allow beside --draft with the dry run it meant, and runs --allow alone dry', async () => { + const bodies: unknown[] = [] + const transport = async (_url: string | URL | Request, init?: RequestInit) => { + bodies.push(JSON.parse(String(init?.body))) + return new Response(JSON.stringify({ data: { runId: 'run_1', status: 'completed' } }), { + headers: { 'content-type': 'application/json' }, + }) + } + const [draftAllow, draftMock, allowOnly] = await Promise.all([ + runEmbeddedCli( + [ + '--workspace', + 'ws_9', + 'workflows', + 'run', + 'wf_1', + '--draft', + '--allow', + 'Save Lead', + '--input', + '{"a":1}', + ], + { ...identity, transport } + ), + runEmbeddedCli(['workflows', 'run', 'wf_1', '--draft', '--mock', 'Score={"s":1}'], { + ...identity, + transport, + }), + runEmbeddedCli(['workflows', 'run', 'wf_1', '--allow', 'Save Lead'], { + ...identity, + transport, + }), + ]) + expect(draftAllow.exitCode).toBe(1) + expect(draftAllow.stderr).toContain('--draft runs every block and sends every write') + expect(draftAllow.stderr).toContain( + `Next: sim --workspace ws_9 workflows run wf_1 --dry --input '{"a":1}' --allow 'Save Lead'` + ) + expect(draftMock.exitCode).toBe(1) + expect(draftMock.stderr).toContain(`Next: sim workflows run wf_1 --dry --mock 'Score={"s":1}'`) + expect(allowOnly.exitCode, allowOnly.stderr).toBe(0) + expect(bodies).toEqual([ + expect.objectContaining({ run: { source: 'draft', dry: true, allow: ['Save Lead'] } }), + ]) + }) + + it('names the shape a JSON flag takes, beside the --yes it also lacks', async () => { + const transport = async () => { + throw new Error('a shape error must not reach the API') + } + const [wrapped, unconfirmed, confirmed] = await Promise.all([ + runEmbeddedCli( + [ + 'workflows', + 'operations', + 'apply', + 'wf_1', + '--operations', + '{"operations":[{"operation_type":"delete","block_id":"b1"}]}', + ], + { ...identity, transport } + ), + runEmbeddedCli(['workflows', 'operations', 'apply', 'wf_1', '--operations', '[]'], { + ...identity, + transport, + }), + runEmbeddedCli( + [ + 'workflows', + 'operations', + 'apply', + 'wf_1', + '--yes', + '--operations', + '{"operation_type":"delete","block_id":"b1"}', + ], + { ...identity, transport } + ), + ]) + expect(wrapped.exitCode).toBe(1) + expect(wrapped.stderr).toContain( + `--operations must be a JSON array, e.g. --operations '[{"operation_type":"edit"` + ) + expect(wrapped.stderr).toContain('Pass the array under its "operations" key itself') + expect(wrapped.stderr).toContain('Also pass --yes: This edits the draft graph') + expect(unconfirmed.stderr).toContain('Re-run with --yes to confirm.') + expect(confirmed.exitCode).toBe(1) + expect(confirmed.stderr).toContain('--operations must be a JSON array') + expect(confirmed.stderr).not.toContain('Pass the array under') + }) + + it('names the wrapping object the server refused under a JSON flag', async () => { + const result = await runEmbeddedCli( + [ + 'tables', + 'columns', + 'update', + 'tbl_1', + '--column-name', + 'phone', + '--updates', + '{"updates":{"name":"mobile"}}', + ], + { + ...identity, + transport: async () => + new Response( + JSON.stringify({ + error: { + code: 'BAD_REQUEST', + message: 'body.updates: Unrecognized key: "updates"', + details: [ + { + code: 'unrecognized_keys', + keys: ['updates'], + path: ['updates'], + message: 'Unrecognized key: "updates"', + }, + ], + }, + }), + { status: 400, headers: { 'content-type': 'application/json' } } + ), + } + ) + expect(result.exitCode).toBe(1) + expect(result.stderr).toContain( + '--updates takes the object itself: pass the value under its "updates" key' + ) + }) + it('names the shape a body variant received and the flag that takes it', async () => { const transport = async () => { throw new Error('a shape error must not reach the API') @@ -195,6 +363,7 @@ describe('embedded CLI output ownership', () => { expect(wrapped.exitCode).toBe(1) expect(wrapped.stderr).toContain(`e.g. --rows '[{"key":"value"}]'; got a JSON object`) expect(wrapped.stderr).toContain('Pass the array under its "rows" key itself') + expect(wrapped.stderr).not.toContain('For that shape') expect(oneRow.stderr).toContain('For that shape use --data.') expect(rowList.stderr).toContain('--data must be a JSON object') expect(rowList.stderr).toContain('For that shape use --rows.') diff --git a/packages/sim-cli/src/runtime/build.ts b/packages/sim-cli/src/runtime/build.ts index 14371ed52a1..19f96a6a38c 100644 --- a/packages/sim-cli/src/runtime/build.ts +++ b/packages/sim-cli/src/runtime/build.ts @@ -6,7 +6,7 @@ import { callsOperations } from './called-operations' import { deriveCommandPath } from './derive' import { executeOperation } from './execute' import { retypeApiError } from './naming' -import { addOperationOptions } from './options' +import { addOperationOptions, JSON_PLACEHOLDER } from './options' import { warnRenamedCommand } from './renamed' import { flagNameFor, @@ -16,6 +16,7 @@ import { RESERVED_PROGRAM_FLAGS, trailingListField, } from './request' +import { shellArgument, typedCommandLine } from './run-next' import type { OperationSpec } from './types' const GROUP_ALIASES: Readonly> = { @@ -144,6 +145,54 @@ function misplacedFlagValue(command: Command): { option: Option; value: string } return extra.length === 1 ? { option: missing[0], value: extra[0] } : undefined } +/** + * Each option of this command or a group above it (the root's `--workspace` too) that took a flag + * as its value, with what the option is for: `run --allow --input '{…}'` gives `--allow` the value `--input` and + * leaves the JSON over as a positional, so the excess is a symptom of the missing value and the + * JSON is not misplaced. + */ +function swallowedFlags(command: Command): string[] { + const owned: { owner: Command; option: Option }[] = [] + for (let owner: Command | null = command; owner; owner = owner.parent) { + for (const option of owner.options) owned.push({ owner, option }) + } + return owned.flatMap(({ owner, option }) => { + const value = owner.getOptionValue(option.attributeName()) + const taken = (Array.isArray(value) ? value : [value]).find( + (given) => + typeof given === 'string' && + owned.some(({ option: other }) => + [other.long, other.short].includes(given.split('=', 1)[0]) + ) + ) + if (taken === undefined) return [] + const purpose = option.description.split(/[;(]/, 1)[0].trim() + return [ + `${option.long ?? option.short} took ${taken} as its value; write ${option.flags}: ${purpose}.`, + ] + }) +} + +/** + * A JSON operand typed where one of the command's JSON flags (`--input `) was meant, + * as the line that moves it there with the positionals and the options typed kept. Null when no operand opens like + * JSON or names a source (`@file`, `@-`), or the command has no such flag or several to choose between. + */ +function misplacedJson(command: Command): string[] | null { + const extra = command.args.slice(command.registeredArguments.length) + const json = extra.find((operand) => /^\s*[[{]|^@./.test(operand)) + const owners = command.options.filter( + (option) => !option.hidden && option.long && option.flags.endsWith(` ${JSON_PLACEHOLDER}`) + ) + if (json === undefined || owners.length !== 1 || !owners[0].long) return null + const flag = owners[0].long + const positionals = command.args.slice(0, command.registeredArguments.length) + return [ + `The JSON was passed as a positional; pass it with ${flag} '' (or ${flag} @file).`, + `Example: ${typedCommandLine(command, positionals)} ${flag} ${shellArgument(json)}`, + ] +} + /** * The visible commands beside this one, or in a group beside it, that answer to a flag this one * does not, by any spelling (a hidden alias such as `--row-ids` too), each with its description, @@ -170,7 +219,8 @@ function siblingsDeclaring(command: Command, flag: string): string[] { * - A missing positional or required flag gets the full command line, and a * value typed as a positional where the flag was wanted is named against * that flag when nothing else could have put it there. - * - Too many positionals get the same command line and the flag list. + * - Too many positionals get the same command line and the flag list; an option that took + * another flag as its value is named, and a JSON operand is moved to the JSON flag it belongs to. * - An unknown option gets the command's own flags, and the sibling commands * that do take it: `tables rows list --filter` belongs to `tables rows * query`, which commander's near-spelling suggestion never reaches. @@ -190,8 +240,15 @@ function parseErrorGuidance(command: Command, code: string | undefined): string[ : [] return [...moved, `Example: ${usageExample(command)}`] } - case 'commander.excessArguments': - return [`Example: ${usageExample(command)}`, optionList(command)] + case 'commander.excessArguments': { + const swallowed = swallowedFlags(command) + const moved = swallowed.length === 0 ? misplacedJson(command) : null + return [ + ...swallowed, + ...(moved ?? [`Example: ${usageExample(command)}`]), + optionList(command), + ] + } case 'commander.unknownOption': { const token = unknownOptionToken(command) if (!token) return [] diff --git a/packages/sim-cli/src/runtime/execute.ts b/packages/sim-cli/src/runtime/execute.ts index 0ccda545442..e503d35b0b3 100644 --- a/packages/sim-cli/src/runtime/execute.ts +++ b/packages/sim-cli/src/runtime/execute.ts @@ -22,6 +22,7 @@ import { buildRequest, cursorSlot, flagNameFor, + inlineShapeRefusal, isProfileWorkspacePath, otherSpellings, PROFILE_INJECTED_FIELD, @@ -482,9 +483,18 @@ export async function executeOperation( * exactly the habit the gate depends on not forming. `dry` is a v2-wide * contract flag meaning "persist nothing", so this holds for every command * that accepts it rather than being a per-command exemption. + * + * A JSON flag typed inline with the wrong shape is named in the same refusal, + * so one retry fixes both. */ if (commandSpec.confirm && !requestFlags.yes && requestFlags.dry !== true) { - throw new SimApiError(`${commandSpec.confirm} Re-run with --yes to confirm.`, 0) + const misshapen = inlineShapeRefusal(operation, requestFlags) + throw new SimApiError( + misshapen + ? `${misshapen} Also pass --yes: ${commandSpec.confirm}` + : `${commandSpec.confirm} Re-run with --yes to confirm.`, + 0 + ) } if (commandSpec.allWorkspaces && requestFlags.allWorkspaces && requestFlags.workspace) { diff --git a/packages/sim-cli/src/runtime/naming.ts b/packages/sim-cli/src/runtime/naming.ts index a15dd6248f1..cdc106fc2fd 100644 --- a/packages/sim-cli/src/runtime/naming.ts +++ b/packages/sim-cli/src/runtime/naming.ts @@ -1,3 +1,4 @@ +import { isRecordLike, toArray } from '@sim/utils/object' import type { CommandSpec } from '../contract/types' import type { V2OperationName } from '../generated/v2-api' import { SimApiError } from '../http/client' @@ -152,6 +153,23 @@ function retypeDetails(details: unknown, spellings: Map): unknow return retyped } +/** + * What to send instead when the server refused a JSON flag's object for a key named like the flag's + * own field (`--updates '{"updates":{…}}'`): the value under that key, not the object wrapping it. + * The CLI cannot tell this apart from a real key before sending, since an object field may hold + * any key; the server's `unrecognized_keys` says which it was. + */ +function wrappedObjectHint(details: unknown, spellings: Map): string | null { + for (const issue of Array.isArray(details) ? details : []) { + if (!isRecordLike(issue) || issue.code !== 'unrecognized_keys') continue + const [field, ...rest] = Array.isArray(issue.path) ? issue.path.map(String) : [] + const flag = field === undefined ? undefined : spellings.get(field) + if (rest.length > 0 || !flag?.startsWith('--') || !toArray(issue.keys).includes(field)) continue + return `${flag} takes the object itself: pass the value under its "${field}" key, not the object wrapping it.` + } + return null +} + /** * Restates a server validation error in the spellings the terminal accepts. * @@ -175,8 +193,10 @@ export function retypeApiError( const spellings = typeableFields(operation, commandSpec, operationSpec) if (spellings.size === 0) return error + const hint = wrappedObjectHint(error.details, spellings) + const message = retypeLocatedMessage(error.message, spellings) return new SimApiError( - retypeLocatedMessage(error.message, spellings), + hint ? `${message} ${hint}` : message, error.status, error.code, error.details === undefined ? undefined : retypeDetails(error.details, spellings), diff --git a/packages/sim-cli/src/runtime/options.ts b/packages/sim-cli/src/runtime/options.ts index 9c6f72f4a5a..49c825cc374 100644 --- a/packages/sim-cli/src/runtime/options.ts +++ b/packages/sim-cli/src/runtime/options.ts @@ -14,6 +14,9 @@ import { } from './request' import type { OperationSpec } from './types' +/** The value placeholder of a flag that takes JSON inline or from a file. */ +export const JSON_PLACEHOLDER = '' + /** Collects every use of a repeatable option, in order. */ export function collectRepeated(value: string, previous: string[] = []): string[] { return [...previous, value] @@ -222,7 +225,7 @@ function addFieldOption( : flag.rowCap ? '' : wantsJson - ? '' + ? JSON_PLACEHOLDER : flag.textSource ? '' : descriptor.nullable @@ -325,13 +328,13 @@ export function addOperationOptions( if (commandSpec.bodyVariants) { for (const variant of commandSpec.bodyVariants) { command.option( - `--${variant.name} `, + `--${variant.name} ${JSON_PLACEHOLDER}`, `${variant.describe} (JSON, or @path / @-; choose exactly one body flag)` ) } } else { command.requiredOption( - '--body ', + `--body ${JSON_PLACEHOLDER}`, 'Request body as JSON (or @path / @- to read a file or stdin) (required)' ) } diff --git a/packages/sim-cli/src/runtime/request.ts b/packages/sim-cli/src/runtime/request.ts index 1ff2dc51d64..dcbb22636ed 100644 --- a/packages/sim-cli/src/runtime/request.ts +++ b/packages/sim-cli/src/runtime/request.ts @@ -9,40 +9,101 @@ import { embeddedFileContent } from '../transfer/local-file' import { camel, kebab } from './derive' import type { OperationSpec } from './types' -const BODY_VARIANT_EXAMPLES: Readonly> = { +type JsonShape = 'object' | 'array' + +const JSON_SHAPE_EXAMPLES: Readonly> = { array: `'[{"key":"value"}]'`, object: `'{"key":"value"}'`, } -function jsonShape(value: unknown): BodyVariantSpec['kind'] | undefined { +function jsonShape(value: unknown): JsonShape | undefined { if (Array.isArray(value)) return 'array' if (isRecordLike(value)) return 'object' return undefined } /** - * The refusal for a body variant given the wrong JSON shape, stating what came - * in and the spelling that takes it. Neither `--rows '{"rows":[...]}'` nor a - * single-row `--rows` is reshaped, because guessing which part the caller + * The refusal for a JSON flag given the wrong shape, stating what came in and a value of the + * right one. An object wrapping the value under the field's own name (`--operations + * '{"operations":[…]}'`) is named as such, but never unwrapped: guessing which part the caller * meant is the server's write to make. */ +function wrongJsonShape( + flag: string, + kind: JsonShape, + property: string, + parsed: unknown, + example = JSON_SHAPE_EXAMPLES[kind] +): string { + const shape = jsonShape(parsed) + const got = shape ? `a JSON ${shape}` : parsed === null ? 'null' : `a JSON ${typeof parsed}` + const base = `${flag} must be a JSON ${kind}, e.g. ${flag} ${example}; got ${got}.` + return isRecordLike(parsed) && jsonShape(parsed[property]) === kind + ? `${base} Pass the ${kind} under its "${property}" key itself, not the object wrapping it.` + : base +} + +/** + * The refusal for a body variant given the wrong JSON shape, naming the variant that takes the + * shape that came in. Neither `--rows '{"rows":[...]}'` nor a single-row `--rows` is reshaped. + */ function bodyVariantShapeError( variant: BodyVariantSpec, parsed: unknown, - shape: BodyVariantSpec['kind'] | undefined, variants: readonly BodyVariantSpec[] ): string { - const flag = `--${variant.name}` - const got = shape ? `a JSON ${shape}` : parsed === null ? 'null' : `a JSON ${typeof parsed}` - const base = `${flag} must be a JSON ${variant.kind}, e.g. ${flag} ${BODY_VARIANT_EXAMPLES[variant.kind]}; got ${got}.` - if (variant.kind === 'array' && isRecordLike(parsed) && Array.isArray(parsed[variant.property])) { - return `${base} Pass the array under its "${variant.property}" key itself, not the object wrapping it.` - } + const base = wrongJsonShape(`--${variant.name}`, variant.kind, variant.property, parsed) + if (isRecordLike(parsed) && jsonShape(parsed[variant.property]) === variant.kind) return base + const shape = jsonShape(parsed) const other = shape && variants.find((candidate) => candidate !== variant && candidate.kind === shape) return other ? `${base} For that shape use --${other.name}.` : base } +/** + * The refusal for an array field given an object, or an object field given an array, with the + * shape it takes, so the server's `expected array, received object` does not cost a round trip + * without saying what to send. Null for any other value, which is the server's to judge. + */ +function shapeRefusal( + field: FieldSpec, + flag: FlagSpec, + flagName: string, + property: string, + value: unknown +): string | null { + if ((field.kind !== 'array' && field.kind !== 'object') || flag.list) return null + const shape = jsonShape(value) + if (shape === undefined || shape === field.kind) return null + return wrongJsonShape(`--${flagName}`, field.kind, property, value, flag.example) +} + +/** + * The shape refusal of the first body field typed inline as JSON (`--operations '{…}'`, not + * `@file` or `@-`, which are read only once the command is confirmed), so a refusal for a missing + * `--yes` names the shape mistake beside it and one retry fixes both. + */ +export function inlineShapeRefusal( + operation: V2OperationName, + flags: Record +): string | null { + const { body } = V2_OPERATIONS[operation] as OperationSpec + for (const [field, descriptor] of Object.entries(body ?? {})) { + const flagName = flagNameFor(operation, field) + const raw = flags[camel(flagName)] + if (typeof raw !== 'string' || raw.startsWith('@')) continue + let parsed: unknown + try { + parsed = JSON.parse(raw) + } catch { + continue + } + const refusal = shapeRefusal(descriptor, flagSpecFor(operation, field), flagName, field, parsed) + if (refusal) return refusal + } + return null +} + /** One request field, as the generator describes it. */ export interface FieldSpec { kind: 'string' | 'number' | 'integer' | 'boolean' | 'enum' | 'array' | 'object' | 'unknown' @@ -808,6 +869,9 @@ export async function buildRequest( const value = await coerce(raw ?? undefined, descriptor, flag, flagName) + const misshapen = shapeRefusal(descriptor, flag, flagName, field, value) + if (misshapen) throw new SimApiError(misshapen, 0) + /** * A non-paginated `limit` is a row cap the route bounds at `1`, which is * what `--help` already tells the caller ("note 0 is not accepted") — so @@ -869,12 +933,8 @@ export async function buildRequest( const raw = flags[camel(variant.name)] if (typeof raw !== 'string') throw new SimApiError(`--${variant.name} is required`, 0) const parsed = await coerce(raw, { kind: variant.kind }, { json: true }, variant.name) - const shape = jsonShape(parsed) - if (shape !== variant.kind) { - throw new SimApiError( - bodyVariantShapeError(variant, parsed, shape, commandSpec.bodyVariants), - 0 - ) + if (jsonShape(parsed) !== variant.kind) { + throw new SimApiError(bodyVariantShapeError(variant, parsed, commandSpec.bodyVariants), 0) } return boundedRequest({ params, diff --git a/packages/sim-cli/src/runtime/run-next.ts b/packages/sim-cli/src/runtime/run-next.ts index 8c9017d523c..c4ca50a089d 100644 --- a/packages/sim-cli/src/runtime/run-next.ts +++ b/packages/sim-cli/src/runtime/run-next.ts @@ -1,4 +1,5 @@ import { isRecordLike, toArray, toRecordOrNull } from '@sim/utils/object' +import type { Command } from 'commander' import type { V2OperationName } from '../generated/v2-api' import type { NextStep } from '../output/next-step' @@ -19,6 +20,40 @@ export function shellArgument(value: string): string { return SAFE_ARGUMENT.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'` } +/** + * The command line that reaches `command` as the caller typed it: each command name from the root + * down with the options typed on it (the root's `--workspace` or `--endpoint` too), `operands` after + * the leaf's name, and none of the leaf's options `omit` names by attribute (`draft`), so a + * corrected command a refusal prints keeps everything the caller chose. + */ +export function typedCommandLine( + command: Command, + operands: readonly string[], + omit: ReadonlySet = new Set() +): string { + const path: Command[] = [] + for (let current: Command | null = command; current; current = current.parent) { + path.unshift(current) + } + const words: string[] = [] + for (const step of path) { + words.push(step.name(), ...(step === command ? operands.map(shellArgument) : [])) + for (const option of step.options) { + const key = option.attributeName() + if (!option.long || step.getOptionValueSource(key) !== 'cli') continue + if (step === command && omit.has(key)) continue + const value = step.getOptionValue(key) + for (const given of Array.isArray(value) ? value : [value]) { + if (typeof given === 'string') words.push(option.long, shellArgument(given)) + else if ((given === true && !option.negate) || (given === false && option.negate)) { + words.push(option.long) + } + } + } + } + return words.join(' ') +} + function resumeCommand(runId: string, workflowId: string, contextId: string): string { return `sim workflows runs resume ${shellArgument(runId)} --workflow ${shellArgument(workflowId)} --context ${shellArgument(contextId)}` }