Skip to content

Commit 2585edb

Browse files
authored
fix(audit): show valid values for rejected filters (#124336)
* fix(audit): validate filter flags before gateway call * refactor(audit): keep filter constants owner-local * fix(audit): keep cursor errors operator-facing
1 parent 4be10d4 commit 2585edb

4 files changed

Lines changed: 127 additions & 39 deletions

File tree

‎packages/gateway-protocol/src/schema/audit-activity.ts‎

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,27 @@ import { NonEmptyString } from "./primitives.js";
55

66
const AuditActivitySchemaVersionV1Schema = Type.Integer({ minimum: 1, maximum: 1 });
77

8-
const AuditActivityStatusV1Schema: TSchema = Type.Union([
9-
Type.Literal("started"),
10-
Type.Literal("succeeded"),
11-
Type.Literal("failed"),
12-
Type.Literal("cancelled"),
13-
Type.Literal("timed_out"),
14-
Type.Literal("blocked"),
15-
Type.Literal("unknown"),
16-
]);
17-
18-
const AuditActivityKindV1Schema: TSchema = Type.Union([
19-
Type.Literal("agent_run"),
20-
Type.Literal("tool_action"),
21-
Type.Literal("message"),
22-
]);
23-
24-
const AuditActivityDirectionV1Schema: TSchema = Type.Union([
25-
Type.Literal("inbound"),
26-
Type.Literal("outbound"),
27-
]);
8+
export const AUDIT_ACTIVITY_STATUSES = [
9+
"started",
10+
"succeeded",
11+
"failed",
12+
"cancelled",
13+
"timed_out",
14+
"blocked",
15+
"unknown",
16+
] as const;
17+
export const AUDIT_ACTIVITY_KINDS = ["agent_run", "tool_action", "message"] as const;
18+
export const AUDIT_ACTIVITY_DIRECTIONS = ["inbound", "outbound"] as const;
19+
20+
const AuditActivityStatusV1Schema: TSchema = Type.Union(
21+
AUDIT_ACTIVITY_STATUSES.map((value) => Type.Literal(value)),
22+
);
23+
const AuditActivityKindV1Schema: TSchema = Type.Union(
24+
AUDIT_ACTIVITY_KINDS.map((value) => Type.Literal(value)),
25+
);
26+
const AuditActivityDirectionV1Schema: TSchema = Type.Union(
27+
AUDIT_ACTIVITY_DIRECTIONS.map((value) => Type.Literal(value)),
28+
);
2829

2930
const AuditActivityConversationKindV1Schema = Type.Union([
3031
Type.Literal("direct"),
@@ -607,9 +608,9 @@ export type AuditActivityListParams = {
607608
agentId?: string;
608609
sessionKey?: string;
609610
runId?: string;
610-
kind?: "agent_run" | "tool_action" | "message";
611-
status?: "started" | "succeeded" | "failed" | "cancelled" | "timed_out" | "blocked" | "unknown";
612-
direction?: "inbound" | "outbound";
611+
kind?: (typeof AUDIT_ACTIVITY_KINDS)[number];
612+
status?: (typeof AUDIT_ACTIVITY_STATUSES)[number];
613+
direction?: (typeof AUDIT_ACTIVITY_DIRECTIONS)[number];
613614
channel?: string;
614615
after?: number;
615616
before?: number;

‎src/cli/program/register.audit.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
// Audit command registration for privacy-preserving activity history.
22
import type { Command } from "commander";
3+
import {
4+
AUDIT_ACTIVITY_DIRECTIONS,
5+
AUDIT_ACTIVITY_KINDS,
6+
AUDIT_ACTIVITY_STATUSES,
7+
} from "../../../packages/gateway-protocol/src/schema/audit-activity.js";
38
import { formatDocsLink } from "../../../packages/terminal-core/src/links.js";
49
import { theme } from "../../../packages/terminal-core/src/theme.js";
510
import { auditListCommand, type AuditListCommandOptions } from "../../commands/audit.js";
611
import { defaultRuntime } from "../../runtime.js";
12+
import { formatHumanList } from "../../shared/human-list.js";
713
import { runCommandWithRuntime } from "../cli-utils.js";
814

915
/** Register the bounded operator audit query command. */
@@ -15,12 +21,12 @@ export function registerAuditCommand(program: Command): void {
1521
.option("--session <key>", "Filter by exact session key")
1622
.option("--run <id>", "Filter by run id")
1723
.option("--execution <id>", "Inspect one exact execution id")
18-
.option("--kind <kind>", "Filter by kind (agent_run, tool_action, or message)")
24+
.option("--kind <kind>", `Filter by kind (${formatHumanList(AUDIT_ACTIVITY_KINDS)})`)
25+
.option("--status <status>", `Filter by status (${formatHumanList(AUDIT_ACTIVITY_STATUSES)})`)
1926
.option(
20-
"--status <status>",
21-
"Filter by status (started, succeeded, failed, cancelled, timed_out, blocked, unknown)",
27+
"--direction <direction>",
28+
`Filter message direction (${formatHumanList(AUDIT_ACTIVITY_DIRECTIONS)})`,
2229
)
23-
.option("--direction <direction>", "Filter message direction (inbound or outbound)")
2430
.option("--channel <channel>", "Filter message channel")
2531
.option("--after <timestamp>", "Include records at/after ISO time or Unix milliseconds")
2632
.option("--before <timestamp>", "Include records at/before ISO time or Unix milliseconds")

‎src/commands/audit.test.ts‎

Lines changed: 65 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import {
3+
AUDIT_ACTIVITY_DIRECTIONS,
4+
AUDIT_ACTIVITY_KINDS,
5+
AUDIT_ACTIVITY_STATUSES,
6+
} from "../../packages/gateway-protocol/src/schema/audit-activity.js";
7+
import { runCommandWithRuntime } from "../cli/cli-utils.js";
28
import type { RuntimeEnv } from "../runtime.js";
39
import { auditListCommand } from "./audit.js";
410

@@ -107,13 +113,39 @@ describe("audit command parsing", () => {
107113
expect(callGateway).not.toHaveBeenCalled();
108114
});
109115

110-
it("rejects unknown event kinds before querying the Gateway", async () => {
111-
await expect(
112-
auditListCommand({ kind: "bogus" as never, limit: "10" }, runtime),
113-
).rejects.toThrow("--kind must be agent_run, tool_action, or message");
116+
it.each([
117+
{
118+
options: { kind: "bogus" as never },
119+
message: "--kind must be agent_run, tool_action, or message.",
120+
},
121+
{
122+
options: { status: "bogus" as never },
123+
message:
124+
"--status must be started, succeeded, failed, cancelled, timed_out, blocked, or unknown.",
125+
},
126+
{
127+
options: { direction: "sideways" as never },
128+
message: "--direction must be inbound or outbound.",
129+
},
130+
])("rejects invalid audit filters before querying the Gateway", async ({ options, message }) => {
131+
await expect(auditListCommand({ ...options, limit: "10" }, runtime)).rejects.toThrow(message);
114132
expect(callGateway).not.toHaveBeenCalled();
115133
});
116134

135+
it.each([
136+
["kind", AUDIT_ACTIVITY_KINDS],
137+
["status", AUDIT_ACTIVITY_STATUSES],
138+
["direction", AUDIT_ACTIVITY_DIRECTIONS],
139+
] as const)("forwards every canonical %s value unchanged", async (filter, values) => {
140+
for (const value of values) {
141+
await auditListCommand({ [filter]: value }, runtime);
142+
expect(callGateway).toHaveBeenLastCalledWith({
143+
method: "audit.activity.list",
144+
params: { limit: 100, [filter]: value },
145+
});
146+
}
147+
});
148+
117149
it("renders activity safely without inventing message provenance", async () => {
118150
callGateway.mockResolvedValue({
119151
events: [
@@ -164,6 +196,8 @@ describe("audit command gateway compatibility", () => {
164196
beforeEach(() => {
165197
callGateway.mockReset();
166198
callGateway.mockResolvedValue({ events: [] });
199+
vi.mocked(runtime.error).mockClear();
200+
vi.mocked(runtime.exit).mockClear();
167201
});
168202

169203
it("forwards all filters to audit.activity.list", async () => {
@@ -278,16 +312,41 @@ describe("audit command gateway compatibility", () => {
278312
expect(callGateway).toHaveBeenCalledTimes(1);
279313
});
280314

281-
it("does not fall back for other request errors", async () => {
315+
it("renders other request errors without the Gateway error class name", async () => {
282316
const error = Object.assign(new Error("invalid audit activity params"), {
283317
name: "GatewayClientRequestError",
284318
gatewayCode: "INVALID_REQUEST",
285319
});
286320
callGateway.mockRejectedValueOnce(error);
287321

288-
await expect(auditListCommand({ limit: "10" }, runtime)).rejects.toBe(error);
322+
await runCommandWithRuntime(runtime, () => auditListCommand({ limit: "10" }, runtime));
323+
324+
expect(runtime.error).toHaveBeenCalledWith("Error: invalid audit activity params");
325+
expect(String(vi.mocked(runtime.error).mock.calls[0]?.[0])).not.toContain(
326+
"GatewayClientRequestError",
327+
);
328+
expect(runtime.exit).toHaveBeenCalledWith(1);
289329
expect(callGateway).toHaveBeenCalledTimes(1);
290330
});
331+
332+
it("turns an opaque cursor rejection into an operator recovery step", async () => {
333+
callGateway.mockRejectedValueOnce(
334+
Object.assign(new Error("invalid audit.activity.list range or cursor"), {
335+
name: "GatewayClientRequestError",
336+
gatewayCode: "INVALID_REQUEST",
337+
}),
338+
);
339+
340+
await runCommandWithRuntime(runtime, () => auditListCommand({ cursor: "abc" }, runtime));
341+
342+
expect(runtime.error).toHaveBeenCalledWith(
343+
"Error: --cursor must be a continuation token returned by a previous audit result.",
344+
);
345+
expect(String(vi.mocked(runtime.error).mock.calls[0]?.[0])).not.toContain(
346+
"audit.activity.list",
347+
);
348+
expect(runtime.exit).toHaveBeenCalledWith(1);
349+
});
291350
});
292351

293352
describe("audit run explanation", () => {

‎src/commands/audit.ts‎

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,18 @@ import type {
1515
ExecutionIdentityContextV1,
1616
PrincipalRefV1,
1717
} from "../../packages/gateway-protocol/src/index.js";
18+
import {
19+
AUDIT_ACTIVITY_DIRECTIONS,
20+
AUDIT_ACTIVITY_KINDS,
21+
AUDIT_ACTIVITY_STATUSES,
22+
} from "../../packages/gateway-protocol/src/schema/audit-activity.js";
1823
import { sanitizeTerminalText } from "../../packages/terminal-core/src/safe-text.js";
1924
import { parsePositiveAuditCursor } from "../audit/audit-cursor.js";
2025
import { parseAbsoluteTimeMs } from "../cron/parse.js";
2126
import { callGateway } from "../gateway/call.js";
27+
import { formatErrorMessage } from "../infra/errors.js";
2228
import { type RuntimeEnv, writeRuntimeJson } from "../runtime.js";
29+
import { formatHumanList } from "../shared/human-list.js";
2330

2431
const DEFAULT_AUDIT_LIMIT = 100;
2532
const MAX_AUDIT_LIMIT = 500;
@@ -161,12 +168,25 @@ function hasMessageSpecificFilters(options: AuditListCommandOptions): boolean {
161168
);
162169
}
163170

164-
function validateAuditKind(kind: AuditListCommandOptions["kind"]): void {
165-
if (kind !== undefined && kind !== "agent_run" && kind !== "tool_action" && kind !== "message") {
166-
throw new Error("--kind must be agent_run, tool_action, or message.");
171+
function validateAuditFilter(
172+
value: string | undefined,
173+
flag: string,
174+
allowed: readonly string[],
175+
): void {
176+
if (value !== undefined && !allowed.includes(value)) {
177+
throw new Error(`${flag} must be ${formatHumanList(allowed)}.`);
167178
}
168179
}
169180

181+
function formatAuditGatewayError(error: unknown): Error {
182+
const message = formatErrorMessage(error);
183+
const operatorMessage =
184+
message === "invalid audit.activity.list range or cursor"
185+
? "--cursor must be a continuation token returned by a previous audit result."
186+
: message;
187+
return new Error(operatorMessage);
188+
}
189+
170190
function toLegacyAuditListParams(params: AuditActivityListParams): AuditListParams {
171191
return {
172192
...(params.agentId ? { agentId: params.agentId } : {}),
@@ -192,7 +212,7 @@ async function queryAuditActivity(
192212
});
193213
} catch (error) {
194214
if (!isUnsupportedActivityMethodError(error)) {
195-
throw error;
215+
throw formatAuditGatewayError(error);
196216
}
197217
if (hasMessageSpecificFilters(options)) {
198218
throw new Error(
@@ -237,7 +257,7 @@ async function queryAuditRunInspection(
237257
return await callGateway<AuditRunInspectResult>({ method: "audit.run.inspect", params });
238258
} catch (error) {
239259
if (!isUnsupportedRunInspectMethodError(error)) {
240-
throw error;
260+
throw formatAuditGatewayError(error);
241261
}
242262
return unsupportedRunInspection(
243263
typeof params.runId === "string"
@@ -503,7 +523,9 @@ export async function auditListCommand(
503523
if (options.executionId) {
504524
throw new Error("--execution requires --explain.");
505525
}
506-
validateAuditKind(options.kind);
526+
validateAuditFilter(options.kind, "--kind", AUDIT_ACTIVITY_KINDS);
527+
validateAuditFilter(options.status, "--status", AUDIT_ACTIVITY_STATUSES);
528+
validateAuditFilter(options.direction, "--direction", AUDIT_ACTIVITY_DIRECTIONS);
507529
const after = parseAuditTimestamp(options.after, "--after");
508530
const before = parseAuditTimestamp(options.before, "--before");
509531
if (after !== undefined && before !== undefined && after > before) {

0 commit comments

Comments
 (0)