Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/docs/content/docs/cli/blocks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ sim blocks get <blockId>
```text
Reading it for `sim workflows operations apply`:
id the type to add: `blocks get table` answers table_v2 (an add of legacy
table is refused)
table is refused); `note` says so when it is not the type asked for
inputSchema the field ids inputs takes; operationInputSchema, an operation's own
inputDefinitions the block's inputs by name; one a pair of fields shares (tableId for
tableSelector and manualTableId) is accepted in place of the pair
Expand Down
2 changes: 2 additions & 0 deletions apps/docs/content/docs/cli/output.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ Machine formats preserve API values: a duration remains `1500`, rather than the

Read rows with `jq '.data[]'` and check `.nextCursor` for continuation. A null cursor means pagination is finished; inspect any command-specific truncation flags or notices too. See [Pagination](/cli/scripting#pagination) for limits and memory behavior.

When the CLI adds a note to a single result, such as `sim blocks get table` reading as `table_v2`, JSON and YAML carry it in the result as `note`, so output captured with `2>&1` still parses. Tables and text print it on stderr.

### Tables and text

Tables show UTC timestamps without milliseconds, formatted sizes, `yes`/`no` booleans, and formatted monetary amounts. Each command's reference specifies its units. Long table cells are clipped to one line; use JSON or YAML to inspect the returned value in full.
Expand Down
2 changes: 1 addition & 1 deletion apps/docs/content/docs/cli/reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ sim blocks get <blockId>
```text
Reading it for `sim workflows operations apply`:
id the type to add: `blocks get table` answers table_v2 (an add of legacy
table is refused)
table is refused); `note` says so when it is not the type asked for
inputSchema the field ids inputs takes; operationInputSchema, an operation's own
inputDefinitions the block's inputs by name; one a pair of fields shares (tableId for
tableSelector and manualTableId) is accepted in place of the pair
Expand Down
6 changes: 3 additions & 3 deletions apps/docs/scripts/fixtures/content-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -2281,8 +2281,8 @@
{
"lang": "text",
"meta": null,
"sha256": "83c910b94eeb65b4b76fd1d9852fc5709862a2786abbcb6a6569b444bd176c6f",
"bytes": 821,
"sha256": "f05f71dd72eecf5ceb36589c30b3e47498b55149def346121b7723b17108d191",
"bytes": 871,
"line": 52
}
],
Expand Down Expand Up @@ -11190,7 +11190,7 @@
{
"lang": "text",
"meta": null,
"sha256": "83c910b94eeb65b4b76fd1d9852fc5709862a2786abbcb6a6569b444bd176c6f",
"sha256": "f05f71dd72eecf5ceb36589c30b3e47498b55149def346121b7723b17108d191",
"bytes": null,
"line": null
},
Expand Down
2 changes: 1 addition & 1 deletion packages/sim-cli/src/contract/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ Run logs:
const BLOCK_DETAIL_GUIDE = `
Reading it for \`sim workflows operations apply\`:
id the type to add: \`blocks get table\` answers table_v2 (an add of legacy
table is refused)
table is refused); \`note\` says so when it is not the type asked for
inputSchema the field ids inputs takes; operationInputSchema, an operation's own
inputDefinitions the block's inputs by name; one a pair of fields shares (tableId for
tableSelector and manualTableId) is accepted in place of the pair
Expand Down
11 changes: 7 additions & 4 deletions packages/sim-cli/src/runtime/block-version-note.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,20 @@ function getBlock(requested: string, answered: string) {
}

describe('blocks get for a base type that reads as its newer version', () => {
it('names the type to add on stderr, which a jq filter on stdout cannot drop', async () => {
it('names the type to add inside the JSON, which stays one document when stderr is merged in (2>&1)', async () => {
const result = await getBlock('table', 'table_v2')
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ id: 'table_v2' })
expect(result.stderr).toContain('"table" reads as "table_v2"')
expect(result.stderr).toContain('"type":"table_v2"')
expect(JSON.parse(result.stdout + result.stderr)).toEqual({
id: 'table_v2',
name: 'Table',
note: '"table" reads as "table_v2", its current version; add it as {"type":"table_v2"}.',
})
})

it('says nothing when the type read is the type asked for', async () => {
const result = await getBlock('table_v2', 'table_v2')
expect(result.exitCode).toBe(0)
expect(result.stderr).toBe('')
expect(JSON.parse(result.stdout)).not.toHaveProperty('note')
})
})
22 changes: 17 additions & 5 deletions packages/sim-cli/src/runtime/execute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ const PUBLISH_CHAT: OperationSpec = {
}

const PUBLIC_NOTE =
'note: auth type is public — anyone with the link can chat; pass --auth-type password|email to restrict it.'
'auth type is public — anyone with the link can chat; pass --auth-type password|email to restrict it.'

/** Publishes a chat past its `--yes` gate with the required fields and the given extras. */
function publishChat(flags: Record<string, unknown>) {
Expand Down Expand Up @@ -163,7 +163,7 @@ function streams() {
}

describe('a chat publish that lands on public auth', () => {
it('notes the exposure on stderr when the default chose public, and keeps stdout the record', async () => {
it('carries the exposure in the JSON record when the default chose public, so stdout and stderr merged still parse', async () => {
request.mockResolvedValue({
data: { id: 'chat_1', identifier: 'support', authType: 'public' },
})
Expand All @@ -172,14 +172,26 @@ describe('a chat publish that lands on public auth', () => {
await publishChat({})

expect(request.mock.calls[0][1].body).not.toHaveProperty('authType')
expect(captured.stderr).toContain(PUBLIC_NOTE)
expect(captured.stdout).not.toContain('note:')
expect(JSON.parse(captured.stdout)).toEqual({
expect(JSON.parse(captured.stdout + captured.stderr)).toEqual({
id: 'chat_1',
identifier: 'support',
authType: 'public',
note: PUBLIC_NOTE,
})
})

it('notes the exposure on stderr for a person reading the table, and keeps it out of stdout', async () => {
output.format = 'table'
request.mockResolvedValue({
data: { id: 'chat_1', identifier: 'support', authType: 'public' },
})
const captured = streams()

await publishChat({})

expect(captured.stderr).toContain(`note: ${PUBLIC_NOTE}`)
expect(captured.stdout).not.toContain('anyone with the link')
})
})

describe('a workflow export', () => {
Expand Down
41 changes: 16 additions & 25 deletions packages/sim-cli/src/runtime/execute.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { getErrorMessage } from '@sim/utils/errors'
import { toRecord } from '@sim/utils/object'
import type { Command } from 'commander'
import { writeStderr } from '#sim-cli/output/io'
import { styles } from '#sim-cli/output/presentation'
import {
assertWorkspaceOperationOutcome,
readWorkspaceOperation,
Expand Down Expand Up @@ -215,16 +214,13 @@ function lengthOf(value: unknown): number {
}

/**
* One line of context a successful result deserves, on stderr, in every format.
* One line of context a successful result deserves, placed by {@link renderResult}.
*
* `workflows chat publish` defaults `authType` to `public`, so a caller who
* never typed `--auth-type` has just put a chat on the open internet, and the
* result — `authType: public` among a dozen other fields of the record — does
* not make that leap out. The note is printed whether the default or an
* not make that leap out. The note is given whether the default or an
* explicit `--auth-type public` chose it: the exposure is the same either way.
* stderr, so `sim workflows chat publish … --output json | jq` still reads
* exactly the record; every format gets it because a JSON consumer is the one
* least likely to look at the record.
*
* Judged on the response first and the request second: the server states what
* it stored, and a body that omitted the field landed on the server's default.
Expand All @@ -233,15 +229,15 @@ const RESULT_NOTES: Readonly<
Partial<
Record<
V2OperationName,
(payload: Record<string, unknown>, request: BuiltRequest) => string | null
(payload: Record<string, unknown>, request: BuiltRequest) => string | undefined
>
>
> = {
replaceWorkflowChatDeployment: (payload, { body }) => {
const authType = payload.authType ?? body?.authType ?? 'public'
return authType === 'public'
? 'note: auth type is public — anyone with the link can chat; pass --auth-type password|email to restrict it.'
: null
? 'auth type is public — anyone with the link can chat; pass --auth-type password|email to restrict it.'
: undefined
},
/**
* `blocks get table` answers with `table_v2`, the type an add takes, and an add of the base
Expand All @@ -251,25 +247,18 @@ const RESULT_NOTES: Readonly<
getBlock: (payload, { params }) => {
const requested = params.blockId
return typeof payload.id === 'string' && requested !== undefined && payload.id !== requested
? `note: "${requested}" reads as "${payload.id}", its current version; add it as {"type":"${payload.id}"}.`
: null
? `"${requested}" reads as "${payload.id}", its current version; add it as {"type":"${payload.id}"}.`
: undefined
},
}

/** Writes the operation's result note to stderr, when it has one and the result calls for it. */
function writeResultNote(
/** The operation's result note, when it has one and the result calls for it. */
function resultNote(
operation: V2OperationName,
payload: unknown,
request: BuiltRequest
): void {
const note = RESULT_NOTES[operation]
if (!note) return
const record =
payload && typeof payload === 'object' && !Array.isArray(payload)
? (payload as Record<string, unknown>)
: {}
const message = note(record, request)
if (message) writeStderr(styles().dim(`${message}\n`))
): string | undefined {
return RESULT_NOTES[operation]?.(toRecord(payload), request)
}

/** The one-line explanation of a bulk call that changed nothing, or `null`. */
Expand Down Expand Up @@ -679,12 +668,14 @@ export async function executeOperation(
profile.output,
payload,
commandSpec,
{ expandedTrace: requestFlags.trace === true },
{
expandedTrace: requestFlags.trace === true,
note: resultNote(operation, payload, request),
},
// The envelope, not just the payload: a list that does not paginate states
// its own truncation there, and unwrapping `data` discarded it.
result
)
writeResultNote(operation, payload, request)

// Printed first, then failed, for the reason `followRun` gives: the envelope
// carries the block outputs that explain *why* the run failed, and exiting
Expand Down
38 changes: 35 additions & 3 deletions packages/sim-cli/src/runtime/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ const RUN_COMMAND_FIELDS: ReadonlySet<string> = new Set(['next', 'next note'])

interface RenderResultOptions {
expandedTrace?: boolean
/** One line of context the CLI adds to a successful result (see {@link renderResult}). */
note?: string
}

function countTraceSpans(value: unknown): number {
Expand Down Expand Up @@ -448,14 +450,25 @@ function writeEnvelopeTruncation(envelope: unknown): void {
}
}

/** Whether `format` prints one parseable document rather than lines for a person. */
function isMachineFormat(format: OutputFormat): boolean {
return format === 'json' || format === 'yaml'
}

/** A result whose `next` a person reads: its command, then why ({@link nextStepText}). */
function withNextText(data: unknown): unknown {
if (!isRecordLike(data)) return data
const step = nextStepText(data.next)
return step === null ? data : { ...data, next: step }
}

/** Renders one non-paginated operation result according to its CLI contract. */
/**
* Renders one non-paginated operation result according to its CLI contract.
*
* `options.note` joins a machine-format result as `note`, so `--output json 2>&1` stays one
* document; a display format, a document, a non-record payload, or one with its own `note` gets
* it on stderr after the record.
*/
export function renderResult(
operation: V2OperationName,
format: OutputFormat,
Expand All @@ -467,7 +480,26 @@ export function renderResult(
// Before any branch: the flag lives on the envelope `execute` unwraps one
// line before rendering, and states a fact about the payload below it.
writeEnvelopeTruncation(envelope)
const { note } = options
const noted =
note !== undefined &&
isMachineFormat(format) &&
!spec.document &&
isRecordLike(raw) &&
!('note' in raw)
? { ...raw, note }
: null
printResult(operation, format, noted ?? raw, spec, options)
if (note !== undefined && !noted) writeStderr(styles().dim(`note: ${note}\n`))
}

function printResult(
operation: V2OperationName,
format: OutputFormat,
raw: unknown,
spec: CommandSpec,
options: RenderResultOptions
): void {
if (spec.document) {
printDocument(format, raw)
return
Expand All @@ -477,8 +509,8 @@ export function renderResult(
// printed nothing. Machine formats print the API's data as the OpenAPI shape the docs and the
// agent reference card are generated from, except a lint report's graph facts, plus the fields
// the CLI adds for a run or deploy: `live`, and `next` with `{ command, reason }` (a person
// reads it as the command, then why).
const machine = format === 'json' || format === 'yaml'
// reads it as the command, then why), and a result's `note` ({@link renderResult}).
const machine = isMachineFormat(format)
const added = withRunNext(
operation,
withDeploymentLive(operation, withLintFindingsOnly(machine ? raw : unwrapResource(raw)))
Expand Down
Loading