Skip to content

fix: align claude-cli prompt hooks - #70625

Merged
mbelinky merged 3 commits into
mainfrom
mariano/claude-cli-prompt-parity
Apr 23, 2026
Merged

mbelinky merged 3 commits into
mainfrom
mariano/claude-cli-prompt-parity

Conversation

@mbelinky

Copy link
Copy Markdown
Contributor

Summary

  • run the Claude CLI backend through the same prompt-build hook path as embedded runs
  • pass real trigger, channel, and live provider context into Claude hook assembly and reuse the embedded prepend-system helper
  • document the Claude CLI setup flow, including logging into claude first and then wiring OpenClaw to the CLI backend

Testing

  • OPENCLAW_VITEST_MAX_WORKERS=1 pnpm test:serial src/auto-reply/reply/agent-runner-execution.test.ts src/agents/cli-runner/prepare.test.ts src/agents/cli-runner.spawn.test.ts src/agents/command/attempt-execution.cli.test.ts
  • pnpm check:changed --staged

@mbelinky
mbelinky requested a review from a team as a code owner April 23, 2026 13:55
@aisle-research-bot

aisle-research-bot Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 3 potential security issue(s) in this PR:

# Severity Title
1 🟡 Medium Unbounded session history loading for CLI prompt-build hooks can cause memory/CPU exhaustion
2 🟡 Medium Potential sensitive data exposure via logging of hook errors in CLI prompt-build path
3 🟡 Medium Origin metadata spoofing via messageChannel forwarded as messageProvider into CLI run hooks/MCP context
1. 🟡 Unbounded session history loading for CLI prompt-build hooks can cause memory/CPU exhaustion
Property Value
Severity Medium
CWE CWE-400
Location src/agents/cli-runner/prepare.ts:59-62

Description

In prepareCliRunContext(), when prompt-build hooks are enabled, the CLI runner loads all entries from the session JSONL file into memory and passes the full messages array into hook execution.

  • loadCliPromptBuildMessages() calls SessionManager.open(sessionFile).getEntries() and then flatMaps all message entries into an array.
  • There is no upper bound (count/bytes/tokens) on the session file size or the number of messages loaded.
  • A long-lived or attacker-influenced session (or a malformed/oversized session.jsonl) can therefore trigger large memory allocation and expensive hook processing, leading to resource exhaustion / denial of service.

Vulnerable code:

function loadCliPromptBuildMessages(sessionFile: string): unknown[] {
  const entries = SessionManager.open(sessionFile).getEntries();
  return entries.flatMap((entry) => (entry.type === "message" ? [entry.message as unknown] : []));
}
...
messages: loadCliPromptBuildMessages(params.sessionFile),

Recommendation

Introduce explicit limits when loading session history for hook context.

Options (can be combined):

  1. Load only the last N messages (or last N bytes/tokens) needed for hooks:
function loadCliPromptBuildMessages(sessionFile: string, maxMessages = 100): unknown[] {
  const entries = SessionManager.open(sessionFile).getEntries();
  const msgs = entries
    .filter((e) => e.type === "message")
    .map((e) => e.message as unknown);
  return msgs.slice(-maxMessages);
}
  1. Enforce a maximum session file size before reading (fail closed or skip hooks with a warning).

  2. If the upstream SessionManager supports it, prefer a streaming/iterative API (e.g., reading from the end, or early-stopping after collecting enough messages) to avoid allocating the full transcript.

Also consider applying the same truncation/session-compaction logic used in the embedded runner path before invoking hooks.

2. 🟡 Potential sensitive data exposure via logging of hook errors in CLI prompt-build path
Property Value
Severity Medium
CWE CWE-532
Location src/agents/cli-runner/prepare.ts:350-352

Description

In prepareCliRunContext, failures from CLI prompt-build hooks are logged using String(error) at warn level:

  • Hook implementations and their runtime may throw errors that include stack traces, environment values, prompt/messages content, or other secrets.
  • The logger writes to console and/or file sinks depending on runtime settings; warn-level logs are commonly collected centrally.

Vulnerable code:

} catch (error) {
  cliBackendLog.warn(`cli prompt-build hook preparation failed: ${String(error)}`);
}

Because String(error) is unstructured and unsanitized, it may leak sensitive data into logs.

Recommendation

Avoid logging raw error strings from hooks at warn/info levels. Log a minimal, non-sensitive summary and keep full details behind an explicit debug flag with redaction.

Example fix:

import { normalizeUnknownError } from "../infra/errors.js"; // or your local helper

} catch (error) {
  const err = normalizeUnknownError(error);
  cliBackendLog.warn("cli prompt-build hook preparation failed", {
    errorName: err.name,
    ​// avoid err.stack and avoid raw err.message if it may contain secrets
  });
  ​// Optionally, only in verbose/debug mode:
  ​// cliBackendLog.debug("cli prompt-build hook preparation failed (details)", { stack: err.stack });
}

If you need the message for troubleshooting, apply a redaction/scrubbing utility before emitting it (API keys/tokens, session keys, prompt text, file paths as appropriate).

3. 🟡 Origin metadata spoofing via messageChannel forwarded as messageProvider into CLI run hooks/MCP context
Property Value
Severity Medium
CWE CWE-290
Location src/agents/command/attempt-execution.ts:324-330

Description

The CLI execution path now forwards untrusted message origin metadata (channel/provider) into both:

  • The CLI runner hook context (before_prompt_build / before_agent_start), and
  • The bundled MCP loopback request header x-openclaw-message-channel via OPENCLAW_MCP_MESSAGE_CHANNEL.

In runAgentAttempt, messageProvider is incorrectly populated from params.messageChannel:

  • params.messageChannel can originate from external request context (e.g., HTTP header x-openclaw-message-channel is accepted elsewhere and normalized but not allow-listed).
  • The value is then treated as messageProvider and passed into hook context (hookCtx.messageProvider) and as channelId fallback.
  • Hook implementations and downstream policy logic may make trust decisions (routing, tool gating, auditing) based on these fields; allowing a caller-controlled header/option to set them enables spoofing and potential policy bypass.

Vulnerable code (incorrect assignment):

messageChannel: params.messageChannel,
...
messageProvider: params.messageChannel,

This conflates two concepts (channel ID vs provider) and forwards a potentially attacker-controlled string into internal security-relevant context.

Recommendation

  • Fix the mapping bug: pass the actual provider field (or omit) instead of reusing messageChannel.
  • Treat message origin metadata as untrusted unless derived from authenticated integration context. If it must come from inbound headers/options, enforce an allow-list of known channels/providers before forwarding into hooks/MCP headers.

Example fix:

runCliAgent({
  ​// ...
  messageChannel: params.messageChannel,
  messageProvider: params.messageProvider, // or undefined
});

And before forwarding:

import { resolveGatewayMessageChannel } from "../../utils/message-channel-normalize.js";

const safeChannel = resolveGatewayMessageChannel(params.messageChannel) ?? undefined;

Only forward safeChannel (and similarly validate provider IDs) into hookCtx / env.


Analyzed PR: #70625 at commit 3de89da

Last updated on: 2026-04-23T14:39:19Z

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Apr 23, 2026
@mbelinky mbelinky self-assigned this Apr 23, 2026
@greptile-apps

greptile-apps Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR aligns the claude-cli backend with the embedded runner by wiring before_prompt_build and before_agent_start hooks into CLI prompt preparation, propagating real trigger, messageChannel, and messageProvider context through the CLI execution paths, and fixing OPENCLAW_MCP_MESSAGE_CHANNEL to prefer messageChannel over messageProvider. Test coverage is thorough across all three changed execution sites (direct command, fallback runner, cron executor).

Confidence Score: 5/5

Safe to merge — all findings are minor style issues.

No P0 or P1 issues found. The hook integration logic is consistent with the embedded runner path, error handling is in place (try/catch around hook invocation), and the three execution sites each set the correct trigger value. The only issue is a duplicate import statement that should be merged.

src/agents/cli-runner/prepare.ts (duplicate import lines 35-36)

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/cli-runner/prepare.ts
Line: 35-36

Comment:
**Duplicate import from the same module**

Both `resolvePromptBuildHookResult` and `resolveAttemptPrependSystemContext` are imported from `attempt.prompt-helpers.js` in separate statements. These should be merged into a single import to follow standard convention and avoid lint warnings.

```suggestion
import { resolveAttemptPrependSystemContext, resolvePromptBuildHookResult } from "../pi-embedded-runner/run/attempt.prompt-helpers.js";
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix: align claude-cli prompt hooks" | Re-trigger Greptile

Comment on lines +35 to +36
import { resolvePromptBuildHookResult } from "../pi-embedded-runner/run/attempt.prompt-helpers.js";
import { resolveAttemptPrependSystemContext } from "../pi-embedded-runner/run/attempt.prompt-helpers.js";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Duplicate import from the same module

Both resolvePromptBuildHookResult and resolveAttemptPrependSystemContext are imported from attempt.prompt-helpers.js in separate statements. These should be merged into a single import to follow standard convention and avoid lint warnings.

Suggested change
import { resolvePromptBuildHookResult } from "../pi-embedded-runner/run/attempt.prompt-helpers.js";
import { resolveAttemptPrependSystemContext } from "../pi-embedded-runner/run/attempt.prompt-helpers.js";
import { resolveAttemptPrependSystemContext, resolvePromptBuildHookResult } from "../pi-embedded-runner/run/attempt.prompt-helpers.js";
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/cli-runner/prepare.ts
Line: 35-36

Comment:
**Duplicate import from the same module**

Both `resolvePromptBuildHookResult` and `resolveAttemptPrependSystemContext` are imported from `attempt.prompt-helpers.js` in separate statements. These should be merged into a single import to follow standard convention and avoid lint warnings.

```suggestion
import { resolveAttemptPrependSystemContext, resolvePromptBuildHookResult } from "../pi-embedded-runner/run/attempt.prompt-helpers.js";
```

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 51a115f515

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

};

function loadCliPromptBuildMessages(sessionFile: string): unknown[] {
const entries = SessionManager.open(sessionFile).getEntries();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use active-branch history for CLI prompt hooks

loadCliPromptBuildMessages reads SessionManager.open(...).getEntries(), which returns messages from the whole transcript tree (including sibling branches created by compaction/rewrite flows), not just the active branch. In sessions that have branched, before_prompt_build/legacy hook callbacks will see stale or unrelated turns and can prepend incorrect context/system text, causing prompt mutations to diverge from the actual conversation state; this should use active-branch/session-context messages instead of full entry history.

Useful? React with 👍 / 👎.

@mbelinky
mbelinky force-pushed the mariano/claude-cli-prompt-parity branch from 51a115f to 303ce20 Compare April 23, 2026 14:18

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5daf7ea34d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +900 to +903
const hookMessageProvider = resolveOriginMessageProvider({
originatingChannel: params.followupRun.originatingChannel,
provider: params.sessionCtx.Provider,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reuse queued messageProvider for CLI hook context

hookMessageProvider is recomputed from sessionCtx.Provider, but queued runs already resolve and persist the authoritative provider in followupRun.run.messageProvider (including cases where Provider/Surface diverge in get-reply-run.ts:699-705). When originatingChannel is unset, this can pass a different provider to CLI hooks/MCP than the one used for routing, so provider-specific prompt hooks run with the wrong channel context. Use the queued run.messageProvider as the source of truth (or at least fallback to it) instead of recomputing from sessionCtx.Provider alone.

Useful? React with 👍 / 👎.

@mbelinky
mbelinky force-pushed the mariano/claude-cli-prompt-parity branch from 5daf7ea to 3b5908a Compare April 23, 2026 14:29
@mbelinky
mbelinky force-pushed the mariano/claude-cli-prompt-parity branch from 3b5908a to 3de89da Compare April 23, 2026 14:32
@mbelinky
mbelinky merged commit 3e956a4 into main Apr 23, 2026
1 check passed
@mbelinky
mbelinky deleted the mariano/claude-cli-prompt-parity branch April 23, 2026 14:34
@mbelinky

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Thanks @mbelinky!

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3de89da38f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +900 to +902
const hookMessageProvider = resolveOriginMessageProvider({
originatingChannel: params.followupRun.originatingChannel,
provider: params.sessionCtx.Provider,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use live OriginatingChannel when resolving CLI hook context

This resolution drops origin-channel metadata whenever followupRun.originatingChannel is unset, even though the live template context can still provide sessionCtx.OriginatingChannel (the queue builder already handles this case by using ctx.OriginatingChannel ?? sessionCtx.OriginatingChannel in get-reply-run.ts). In those relayed-message sessions, CLI runs now send messageProvider/channelId as the provider fallback instead of the true origin channel, so channel-scoped prompt hooks and MCP routing can execute against the wrong channel.

Useful? React with 👍 / 👎.

zhongmairen pushed a commit to agencyos-cn/openclaw-bad that referenced this pull request Apr 23, 2026
* 'main' of https://github.com/openclaw/openclaw: (906 commits)
  docs(tools): restructure browser reference with tabs/accordions and trim redundant prose
  fix: tolerate post-update json in install smoke
  docs: expand Tencent Hy3 provider guide
  test: skip flaky live probe routes
  docs: add gateway diagnostics guide
  chore(release): update appcast for 2026.4.22
  docs(plugins): trim skill-workshop headings and collapse example variants; tighten codex-harness guardian explainer
  fix: keep root memory uppercase (openclaw#70621)
  fix: restore bundled plugin SDK alias
  test: skip additional stale live probe routes
  docs: msteams restructure - Azure Bot Steps, sentence-case headings, grouped config
  build: update tsgo native preview
  docs: collapse Slack manifest duplication and trim noise bullets
  test: skip stale live probe routes
  docs: extract Matrix push rules runbook, table verify CLI, merge E2EE H3s
  docs: add GitHub API polling guidance
  fix: honor explicit CI timing run id
  ci: validate docs mdx before publish
  ci: remove runner caps after timing review
  fix: align claude-cli prompt hooks (openclaw#70625)
  ...
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
Merged via squash.

Prepared head SHA: 3de89da
Co-authored-by: mbelinky <[email protected]>
Co-authored-by: mbelinky <[email protected]>
Reviewed-by: @mbelinky
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request May 13, 2026
Merged via squash.

Prepared head SHA: 3de89da
Co-authored-by: mbelinky <[email protected]>
Co-authored-by: mbelinky <[email protected]>
Reviewed-by: @mbelinky
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
Merged via squash.

Prepared head SHA: 3de89da
Co-authored-by: mbelinky <[email protected]>
Co-authored-by: mbelinky <[email protected]>
Reviewed-by: @mbelinky
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
Merged via squash.

Prepared head SHA: 3de89da
Co-authored-by: mbelinky <[email protected]>
Co-authored-by: mbelinky <[email protected]>
Reviewed-by: @mbelinky
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
Merged via squash.

Prepared head SHA: 3de89da
Co-authored-by: mbelinky <[email protected]>
Co-authored-by: mbelinky <[email protected]>
Reviewed-by: @mbelinky
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
Merged via squash.

Prepared head SHA: 3de89da
Co-authored-by: mbelinky <[email protected]>
Co-authored-by: mbelinky <[email protected]>
Reviewed-by: @mbelinky
Heetisk pushed a commit to Heetisk/openclaw that referenced this pull request Sep 28, 2026
Merged via squash.

Prepared head SHA: 3de89da
Co-authored-by: mbelinky <[email protected]>
Co-authored-by: mbelinky <[email protected]>
Reviewed-by: @mbelinky
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant