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
4 changes: 2 additions & 2 deletions apps/docs/content/docs/cli/output.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ 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.
What the CLI states about a successful result travels inside it in JSON and YAML, so output captured with `2>&1` still parses: a server-side clip as the response's truncation flag (`truncated`, `toolNamesTruncated`), a fact about a whole list as its envelope field beside `data` and `nextCursor` (`sim billing logs` carries `scope`), and the CLI's own notes as `note`, one per line, such as `sim blocks get table` reading as `table_v2` or a renamed command or flag. Tables and text print each on stderr. A result that is not an object, or a document such as `sim workflows export`, keeps them on stderr.

### Tables and text

Expand All @@ -52,7 +52,7 @@ An absent value displays as an em dash in a table and an empty field in text. Us

## Separate results and diagnostics

Results go to stdout. Errors, progress, update notices, and operational notes go to stderr, so this pipe receives only the result:
Results go to stdout. Errors, progress, and update notices go to stderr, so this pipe receives only the result. In JSON and YAML output, a rate-limit retry notice is shown only when stderr is a terminal:

```bash
sim logs list --output json | jq '.data[]'
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 @@ -315,7 +315,7 @@ export const CLI_CONTRACT: CliContract = {
// Which ledger answered: a user credential reports only the calling user's
// events, a workspace key the whole workspace. The difference was silent —
// same workspace, same window, same flags, a strictly smaller result.
pageNote: { path: 'scope', label: 'scope' },
pageNote: { field: 'scope', label: 'scope' },
columns: [
{ header: 'at', path: 'createdAt', format: 'timestamp' },
{ header: 'workspace', path: 'workspaceId' },
Expand Down
14 changes: 6 additions & 8 deletions packages/sim-cli/src/contract/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,19 +326,17 @@ export interface CommandSpec {
/** Dot path to a nested result array rendered as the command's human list. */
itemsPath?: string
/**
* A page-envelope field that qualifies the whole list, stated once for the
* human formats.
* A top-level page-envelope field that qualifies the whole list.
*
* `billing logs` answers a different question depending on the credential —
* an OAuth login or personal key sees the caller's own events, while a
* workspace key sees the whole workspace ledger. The response says which. The value
* belongs to the query rather than to any row, so it is not a column; it goes
* to stderr so that a `--output text` consumer cutting tab-separated fields
* still reads only rows. `json` and `yaml` print the unwrapped `data` array
* and so drop the field too, which is why the note is not limited to the
* human formats — see `runtime/result`.
* belongs to the query rather than to any row, so it is not a column: `json` and
* `yaml` carry it beside `data` and `nextCursor` under its wire name, and the human
* formats state it once on stderr as `label`, so a `--output text` consumer cutting
* tab-separated fields still reads only rows — see `runtime/result`.
*/
pageNote?: { path: string; label: string }
pageNote?: { field: string; label: string }
/** Allow an optional workspaceId field to omit the configured workspace filter. */
allWorkspaces?: boolean
/**
Expand Down
67 changes: 34 additions & 33 deletions packages/sim-cli/src/http/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,17 @@ afterEach(() => {
// SIM_DEBUG set for one test would otherwise configure every test after it.
})

function client(options: { apiKey?: string } = { apiKey: 'key' }): SimClient {
function client(
options: { apiKey?: string; output?: 'json' | 'table' } = { apiKey: 'key' }
): SimClient {
return new SimClient({
name: 'default',
endpoint: 'https://sim.example',
authProfile: 'default',
apiKey: options.apiKey ?? null,
oauth: null,
workspaceId: 'ws_1',
output: 'json',
output: options.output ?? 'json',
sources: {
endpoint: 'default',
credential: 'env',
Expand All @@ -33,7 +35,7 @@ function client(options: { apiKey?: string } = { apiKey: 'key' }): SimClient {
})
}

function _stubStderr(isTTY: boolean): { writes: string[]; restore: () => void } {
function stubStderr(isTTY: boolean): { writes: string[]; restore: () => void } {
const writes: string[] = []
const originalTTY = Object.getOwnPropertyDescriptor(process.stderr, 'isTTY')
const originalWrite = process.stderr.write
Expand Down Expand Up @@ -474,36 +476,35 @@ describe('rate limiting', () => {
expect(fetch).toHaveBeenCalledTimes(2)
})

it('says on stderr how long it waits before resending a request answered 429', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
const written: string[] = []
const write = vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => {
written.push(String(chunk))
return true
})
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValueOnce(limited('7'))
.mockResolvedValueOnce(Response.json({ data: {} }))
)
it.each([
{ output: 'json', said: false },
{ output: 'table', said: true },
] as const)(
'off a terminal, says it waits on a 429 for $output output only when that is not a document a 2>&1 capture parses',
async ({ output, said }) => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
const stderr = stubStderr(false)
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValueOnce(limited('7'))
.mockResolvedValueOnce(Response.json({ data: {} }))
)

await settle(client().request('/api/v2/tables/tbl_1'))
write.mockRestore()
await settle(client({ apiKey: 'key', output }).request('/api/v2/tables/tbl_1'))
stderr.restore()

expect(written.join('')).toMatch(/Rate limited \(HTTP 429\); retrying in 7s \(retry 1 of 6\)/)
})
expect(fetch).toHaveBeenCalledTimes(2)
expect(stderr.writes.join('')).toBe(
said ? 'Rate limited (HTTP 429); retrying in 7s (retry 1 of 6).\n' : ''
)
}
)

it('clears a terminal progress line before saying it waits on a 429', async () => {
it('says at a terminal how long it waits on a 429, clearing a progress line first', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
const written: string[] = []
const tty = Object.getOwnPropertyDescriptor(process.stderr, 'isTTY')
Object.defineProperty(process.stderr, 'isTTY', { value: true, configurable: true })
const write = vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => {
written.push(String(chunk))
return true
})
const stderr = stubStderr(true)
vi.stubGlobal(
'fetch',
vi
Expand All @@ -513,11 +514,11 @@ describe('rate limiting', () => {
)

await settle(client().request('/api/v2/tables/tbl_1'))
write.mockRestore()
if (tty) Object.defineProperty(process.stderr, 'isTTY', tty)
else Reflect.deleteProperty(process.stderr, 'isTTY')
stderr.restore()

expect(written.join('')).toMatch(/^\r\u001b\[K.*Rate limited \(HTTP 429\)/)
expect(stderr.writes.join('')).toMatch(
/^\r\u001b\[K.*Rate limited \(HTTP 429\); retrying in 7s \(retry 1 of 6\)/
)
})

it('resends a GET answered 429 even when that response body is lost', async () => {
Expand Down
14 changes: 10 additions & 4 deletions packages/sim-cli/src/http/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -786,10 +786,16 @@ export class SimClient {
)
const backoffMs = backoffWithJitter(rateLimitResends + 1, null, RATE_LIMIT_BACKOFF)
const waitMs = Math.max(retryAfterMs ?? 0, backoffMs)
// On a terminal, clear a `fetched N…` paging line first, so the notice starts its own line.
writeStderr(
`${hasProgressTerminal() ? '\r\u001b[K' : ''}${styles().dim(`Rate limited (HTTP 429); retrying in ${Math.ceil(waitMs / 1000)}s (retry ${rateLimitResends + 1} of ${RATE_LIMIT_RETRIES}).`)}\n`
)
// Explains a wait of up to minutes, at a terminal or in a CI log of human output. Not in a
// JSON or YAML run off a terminal: there it would land inside a `--output json 2>&1`
// capture of a request that then succeeds, and one whose retries run out is its error.
// On a terminal, a `fetched N…` paging line is cleared first.
const terminal = hasProgressTerminal()
if (terminal || (this.profile.output !== 'json' && this.profile.output !== 'yaml')) {
writeStderr(
`${terminal ? '\r\u001b[K' : ''}${styles().dim(`Rate limited (HTTP 429); retrying in ${Math.ceil(waitMs / 1000)}s (retry ${rateLimitResends + 1} of ${RATE_LIMIT_RETRIES}).`)}\n`
)
}
await interruptibleSleep(waitMs, caller)
if (caller?.aborted) throw new SimApiError('Request cancelled.', 0, REQUEST_CANCELLED)
return this.send(path, options, retriedAfterRefresh, rateLimitResends + 1)
Expand Down
27 changes: 20 additions & 7 deletions packages/sim-cli/src/runtime/build.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
buildGeneratedCommands,
} from './build'
import { kebab } from './derive'
import { resetRenameWarnings } from './renamed'
import type { OperationSpec } from './types'

/**
Expand Down Expand Up @@ -824,7 +823,10 @@ describe('bodies and fields the generator cannot flatten', () => {

describe('spellings the CLI has retired', () => {
beforeEach(() => {
resetRenameWarnings()
output.format = 'table'
return () => {
output.format = 'json'
}
})

function warnings(): string[] {
Expand All @@ -845,6 +847,14 @@ describe('spellings the CLI has retired', () => {
expect(written.join('')).toContain('"--q" has been renamed to "--query"')
})

it('warns once when a successful answer cannot be printed after the warning was written', async () => {
const written = warnings()
await expect(
run(['tables', 'rows', 'find', 'tbl_1', '--q', 'needle'], { data: { matches: 'not a list' } })
).rejects.toThrow('expected an array')
expect(written.join('').match(/"--q" has been renamed/g)).toHaveLength(1)
})

it('refuses both spellings of one flag rather than picking a winner', async () => {
await expect(
run([
Expand Down Expand Up @@ -1007,17 +1017,18 @@ describe('a list that is not the whole answer', () => {
/**
* The server clips an inventory itself and says so on the envelope, which the
* CLI reports separately from data and nextCursor so a reconciling caller
* can distinguish a clipped inventory from a complete one.
* can distinguish a clipped inventory from a complete one. JSON carries the
* flag beside them (`result-notices.test.ts`); a person reads it on stderr.
*/
it('carries a truncation the server stated on the envelope', async () => {
const paged = await noteFor('json', ['workflow-mcp-servers', 'list'], {
it('tells a person about a truncation the server stated on the envelope', async () => {
const paged = await noteFor('table', ['workflow-mcp-servers', 'list'], {
data: [{ id: 'srv_1' }],
nextCursor: null,
toolNamesTruncated: true,
})
expect(paged).toContain('tool names truncated')

const unpaged = await noteFor('json', ['workflow-mcp-servers', 'tools', 'list', 'srv_1'], {
const unpaged = await noteFor('table', ['workflow-mcp-servers', 'tools', 'list', 'srv_1'], {
data: [{ toolName: 't' }],
nextCursor: null,
truncated: true,
Expand All @@ -1026,7 +1037,7 @@ describe('a list that is not the whole answer', () => {
})

/** A flag raised on a later page is the same fact, and used to be lost. */
it('carries a truncation stated on a page after the first', async () => {
it('tells a person about a truncation stated on a page after the first', async () => {
mockRequest.mockReset()
mockRequest
.mockResolvedValueOnce({ data: [{ id: 'a' }], nextCursor: 'c1', toolNamesTruncated: false })
Expand All @@ -1040,9 +1051,11 @@ describe('a list that is not the whole answer', () => {
return true
})

output.format = 'table'
try {
await program().parseAsync(['node', 'sim', 'workflow-mcp-servers', 'list', '--limit', '0'])
} finally {
output.format = 'json'
written.mockRestore()
}

Expand Down
15 changes: 10 additions & 5 deletions packages/sim-cli/src/runtime/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { deriveCommandPath } from './derive'
import { executeOperation } from './execute'
import { retypeApiError } from './naming'
import { addOperationOptions, JSON_PLACEHOLDER } from './options'
import { warnRenamedCommand } from './renamed'
import { warnRenamedCommand, writeRenameWarnings } from './renamed'
import {
flagNameFor,
flagSpecFor,
Expand Down Expand Up @@ -524,9 +524,14 @@ function configureOperation(
// The last frame that still knows which operation ran, and so the only one
// that can say `--include-job-runs` where the server said `includeJobRuns`.
command.action((...invocation: unknown[]) =>
executeOperation(operation, spec, operationSpec, invocation).catch((error) => {
throw retypeApiError(error, operation, spec, operationSpec)
})
// A rename warning no result took (a failure, or a path that prints none) still reaches stderr.
executeOperation(operation, spec, operationSpec, invocation).then(
() => writeRenameWarnings(command),
(error) => {
writeRenameWarnings(command)
throw retypeApiError(error, operation, spec, operationSpec)
}
)
)
return command
}
Expand Down Expand Up @@ -562,7 +567,7 @@ function addRenamedCommand(
}

const leaf = configureOperation(new Command(rest[rest.length - 1]), operation, spec)
leaf.hook('preAction', () => warnRenamedCommand(from, to))
leaf.hook('preAction', () => warnRenamedCommand(leaf, from, to))
addSubcommand(parent, leaf, { hidden: true })
}

Expand Down
19 changes: 14 additions & 5 deletions packages/sim-cli/src/runtime/execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { safeOneLine } from '../output/render'
import { connect } from './called-operations'
import { camel } from './derive'
import { DEFAULT_PAGE_SIZE, defaultListLimit } from './options'
import { warnRenamedFlag } from './renamed'
import { deliveredRenameWarnings, owedRenameWarnings, warnRenamedFlag } from './renamed'
import {
type BuiltRequest,
buildRequest,
Expand Down Expand Up @@ -375,6 +375,7 @@ function assertSelectorIsUsable(operation: V2OperationName, flags: Record<string
* reading of "the documented one wins" is more likely to be the intended one.
*/
function foldOtherSpellings(
host: Command,
operation: V2OperationName,
commandSpec: CommandSpec,
flags: Record<string, unknown>
Expand All @@ -390,7 +391,7 @@ function foldOtherSpellings(
0
)
}
if (renamed) warnRenamedFlag(name, current)
if (renamed) warnRenamedFlag(host, name, current)
flags[camel(current)] = supplied
}
}
Expand Down Expand Up @@ -459,7 +460,7 @@ export async function executeOperation(
requestFlags[camel(name)] = trailingValues
}

foldOtherSpellings(operation, commandSpec, requestFlags)
foldOtherSpellings(host, operation, commandSpec, requestFlags)
assertCapIsUsable(operation, requestFlags)
assertSelectorIsUsable(operation, requestFlags)

Expand Down Expand Up @@ -588,7 +589,10 @@ export async function executeOperation(
} finally {
progress.finish()
}
renderPage(profile.output, { data: rows, nextCursor: cursor }, commandSpec, envelope)
renderPage(profile.output, { data: rows, nextCursor: cursor }, commandSpec, envelope, {
warnings: owedRenameWarnings(host),
warningsDelivered: () => deliveredRenameWarnings(host),
})
return
}

Expand Down Expand Up @@ -669,7 +673,10 @@ export async function executeOperation(
report
))
payload = report
renderResult(operation, profile.output, payload, commandSpec)
renderResult(operation, profile.output, payload, commandSpec, {
warnings: owedRenameWarnings(host),
warningsDelivered: () => deliveredRenameWarnings(host),
})
assertWorkspaceOperationOutcome(report, timedOut)
return
}
Expand All @@ -681,6 +688,8 @@ export async function executeOperation(
{
expandedTrace: requestFlags.trace === true,
note: resultNote(operation, payload, request),
warnings: owedRenameWarnings(host),
warningsDelivered: () => deliveredRenameWarnings(host),
},
// The envelope, not just the payload: a list that does not paginate states
// its own truncation there, and unwrapping `data` discarded it.
Expand Down
Loading
Loading