Skip to content

Commit c5b7b8e

Browse files
authored
fix(system-agent): setup chat fails silently on dev-roster gateways (#121784)
* fix(system-agent): repair setup-chat execution identity, harness fallback, and error surfacing Always inject the reserved "openclaw" execution entry for off-roster system-agent runs. Keep implicit harness runtime selection implicit so Codex refusal falls back to the OpenClaw harness, while explicit policy remains fail-closed. Log openclaw.chat turn failures and surface their underlying causes in the UNAVAILABLE response. * chore(plugin-sdk): refresh agent harness API baseline * test(system-agent): align fixtures with optional harness routes * fix(system-agent): keep execution roster out of TUI catalog lookup * refactor(system-agent): keep verified state types internal * fix(system-agent): separate setup policy and execution config
1 parent c896b9b commit c5b7b8e

17 files changed

Lines changed: 276 additions & 99 deletions

‎docs/.generated/plugin-sdk-api-baseline.jsonl‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/gateway/server-methods/system-agent.test.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import { getActiveGatewayRootWorkCount } from "../../process/gateway-work-admiss
1515
import { CommandLane } from "../../process/lanes.js";
1616
import { defaultRuntime } from "../../runtime.js";
1717
import { SystemAgentChatEngine } from "../../system-agent/chat-engine.js";
18-
import { SystemAgentInferenceUnavailableError } from "../../system-agent/inference-error.js";
1918
import {
2019
createSystemAgentVerifiedInferenceTestFixture,
2120
installSystemAgentPluginMetadataTestSnapshot,
@@ -934,10 +933,14 @@ describe("openclaw.chat", () => {
934933

935934
it("reuses a live session, then requires fresh fallback verification after failure", async () => {
936935
stubEngineOverview();
937-
const engine = makeVerifiedEngine();
938-
vi.spyOn(engine, "handle").mockRejectedValue(
939-
new SystemAgentInferenceUnavailableError("conversation"),
940-
);
936+
const engine = new SystemAgentChatEngine({
937+
verifiedInference: requireVerifiedInferenceFixture(),
938+
runAgentTurn: async () => {
939+
throw new Error("workspace owner openclaw is missing from the roster");
940+
},
941+
planWithAssistant: async () => null,
942+
deps: requireVerifiedInferenceDeps(),
943+
});
941944
const dispose = vi.spyOn(engine, "dispose").mockResolvedValue();
942945
const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]);
943946
const context = makeContext(sessions);
@@ -948,7 +951,7 @@ describe("openclaw.chat", () => {
948951
ok: false,
949952
error: {
950953
code: "UNAVAILABLE",
951-
message: expect.stringContaining("working inference"),
954+
message: expect.stringContaining("workspace owner openclaw is missing from the roster"),
952955
details: { code: "system_agent_session_invalidated" },
953956
},
954957
});

‎src/system-agent/chat-engine.test.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ const mocks = vi.hoisted(() => ({
5555
runSetupMemoryImportStep: vi.fn(),
5656
writeWizardConfigFile: vi.fn(),
5757
runCollectedChannelOnboardingPostWriteHooks: vi.fn(async () => {}),
58+
chatWarn: vi.fn(),
5859
sharedVerifiedInference: undefined as SystemAgentVerifiedInferenceBinding | undefined,
5960
}));
6061

@@ -65,6 +66,17 @@ vi.mock("../config/config.js", async (importOriginal) => ({
6566
readConfigFileSnapshot: mocks.readConfigFileSnapshot,
6667
}));
6768

69+
vi.mock("../logging/subsystem.js", async (importOriginal) => {
70+
const actual = await importOriginal<typeof import("../logging/subsystem.js")>();
71+
return {
72+
...actual,
73+
createSubsystemLogger: (subsystem: string) =>
74+
subsystem === "system-agent/chat-engine"
75+
? ({ warn: mocks.chatWarn } as unknown as ReturnType<typeof actual.createSubsystemLogger>)
76+
: actual.createSubsystemLogger(subsystem),
77+
};
78+
});
79+
6880
vi.mock("../wizard/setup.shared.js", async (importOriginal) => ({
6981
...(await importOriginal<typeof import("../wizard/setup.shared.js")>()),
7082
readSetupConfigFileSnapshot: mocks.readSetupConfigFileSnapshot,
@@ -174,7 +186,9 @@ function testHarnessBinding(route: SystemAgentConfiguredRoute) {
174186
return { auth: {}, deps: {} };
175187
}
176188
const agentHarnessId =
177-
route.agentHarnessRuntimeOverride === "auto" ? "openclaw" : route.agentHarnessRuntimeOverride;
189+
route.agentHarnessRuntimeOverride === "auto"
190+
? "openclaw"
191+
: (route.agentHarnessRuntimeOverride ?? "codex");
178192
if (agentHarnessId === "openclaw") {
179193
return { auth: { agentHarnessId }, deps: {} };
180194
}
@@ -3148,13 +3162,15 @@ describe("SystemAgentChatEngine", () => {
31483162
it("fails closed when neither inference path is usable", async () => {
31493163
const planner = vi.fn(async () => null);
31503164
const engine = new SystemAgentChatEngine({
3151-
runAgentTurn: async () => null,
3165+
runAgentTurn: async () => {
3166+
throw new Error("workspace owner openclaw is missing from the roster");
3167+
},
31523168
planWithAssistant: planner,
31533169
deps: { loadOverview: fakeOverviewLoader() },
31543170
});
31553171

3156-
await expect(engine.handle("please make everything nice")).rejects.toBeInstanceOf(
3157-
SystemAgentInferenceUnavailableError,
3172+
await expect(engine.handle("please make everything nice")).rejects.toThrow(
3173+
"workspace owner openclaw is missing from the roster",
31583174
);
31593175
});
31603176
});
@@ -3272,6 +3288,7 @@ describe("OpenClaw agent loop backends", () => {
32723288

32733289
expect(runCliAgent).toHaveBeenCalledOnce();
32743290
expect(reply.text).toContain("planner fallback reply");
3291+
expect(mocks.chatWarn).toHaveBeenCalledWith(expect.stringContaining("claude exploded"));
32753292
});
32763293
});
32773294

‎src/system-agent/chat-engine.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1136,6 +1136,7 @@ export class SystemAgentChatEngine {
11361136
session: this.agentSession,
11371137
});
11381138
} catch (error) {
1139+
log.warn(`agent turn failed before planner fallback: ${formatErrorMessage(error)}`);
11391140
agentFailure = error;
11401141
loopReply = null;
11411142
}

‎src/system-agent/inference-error.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,24 @@
1+
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
2+
import { formatErrorMessage } from "../infra/errors.js";
3+
14
type SystemAgentInferenceStage = "agent-turn" | "planner" | "conversation";
25

6+
const INFERENCE_UNAVAILABLE_MESSAGE =
7+
"OpenClaw could not reach working inference. Run `openclaw onboard` on the machine running OpenClaw to reconnect — it live-tests the route before saving it. Then try again.";
8+
const INFERENCE_FAILURE_SUMMARY_MAX_CHARS = 300;
9+
10+
function inferenceUnavailableMessage(failures: readonly unknown[]): string {
11+
const detail = failures.length > 0 ? formatErrorMessage(failures[0]).trim() : "";
12+
if (!detail) {
13+
return INFERENCE_UNAVAILABLE_MESSAGE;
14+
}
15+
const summary =
16+
detail.length > INFERENCE_FAILURE_SUMMARY_MAX_CHARS
17+
? `${truncateUtf16Safe(detail, INFERENCE_FAILURE_SUMMARY_MAX_CHARS - 1)}…`
18+
: detail;
19+
return `${INFERENCE_UNAVAILABLE_MESSAGE} Cause: ${summary}`;
20+
}
21+
322
/** Safe public error for an OpenClaw turn that could not complete with intelligence. */
423
export class SystemAgentInferenceUnavailableError extends Error {
524
readonly code = "SYSTEM_AGENT_INFERENCE_UNAVAILABLE";
@@ -8,9 +27,7 @@ export class SystemAgentInferenceUnavailableError extends Error {
827
readonly stage: SystemAgentInferenceStage,
928
readonly failures: readonly unknown[] = [],
1029
) {
11-
super(
12-
"OpenClaw could not reach working inference. Run `openclaw onboard` on the machine running OpenClaw to reconnect — it live-tests the route before saving it. Then try again.",
13-
);
30+
super(inferenceUnavailableMessage(failures));
1431
this.name = "SystemAgentInferenceUnavailableError";
1532
}
1633
}
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { clearAgentHarnesses, registerAgentHarness } from "../agents/harness/registry.js";
3+
import { selectAgentHarness } from "../agents/harness/selection.js";
4+
import { resolveRunWorkspaceDir } from "../agents/workspace-run.js";
5+
import type { OpenClawConfig } from "../config/types.openclaw.js";
6+
import { SYSTEM_AGENT_ID } from "./agent-id.js";
7+
import { resolveSystemAgentConfiguredRouteFromConfig } from "./inference-route.js";
8+
9+
function devConfig(agentRuntime?: string): OpenClawConfig {
10+
return {
11+
agents: {
12+
defaults: { model: "openai/gpt-5.5" },
13+
entries: {
14+
dev: { default: true, workspace: "/tmp/x" },
15+
},
16+
},
17+
models: {
18+
providers: {
19+
openai: {
20+
api: "openai-responses",
21+
baseUrl: "https://api.openai.com/v1",
22+
...(agentRuntime ? { agentRuntime: { id: agentRuntime } } : {}),
23+
models: [
24+
{
25+
id: "gpt-5.5",
26+
name: "GPT-5.5",
27+
reasoning: true,
28+
input: ["text"],
29+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
30+
contextWindow: 128_000,
31+
maxTokens: 8_192,
32+
},
33+
],
34+
},
35+
},
36+
},
37+
};
38+
}
39+
40+
afterEach(() => {
41+
clearAgentHarnesses();
42+
});
43+
44+
describe("resolveSystemAgentConfiguredRouteFromConfig", () => {
45+
it("admits the reserved execution agent for a dev-shaped roster", async () => {
46+
const route = await resolveSystemAgentConfiguredRouteFromConfig(devConfig());
47+
48+
expect(route).not.toBeNull();
49+
expect(() =>
50+
resolveRunWorkspaceDir({
51+
workspaceDir: "/tmp/x",
52+
agentId: SYSTEM_AGENT_ID,
53+
config: route!.runConfig,
54+
}),
55+
).not.toThrow();
56+
});
57+
58+
it("keeps implicit harness selection fallible while forcing explicit policy", async () => {
59+
const supports = vi.fn((ctx: { modelProvider?: { requestTransportOverrides?: string } }) =>
60+
ctx.modelProvider?.requestTransportOverrides === "present"
61+
? { supported: false as const, reason: "authored request transport overrides" }
62+
: { supported: true as const, priority: 100 },
63+
);
64+
registerAgentHarness({
65+
id: "codex",
66+
label: "Codex",
67+
supports: supports as never,
68+
runAttempt: vi.fn() as never,
69+
});
70+
const preparedModelProvider = {
71+
api: "openai-responses",
72+
baseUrl: "https://api.openai.com/v1",
73+
requestTransportOverrides: "present" as const,
74+
};
75+
76+
const implicitRoute = await resolveSystemAgentConfiguredRouteFromConfig(devConfig());
77+
expect(implicitRoute).toMatchObject({ runner: "embedded" });
78+
expect(implicitRoute).not.toHaveProperty("agentHarnessRuntimeOverride");
79+
expect(
80+
selectAgentHarness({
81+
provider: "openai",
82+
modelId: "gpt-5.5",
83+
modelProvider: preparedModelProvider,
84+
config: implicitRoute!.runConfig,
85+
agentHarnessRuntimeOverride:
86+
implicitRoute!.runner === "embedded"
87+
? implicitRoute!.agentHarnessRuntimeOverride
88+
: undefined,
89+
}).id,
90+
).toBe("openclaw");
91+
92+
const explicitRoute = await resolveSystemAgentConfiguredRouteFromConfig(devConfig("codex"));
93+
expect(explicitRoute).toMatchObject({
94+
runner: "embedded",
95+
agentHarnessRuntimeOverride: "codex",
96+
});
97+
expect(() =>
98+
selectAgentHarness({
99+
provider: "openai",
100+
modelId: "gpt-5.5",
101+
modelProvider: preparedModelProvider,
102+
config: explicitRoute!.runConfig,
103+
agentHarnessRuntimeOverride:
104+
explicitRoute!.runner === "embedded"
105+
? explicitRoute!.agentHarnessRuntimeOverride
106+
: undefined,
107+
}),
108+
).toThrow("authored request transport overrides");
109+
});
110+
});

‎src/system-agent/inference-route.ts‎

Lines changed: 18 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
import type { OpenClawConfig } from "../config/types.openclaw.js";
1515
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.types.js";
1616
import { normalizeAgentId } from "../routing/session-key.js";
17+
import { SYSTEM_AGENT_ID } from "./agent-id.js";
1718

1819
export type SystemAgentConfiguredRoute = {
1920
runConfig: OpenClawConfig;
@@ -27,7 +28,7 @@ export type SystemAgentConfiguredRoute = {
2728
| { runner: "cli" }
2829
| {
2930
runner: "embedded";
30-
agentHarnessRuntimeOverride: string;
31+
agentHarnessRuntimeOverride?: string;
3132
}
3233
);
3334

@@ -70,42 +71,20 @@ export type DefaultInferenceRouteProjection = {
7071
tools: OpenClawConfig["tools"];
7172
};
7273

73-
const SYSTEM_AGENT_EXECUTION_AGENT_ID = "openclaw";
74-
7574
function projectSystemAgentExecutionConfig(
7675
config: OpenClawConfig,
7776
routeAgentId: string,
7877
): OpenClawConfig {
7978
const agents = listAgentEntries(config);
80-
if (agents.length === 0) {
81-
return config;
82-
}
83-
const routeAgent =
84-
routeAgentId === SYSTEM_AGENT_EXECUTION_AGENT_ID
85-
? undefined
86-
: agents.find((agent) => normalizeAgentId(agent.id) === routeAgentId);
87-
const retainedAgents = agents.filter(
88-
(agent) => normalizeAgentId(agent.id) !== SYSTEM_AGENT_EXECUTION_AGENT_ID,
89-
);
90-
const hasProjectedSettings = routeAgent?.params !== undefined || routeAgent?.tools !== undefined;
91-
if (retainedAgents.length === agents.length && !hasProjectedSettings) {
92-
return config;
93-
}
79+
const routeAgent = agents.find((agent) => normalizeAgentId(agent.id) === routeAgentId);
80+
const retainedAgents = agents.filter((agent) => normalizeAgentId(agent.id) !== SYSTEM_AGENT_ID);
9481
const projectedAgents = [
9582
...retainedAgents,
96-
...(hasProjectedSettings
97-
? [
98-
{
99-
id: SYSTEM_AGENT_EXECUTION_AGENT_ID,
100-
...(routeAgent?.params !== undefined
101-
? { params: structuredClone(routeAgent.params) }
102-
: {}),
103-
...(routeAgent?.tools !== undefined
104-
? { tools: structuredClone(routeAgent.tools) }
105-
: {}),
106-
},
107-
]
108-
: []),
83+
{
84+
id: SYSTEM_AGENT_ID,
85+
...(routeAgent?.params !== undefined ? { params: structuredClone(routeAgent.params) } : {}),
86+
...(routeAgent?.tools !== undefined ? { tools: structuredClone(routeAgent.tools) } : {}),
87+
},
10988
];
11089
const { list: _legacyList, ...agentsConfig } = config.agents ?? {};
11190
return {
@@ -195,13 +174,17 @@ export async function resolveSystemAgentConfiguredRouteFromConfig(
195174
if (isCliRoute) {
196175
return { runner: "cli", ...base };
197176
}
198-
const runtime = harnessPolicy.resolveAgentHarnessPolicy({
177+
const policy = harnessPolicy.resolveAgentHarnessPolicy({
199178
config: runConfig,
200179
agentId: modelOwnerAgentId,
201180
provider: selection.provider,
202181
modelId: selection.modelId,
203-
}).runtime;
204-
return { runner: "embedded", agentHarnessRuntimeOverride: runtime, ...base };
182+
});
183+
return {
184+
runner: "embedded",
185+
...(policy.runtimeSource === "implicit" ? {} : { agentHarnessRuntimeOverride: policy.runtime }),
186+
...base,
187+
};
205188
}
206189

207190
function projectRelevantModelMap(params: {
@@ -248,7 +231,7 @@ export async function projectInferenceRoute(
248231
const list = listAgentEntries(config);
249232
const agent = list.find((entry) => normalizeAgentId(entry.id) === routeAgentId);
250233
const executionAgent = listAgentEntries(route?.runConfig ?? {}).find(
251-
(entry) => normalizeAgentId(entry.id) === SYSTEM_AGENT_EXECUTION_AGENT_ID,
234+
(entry) => normalizeAgentId(entry.id) === SYSTEM_AGENT_ID,
252235
);
253236
const defaults = config.agents?.defaults;
254237
const logicalProvider = normalizeProviderId(route?.modelLabel.split("/", 1)[0] ?? "");
@@ -344,7 +327,7 @@ export async function projectInferenceRoute(
344327
...(executionAgent
345328
? {
346329
executionAgent: {
347-
id: SYSTEM_AGENT_EXECUTION_AGENT_ID,
330+
id: SYSTEM_AGENT_ID,
348331
params: structuredClone(executionAgent.params),
349332
tools: structuredClone(executionAgent.tools),
350333
},

‎src/system-agent/revalidate-inference-owner.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ export async function revalidateSetupInferenceOwner(params: {
2222
}): Promise<SystemAgentVerifiedInferenceBinding> {
2323
const configuredHarnessId =
2424
params.route.runner === "embedded"
25-
? params.route.agentHarnessRuntimeOverride.trim()
25+
? params.route.agentHarnessRuntimeOverride?.trim()
2626
: undefined;
2727
const successfulHarnessId =
2828
params.auth.agentHarnessId?.trim() ||

0 commit comments

Comments
 (0)