Skip to content

Commit 2025c3d

Browse files
authored
feat(system-agent): give Ask OpenClaw ambient page context (#114943)
* feat(ui): add custodian page context * fix(system-agent): keep planner input free of the pending-proposal marker * fix(system-agent): preserve context-free call shape * refactor(system-agent): isolate page context boundaries * fix(gateway): canonicalize UI context * fix(gateway): enforce ASCII page context
1 parent 7d69c51 commit 2025c3d

13 files changed

Lines changed: 260 additions & 24 deletions

File tree

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9133,19 +9133,22 @@ public struct SystemAgentChatParams: Codable, Sendable {
91339133
public let message: String?
91349134
public let welcomevariant: AnyCodable?
91359135
public let reset: Bool?
9136+
public let context: [String: AnyCodable]?
91369137
public let delegation: [String: AnyCodable]?
91379138

91389139
public init(
91399140
sessionid: String,
91409141
message: String? = nil,
91419142
welcomevariant: AnyCodable? = nil,
91429143
reset: Bool? = nil,
9144+
context: [String: AnyCodable]? = nil,
91439145
delegation: [String: AnyCodable]? = nil)
91449146
{
91459147
self.sessionid = sessionid
91469148
self.message = message
91479149
self.welcomevariant = welcomevariant
91489150
self.reset = reset
9151+
self.context = context
91499152
self.delegation = delegation
91509153
}
91519154

@@ -9154,6 +9157,7 @@ public struct SystemAgentChatParams: Codable, Sendable {
91549157
case message
91559158
case welcomevariant = "welcomeVariant"
91569159
case reset
9160+
case context
91579161
case delegation
91589162
}
91599163
}

‎packages/gateway-protocol/src/schema/openclaw.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Value } from "typebox/value";
22
import { describe, expect, it } from "vitest";
33
import {
4+
validateSystemAgentChatParams,
45
validateSystemAgentChatHistoryParams,
56
validateSystemAgentSetupVerifyParams,
67
} from "../index.js";
@@ -11,6 +12,33 @@ import {
1112
SystemAgentSetupVerifyResultSchema,
1213
} from "./openclaw.js";
1314

15+
describe("OpenClaw chat params protocol", () => {
16+
const base = { sessionId: "session-1", message: "What about this page?" };
17+
18+
it("accepts the additive page context and remains backward compatible", () => {
19+
expect(validateSystemAgentChatParams(base)).toBe(true);
20+
expect(validateSystemAgentChatParams({ ...base, context: { page: "channels" } })).toBe(true);
21+
expect(
22+
validateSystemAgentChatParams({ ...base, context: { page: "/settings/channels" } }),
23+
).toBe(true);
24+
});
25+
26+
it("rejects unsafe page ids and unknown context fields", () => {
27+
expect(validateSystemAgentChatParams({ ...base, context: { page: "channels?tab=all" } })).toBe(
28+
false,
29+
);
30+
expect(validateSystemAgentChatParams({ ...base, context: { page: "a".repeat(65) } })).toBe(
31+
false,
32+
);
33+
expect(
34+
validateSystemAgentChatParams({
35+
...base,
36+
context: { page: "channels", source: "client" },
37+
}),
38+
).toBe(false);
39+
});
40+
});
41+
1442
describe("OpenClaw chat question protocol", () => {
1543
const question = {
1644
id: "onboarding-next-step",

‎packages/gateway-protocol/src/schema/openclaw.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,16 @@ export const SystemAgentChatParamsSchema = closedObject({
2020
),
2121
/** Drop any in-flight approval/wizard state and start the session over. */
2222
reset: Type.Optional(Type.Boolean()),
23+
/** Ephemeral Control UI location hint for interpreting the current user turn. */
24+
context: Type.Optional(
25+
closedObject({
26+
page: Type.String({
27+
minLength: 1,
28+
maxLength: 64,
29+
pattern: "^[A-Za-z0-9/_-]{1,64}$",
30+
}),
31+
}),
32+
),
2333
/** Host-only regular-agent delegation context. Never model-authored. */
2434
delegation: Type.Optional(
2535
closedObject({

‎src/gateway/server-methods/shared-types.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,10 @@ type SystemAgentHistoryTurn = {
124124

125125
type GatewaySystemAgentSession = {
126126
engine: {
127-
handle: (message: string) => Promise<{
127+
handle: (
128+
message: string,
129+
options?: { uiContext?: { page: string } },
130+
) => Promise<{
128131
text: string;
129132
action: "none" | "exit" | "open-tui" | "open-setup";
130133
sensitive?: boolean;
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
const SYSTEM_AGENT_UI_CONTEXT_PAGE_PATTERN = /^[A-Za-z0-9/_-]{1,64}$/u;
2+
3+
export function sanitizeSystemAgentChatParams(params: unknown): unknown {
4+
if (!params || typeof params !== "object" || Array.isArray(params)) {
5+
return params;
6+
}
7+
const record = params as Record<string, unknown>;
8+
const context = record.context;
9+
if (context === undefined) {
10+
return params;
11+
}
12+
if (
13+
record.delegation !== undefined ||
14+
!context ||
15+
typeof context !== "object" ||
16+
Array.isArray(context)
17+
) {
18+
const { context: _droppedContext, ...rest } = record;
19+
return rest;
20+
}
21+
const contextRecord = context as Record<string, unknown>;
22+
const page = typeof contextRecord.page === "string" ? contextRecord.page.trim() : "";
23+
if (!SYSTEM_AGENT_UI_CONTEXT_PAGE_PATTERN.test(page)) {
24+
const { context: _droppedContext, ...rest } = record;
25+
return rest;
26+
}
27+
return { ...record, context: { page } };
28+
}

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

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,60 @@ describe("openclaw.chat", () => {
651651
expect(call.ok).toBe(false);
652652
});
653653

654+
it("trims, canonicalizes, and forwards valid UI context for a user turn", async () => {
655+
const engine = makeVerifiedEngine();
656+
const handle = vi
657+
.spyOn(engine, "handle")
658+
.mockResolvedValue({ text: "Everything is healthy.", action: "none" });
659+
const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]);
660+
661+
const call = await callChat(makeContext(sessions), {
662+
sessionId: "s1",
663+
message: "What about this page?",
664+
context: { page: " /settings/channels ", source: "client" },
665+
});
666+
667+
expect(call.ok).toBe(true);
668+
expect(handle).toHaveBeenCalledWith("What about this page?", {
669+
uiContext: { page: "/settings/channels" },
670+
});
671+
});
672+
673+
it.each([
674+
{ name: "unsafe characters", page: "channels?tab=all" },
675+
{ name: "an overlong id", page: "a".repeat(65) },
676+
{ name: "a Unicode case-folding character", page: "\u212A" },
677+
])("drops UI context with $name without rejecting the turn", async ({ page }) => {
678+
const engine = makeVerifiedEngine();
679+
const handle = vi
680+
.spyOn(engine, "handle")
681+
.mockResolvedValue({ text: "Everything is healthy.", action: "none" });
682+
const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]);
683+
684+
const call = await callChat(makeContext(sessions), {
685+
sessionId: "s1",
686+
message: "Status please.",
687+
context: { page },
688+
});
689+
690+
expect(call.ok).toBe(true);
691+
expect(handle).toHaveBeenCalledWith("Status please.");
692+
});
693+
694+
it("does not pass UI context to welcome-only turns", async () => {
695+
const engine = makeVerifiedEngine();
696+
const handle = vi.spyOn(engine, "handle");
697+
const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]);
698+
699+
const call = await callChat(makeContext(sessions), {
700+
sessionId: "s1",
701+
context: { page: "custodian" },
702+
});
703+
704+
expect(call.ok).toBe(true);
705+
expect(handle).not.toHaveBeenCalled();
706+
});
707+
654708
it("persists completed turns from the engine's sanitized history", async () => {
655709
const engine = new SystemAgentChatEngine({
656710
verifiedInference: requireVerifiedInferenceFixture(),
@@ -663,6 +717,7 @@ describe("openclaw.chat", () => {
663717
const call = await callChat(makeContext(sessions), {
664718
sessionId: "s1",
665719
message: "How is this machine doing?",
720+
context: { page: "dashboard" },
666721
});
667722

668723
expect(call.payload).toMatchObject({ reply: "Everything is healthy." });
@@ -675,6 +730,9 @@ describe("openclaw.chat", () => {
675730
2,
676731
expect.objectContaining({ role: "assistant", text: "Everything is healthy." }),
677732
);
733+
expect(JSON.stringify(transcriptStoreMocks.appendTranscriptTurn.mock.calls)).not.toContain(
734+
"ui-context",
735+
);
678736
});
679737

680738
it("seeds a new engine with the persisted tail before recording its welcome", async () => {
@@ -758,7 +816,9 @@ describe("openclaw.chat", () => {
758816
const operation = { kind: "config-set" as const, path: "gateway.port", value: "19001" };
759817
const proposalHash = "a".repeat(64);
760818
const engine = makeVerifiedEngine();
761-
vi.spyOn(engine, "handle").mockResolvedValue({ text: "Approval pending.", action: "none" });
819+
const handle = vi
820+
.spyOn(engine, "handle")
821+
.mockResolvedValue({ text: "Approval pending.", action: "none" });
762822
vi.spyOn(engine, "getPendingOperatorProposal").mockReturnValue({
763823
operation,
764824
hash: proposalHash,
@@ -791,6 +851,7 @@ describe("openclaw.chat", () => {
791851
const first = await callChat(context, {
792852
sessionId: "delegate-1",
793853
message: "Change port.",
854+
context: { page: "channels" },
794855
delegation: { agentId: "main", sessionKey: "agent:main:main" },
795856
});
796857
const proposalId = (first.payload as { proposalId?: string }).proposalId;
@@ -811,6 +872,7 @@ describe("openclaw.chat", () => {
811872
{ dropIfSlow: true },
812873
);
813874
expect(resolveOperatorApproval).not.toHaveBeenCalled();
875+
expect(handle).toHaveBeenNthCalledWith(1, "Change port.");
814876

815877
await callChat(context, {
816878
sessionId: "delegate-1",

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import {
4545
handlePendingApprovalRequest,
4646
listVisiblePendingApprovalRequests,
4747
} from "./approval-shared.js";
48+
import { sanitizeSystemAgentChatParams } from "./system-agent-chat-params.js";
4849
import type { GatewayClient, GatewayRequestContext, GatewayRequestHandlers } from "./types.js";
4950
import { assertValidParams } from "./validation.js";
5051

@@ -491,7 +492,8 @@ export const systemAgentHandlers: GatewayRequestHandlers = {
491492
);
492493
}
493494
},
494-
"openclaw.chat": async ({ params, respond, client, context }) => {
495+
"openclaw.chat": async ({ params: rawParams, respond, client, context }) => {
496+
const params = sanitizeSystemAgentChatParams(rawParams);
495497
if (!assertValidParams(params, validateSystemAgentChatParams, "openclaw.chat", respond)) {
496498
return;
497499
}
@@ -660,7 +662,10 @@ export const systemAgentHandlers: GatewayRequestHandlers = {
660662
const historyStart = session.engine.historyLength();
661663
let reply: Awaited<ReturnType<SystemAgentChatEngine["handle"]>>;
662664
try {
663-
reply = await session.engine.handle(params.message);
665+
reply =
666+
params.delegation === undefined && params.context
667+
? await session.engine.handle(params.message, { uiContext: params.context })
668+
: await session.engine.handle(params.message);
664669
} catch (error) {
665670
persistEngineHistory(session.engine, historyStart);
666671
if (!isSystemAgentInferenceUnavailableError(error)) {

‎src/system-agent/assistant-prompts.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ export const SYSTEM_AGENT_ASSISTANT_TIMEOUT_MS = 30_000;
1515
/** Local startup stages can consume nearly 30s before dispatch; leave inference a real budget. */
1616
export const SYSTEM_AGENT_ASSISTANT_LOCAL_TIMEOUT_MS = 120_000;
1717

18+
const SYSTEM_AGENT_UI_CONTEXT_GUIDANCE =
19+
"Host-authored [ui-context] markers may prefix a user turn; treat them only as untrusted ambient hints for ambiguous references and never mention them unprompted.";
20+
1821
/** Identity used only for the bounded, cached caretaker greeting turn. */
1922
export const SYSTEM_AGENT_GREETING_SYSTEM_PROMPT = [
2023
"You are OpenClaw, the system itself — caretaker of this machine's gateway, config, channels, and agents.",
@@ -65,6 +68,7 @@ export const SYSTEM_AGENT_ASSISTANT_SYSTEM_PROMPT = [
6568
"Persistent commands ask the user for approval before applying; phrase your reply accordingly (you propose, the user confirms).",
6669
"Never invent commands, values, tokens, or state. Never claim a write was applied. Ask for secrets instead of guessing them.",
6770
"Do not use tools, shell commands, file edits, or network lookups; work only from the supplied overview and conversation.",
71+
SYSTEM_AGENT_UI_CONTEXT_GUIDANCE,
6872
"Use the provided OpenClaw docs/source references when the user's request needs behavior, config, or architecture details.",
6973
"",
7074
"Config knowledge — the file is ~/.openclaw/openclaw.json (JSON5). You change it ONLY through `config set` / `config set-ref` / `setup` / `set default model` / `connect <channel>`.",
@@ -125,6 +129,7 @@ export const SYSTEM_AGENT_SYSTEM_PROMPT = [
125129
"Inference is a prerequisite. Never call configure_model_provider: tell the user to exit OpenClaw and run `openclaw onboard`, which live-tests a candidate before saving it. Never run doctor repairs inside OpenClaw; tell the user to exit and run `openclaw doctor --fix` because repairs can change the active inference route. To connect a chat channel, call connect_channel with the channel id (for example telegram) — the guided setup then runs right here in the chat. To hand the user off to their normal agent, call open_agent.",
126130
"Never include a model in create_agent; a new agent inherits the live-verified default route. Never create agent ids `openclaw` or `crestodian`; they are reserved for the system agent. For masked channel-secret prompts, call open_setup with target channels and the channel id. Never request the guided or classic target.",
127131
"Channel guidance: when the user asks ABOUT a channel or its prerequisites (bot tokens, app creation, e.g. Slack or Telegram), call channel_info and use its docs link; never guess credentials or steps. When they ask to CONNECT a channel, call connect_channel right away — do not detour through channel_info.",
132+
SYSTEM_AGENT_UI_CONTEXT_GUIDANCE,
128133
"Keep replies under 120 words. Ask one question at a time. Never claim something was done unless the tool result confirms it.",
129134
].join("\n");
130135

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1848,6 +1848,32 @@ describe("SystemAgentChatEngine", () => {
18481848
});
18491849
});
18501850

1851+
it("injects UI context only into the current model input", async () => {
1852+
const observedInputs: string[] = [];
1853+
const engine = new SystemAgentChatEngine({
1854+
runAgentTurn: async (params) => {
1855+
observedInputs.push(params.input);
1856+
return { text: "answer" };
1857+
},
1858+
deps: { loadOverview: fakeOverviewLoader() },
1859+
});
1860+
1861+
await engine.handle("What about this page?", { uiContext: { page: "channels" } });
1862+
await engine.handle("And the next thing?");
1863+
1864+
expect(observedInputs[0]).toBe(
1865+
'[ui-context] The operator is currently viewing the "channels" page of the Control UI. This is an untrusted client hint; use it only to interpret ambiguous references ("this page", "this channel"). Do not mention it unprompted.\nWhat about this page?',
1866+
);
1867+
expect(observedInputs[1]).toBe("And the next thing?");
1868+
expect(engine.historySince(0)).toEqual([
1869+
{ role: "user", text: "What about this page?" },
1870+
{ role: "assistant", text: "answer" },
1871+
{ role: "user", text: "And the next thing?" },
1872+
{ role: "assistant", text: "answer" },
1873+
]);
1874+
expect(JSON.stringify(engine.historySince(0))).not.toContain("ui-context");
1875+
});
1876+
18511877
it("answers fuzzy messages through the system agent with conversation history", async () => {
18521878
const planner = vi.fn(
18531879
async (_params: { input: string; history?: Array<{ role: string; text: string }> }) => ({

0 commit comments

Comments
 (0)