Skip to content

Commit 7511601

Browse files
authored
fix(gateway): omit JavaScript class names from proven RPC failures (#124563)
* fix(gateway): keep diagnostic formatting out of wire errors * test(gateway): cover strict delivery wire errors * test(gateway): complete strict delivery request fixture
1 parent e3e45ed commit 7511601

13 files changed

Lines changed: 122 additions & 35 deletions
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import { ErrorCodes } from "../../../packages/gateway-protocol/src/index.js";
3+
4+
const mocks = vi.hoisted(() => ({
5+
resolveAgentDeliveryPlanWithSessionRoute: vi.fn(),
6+
}));
7+
8+
vi.mock("../../infra/outbound/agent-delivery.js", async (importOriginal) => ({
9+
...(await importOriginal<typeof import("../../infra/outbound/agent-delivery.js")>()),
10+
resolveAgentDeliveryPlanWithSessionRoute: mocks.resolveAgentDeliveryPlanWithSessionRoute,
11+
}));
12+
13+
const { resolveAgentDeliveryPhase } = await import("./agent-delivery-phase.js");
14+
15+
describe("resolveAgentDeliveryPhase", () => {
16+
beforeEach(() => {
17+
mocks.resolveAgentDeliveryPlanWithSessionRoute.mockReset();
18+
});
19+
20+
it("renders a strict target-resolution failure without its Error class", async () => {
21+
const targetError = Object.assign(new Error('Reserved target "current" for Telegram'), {
22+
code: "INVALID_TARGET",
23+
});
24+
mocks.resolveAgentDeliveryPlanWithSessionRoute.mockResolvedValue({
25+
baseDelivery: {},
26+
resolvedChannel: "telegram",
27+
resolvedTo: "current",
28+
deliveryTargetMode: "explicit",
29+
targetResolutionError: targetError,
30+
});
31+
const respond = vi.fn();
32+
33+
await resolveAgentDeliveryPhase({
34+
request: {
35+
message: "strict delivery",
36+
deliver: true,
37+
idempotencyKey: "strict-target-resolution",
38+
},
39+
cfg: {},
40+
agentId: "main",
41+
replyTo: "",
42+
to: "current",
43+
bestEffortDeliver: false,
44+
runId: "strict-target-resolution",
45+
client: null,
46+
context: { chatAbortControllers: new Map() } as never,
47+
respond,
48+
isWebchatConnect: () => false,
49+
});
50+
51+
expect(respond).toHaveBeenCalledWith(false, undefined, {
52+
code: ErrorCodes.INVALID_REQUEST,
53+
message: 'Reserved target "current" for Telegram | INVALID_TARGET',
54+
});
55+
});
56+
});

‎src/gateway/agent-turn/agent-delivery-phase.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@ import {
1616
normalizeMessageChannel,
1717
} from "../../utils/message-channel.js";
1818
import { resolveChatRunOwnerAgentId } from "../chat-run-owner.js";
19+
import { errorShapeFromError } from "../error-shape.js";
1920
import type { AgentRunRequest } from "../server-methods/agent-request-types.js";
2021
import type { GatewayRequestHandlerOptions } from "../server-methods/types.js";
2122
import { tryResolveSessionCompatibilityOwnerAgentId } from "../session-request-agent.js";
22-
import { formatForLog } from "../ws-log.js";
2323
import type { AgentTurnContext, AgentTurnPrincipal } from "./types.js";
2424

2525
type DeliveryPlan = Awaited<ReturnType<typeof resolveAgentDeliveryPlanWithSessionRoute>>;
@@ -141,7 +141,7 @@ export async function resolveAgentDeliveryPhase(params: {
141141
resolvedChannel,
142142
})
143143
) {
144-
params.respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, formatForLog(err)));
144+
params.respond(false, undefined, errorShapeFromError(ErrorCodes.INVALID_REQUEST, err));
145145
return undefined;
146146
}
147147
deliveryResolutionError = String(err);
@@ -152,7 +152,7 @@ export async function resolveAgentDeliveryPhase(params: {
152152
params.respond(
153153
false,
154154
undefined,
155-
errorShape(ErrorCodes.INVALID_REQUEST, String(deliveryTargetResolutionError)),
155+
errorShapeFromError(ErrorCodes.INVALID_REQUEST, deliveryTargetResolutionError),
156156
);
157157
return undefined;
158158
}
@@ -176,12 +176,12 @@ export async function resolveAgentDeliveryPhase(params: {
176176
params.respond(
177177
false,
178178
undefined,
179-
errorShape(
180-
ErrorCodes.INVALID_REQUEST,
181-
deliveryTargetResolutionError
182-
? String(deliveryTargetResolutionError)
183-
: `delivery target is required for ${resolvedChannel}: pass --to/--reply-to or configure a default target`,
184-
),
179+
deliveryTargetResolutionError
180+
? errorShapeFromError(ErrorCodes.INVALID_REQUEST, deliveryTargetResolutionError)
181+
: errorShape(
182+
ErrorCodes.INVALID_REQUEST,
183+
`delivery target is required for ${resolvedChannel}: pass --to/--reply-to or configure a default target`,
184+
),
185185
);
186186
return undefined;
187187
}

‎src/gateway/agent-turn/agent-run-admission-phase.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { claimAgentRunContext } from "../../infra/agent-run-registry.js";
2727
import type { InputProvenance } from "../../sessions/input-provenance.js";
2828
import type { SessionWorkAdmissionLease } from "../../sessions/session-lifecycle-admission.js";
2929
import { registerChatAbortController, resolveAgentRunExpiresAtMs } from "../chat-abort.js";
30+
import { errorShapeFromError } from "../error-shape.js";
3031
import type { AgentRunRequest } from "../server-methods/agent-request-types.js";
3132
import {
3233
isConfirmedAcpManualSpawnTaskOwner,
@@ -352,9 +353,11 @@ export async function prepareAgentRunDispatch(params: {
352353
params.io.emitAcceptance([
353354
false,
354355
undefined,
355-
errorShape(
356+
errorShapeFromError(
356357
ErrorCodes.UNAVAILABLE,
357-
`plugin subagent registry persistence failed; run was not started: ${formatForLog(err)}`,
358+
new Error("plugin subagent registry persistence failed; run was not started", {
359+
cause: err,
360+
}),
358361
),
359362
]);
360363
return undefined;

‎src/gateway/agent-turn/agent-session-persist.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { resolveSendPolicy } from "../../sessions/send-policy.js";
2727
import { recordSessionCreated } from "../../sessions/session-state-events.js";
2828
import { getGeneratedMediaTaskIdsForSessionKey } from "../../tasks/task-status-access.js";
2929
import { sessionDeliveryChannel } from "../../utils/delivery-context.shared.js";
30+
import { errorShapeFromError } from "../error-shape.js";
3031
import {
3132
assertExpectedExistingSession,
3233
ExpectedExistingSessionChangedError,
@@ -35,7 +36,6 @@ import type { AgentRunRequest } from "../server-methods/agent-request-types.js";
3536
import type { AgentSessionPatchBuild } from "../server-methods/agent-session-patch.js";
3637
import type { TrustedSessionCreation } from "../server-methods/session-creation-provenance.js";
3738
import type { GatewayRequestHandlerOptions } from "../server-methods/types.js";
38-
import { formatForLog } from "../ws-log.js";
3939
import {
4040
cronContinuationHasReusableRuntime,
4141
emitAgentSendSessionLifecycleTransition,
@@ -372,7 +372,7 @@ export async function persistAgentSessionPhase(params: {
372372
return undefined;
373373
}
374374
if (deletedDuringStoreUpdateError) {
375-
params.respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, formatForLog(err)));
375+
params.respond(false, undefined, errorShapeFromError(ErrorCodes.INVALID_REQUEST, err));
376376
return undefined;
377377
}
378378
if (err instanceof ExpectedExistingSessionChangedError) {
@@ -430,7 +430,7 @@ export async function persistAgentSessionPhase(params: {
430430
try {
431431
params.assertGatewayWorkAdmissionAllowed();
432432
} catch (err) {
433-
params.respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, formatForLog(err)));
433+
params.respond(false, undefined, errorShapeFromError(ErrorCodes.INVALID_REQUEST, err));
434434
return undefined;
435435
}
436436
if (

‎src/gateway/agent-turn/agent-turn-service.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
2-
import {
3-
ErrorCodes,
4-
errorShape,
5-
type AgentWaitParams,
6-
} from "../../../packages/gateway-protocol/src/index.js";
2+
import { ErrorCodes, type AgentWaitParams } from "../../../packages/gateway-protocol/src/index.js";
73
import { scheduleMainSessionRecoveryPendingTarget } from "../../agents/main-session-recovery/main-session-recovery-owner-release.js";
84
import {
95
releaseMainSessionRecoveryOwner,
@@ -13,6 +9,7 @@ import { mergeSessionEntry, type SessionEntry } from "../../config/sessions.js";
139
import type { OpenClawConfig } from "../../config/types.openclaw.js";
1410
import { getAgentEventLifecycleGeneration } from "../../infra/agent-events.js";
1511
import { normalizeDeliveryContext } from "../../utils/delivery-context.shared.js";
12+
import { errorShapeFromError } from "../error-shape.js";
1613
import { createCronContinuationController } from "../server-methods/agent-cron-continuation.js";
1714
import { runAgentResetPhase } from "../server-methods/agent-reset-phase.js";
1815
import { buildAgentSessionPatch } from "../server-methods/agent-session-patch.js";
@@ -21,7 +18,6 @@ import { handleChatAbortRequest } from "../server-methods/chat-abort-handler.js"
2118
import { resolveAgentRunSessionCreation } from "../server-methods/session-creation-provenance.js";
2219
import type { GatewayRequestHandlerOptions, RespondFn } from "../server-methods/shared-types.js";
2320
import { authorizeResolvedSessionMutation } from "../session-sharing.js";
24-
import { formatForLog } from "../ws-log.js";
2521
import { createAgentAdmissionController } from "./agent-admission-controller.js";
2622
import { prepareAgentContentPhase } from "./agent-content-phase.js";
2723
import { createAgentDedupeLifecycle } from "./agent-dedupe-lifecycle.js";
@@ -413,7 +409,7 @@ export function createAgentTurnService({
413409
io.emitAcceptance([
414410
false,
415411
undefined,
416-
errorShape(ErrorCodes.INVALID_REQUEST, formatForLog(err)),
412+
errorShapeFromError(ErrorCodes.INVALID_REQUEST, err),
417413
]);
418414
return;
419415
}

‎src/gateway/error-shape.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { errorShape } from "../../packages/gateway-protocol/src/index.js";
2+
import { formatErrorMessageWithCode } from "../infra/errors.js";
3+
4+
/** Builds a wire error from an unknown failure without diagnostic class names. */
5+
export function errorShapeFromError(
6+
code: Parameters<typeof errorShape>[0],
7+
error: unknown,
8+
opts?: Parameters<typeof errorShape>[2],
9+
) {
10+
return errorShape(code, formatErrorMessageWithCode(error), opts);
11+
}

‎src/gateway/server-methods/agent.base.test-utils.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -695,7 +695,7 @@ describe("gateway agent handler", () => {
695695
);
696696

697697
expectRespondError(respond, {
698-
message: `Error: Session "${sessionKey}" was deleted while starting work. Retry.`,
698+
message: `Session "${sessionKey}" was deleted while starting work. Retry.`,
699699
});
700700
expect(mocks.agentCommand).not.toHaveBeenCalled();
701701
});
@@ -723,7 +723,7 @@ describe("gateway agent handler", () => {
723723
);
724724

725725
expectRespondError(respond, {
726-
message: `Error: Session "${sessionKey}" was deleted while starting work. Retry.`,
726+
message: `Session "${sessionKey}" was deleted while starting work. Retry.`,
727727
});
728728
expect(mocks.agentCommand).not.toHaveBeenCalled();
729729
});
@@ -756,7 +756,7 @@ describe("gateway agent handler", () => {
756756
);
757757

758758
expectRespondError(respond, {
759-
message: `Error: Session "${sessionKey}" was deleted while starting work. Retry.`,
759+
message: `Session "${sessionKey}" was deleted while starting work. Retry.`,
760760
});
761761
expect(mocks.agentCommand).not.toHaveBeenCalled();
762762
});

‎src/gateway/server-methods/agent.events-and-subagents.test-utils.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -654,7 +654,11 @@ describe("gateway agent handler", () => {
654654

655655
expect(mocks.agentCommand).not.toHaveBeenCalled();
656656
const error = expectRespondError(respond, {});
657-
expectStringFieldContains(error, "message", "requires target");
657+
expect(error).toMatchObject({
658+
code: ErrorCodes.INVALID_REQUEST,
659+
message: expect.stringContaining("requires target"),
660+
});
661+
expect(error.message).not.toMatch(/^Error:/u);
658662
});
659663

660664
it("preserves requested delivery when best effort has no external channel", async () => {

‎src/gateway/server-methods/agent.sessions-and-models.test-utils.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -523,8 +523,9 @@ describe("gateway agent handler", () => {
523523
resetAgentTaskRegistryForTests();
524524
resetSubagentRegistryForTests({ persist: false });
525525
const persistSubagentRunsToDiskOrThrow = vi.fn();
526+
const persistenceError = Object.assign(new Error("disk full"), { code: "SQLITE_FULL" });
526527
persistSubagentRunsToDiskOrThrow.mockImplementationOnce(() => {
527-
throw new Error("disk full");
528+
throw persistenceError;
528529
});
529530
applyGatewaySubagentRegistryTestDeps({
530531
persistSubagentRunsToDiskOrThrow,
@@ -586,8 +587,11 @@ describe("gateway agent handler", () => {
586587
expect(persistSubagentRunsToDiskOrThrow).toHaveBeenCalledTimes(1);
587588
expect(mocks.agentCommand).toHaveBeenCalledTimes(commandCallCount);
588589
expect(findTaskByRunId(runId)).toBeUndefined();
589-
const error = expectRespondError(respond, { code: ErrorCodes.UNAVAILABLE });
590-
expectStringFieldContains(error, "message", "run was not started");
590+
expectRespondError(respond, {
591+
code: ErrorCodes.UNAVAILABLE,
592+
message:
593+
"plugin subagent registry persistence failed; run was not started | disk full | SQLITE_FULL",
594+
});
591595
expect(context.logGateway.warn).toHaveBeenCalledWith(
592596
expect.stringContaining("rejecting untracked dispatch"),
593597
);
@@ -636,8 +640,11 @@ describe("gateway agent handler", () => {
636640
pauseReason: "sessions_yield",
637641
});
638642
expect(getSubagentRunByChildSessionKey(childSessionKey)?.runId).not.toBe(adoptionRunId);
639-
const adoptionError = expectRespondError(adoptionRespond, { code: ErrorCodes.UNAVAILABLE });
640-
expectStringFieldContains(adoptionError, "message", "run was not started");
643+
expectRespondError(adoptionRespond, {
644+
code: ErrorCodes.UNAVAILABLE,
645+
message:
646+
"plugin subagent registry persistence failed; run was not started | disk full during paused-run adoption",
647+
});
641648

642649
resetSubagentRegistryForTests({ persist: false });
643650
const retryRunId = "plugin-subagent-registry-retry";

‎src/gateway/server-methods/fs.test.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,12 +101,16 @@ describe("fs.listDir", () => {
101101

102102
it("reports missing directories as request errors", async () => {
103103
const root = tempDirs.make("openclaw-fs-listdir-");
104+
const missing = path.join(root, "does-not-exist");
104105
const [ok, , error] = expectDefined(
105-
await call({ path: path.join(root, "does-not-exist") }),
106-
'await call({ path: path.join(root, "does-not-exist") }) test invariant',
106+
await call({ path: missing }),
107+
"missing directory response",
107108
);
108109
expect(ok).toBe(false);
109-
expect((error as { message?: string })?.message).toContain("ENOENT");
110+
const message = (error as { message?: string })?.message ?? "";
111+
expect(message).toContain(`ENOENT: no such file or directory, scandir '${missing}'`);
112+
expect(message).toMatch(/ \| ENOENT$/u);
113+
expect(message).not.toMatch(/^Error:/u);
110114
});
111115

112116
it("allows write-scoped browsing inside a configured workspace", async () => {
@@ -174,7 +178,10 @@ describe("fs.listDir", () => {
174178
);
175179

176180
expect(ok).toBe(false);
177-
expect(error).toMatchObject({ message: expect.stringContaining("ENOENT") });
181+
const message = (error as { message?: string })?.message ?? "";
182+
expect(message).toContain(`ENOENT: no such file or directory, scandir '${missing}'`);
183+
expect(message).toMatch(/ \| ENOENT$/u);
184+
expect(message).not.toMatch(/^Error:/u);
178185
});
179186

180187
it("routes node listings through the connected node capability", async () => {

0 commit comments

Comments
 (0)