Skip to content

Commit 48e8965

Browse files
committed
fix(agents): keep cli session binding facts session-stable
Keep CLI session reuse hashes keyed to stable session prompt facts while preserving per-turn room-event message-tool delivery for execution and MCP scoping. Thread cliSessionBindingFacts from reply assembly through queued/followup CLI runs, make the stable CLI prompt delivery-neutral, and cover production-shaped room-event opts so forced message_tool_only delivery cannot poison binding identity. Fixes #99372 Release note: Telegram/room-event CLI backends can resume sessions across interactive turns again instead of replaying full history after system-prompt invalidations.
1 parent 6638a57 commit 48e8965

17 files changed

Lines changed: 533 additions & 47 deletions

‎src/agents/cli-runner/prepare.test.ts‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2012,6 +2012,111 @@ describe("shouldSkipLocalCliCredentialEpoch", () => {
20122012
}
20132013
});
20142014

2015+
it.each([
2016+
{
2017+
name: "automatic config",
2018+
stableMode: "automatic",
2019+
staticPrompt: "group:telegram:group:automatic",
2020+
expectedStrongPrompt: false,
2021+
},
2022+
{
2023+
name: "message-tool config",
2024+
stableMode: "message_tool_only",
2025+
staticPrompt: "group:telegram:group:message_tool_only",
2026+
expectedStrongPrompt: true,
2027+
},
2028+
] as const)(
2029+
"reuses CLI session bindings across new inbound messages with stable binding facts for $name",
2030+
async ({ stableMode, staticPrompt, expectedStrongPrompt }) => {
2031+
const { dir, sessionFile } = createSessionFile();
2032+
try {
2033+
const getActiveMcpLoopbackRuntime = vi.fn(() => ({
2034+
port: 31783,
2035+
ownerToken: "loopback-owner-token",
2036+
nonOwnerToken: "loopback-non-owner-token",
2037+
}));
2038+
const resolveMcpLoopbackScopedTools = vi.fn(() => ({
2039+
agentId: "main",
2040+
tools: [
2041+
{
2042+
name: "message",
2043+
label: "Message",
2044+
description: "Send a message",
2045+
parameters: { type: "object", properties: {} },
2046+
execute: vi.fn(),
2047+
},
2048+
],
2049+
}));
2050+
setCliRunnerPrepareTestDeps({
2051+
getActiveMcpLoopbackRuntime,
2052+
resolveMcpLoopbackScopedTools,
2053+
});
2054+
const cliSessionBindingFacts = {
2055+
extraSystemPromptStatic: staticPrompt,
2056+
sourceReplyDeliveryMode: stableMode,
2057+
};
2058+
const first = await prepareCliRunContext({
2059+
sessionId: "session-test",
2060+
sessionKey: "main",
2061+
sessionFile,
2062+
workspaceDir: dir,
2063+
prompt: "first ask",
2064+
provider: "test-cli",
2065+
model: "test-model",
2066+
timeoutMs: 1_000,
2067+
runId: "run-test-stable-binding-facts-a",
2068+
extraSystemPrompt: `volatile msg-1\n\n${staticPrompt}`,
2069+
sourceReplyDeliveryMode: "message_tool_only",
2070+
currentMessageId: "msg-1",
2071+
cliSessionBindingFacts,
2072+
config: createCliBackendConfig({ bundleMcp: true }),
2073+
});
2074+
const second = await prepareCliRunContext({
2075+
sessionId: "session-test",
2076+
sessionKey: "main",
2077+
sessionFile,
2078+
workspaceDir: dir,
2079+
prompt: "second ask",
2080+
provider: "test-cli",
2081+
model: "test-model",
2082+
timeoutMs: 1_000,
2083+
runId: "run-test-stable-binding-facts-b",
2084+
extraSystemPrompt: `volatile msg-2\n\n${staticPrompt}`,
2085+
sourceReplyDeliveryMode: stableMode,
2086+
currentMessageId: "msg-2",
2087+
cliSessionBindingFacts,
2088+
cliSessionBinding: {
2089+
sessionId: "cli-session",
2090+
extraSystemPromptHash: first.extraSystemPromptHash,
2091+
messageToolPolicyHash: first.messageToolPolicyHash,
2092+
promptToolNamesHash: first.promptToolNamesHash,
2093+
cwdHash: hashCliSessionText(dir),
2094+
},
2095+
config: createCliBackendConfig({ bundleMcp: true }),
2096+
});
2097+
2098+
expect(first.extraSystemPromptHash).toBe(hashCliSessionText(staticPrompt));
2099+
expect(first.messageToolPolicyHash).toBeDefined();
2100+
expect(second.extraSystemPromptHash).toBe(first.extraSystemPromptHash);
2101+
expect(second.messageToolPolicyHash).toBe(first.messageToolPolicyHash);
2102+
expect(second.promptToolNamesHash).toBe(first.promptToolNamesHash);
2103+
if (expectedStrongPrompt) {
2104+
expect(first.systemPrompt).toContain(
2105+
"use `message(action=send)` for visible source-channel output",
2106+
);
2107+
} else {
2108+
expect(first.systemPrompt).toContain("final text normally routes to the source channel");
2109+
expect(first.systemPrompt).toContain(
2110+
"if current-turn context says final text stays private, use `message(action=send)`",
2111+
);
2112+
}
2113+
expect(second.reusableCliSession).toEqual({ sessionId: "cli-session" });
2114+
} finally {
2115+
fs.rmSync(dir, { recursive: true, force: true });
2116+
}
2117+
},
2118+
);
2119+
20152120
it("prepares raw-tail history for safe invalidations only when the backend opts in", async () => {
20162121
const { dir, sessionFile } = createSessionFile();
20172122
appendTranscriptEntry(sessionFile, {

‎src/agents/cli-runner/prepare.ts‎

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -347,25 +347,35 @@ export async function prepareCliRunContext(
347347
}
348348
}
349349
const extraSystemPrompt = params.extraSystemPrompt?.trim() ?? "";
350-
// Use the static portion (excluding per-message inbound metadata) for session reuse hashing.
351-
// Per-message metadata (timestamps, message IDs) changes every turn and must not trigger session resets.
350+
const bindingFacts = params.cliSessionBindingFacts;
351+
const bindingExtraSystemPromptStatic =
352+
bindingFacts?.extraSystemPromptStatic ?? params.extraSystemPromptStatic;
352353
const extraSystemPromptHash =
353-
params.extraSystemPromptStatic !== undefined
354-
? hashCliSessionText(params.extraSystemPromptStatic.trim() || undefined)
354+
bindingExtraSystemPromptStatic !== undefined
355+
? hashCliSessionText(bindingExtraSystemPromptStatic.trim() || undefined)
355356
: hashCliSessionText(extraSystemPrompt);
356357
const requireExplicitMessageTarget =
357358
params.requireExplicitMessageTarget ?? isSubagentSessionKey(params.sessionKey);
358-
const messageToolPolicyHash =
359-
params.sourceReplyDeliveryMode !== undefined ||
360-
params.requireExplicitMessageTarget !== undefined ||
361-
requireExplicitMessageTarget
362-
? hashCliSessionText(
363-
JSON.stringify({
364-
sourceReplyDeliveryMode: params.sourceReplyDeliveryMode,
365-
requireExplicitMessageTarget,
366-
}),
367-
)
368-
: undefined;
359+
const hasCliSessionBindingFacts = bindingFacts !== undefined;
360+
const bindingRequireExplicitMessageTarget =
361+
bindingFacts?.requireExplicitMessageTarget ?? requireExplicitMessageTarget;
362+
const bindingSourceReplyDeliveryMode = hasCliSessionBindingFacts
363+
? bindingFacts.sourceReplyDeliveryMode
364+
: params.sourceReplyDeliveryMode;
365+
const hasBindingMessageToolPolicy =
366+
bindingSourceReplyDeliveryMode !== undefined ||
367+
(hasCliSessionBindingFacts
368+
? bindingFacts.requireExplicitMessageTarget !== undefined ||
369+
bindingRequireExplicitMessageTarget
370+
: params.requireExplicitMessageTarget !== undefined || bindingRequireExplicitMessageTarget);
371+
const messageToolPolicyHash = hasBindingMessageToolPolicy
372+
? hashCliSessionText(
373+
JSON.stringify({
374+
sourceReplyDeliveryMode: bindingSourceReplyDeliveryMode,
375+
requireExplicitMessageTarget: bindingRequireExplicitMessageTarget,
376+
}),
377+
)
378+
: undefined;
369379

370380
const modelId = (params.model ?? "default").trim() || "default";
371381
const normalizedModel = normalizeCliModel(modelId, backendResolved.config);
@@ -708,8 +718,8 @@ export async function prepareCliRunContext(
708718
config: params.config,
709719
defaultThinkLevel: params.thinkLevel,
710720
extraSystemPrompt,
711-
sourceReplyDeliveryMode: params.sourceReplyDeliveryMode,
712-
requireExplicitMessageTarget,
721+
sourceReplyDeliveryMode: bindingSourceReplyDeliveryMode,
722+
requireExplicitMessageTarget: bindingRequireExplicitMessageTarget,
713723
silentReplyPromptMode: params.silentReplyPromptMode,
714724
runtimeChannel,
715725
runtimeChatType: params.sessionEntry?.chatType,

‎src/agents/cli-runner/types.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ export type RunCliAgentParams = {
9393
allowEmptyAssistantReplyAsSilent?: boolean;
9494
/** Static portion of extraSystemPrompt (excluding per-message inbound metadata) for session reuse hashing. */
9595
extraSystemPromptStatic?: string;
96+
cliSessionBindingFacts?: CliSessionBindingFacts;
9697
streamParams?: import("../command/types.js").AgentStreamParams;
9798
ownerNumbers?: string[];
9899
cliSessionId?: string;
@@ -179,6 +180,12 @@ export type CliReusableSession = {
179180
| "orphaned-tool-use";
180181
};
181182

183+
export type CliSessionBindingFacts = {
184+
extraSystemPromptStatic?: string;
185+
sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
186+
requireExplicitMessageTarget?: boolean;
187+
};
188+
182189
/** Fully prepared execution context consumed by the CLI runner executor. */
183190
export type PreparedCliRunContext = {
184191
params: RunCliAgentParams;

‎src/agents/system-prompt.test.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,23 @@ describe("buildAgentSystemPrompt", () => {
174174
expect(prompt).toContain('reply with exactly "NO_REPLY"');
175175
});
176176

177+
it("keeps source delivery guidance mode-neutral when silent replies are suppressed", () => {
178+
const prompt = buildAgentSystemPrompt({
179+
workspaceDir: "/tmp/openclaw",
180+
toolNames: ["message"],
181+
silentReplyPromptMode: "none",
182+
runtimeInfo: {
183+
channel: "telegram",
184+
},
185+
});
186+
187+
expect(prompt).toContain("final text normally routes to the source channel");
188+
expect(prompt).toContain("Follow current-turn delivery context");
189+
expect(prompt).not.toContain(
190+
"Do not use `message(action=send)` to deliver the current source-channel reply",
191+
);
192+
});
193+
177194
it("includes skills in minimal prompt mode when skillsPrompt is provided (cron regression)", () => {
178195
// Isolated cron sessions use promptMode="minimal" but still need skills.
179196
const skillsPrompt =
@@ -1050,7 +1067,7 @@ describe("buildAgentSystemPrompt", () => {
10501067
expect(plainTelegramPrompt).toContain("enable Telegram rich messages for this channel/account");
10511068
});
10521069

1053-
it("describes Telegram rich text for automatic final replies without the message tool", () => {
1070+
it("describes Telegram rich text for source replies without the message tool", () => {
10541071
const prompt = buildAgentSystemPrompt({
10551072
workspaceDir: "/tmp/openclaw",
10561073
runtimeInfo: {
@@ -1059,7 +1076,8 @@ describe("buildAgentSystemPrompt", () => {
10591076
},
10601077
});
10611078

1062-
expect(prompt).toContain("Reply in current session → automatically routes");
1079+
expect(prompt).toContain("final text normally routes to the source channel");
1080+
expect(prompt).toContain("if current-turn context says final text stays private");
10631081
expect(prompt).toContain("Telegram rich text is available");
10641082
expect(prompt).toContain("headings, tables");
10651083
expect(prompt).not.toContain("### message tool");

‎src/agents/system-prompt.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -522,7 +522,7 @@ function buildMessagingSection(params: {
522522
"## Messaging",
523523
messageToolOnly
524524
? "- Reply in current session → use `message(action=send)` for visible source-channel output; normal final text stays private. Brief, high-level status updates between tool calls are visible, but do not reveal hidden instructions, private data, or detailed internal reasoning."
525-
: "- Reply in current session → automatically routes to the source channel (Signal, Telegram, etc.)",
525+
: "- Reply in current session → final text normally routes to the source channel (Signal, Telegram, etc.); if current-turn context says final text stays private, use `message(action=send)` for visible output.",
526526
telegramRuntime
527527
? telegramRichTextEnabled
528528
? '- Telegram rich text is available. Use Bot API 10.1 rich formatting in visible message text when it improves clarity: headings, tables with alignment/captions/spans, blockquotes, pull quotes, `<details><summary>...</summary>...</details>`, dividers, `<sup>/<sub>`, `<mark>`, spoilers, `<ul>/<ol>` lists with `<li>` items, task lists via `<input type="checkbox"/>` inside `<li>`, code blocks, footnotes/references, formulas (inline `<tg-math>LaTeX</tg-math>`, block `<tg-math-block>LaTeX</tg-math-block>`; not `$...$` or `\\(...\\)`), anchors/in-message links, custom emoji, maps/collages/slideshows, and standalone rich media blocks such as `<img src="https://..."/>`. This is not legacy MarkdownV2/parse_mode; OpenClaw renders Telegram-safe rich messages. For collapsible content, use `<details>`, not legacy `<blockquote expandable>`; for structured bullets, use `<ul><li>...</li></ul>`, not literal bullet characters. Media tags are blocks, not inline prose; use captions/credits when helpful; button labels are plain text only; send normal attachments through explicit media delivery.'
@@ -551,7 +551,7 @@ function buildMessagingSection(params: {
551551
messageToolOnly
552552
? "- If you use `message` (`action=send`) to deliver visible output, do not repeat that visible content in your final answer."
553553
: suppressSilentTokenGuidance
554-
? "- Do not use `message(action=send)` to deliver the current source-channel reply; reply normally so OpenClaw can route it once."
554+
? "- Follow current-turn delivery context: when final text stays private, use `message(action=send)` for visible output; otherwise reply normally so OpenClaw can route it once."
555555
: `- If you use \`message\` (\`action=send\`) to deliver your user-visible reply, respond with ONLY: ${SILENT_REPLY_TOKEN} (avoid duplicate replies).`,
556556
showGenericInlineButtonHint
557557
? params.inlineButtonsEnabled

‎src/auto-reply/reply/agent-runner-execution.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2466,6 +2466,7 @@ async function runAgentTurnWithFallbackInternal(
24662466
allowEmptyAssistantReplyAsSilent:
24672467
params.followupRun.run.allowEmptyAssistantReplyAsSilent,
24682468
extraSystemPromptStatic: params.followupRun.run.extraSystemPromptStatic,
2469+
cliSessionBindingFacts: params.followupRun.run.cliSessionBindingFacts,
24692470
ownerNumbers: params.followupRun.run.ownerNumbers,
24702471
cliSessionId: cliSessionBinding?.sessionId,
24712472
cliSessionBinding,

‎src/auto-reply/reply/dispatch-from-config.test.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,13 @@ const automaticGroupReplyConfig = {
627627
},
628628
},
629629
} as const satisfies OpenClawConfig;
630+
const messageToolGroupReplyConfig = {
631+
messages: {
632+
groupChat: {
633+
visibleReplies: "message_tool",
634+
},
635+
},
636+
} as const satisfies OpenClawConfig;
630637
const automaticDirectReplyConfig = {
631638
messages: {
632639
visibleReplies: "automatic",
@@ -3543,6 +3550,75 @@ describe("dispatchReplyFromConfig", () => {
35433550
expect(dispatcher.sendFinalReply).not.toHaveBeenCalled();
35443551
});
35453552

3553+
it.each([
3554+
{
3555+
name: "automatic",
3556+
cfg: automaticGroupReplyConfig,
3557+
expectedUserRequestMode: "automatic",
3558+
expectedStableMode: "automatic",
3559+
},
3560+
{
3561+
name: "message-tool",
3562+
cfg: messageToolGroupReplyConfig,
3563+
expectedUserRequestMode: "message_tool_only",
3564+
expectedStableMode: "message_tool_only",
3565+
},
3566+
] as const)(
3567+
"threads $name session-stable source delivery mode to reply runs",
3568+
async ({ cfg, expectedUserRequestMode, expectedStableMode }) => {
3569+
setNoAbort();
3570+
const dispatcher = createDispatcher();
3571+
type CapturedReplyOptions = GetReplyOptions & {
3572+
sessionPromptSourceReplyDeliveryMode?: GetReplyOptions["sourceReplyDeliveryMode"];
3573+
};
3574+
const seen: Array<{
3575+
effective?: GetReplyOptions["sourceReplyDeliveryMode"];
3576+
stable?: GetReplyOptions["sourceReplyDeliveryMode"];
3577+
}> = [];
3578+
const replyResolver = vi.fn(async (_ctx: MsgContext, opts?: CapturedReplyOptions) => {
3579+
seen.push({
3580+
effective: opts?.sourceReplyDeliveryMode,
3581+
stable: opts?.sessionPromptSourceReplyDeliveryMode,
3582+
});
3583+
return { text: "done" } satisfies ReplyPayload;
3584+
});
3585+
const baseCtx = {
3586+
Provider: "telegram",
3587+
Surface: "telegram",
3588+
ChatType: "group",
3589+
From: "telegram:group:-100123",
3590+
SessionKey: "agent:main:telegram:group:-100123",
3591+
};
3592+
3593+
await dispatchReplyFromConfig({
3594+
ctx: buildTestCtx({
3595+
...baseCtx,
3596+
Body: "@bot check this",
3597+
CommandBody: "@bot check this",
3598+
}),
3599+
cfg,
3600+
dispatcher,
3601+
replyResolver,
3602+
});
3603+
await dispatchReplyFromConfig({
3604+
ctx: buildTestCtx({
3605+
...baseCtx,
3606+
Body: "@bot check this",
3607+
CommandBody: "@bot check this",
3608+
InboundEventKind: "room_event",
3609+
}),
3610+
cfg,
3611+
dispatcher,
3612+
replyResolver,
3613+
});
3614+
3615+
expect(seen).toEqual([
3616+
{ effective: expectedUserRequestMode, stable: expectedStableMode },
3617+
{ effective: "message_tool_only", stable: expectedStableMode },
3618+
]);
3619+
},
3620+
);
3621+
35463622
it("forwards channel-owned room-event progress callbacks while source delivery is suppressed", async () => {
35473623
setNoAbort();
35483624
sessionStoreMocks.currentEntry = {

‎src/auto-reply/reply/dispatch-from-config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2047,6 +2047,7 @@ export async function dispatchReplyFromConfig(
20472047
});
20482048
const {
20492049
sourceReplyDeliveryMode,
2050+
sessionStableSourceReplyDeliveryMode,
20502051
suppressAutomaticSourceDelivery,
20512052
suppressDelivery,
20522053
sendPolicyDenied,
@@ -3073,6 +3074,7 @@ export async function dispatchReplyFromConfig(
30733074
{
30743075
...getReplyOptions(),
30753076
sourceReplyDeliveryMode,
3077+
sessionPromptSourceReplyDeliveryMode: sessionStableSourceReplyDeliveryMode,
30763078
...({
30773079
onSessionMetadataChanges: notifySessionMetadataChanges,
30783080
onSessionPrepared: notePreparedSession,

‎src/auto-reply/reply/followup-runner.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1102,6 +1102,7 @@ export function createFollowupRunner(params: {
11021102
silentReplyPromptMode: run.silentReplyPromptMode,
11031103
allowEmptyAssistantReplyAsSilent: run.allowEmptyAssistantReplyAsSilent,
11041104
extraSystemPromptStatic: run.extraSystemPromptStatic,
1105+
cliSessionBindingFacts: run.cliSessionBindingFacts,
11051106
ownerNumbers: run.ownerNumbers,
11061107
cliSessionId: cliSessionBinding?.sessionId,
11071108
cliSessionBinding,

0 commit comments

Comments
 (0)