Skip to content

fix(agents): persist cli transcript turns - #67490

Merged
obviyus merged 5 commits into
openclaw:mainfrom
obviyus:fix-67469-cli-transcript-persistence
Apr 16, 2026
Merged

obviyus merged 5 commits into
openclaw:mainfrom
obviyus:fix-67469-cli-transcript-persistence

Conversation

@obviyus

@obviyus obviyus commented Apr 16, 2026

Copy link
Copy Markdown
Collaborator

Persist successful CLI turns into the OpenClaw session transcript and add a regression test for google-gemini-cli.

Fixes #67469.

@aisle-research-bot

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

Copy link
Copy Markdown

🔒 Aisle Security Analysis

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

# Severity Title
1 🟡 Medium Unbounded CLI payload concatenation and transcript persistence can cause resource exhaustion (DoS)
2 🟡 Medium Untrusted CLI agent metadata persisted into transcripts (provider/model/usage spoofing)
3 🟡 Medium CLI agent outputs and prompts persisted to session transcript without redaction (possible secret leakage)
1. 🟡 Unbounded CLI payload concatenation and transcript persistence can cause resource exhaustion (DoS)
Property Value
Severity Medium
CWE CWE-400
Location src/agents/command/attempt-execution.ts:146-156

Description

persistCliTurnTranscript() builds assistant reply text from CLI/embedded agent output via resolveCliTranscriptReplyText(). The code concatenates all non-error/non-reasoning payload texts with join("\n\n") and then persists the resulting string into the session transcript.

This is vulnerable to denial-of-service via oversized outputs:

  • A malicious/buggy CLI provider can return an extremely large payloads array and/or huge payload.text blobs.
  • join("\n\n") requires holding all strings in memory, potentially causing high memory usage and CPU overhead.
  • The resulting large replyText is written into the transcript via SessionManager.appendMessage(...), potentially creating very large session files and degrading UI/transcript operations.

Vulnerable code (unbounded concatenation):

return (result.payloads ?? [])
  .filter((payload) => !payload.isError && !payload.isReasoning)
  .map((payload) => payload.text?.trim() ?? "")
  .filter(Boolean)
  .join("\n\n");

Vulnerable code (unbounded persistence):

sessionManager.appendMessage({
  role: "assistant",
  content: [{ type: "text", text: replyText }],
  ...
});

Recommendation

Add hard limits before concatenation/persistence:

  • Limit number of payloads processed (e.g., first N non-error payloads)
  • Limit total character budget for the persisted reply (truncate beyond a max)
  • Consider streaming/append-in-chunks rather than building one large string
  • Optionally record that truncation occurred (so users know output was cut)

Example:

const MAX_PAYLOADS = 50;
const MAX_REPLY_CHARS = 50_000;

function resolveCliTranscriptReplyText(result: EmbeddedPiRunResult): string {
  const visibleText = result.meta.finalAssistantVisibleText?.trim();
  if (visibleText) return visibleText.slice(0, MAX_REPLY_CHARS);

  let out = "";
  for (const payload of (result.payloads ?? [])) {
    if (payload.isError || payload.isReasoning) continue;
    const chunk = (payload.text ?? "").trim();
    if (!chunk) continue;
    if (out) out += "\n\n";
    out += chunk;
    if (out.length >= MAX_REPLY_CHARS) {
      out = out.slice(0, MAX_REPLY_CHARS);
      break;
    }
  }
  return out;
}

Also consider enforcing a maximum transcript file size or triggering compaction/rotation when exceeding a threshold.

2. 🟡 Untrusted CLI agent metadata persisted into transcripts (provider/model/usage spoofing)
Property Value
Severity Medium
CWE CWE-345
Location src/agents/command/attempt-execution.ts:193-214

Description

persistCliTurnTranscript persists provider, model, and usage from result.meta.agentMeta (CLI-provider controlled) into the session transcript as if it were authoritative.

This creates a trust-boundary violation:

  • Input (untrusted): EmbeddedPiRunResult.meta.agentMeta is supplied by the CLI provider implementation.
  • Persistence (sink): values are written into the session transcript via sessionManager.appendMessage.
  • Downstream impact: transcript parsing in src/infra/session-cost-usage.ts uses provider/model from transcript entries to resolve pricing (resolveModelCostConfig) and compute cost/usage totals. A malicious/buggy CLI provider can spoof provider/model and usage to mislead audit trails and cost/billing reports, and potentially skew dashboards/alerts.

Vulnerable flow (new behavior):

  • provider/model/usage come from params.result.meta.agentMeta and are persisted without validation or marking as untrusted.
const provider = params.result.meta.agentMeta?.provider?.trim() ?? "cli";
const model = params.result.meta.agentMeta?.model?.trim() ?? "default";
...
usage: params.result.meta.agentMeta?.usage,

Additionally, numeric usage fields are not bounded here; very large values can cause extreme totals/costs in reports (integrity/DoS-on-reporting).

Recommendation

Treat CLI-returned metadata as untrusted and prevent it from becoming authoritative billing/audit data.

Recommended fixes:

  1. Do not persist provider/model from CLI metadata as authoritative. Prefer values derived from configured provider/model selection (e.g., providerOverride/modelOverride) or persist them under a separate untrustedMeta field.
  2. Validate and clamp usage before persisting:
    • enforce non-negative integers
    • enforce reasonable maximums (e.g., per-message token cap)
    • drop/ignore invalid values

Example approach:

function sanitizeTokenCount(v: unknown, max = 5_000_000): number | undefined {
  if (typeof v !== "number" || !Number.isFinite(v)) return undefined;
  const n = Math.floor(v);
  if (n < 0) return 0;
  if (n > max) return max;
  return n;
}

const safeProvider = "cli"; // or derived from config/providerOverride
const safeModel = "default"; // or derived from modelOverride
const safeUsage = {
  input: sanitizeTokenCount(meta?.usage?.input),
  output: sanitizeTokenCount(meta?.usage?.output),
  cacheRead: sanitizeTokenCount(meta?.usage?.cacheRead),
  cacheWrite: sanitizeTokenCount(meta?.usage?.cacheWrite),
  total: sanitizeTokenCount(meta?.usage?.total),
};
  1. In cost reporting (session-cost-usage), consider ignoring provider/model for CLI transcripts unless they are from a trusted allowlist or accompanied by a trusted signature.
3. 🟡 CLI agent outputs and prompts persisted to session transcript without redaction (possible secret leakage)
Property Value
Severity Medium
CWE CWE-200
Location src/agents/command/attempt-execution.ts:121-140

Description

The CLI-backed runner now persists both the user prompt (body) and CLI agent output into the session transcript whenever result.meta.executionTrace?.runner === "cli".

This is risky because CLI providers commonly:

  • Read local files (e.g., .env, SSH keys, config files)
  • Invoke local tools that print credentials/tokens
  • Surface other sensitive workspace data

The persisted transcript is written to disk and an update event is emitted, which can make the full text available to other components (e.g., UI/session viewers). No explicit opt-in, allowlist, or secret redaction/scrubbing is applied to either the prompt or the reply text before persistence.

Vulnerable flow:

  • Input: body (user prompt) and result.payloads / result.meta.finalAssistantVisibleText (CLI output)
  • Transformation: resolveCliTranscriptReplyText() concatenates non-error, non-reasoning payload text
  • Sink: SessionManager.appendMessage() writes plaintext to the session transcript file

Vulnerable code (persistence enabled for CLI runner):

if (result.meta.executionTrace?.runner === "cli") {
  sessionEntry = await attemptExecutionRuntime.persistCliTurnTranscript({
    body,
    result,
    ​// ...
  });
}

Vulnerable code (no redaction before writing):

if (promptText) {
  sessionManager.appendMessage({ role: "user", content: promptText, timestamp: Date.now() });
}

if (replyText) {
  sessionManager.appendMessage({
    role: "assistant",
    content: [{ type: "text", text: replyText }],
    api: params.assistant.api,
    provider: params.assistant.provider,
    model: params.assistant.model,
    usage: resolveTranscriptUsage(params.assistant.usage),
    stopReason: "stop",
    timestamp: Date.now(),
  });
}

Even though newly created session files are written with mode 0o600, the content is still retained long-term on disk and may be surfaced elsewhere via transcript update events.

Recommendation

Add a safety gate and redaction before persisting CLI transcripts.

Recommended mitigations (use both):

  1. Explicit opt-in / config flag for persisting CLI runner transcripts (default off), because CLI agents can access local secrets.
  2. Secret scrubbing for both prompt and reply text before writing to disk and emitting transcript updates.

Example approach:

function redactSecrets(text: string): string {
  ​// Apply your existing secret redaction utilities or implement patterns for:
  ​// - API keys/tokens
  ​// - PEM blocks
  ​// - AWS/GCP credentials
  ​// - .env key=value lines
  return scrubKnownSecrets(text);
}

if (cfg.persistCliTranscripts === true) {
  const safePrompt = redactSecrets(body);
  const safeReply = redactSecrets(resolveCliTranscriptReplyText(result));
  await persistTextTurnTranscript({ ...params, body: safePrompt, finalText: safeReply, assistant: { ... } });
}

Also consider:

  • Storing only finalAssistantVisibleText (already curated) and never raw payload concatenations
  • Adding an allowlist of message types that can be persisted
  • Providing a per-session “do not persist” mode for sensitive runs

Analyzed PR: #67490 at commit 00d2af3

Last updated on: 2026-04-16T03:58:06Z

@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations agents Agent runtime and tooling size: M maintainer Maintainer-authored PR labels Apr 16, 2026
@greptile-apps

greptile-apps Bot commented Apr 16, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds persistence of successful CLI agent turn transcripts (user message + assistant reply) to the OpenClaw session file, and introduces a regression test covering the google-gemini-cli provider. The implementation refactors the existing persistAcpTurnTranscript into a shared persistTextTurnTranscript helper parameterised on assistant metadata, then adds persistCliTurnTranscript which reads provider/model/usage from the EmbeddedPiRunResult and delegates to that shared helper.

Confidence Score: 5/5

Safe to merge; the only finding is a semantic inconsistency in the api field that has no runtime impact.

The core logic — persisting CLI transcript turns, the shared helper refactor, the try/catch guard, and the regression test — is all correct. The single P2 finding is a style/semantic issue on the api field that does not affect observable behaviour.

src/agents/command/attempt-execution.ts — the api field in persistCliTurnTranscript.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/command/attempt-execution.ts
Line: 207-213

Comment:
**`api` field set to provider name instead of wire-protocol format**

`api: provider` stores the CLI provider name (e.g. `"google-gemini-cli"`) in the `api` field of the transcript message. Every other transcript write in the codebase uses an API format string like `"openai-responses"` or `"anthropic-messages"`. `transport-message-transform.ts` uses `msg.api` for `isSameModel` checks, so a novel value here won't break anything functionally, but it is semantically inconsistent and may confuse tooling or UI code that interprets the field. Consider a constant like `"cli"` or mapping to the backing API format if known.

```suggestion
    assistant: {
      api: "cli",
      provider,
      model,
      usage: params.result.meta.agentMeta?.usage,
    },
```

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

Reviews (1): Last reviewed commit: "fix(agents): persist cli transcript turn..." | Re-trigger Greptile

Comment thread src/agents/command/attempt-execution.ts Resolved
@obviyus obviyus self-assigned this Apr 16, 2026
@obviyus
obviyus force-pushed the fix-67469-cli-transcript-persistence branch from 2d40d2f to ee37797 Compare April 16, 2026 03:35

@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: 68013eead4

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/agent-command.ts Resolved
@obviyus
obviyus force-pushed the fix-67469-cli-transcript-persistence branch from 57cbcbb to 00d2af3 Compare April 16, 2026 03:50
@obviyus
obviyus merged commit 898fd04 into openclaw:main Apr 16, 2026
41 of 44 checks passed
@obviyus

obviyus commented Apr 16, 2026

Copy link
Copy Markdown
Collaborator Author

Landed on main.

globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request May 13, 2026
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
@clawsweeper clawsweeper Bot mentioned this pull request Jun 22, 2026
2 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations maintainer Maintainer-authored PR size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: google-gemini-cli replies stop being persisted to OpenClaw session transcripts / WebUI history

1 participant