Skip to content

Commit aeff737

Browse files
authored
fix(agents): prevent invalid names from targeting the default agent (#124670)
* fix(agents): reject unrepresentable agent ids * refactor(system-agent): split model selection setup * chore: shrink assertion safety baseline * docs: record strict agent id validation proof * style: format strict agent id report * chore: drop stray unrelated report artifact * chore: restore REPORT.md to main state
1 parent 63401b7 commit aeff737

38 files changed

Lines changed: 578 additions & 278 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3858,7 +3858,6 @@ src/snapshot/manifest.ts 1
38583858
src/state/agent-deletion-journal.ts 15
38593859
src/state/backup-run-records.ts 1
38603860
src/state/config-machine-state.ts 2
3861-
src/state/control-ui-device-auth-migration.ts 1
38623861
src/state/local-onboarding-state.ts 1
38633862
src/state/openclaw-agent-board-schema.ts 1
38643863
src/state/openclaw-agent-db-migration-required.ts 1
@@ -4150,7 +4149,7 @@ ui/src/lib/cron/index.ts 16
41504149
ui/src/lib/gateway-diagnostics.ts 3
41514150
ui/src/lib/gateway-errors.ts 1
41524151
ui/src/lib/keyboard-shortcuts.ts 1
4153-
ui/src/lib/nodes/index.ts 4
4152+
ui/src/lib/nodes/index.ts 3
41544153
ui/src/lib/nodes/inventory.ts 1
41554154
ui/src/lib/plugin-activation.ts 3
41564155
ui/src/lib/session-pull-requests.ts 2

‎docs/plugins/sdk-subpaths.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ Use `isLoopbackHost(host)` when a plugin must accept only the local machine. It
253253
| `plugin-sdk/cron-store-runtime` | Private-local after July 2026; Cron store path/load/save helpers |
254254
| `plugin-sdk/state-paths` | State/OAuth dir path helpers |
255255
| `plugin-sdk/plugin-state-runtime` | Private-local after July 2026; Plugin-scoped keyed-state and BLOB contracts plus connection pragma, verified WAL maintenance, and atomic STRICT-schema migration helpers. Plugin-state leases were removed; use SQLite transactions and keyed stores instead |
256-
| `plugin-sdk/routing` | Route/session-key/account binding helpers such as `resolveAgentRoute`, `buildAgentSessionKey`, and `resolveDefaultAgentBoundAccountId` |
256+
| `plugin-sdk/routing` | Route/session-key/account binding helpers such as `resolveAgentRoute`, `buildAgentSessionKey`, and `resolveDefaultAgentBoundAccountId`. Use `normalizeAgentId` when omitted input should resolve to `main`; use the Result-returning `normalizeAgentIdStrict` for an explicitly supplied ID that must not fall back to the default agent. |
257257
| `plugin-sdk/status-helpers` | Shared channel/account status summary helpers, runtime-state defaults, and issue metadata helpers |
258258
| `plugin-sdk/target-resolver-runtime` | Private-local after July 2026; Shared target resolver helpers |
259259
| `plugin-sdk/string-normalization-runtime` | Private-local after July 2026; Slug/string normalization helpers |

‎packages/normalization-core/src/agent-id.test.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { isValidAgentId, normalizeAgentId } from "@openclaw/normalization-core/agent-id";
1+
import {
2+
isValidAgentId,
3+
normalizeAgentId,
4+
normalizeAgentIdStrict,
5+
} from "@openclaw/normalization-core/agent-id";
26
import { describe, expect, it } from "vitest";
37

48
describe("normalization-core/agent-id", () => {
@@ -21,4 +25,16 @@ describe("normalization-core/agent-id", () => {
2125
])("validates %j", (input, expected) => {
2226
expect(isValidAgentId(input)).toBe(expected);
2327
});
28+
29+
it.each([
30+
["", { ok: false, error: "unrepresentable" }],
31+
[" ", { ok: false, error: "unrepresentable" }],
32+
["агент✨", { ok: false, error: "unrepresentable" }],
33+
["---", { ok: false, error: "unrepresentable" }],
34+
["valid-id", { ok: true, value: "valid-id" }],
35+
["../../etc/evil", { ok: true, value: "etc-evil" }],
36+
["a".repeat(65), { ok: true, value: "a".repeat(64) }],
37+
])("strictly normalizes %j", (input, expected) => {
38+
expect(normalizeAgentIdStrict(input)).toEqual(expected);
39+
});
2440
});

‎packages/normalization-core/src/agent-id.ts‎

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { err, ok, type Result } from "./result.js";
12
import { normalizeLowercaseStringOrEmpty } from "./string-coerce.js";
23

34
const DEFAULT_AGENT_ID = "main";
@@ -8,21 +9,25 @@ const TRAILING_DASH_RE = /-+$/;
89

910
/** Normalizes an OpenClaw agent id to its filesystem-safe canonical form. */
1011
export function normalizeAgentId(value: string | undefined | null): string {
12+
const result = normalizeAgentIdStrict(value);
13+
return result.ok ? result.value : DEFAULT_AGENT_ID;
14+
}
15+
16+
/** Normalizes an explicitly supplied agent id without falling back to the default agent. */
17+
export function normalizeAgentIdStrict(
18+
value: string | undefined | null,
19+
): Result<string, "unrepresentable"> {
1120
const trimmed = (value ?? "").trim();
12-
if (!trimmed) {
13-
return DEFAULT_AGENT_ID;
14-
}
1521
const normalized = normalizeLowercaseStringOrEmpty(trimmed);
1622
if (VALID_ID_RE.test(trimmed)) {
17-
return normalized;
23+
return ok(normalized);
1824
}
19-
return (
20-
normalized
21-
.replace(INVALID_CHARS_RE, "-")
22-
.replace(LEADING_DASH_RE, "")
23-
.replace(TRAILING_DASH_RE, "")
24-
.slice(0, 64) || DEFAULT_AGENT_ID
25-
);
25+
const agentId = normalized
26+
.replace(INVALID_CHARS_RE, "-")
27+
.replace(LEADING_DASH_RE, "")
28+
.replace(TRAILING_DASH_RE, "")
29+
.slice(0, 64);
30+
return agentId ? ok(agentId) : err("unrepresentable");
2631
}
2732

2833
/** Returns whether a value is already a canonical agent-id input. */

‎scripts/check-coercion-helper-declarations.mts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export const CANONICAL_COERCION_HELPER_OWNERS = [
3333
{
3434
file: "packages/normalization-core/src/agent-id.ts",
3535
kind: "function",
36-
names: ["isValidAgentId", "normalizeAgentId"],
36+
names: ["isValidAgentId", "normalizeAgentId", "normalizeAgentIdStrict"],
3737
},
3838
{
3939
file: "packages/normalization-core/src/string-coerce.ts",

‎scripts/plugin-sdk-surface-report.mts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,8 @@ export function readPluginSdkSurfaceBudgets(env: NodeJS.ProcessEnv = process.env
287287
// -17: retire the messaging-targets subpath, embedded Pi aliases, and shipped
288288
// channel setup compatibility helpers.
289289
// +1: concrete plugin side-effect owner resolution for agent harness runtimes.
290-
4317,
290+
// +1: strict explicit agent-id normalization without default-agent fallback.
291+
4318,
291292
env,
292293
),
293294
publicFunctionExports: readPluginSdkSurfaceBudgetEnv(
@@ -362,7 +363,8 @@ export function readPluginSdkSurfaceBudgets(env: NodeJS.ProcessEnv = process.env
362363
// -1: remove the orphan diagnostic traceparent propagation export.
363364
// -12: retire the callable messaging-targets, embedded Pi, and channel setup helpers.
364365
// +1: concrete plugin side-effect owner resolution for agent harness runtimes.
365-
2565,
366+
// +1: strict explicit agent-id normalization without default-agent fallback.
367+
2566,
366368
env,
367369
),
368370
publicDeprecatedExports: readPluginSdkSurfaceBudgetEnv(

‎src/agents/agent-create.ts‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import { resolveSessionTranscriptsDirForAgent } from "../config/sessions/paths.j
1818
import type { OptionalBootstrapFileName } from "../config/types.agent-defaults.js";
1919
import type { OpenClawConfig } from "../config/types.openclaw.js";
2020
import { FsSafeError, root } from "../infra/fs-safe.js";
21-
import { normalizeAgentId } from "../routing/session-key.js";
21+
import { normalizeAgentId, normalizeAgentIdStrict } from "../routing/session-key.js";
2222
import { readAgentDeletionJournal } from "../state/agent-deletion-journal.js";
2323
import { isReservedSystemAgentId } from "../system-agent/agent-id.js";
2424
import { resolveUserPath } from "../utils.js";
@@ -99,26 +99,22 @@ function createError(
9999
return { status: "error", reason, message, ...(agentId ? { agentId } : {}) };
100100
}
101101

102-
/** True when raw user input contains a character that can survive agent-id normalization. */
103-
function hasValidRawAgentIdCharacters(value: string): boolean {
104-
return /[a-z0-9]/iu.test(value);
105-
}
106-
107102
export function validateAgentIdInput(
108103
rawId: string,
109104
options: { displayName?: string } = {},
110105
):
111106
| { ok: true; agentId: string }
112107
| { ok: false; reason: "invalid-name" | "reserved-id"; message: string; agentId?: string } {
113108
const displayName = options.displayName ?? rawId;
114-
if (!hasValidRawAgentIdCharacters(rawId)) {
109+
const normalized = normalizeAgentIdStrict(rawId);
110+
if (!normalized.ok) {
115111
return {
116112
ok: false,
117113
reason: "invalid-name",
118-
message: `agent name "${displayName}" has no valid id characters`,
114+
message: `Agent name "${displayName}" has no valid id characters. Use at least one letter a-z or digit.`,
119115
};
120116
}
121-
const agentId = normalizeAgentId(rawId);
117+
const agentId = normalized.value;
122118
if (isReservedSystemAgentId(agentId)) {
123119
return { ok: false, reason: "reserved-id", message: `"${agentId}" is reserved`, agentId };
124120
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { describe, expect, it } from "vitest";
2+
import { resolveTargetAcpAgentId } from "./acp-spawn-target.js";
3+
4+
describe("resolveTargetAcpAgentId", () => {
5+
it.each(["", " ", "агент✨", "---"])(
6+
"rejects explicit unrepresentable ACP agent id %j",
7+
(agentId) => {
8+
expect(
9+
resolveTargetAcpAgentId({
10+
requestedAgentId: agentId,
11+
cfg: { acp: { defaultAgent: "codex" } },
12+
}),
13+
).toEqual({ ok: false, error: `agentId "${agentId}" was not found` });
14+
},
15+
);
16+
17+
it("keeps omitted ACP agent ids on the configured default path", () => {
18+
expect(
19+
resolveTargetAcpAgentId({
20+
cfg: { acp: { defaultAgent: "codex" } },
21+
}),
22+
).toEqual({ ok: true, agentId: "codex" });
23+
});
24+
});

‎src/agents/subagents/spawn/acp-spawn-target.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
import type { OpenClawConfig } from "../../../config/types.openclaw.js";
2-
import { normalizeOptionalAgentId } from "../../../routing/session-key.js";
2+
import { normalizeAgentIdStrict, normalizeOptionalAgentId } from "../../../routing/session-key.js";
33
import { listAgentEntries } from "../../agent-scope-config.js";
44
import { listAgentIds } from "../../agent-scope.js";
55

66
export function resolveTargetAcpAgentId(params: {
77
requestedAgentId?: string;
88
cfg: OpenClawConfig;
99
}): { ok: true; agentId: string; configAgentId?: string } | { ok: false; error: string } {
10-
const requested = normalizeOptionalAgentId(params.requestedAgentId);
10+
const normalizedRequest =
11+
params.requestedAgentId === undefined ? null : normalizeAgentIdStrict(params.requestedAgentId);
12+
if (normalizedRequest && !normalizedRequest.ok) {
13+
return { ok: false, error: `agentId "${params.requestedAgentId}" was not found` };
14+
}
15+
const requested = normalizedRequest?.value;
1116
if (requested) {
1217
const configuredAgent = listAgentEntries(params.cfg).find(
1318
(agent) => normalizeOptionalAgentId(agent.id) === requested,

‎src/agents/tools/sessions-send-tool.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
isSubagentSessionKey,
3535
normalizeAccountId,
3636
normalizeAgentId,
37+
normalizeAgentIdStrict,
3738
toAgentStoreSessionKey,
3839
} from "../../routing/session-key.js";
3940
import { annotateInterSessionPromptText } from "../../sessions/input-provenance.js";
@@ -500,30 +501,38 @@ export function createSessionsSendTool(opts?: {
500501

501502
const sessionKeyParam = readToolStringParam(params, "sessionKey");
502503
const labelParam = normalizeOptionalString(readToolStringParam(params, "label"));
503-
const labelAgentIdParam = normalizeOptionalString(readToolStringParam(params, "agentId"));
504+
const labelAgentIdInput = readToolStringParam(params, "agentId");
505+
const normalizedLabelAgentId =
506+
labelAgentIdInput === undefined ? null : normalizeAgentIdStrict(labelAgentIdInput);
507+
if (normalizedLabelAgentId && !normalizedLabelAgentId.ok) {
508+
return jsonResult({
509+
runId: crypto.randomUUID(),
510+
status: "error",
511+
error: `Agent "${labelAgentIdInput}" not found. Run openclaw agents list to see configured agents.`,
512+
});
513+
}
514+
const explicitTargetAgentId = normalizedLabelAgentId?.value;
504515

505516
let sessionKey = sessionKeyParam;
506517
let resolvedTargetAgentId: string | undefined;
507518
let resolvedLabelKey: string | undefined;
508-
if (!sessionKey && !labelParam && labelAgentIdParam) {
519+
if (!sessionKey && !labelParam && explicitTargetAgentId) {
509520
const agentMainKey = resolveConfiguredAgentMainSessionKey({
510521
cfg,
511-
agentId: labelAgentIdParam,
522+
agentId: explicitTargetAgentId,
512523
mainKey,
513524
});
514525
if (!agentMainKey) {
515526
return jsonResult({
516527
runId: crypto.randomUUID(),
517528
status: "error",
518-
error: `agent not found: ${labelAgentIdParam}`,
529+
error: `Agent "${labelAgentIdInput}" not found. Run openclaw agents list to see configured agents.`,
519530
});
520531
}
521532
sessionKey = agentMainKey;
522533
}
523534
if (!sessionKey && labelParam) {
524-
const requestedAgentId = labelAgentIdParam
525-
? normalizeAgentId(labelAgentIdParam)
526-
: undefined;
535+
const requestedAgentId = explicitTargetAgentId;
527536

528537
if (restrictToSpawned && requestedAgentId && requestedAgentId !== requesterAgentId) {
529538
return jsonResult({
@@ -700,7 +709,7 @@ export function createSessionsSendTool(opts?: {
700709
const resolvedTargetOwner =
701710
visibleSession.agentId ??
702711
resolvedTargetAgentId ??
703-
(labelParam && labelAgentIdParam ? normalizeAgentId(labelAgentIdParam) : undefined);
712+
(labelParam ? explicitTargetAgentId : undefined);
704713
if (
705714
persistedTargetOwner.kind === "configured" &&
706715
resolvedTargetOwner &&

0 commit comments

Comments
 (0)