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/cli-docs/src/content/docs/agent-guidance.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ sentry trace logs abc123def456...

```bash
# Stream logs in real-time (auto-detects org/project)
sentry log list --follow
sentry log tail

# Filter logs by severity
sentry log list --query "severity:error"
Expand Down
2 changes: 1 addition & 1 deletion apps/cli-docs/src/content/docs/contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ toolkit/
│ │ │ ├── integration/ # delete, list
│ │ │ ├── issue/ # archive, events, explain, link, list, merge, plan, resolve, tags, unlink, unresolve, view
│ │ │ ├── local/ # close, create, list, reset, restart, retention, run, serve, start, status, stop, view
│ │ │ ├── log/ # list, view
│ │ │ ├── log/ # list, tail, view
│ │ │ ├── monitor/ # list, run
│ │ │ ├── org/ # list, view
│ │ │ ├── platform/ # list
Expand Down
11 changes: 6 additions & 5 deletions apps/cli-docs/src/content/docs/library-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,14 +277,15 @@ The WASM SQLite fallback (Node.js 20–22.14) does not support [WAL mode](https:

## Streaming Commands

Two commands support real-time streaming: `log list --follow` and `dashboard view --refresh`.
When using streaming flags, methods return an `AsyncIterable` instead of a `Promise`:
Two commands support real-time streaming: `log tail` and `dashboard view --refresh`.
`sdk.log.tail()` always returns an `AsyncIterable`; `dashboard view` returns one when you
pass `--refresh`. Other methods return a `Promise`:

```typescript
const sdk = createSentrySDK({ token: "sntrys_..." });

// Stream logs as they arrive (polls every 5 seconds)
for await (const log of sdk.log.list({ follow: "5" }, "acme/backend")) {
for await (const log of sdk.log.tail({ interval: 5 }, "acme/backend")) {
console.log(log);
}

Expand All @@ -294,7 +295,7 @@ for await (const snapshot of sdk.run("dashboard", "view", "123", "--refresh", "3
}

// Stop streaming by breaking out of the loop
for await (const log of sdk.log.list({ follow: "2" })) {
for await (const log of sdk.log.tail()) {
if (someCondition) break; // Streaming stops immediately
}
```
Expand All @@ -311,7 +312,7 @@ const sdk = createSentrySDK({ token: "...", signal: controller.signal });
// Cancel after 30 seconds
setTimeout(() => controller.abort(), 30_000);

for await (const log of sdk.log.list({ follow: "5" })) {
for await (const log of sdk.log.tail({ interval: 5 })) {
console.log(log);
}
// Loop exits when signal fires
Expand Down
2 changes: 1 addition & 1 deletion apps/cli-docs/src/fragments/commands/log.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ available scan accuracy.

Use `--json` for machine-readable output.

In streaming mode with `--json`, each log entry is output as a separate JSON object (newline-delimited JSON), making it suitable for piping to other tools.
With `sentry log tail --json`, each log entry is output as a separate JSON object (newline-delimited JSON), making it suitable for piping to other tools.
9 changes: 8 additions & 1 deletion design/sentry-cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,14 @@ a terminal, with as little setup as the current project allows.
- The CLI never prints a token in full.
- Telemetry goes only to the Sentry CLI's own project, and
`SENTRY_CLI_NO_TELEMETRY=1` or `DO_NOT_TRACK=1` turns it off.
- `-f` means `--fresh` in every command that can bypass the response cache,
and a cached result's footer names the flag that refreshes that command.
- Live output is its own command, such as `sentry log tail`, not a mode flag
on a list or view command. List and view commands return once.
- The library SDK returns an `AsyncIterable` for exactly the invocations that
stream, in its typed methods and in `sdk.run()` alike.

## Gaps

None.
- `sentry dashboard view --refresh` keeps redrawing through a flag instead of
its own command.
2 changes: 1 addition & 1 deletion packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ Options (all optional):
- `text` — Return human-readable string instead of parsed JSON (affects `run()` only).
- `cwd` — Working directory for DSN auto-detection. Defaults to `process.cwd()`.
- `headers` — Extra HTTP headers for self-hosted instances behind a reverse proxy (same as `SENTRY_CUSTOM_HEADERS`). Ignored for sentry.io.
- `signal` — `AbortSignal` to cancel streaming commands (`--follow`, `--refresh`).
- `signal` — `AbortSignal` to cancel streaming commands (`log tail`, `dashboard view --refresh`).

Streaming commands return `AsyncIterable` — use `for await...of` and `break` to stop.

Expand Down
3 changes: 2 additions & 1 deletion packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ sentry trace logs abc123def456...

```bash
# Stream logs in real-time (auto-detects org/project)
sentry log list --follow
sentry log tail

# Filter logs by severity
sentry log list --query "severity:error"
Expand Down Expand Up @@ -728,6 +728,7 @@ Manage User Feedback
View Sentry logs

- `sentry log list <org/project-or-trace-id...>` — List logs from a project
- `sentry log tail <org/project-or-trace-id...>` — Stream new logs from a project or trace
- `sentry log view <org/project/log-id...>` — View details of one or more log entries

→ Full flags and examples: `references/log.md`
Expand Down
55 changes: 45 additions & 10 deletions packages/cli/plugins/sentry-cli/skills/sentry-cli/references/log.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,9 @@ List logs from a project
**Flags:**
- `-n, --limit <value> - Number of log entries (1-1000) - (default: "100")`
- `-q, --query <value> - Filter query (e.g., "severity:error", "project:backend", "project:[a,b]")`
- `-f, --follow <value> - Stream logs (optionally specify poll interval in seconds)`
- `-t, --period <value> - Time range: "7d", "2024-01-01..2024-02-01", ">=2024-01-01"`
- `-s, --sort <value> - Sort order: "newest" (default) or "oldest" - (default: "newest")`
- `--fresh - Bypass cache, re-detect projects, and fetch fresh data`
- `-f, --fresh - Bypass cache, re-detect projects, and fetch fresh data`

**JSON Fields** (use `--json --fields` to select specific fields):

Expand Down Expand Up @@ -61,20 +60,56 @@ sentry log list --limit 50
# List logs for a trace
sentry log list abc123def456abc123def456abc12345

# Filter JSON output with jq
sentry log list --json | jq '.data[] | select(.severity == "error")'

# Filter by trace in an explicit organization
sentry log list my-org/abc123def456abc123def456abc12345
```

### `sentry log tail <org/project-or-trace-id...>`

Stream new logs from a project or trace

**Arguments:**

| Argument | Description |
|----------|-------------|
| `<org/project-or-trace-id...>` | [&lt;org&gt;/[&lt;project&gt;/]]&lt;trace-id&gt;, &lt;org&gt;/&lt;project&gt;, or &lt;project&gt; |

**Flags:**
- `-n, --limit <value> - Max log entries per poll (1-1000) - (default: "100")`
- `-q, --query <value> - Filter query (e.g., "severity:error", "project:backend", "project:[a,b]")`
- `-i, --interval <value> - Poll interval in seconds - (default: "2")`

**JSON Fields** (use `--json --fields` to select specific fields):

| Field | Type | Description |
|-------|------|-------------|
| `sentry.item_id` | string | Unique log entry ID |
| `timestamp` | string | Log timestamp (ISO 8601) |
| `timestamp_precise` | number | Nanosecond-precision timestamp |
| `message` | string \| null | Log message |
| `severity` | string \| null | Severity level (error, warning, info, debug) |
| `trace` | string \| null | Trace ID for correlation |

**Examples:**

```bash
# Stream logs (2-second poll interval)
sentry log list -f
sentry log tail

# Stream logs (5-second poll interval)
sentry log list -f 5
# Poll every 5 seconds
sentry log tail --interval 5

# Stream error logs from a specific project
sentry log list my-org/backend -f -q 'severity:error'
sentry log tail my-org/backend -q 'severity:error'

# Filter JSON output with jq
sentry log list --json | jq '.data[] | select(.severity == "error")'
# Stream the logs of a trace
sentry log tail abc123def456abc123def456abc12345

# Filter by trace in an explicit organization
sentry log list my-org/abc123def456abc123def456abc12345
# Stream JSONL for another tool
sentry log tail --json | jq 'select(.severity == "error")'
```

### `sentry log view <org/project/log-id...>`
Expand Down
73 changes: 59 additions & 14 deletions packages/cli/script/generate-sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
withJsDoc,
} from "./ts-codegen.js";
import { logger } from "../src/lib/logger.js";
import { streamingModeOf } from "../src/lib/streaming-commands.js";

// ---------------------------------------------------------------------------
// Configuration
Expand All @@ -54,9 +55,6 @@ const INTERNAL_FLAGS = new Set([
"fields",
]);

/** Flags that trigger streaming mode — included in params but change return type */
const STREAMING_FLAGS = new Set(["refresh", "follow"]);

/** Regex for stripping angle-bracket/ellipsis decorators from placeholder names */
const PLACEHOLDER_CLEAN_RE = /[<>.]/g;

Expand Down Expand Up @@ -405,6 +403,8 @@ type SdkMethod = {
flags: SdkFlagInfo[];
/** Flags that switch the command into streaming mode (`AsyncIterable` result). */
streamingFlags: SdkFlagInfo[];
/** Whether the command always streams (`log tail`), whatever its flags. */
alwaysStreams: boolean;
/** Name of the params type, when the command has named params. */
paramsTypeName?: string | undefined;
/** Whether a required flag makes the params object mandatory. */
Expand All @@ -413,6 +413,13 @@ type SdkMethod = {
resultTypeName?: string | undefined;
};

/** `AsyncIterable<unknown>`, the result of a streaming call. */
function asyncIterableType(): ts.TypeNode {
return typeRef("AsyncIterable", [
f.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
]);
}

/** The method's result type (`FooResult`, or `unknown`). */
function resultType(method: SdkMethod): ts.TypeNode {
return method.resultTypeName
Expand Down Expand Up @@ -464,7 +471,7 @@ function methodParameters(

/**
* Params type for the streaming overload: the regular params with every streaming
* flag required (`LogListParams & { follow: string }`).
* flag required (`DashboardViewParams & { refresh: string }`).
*/
function streamingParamsType(method: SdkMethod): ts.TypeNode {
const base = method.paramsTypeName
Expand All @@ -487,6 +494,20 @@ function streamingParamsType(method: SdkMethod): ts.TypeNode {
* signatures: passing a streaming flag returns an `AsyncIterable`, otherwise a `Promise`.
*/
function methodTypeMember(method: SdkMethod, name: string): ts.TypeElement {
if (method.alwaysStreams) {
return withJsDoc(
f.createMethodSignature(
undefined,
propertyName(name),
undefined,
undefined,
methodParameters(method),
asyncIterableType(),
),
method.brief,
);
}

const promise = typeRef("Promise", [resultType(method)]);

if (method.streamingFlags.length === 0) {
Expand All @@ -507,9 +528,7 @@ function methodTypeMember(method: SdkMethod, name: string): ts.TypeElement {
f.createCallSignature(
undefined,
methodParameters(method, streamingParamsType(method)),
typeRef("AsyncIterable", [
f.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
]),
asyncIterableType(),
),
f.createCallSignature(undefined, methodParameters(method), promise),
]);
Expand Down Expand Up @@ -545,8 +564,15 @@ function positionalArgs(positional: PositionalInfo): ts.Expression {
);
}

/** `invoke<Result>(path, flags, positional[, { streaming }])` */
function invokeCall(method: SdkMethod, streaming: boolean): ts.CallExpression {
/**
* `invoke<Result>(path, flags, positional[, { streaming }])`. `streaming` picks
* `meta`: `"runtime"` passes the local `streaming` variable, `"always"` passes
* `true`, and omitting it passes no `meta` for commands that never stream.
*/
function invokeCall(
method: SdkMethod,
streaming?: "runtime" | "always",
): ts.CallExpression {
const path = f.createArrayLiteralExpression(
method.path.map((segment) => f.createStringLiteral(segment)),
);
Expand All @@ -562,7 +588,9 @@ function invokeCall(method: SdkMethod, streaming: boolean): ts.CallExpression {
if (streaming) {
args.push(
f.createObjectLiteralExpression([
f.createShorthandPropertyAssignment("streaming"),
streaming === "always"
? f.createPropertyAssignment("streaming", f.createTrue())
: f.createShorthandPropertyAssignment("streaming"),
]),
);
}
Expand All @@ -589,11 +617,24 @@ function sdkMemberType(path: string[]): ts.TypeNode {
* The method's implementation inside `createSDKMethods`.
*
* Regular commands narrow the invoker's `Promise | AsyncIterable` union to a `Promise`,
* since they never pass `meta.streaming`. Streaming commands decide at runtime whether a
* since they never pass `meta.streaming`; always-streaming commands narrow it to the
* `AsyncIterable`. Streaming commands decide at runtime whether a
* streaming flag is present; a single arrow cannot express their overloads, so it is
* asserted to the overloaded type declared in `SentrySDK`.
*/
function methodImplementation(method: SdkMethod): ts.Expression {
if (method.alwaysStreams) {
const iterable = asyncIterableType();
return f.createArrowFunction(
undefined,
undefined,
methodParameters(method),
iterable,
undefined,
f.createAsExpression(invokeCall(method, "always"), iterable),
);
}

const promise = typeRef("Promise", [resultType(method)]);

if (method.streamingFlags.length === 0) {
Expand All @@ -603,7 +644,7 @@ function methodImplementation(method: SdkMethod): ts.Expression {
methodParameters(method),
promise,
undefined,
f.createAsExpression(invokeCall(method, false), promise),
f.createAsExpression(invokeCall(method), promise),
);
}

Expand Down Expand Up @@ -632,7 +673,7 @@ function methodImplementation(method: SdkMethod): ts.Expression {
ts.NodeFlags.Const,
),
),
f.createReturnStatement(invokeCall(method, true)),
f.createReturnStatement(invokeCall(method, "runtime")),
],
true,
);
Expand Down Expand Up @@ -765,6 +806,7 @@ export async function emit(): Promise<void> {

for (const { path, command } of allCommands) {
const flags = extractSdkFlags(command);
const streaming = streamingModeOf(command);
const positional = derivePositional(command);

const returnType = buildReturnType(command, `${buildTypeName(path)}Result`);
Expand All @@ -786,7 +828,10 @@ export async function emit(): Promise<void> {
brief: command.brief || path.join(" "),
positional,
flags,
streamingFlags: flags.filter((flag) => STREAMING_FLAGS.has(flag.name)),
streamingFlags: flags.filter(
(flag) => streaming?.flag !== undefined && flag.name === streaming.flag,
),
alwaysStreams: streaming !== undefined && streaming.flag === undefined,
paramsTypeName: params?.name.text,
paramsRequired: flags.some((flag) => !flag.optional),
resultTypeName: returnType?.name.text,
Expand Down
36 changes: 36 additions & 0 deletions packages/cli/script/generate-streaming-commands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Generate Which Commands Stream, for `sdk.run()`
*
* `sdk.run()` takes raw CLI arguments and must decide between a `Promise`
* and an `AsyncIterable` before it loads any command. This script reads the
* `streams` marker of every command in the loaded route tree and writes them
* out, so the runtime check comes from the command definitions instead of a
* hand-kept list.
*
* The output is gitignored and regenerated by `generate:docs`, which runs as
* part of `dev`, `build`, `bundle`, `typecheck`, and `test`.
*
* Usage: pnpm ts script/generate.ts streaming-commands
* Output: src/generated/streaming-commands.json
*/

import { mkdirSync } from "node:fs";
import { writeFile } from "node:fs/promises";
import { routes } from "../src/app.js";
import type { RouteMap } from "../src/lib/introspect.js";
import { logger } from "../src/lib/logger.js";
import { collectStreamingCommands } from "../src/lib/streaming-commands.js";

const OUTPUT_PATH = "src/generated/streaming-commands.json";

/** Write the streaming mode of every streaming command. */
export async function emit(): Promise<void> {
const commands = collectStreamingCommands(routes as unknown as RouteMap);

mkdirSync("src/generated", { recursive: true });
await writeFile(OUTPUT_PATH, `${JSON.stringify(commands, null, 2)}\n`);

logger.success(
`Generated ${OUTPUT_PATH} (${Object.keys(commands).length} commands)`,
);
}
Loading
Loading