Skip to content

feat(codex-cli): prefer output-last-message artifacts - #66081

Closed
Rohan5commit wants to merge 1 commit into
openclaw:mainfrom
Rohan5commit:feat/codex-output-last-message
Closed

Rohan5commit wants to merge 1 commit into
openclaw:mainfrom
Rohan5commit:feat/codex-output-last-message

Conversation

@Rohan5commit

Copy link
Copy Markdown
Contributor

Summary

  • Problem: direct codex-cli runs still finalize the user-visible reply from stdout even though Codex can write a dedicated final-message artifact
  • Why it matters: stdout is useful for transport and telemetry, but it is a weaker source of truth for the final assistant answer than Codex's explicit --output-last-message output
  • What changed: codex-cli runs now allocate a temp --output-last-message file, prefer that artifact when it contains text, and keep stdout parsing as the fallback path
  • What did NOT change (scope boundary): other CLI backends still use their existing stdout/json/jsonl parsing paths, and this PR does not change failure classification or streaming behavior

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Root Cause (if applicable)

  • Root cause: the direct codex-cli runner only treated stdout parsing as the final reply source even though Codex already exposes a more stable final-message artifact contract
  • Missing detection / guardrail: there was no runner-level test that forced stdout and the final-message artifact to disagree and verified that OpenClaw finalized from the artifact
  • Contributing context (if known): Codex CLI already supports --output-last-message, but OpenClaw was not wiring that contract into the codex-cli backend path

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: src/agents/cli-runner.spawn.test.ts, src/agents/cli-output.test.ts
  • Scenario the test should lock in: when Codex writes both stdout JSONL and an --output-last-message file, OpenClaw should prefer the artifact when it is non-empty and fall back to parsed stdout when the artifact is empty
  • Why this is the smallest reliable guardrail: it exercises the exact runner boundary where args are built, the artifact is read, stdout is still parsed, and the final reply is selected
  • Existing test that already covers this (if any): none covered the artifact-vs-stdout precedence or Codex message-content JSONL fallback
  • If no new test is added, why not:

User-visible / Behavior Changes

  • codex-cli replies now finalize from Codex's explicit final-message artifact when available, which makes delegated Codex runs less dependent on stdout formatting details.

Diagram (if applicable)

Before:
[codex exec --json] -> [stdout parsed] -> [reply text selected from stdout]

After:
[codex exec --json --output-last-message <file>]
  -> [stdout parsed for session/usage/fallback]
  -> [artifact read]
  -> [artifact text wins when present]

Security Impact (required)

  • New permissions/capabilities? (No)
  • Secrets/tokens handling changed? (No)
  • New/changed network calls? (No)
  • Command/tool execution surface changed? (Yes)
  • Data access scope changed? (No)
  • If any Yes, explain risk + mitigation:
    • This only adds Codex's own --output-last-message flag plus a temp file under OpenClaw's preferred temp dir. The file is per-run, read back locally, and deleted in cleanup even when parsing falls back to stdout.

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: local pnpm/vitest
  • Model/provider: codex-cli/gpt-5.4
  • Integration/channel (if any): direct CLI runner
  • Relevant config (redacted): default codex-cli backend with --json

Steps

  1. Run a direct codex-cli execution through the CLI runner.
  2. Have Codex emit stdout JSONL and write a final-message artifact.
  3. Compare the final reply selection when the artifact is populated vs empty.

Expected

  • OpenClaw should prefer the artifact text when it exists and keep stdout parsing as the fallback.

Actual

  • Before this change, the runner always finalized from stdout because it never requested or read Codex's final-message artifact.

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

  • Verified scenarios: targeted vitest run for src/agents/cli-output.test.ts, src/agents/cli-runner.spawn.test.ts, and src/agents/cli-runner.reliability.test.ts
  • Edge cases checked: non-empty artifact overriding stdout; empty artifact falling back to stdout; Codex JSONL message content still parsing to plain assistant text
  • What you did not verify: full repo-wide pnpm check / pnpm test lanes and a live end-to-end Codex CLI run against the actual binary in this branch

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? (Yes)
  • Config/env changes? (No)
  • Migration needed? (No)
  • If yes, exact upgrade steps:

Risks and Mitigations

  • Risk: temp artifact cleanup could leak files if the runner exits early
    • Mitigation: cleanup runs in the outer finally, and the unit test asserts the artifact path is removed after success
  • Risk: Codex stdout fallback could regress if the artifact is empty and stdout uses the normal message-content JSONL shape
    • Mitigation: parseCliJsonl now extracts text from Codex message content records, and the fallback path is covered by a dedicated unit test

AI-assisted: Yes (Codex). Testing: targeted vitest coverage listed above. I attempted codex review --base origin/main, but the local Codex CLI is currently rate-limited.

Copilot AI review requested due to automatic review settings April 13, 2026 17:17
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Apr 13, 2026

Copilot AI 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.

Pull request overview

Updates the direct codex-cli runner to prefer Codex’s dedicated --output-last-message artifact as the source of truth for the final assistant reply, while keeping existing stdout parsing as a fallback for telemetry and compatibility.

Changes:

  • Add temp --output-last-message artifact wiring for codex-cli runs and prefer artifact text when present.
  • Extend JSONL parsing to extract Codex message text from content records.
  • Add unit tests covering artifact-vs-stdout precedence and stdout fallback.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
src/agents/cli-runner/execute.ts Create/read/cleanup Codex last-message artifact and prefer it over parsed stdout text.
src/agents/cli-runner.spawn.test.ts Add tests asserting artifact precedence and stdout fallback, plus artifact cleanup.
src/agents/cli-output.ts Teach parseCliJsonl to extract Codex message text from content/message-like fields.
src/agents/cli-output.test.ts Add coverage for Codex JSONL content-record text extraction.

Comment on lines +272 to +279
const codexLastMessageArtifact = isCodexCliBackend(context)
? await prepareCodexLastMessageArtifact({
runId: params.runId,
})
: undefined;
if (codexLastMessageArtifact) {
args.push("--output-last-message", codexLastMessageArtifact.filePath);
}
@greptile-apps

greptile-apps Bot commented Apr 13, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds Codex-specific --output-last-message artifact support to the codex-cli runner path: a per-run temp file is allocated before spawn, the artifact is read after process exit, and it takes precedence over parsed stdout when non-empty. Cleanup runs in the outer finally and the fallback to stdout JSONL parsing is well-tested.

One concern worth resolving before merge: the new text-extraction fallback added to parseCliJsonl (collectCliText(parsed.message/content/result/response)) is not guarded by providerId, so it applies to all JSONL-configured backends despite the PR description stating otherwise. While Claude CLI is protected by the parseClaudeCliJsonlResult early-return, any other JSONL backend that emits structured records with these top-level fields could have unexpected text folded into the reply.

Confidence Score: 4/5

Safe to merge after addressing the unguarded parseCliJsonl fallback; the artifact flow itself is well-implemented.

One P1 finding: the new fallback text extraction in parseCliJsonl is not scoped to codex-cli, contradicting the PR's stated scope boundary and creating a latent correctness risk for other JSONL backends. The artifact management in execute.ts is clean and well-tested.

src/agents/cli-output.ts — the new fallback block needs a providerId === "codex-cli" guard

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/cli-output.ts
Line: 486-493

Comment:
**New fallback text extraction applies to all JSONL backends, not just `codex-cli`**

The PR description explicitly states "other CLI backends still use their existing stdout/json/jsonl parsing paths," but this new fallback block runs for every provider whose output mode is `jsonl`. Any JSONL-configured backend that emits records with top-level `result`, `response`, `content`, or `message` fields for non-final-text purposes (e.g. structured diagnostics, tool results, operational metadata) will have those values incorrectly appended to the reply text.

`parseClaudeCliJsonlResult` provides an early return for Claude CLI's `{ type: "result" }` records, so the most common existing backend is safe. But this is fragile going forward — a future JSONL backend that emits `{ type: "tool-result", result: "..." }` or `{ type: "status", message: "Session started" }` would have those strings silently folded into the final reply.

Guard the new block with the `providerId` that is already in scope:

```suggestion
      if (providerId === "codex-cli") {
        const messageText =
          collectCliText(parsed.message) ||
          collectCliText(parsed.content) ||
          collectCliText(parsed.result) ||
          collectCliText(parsed.response);
        if (messageText.trim()) {
          texts.push(messageText.trim());
        }
      }
```

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

---

This is a comment left during a code review.
Path: src/agents/cli-runner/execute.ts
Line: 272-279

Comment:
**`--output-last-message` path is not masked in verbose log output**

`buildCliLogArgs` masks known sensitive args (`systemPromptArg`, `sessionArg`, `modelArg`, `imageArg`) but has no handler for `--output-last-message`. The temp file path will appear in verbose CLI arg logs (`cli argv: codex --output-last-message /tmp/openclaw-codex-last-message-xxx/run-xxx.txt ...`). The path itself is not sensitive, but it exposes the temp dir structure and naming convention. Adding a masking case (or at least truncating the path) would be consistent with the existing pattern for other injected paths.

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

Reviews (1): Last reviewed commit: "feat(codex-cli): prefer output-last-mess..." | Re-trigger Greptile

Comment thread src/agents/cli-output.ts
Comment on lines +486 to 493
const messageText =
collectCliText(parsed.message) ||
collectCliText(parsed.content) ||
collectCliText(parsed.result) ||
collectCliText(parsed.response);
if (messageText.trim()) {
texts.push(messageText.trim());
}

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.

P1 New fallback text extraction applies to all JSONL backends, not just codex-cli

The PR description explicitly states "other CLI backends still use their existing stdout/json/jsonl parsing paths," but this new fallback block runs for every provider whose output mode is jsonl. Any JSONL-configured backend that emits records with top-level result, response, content, or message fields for non-final-text purposes (e.g. structured diagnostics, tool results, operational metadata) will have those values incorrectly appended to the reply text.

parseClaudeCliJsonlResult provides an early return for Claude CLI's { type: "result" } records, so the most common existing backend is safe. But this is fragile going forward — a future JSONL backend that emits { type: "tool-result", result: "..." } or { type: "status", message: "Session started" } would have those strings silently folded into the final reply.

Guard the new block with the providerId that is already in scope:

Suggested change
const messageText =
collectCliText(parsed.message) ||
collectCliText(parsed.content) ||
collectCliText(parsed.result) ||
collectCliText(parsed.response);
if (messageText.trim()) {
texts.push(messageText.trim());
}
if (providerId === "codex-cli") {
const messageText =
collectCliText(parsed.message) ||
collectCliText(parsed.content) ||
collectCliText(parsed.result) ||
collectCliText(parsed.response);
if (messageText.trim()) {
texts.push(messageText.trim());
}
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/cli-output.ts
Line: 486-493

Comment:
**New fallback text extraction applies to all JSONL backends, not just `codex-cli`**

The PR description explicitly states "other CLI backends still use their existing stdout/json/jsonl parsing paths," but this new fallback block runs for every provider whose output mode is `jsonl`. Any JSONL-configured backend that emits records with top-level `result`, `response`, `content`, or `message` fields for non-final-text purposes (e.g. structured diagnostics, tool results, operational metadata) will have those values incorrectly appended to the reply text.

`parseClaudeCliJsonlResult` provides an early return for Claude CLI's `{ type: "result" }` records, so the most common existing backend is safe. But this is fragile going forward — a future JSONL backend that emits `{ type: "tool-result", result: "..." }` or `{ type: "status", message: "Session started" }` would have those strings silently folded into the final reply.

Guard the new block with the `providerId` that is already in scope:

```suggestion
      if (providerId === "codex-cli") {
        const messageText =
          collectCliText(parsed.message) ||
          collectCliText(parsed.content) ||
          collectCliText(parsed.result) ||
          collectCliText(parsed.response);
        if (messageText.trim()) {
          texts.push(messageText.trim());
        }
      }
```

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

Comment on lines +272 to +279
const codexLastMessageArtifact = isCodexCliBackend(context)
? await prepareCodexLastMessageArtifact({
runId: params.runId,
})
: undefined;
if (codexLastMessageArtifact) {
args.push("--output-last-message", codexLastMessageArtifact.filePath);
}

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 --output-last-message path is not masked in verbose log output

buildCliLogArgs masks known sensitive args (systemPromptArg, sessionArg, modelArg, imageArg) but has no handler for --output-last-message. The temp file path will appear in verbose CLI arg logs (cli argv: codex --output-last-message /tmp/openclaw-codex-last-message-xxx/run-xxx.txt ...). The path itself is not sensitive, but it exposes the temp dir structure and naming convention. Adding a masking case (or at least truncating the path) would be consistent with the existing pattern for other injected paths.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/cli-runner/execute.ts
Line: 272-279

Comment:
**`--output-last-message` path is not masked in verbose log output**

`buildCliLogArgs` masks known sensitive args (`systemPromptArg`, `sessionArg`, `modelArg`, `imageArg`) but has no handler for `--output-last-message`. The temp file path will appear in verbose CLI arg logs (`cli argv: codex --output-last-message /tmp/openclaw-codex-last-message-xxx/run-xxx.txt ...`). The path itself is not sensitive, but it exposes the temp dir structure and naming convention. Adding a masking case (or at least truncating the path) would be consistent with the existing pattern for other injected paths.

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: 9aea402bc3

ℹ️ 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 on lines +272 to +275
const codexLastMessageArtifact = isCodexCliBackend(context)
? await prepareCodexLastMessageArtifact({
runId: params.runId,
})

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 Create Codex artifact inside the guarded cleanup block

In executePreparedCliRun, prepareCodexLastMessageArtifact is awaited before the outer try/finally begins, so an fs.mkdtemp failure (for example ENOSPC or temp-dir permission issues) aborts the function before cleanup runs for already-created resources like systemPromptFile, prompt images, and the Claude skills plugin handle. This is a regression from the previous flow because it introduces a new pre-try I/O failure point that can leave temp files behind (including system-prompt artifacts) on error paths.

Useful? React with 👍 / 👎.

@clawsweeper

clawsweeper Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I did a careful shell check against current main, and the useful part of this older PR is already implemented there.

This stale PR should close because current main and the latest release moved the supported Codex path away from the bundled direct codex-cli backend, and the remaining local Codex CLI resume path already uses the Codex final-message artifact in the Codex plugin. The branch’s leftover core special-casing is now obsolete and merge-risky rather than a useful landing path.

So I’m closing this older PR as already covered on main rather than keeping a mostly-duplicated branch open.

Review details

Best possible solution:

Keep the shipped Codex app-server/plugin-owned implementation and close this stale core special-case branch; handle any remaining explicit custom CLI backend need as a new plugin-owned proposal with current-main config proof.

Do we have a high-confidence way to reproduce the issue?

Not applicable as a feature PR. Current-main and release source inspection is enough to verify the supported Codex path no longer uses a bundled direct codex-cli backend, and the remaining Codex CLI resume helper already reads the last-message artifact.

Is this the best way to solve the issue?

No. The PR was a plausible fix for the old direct codex-cli runner, but current main’s Codex app-server/plugin-owned route is the better owner boundary; any custom backend artifact mode should be proposed against that current design.

Security review:

Security review cleared: The diff adds temp-file handling and command arguments but no new dependency, workflow, permission, secret, network, or package-publishing surface; the remaining concern is compatibility, not a concrete security defect.

AGENTS.md: found and applied where relevant.

What I checked:

  • Root policy read: Read the full root AGENTS.md and scoped src/agents/AGENTS.md; the review applied the Codex-source inspection gate and plugin/core ownership rules. (AGENTS.md:1, c78f9376d929)
  • Current main removes bundled direct Codex CLI backend: Current docs say OpenAI Codex agent runs use the Codex app-server harness through openai/* and OpenClaw no longer registers a bundled codex-cli backend. Public docs: docs/gateway/cli-backends.md. (docs/gateway/cli-backends.md:303, c78f9376d929)
  • Core has no built-in CLI backend fallback policy: The current CLI backend resolver has an empty FALLBACK_CLI_BACKEND_POLICIES map, so codex-cli is not a core-owned built-in backend without plugin or explicit user config. (src/agents/cli-backends.ts:97, c78f9376d929)
  • Codex plugin owns the remaining local Codex CLI artifact path: The current Codex plugin's node-backed resume helper invokes codex exec resume with --output-last-message and reads the resulting last-message file, covering the useful artifact contract in the owner plugin boundary. (extensions/codex/src/node-cli-sessions.ts:266, c78f9376d929)
  • Release contains the implemented behavior: The latest release tag v2026.6.6 contains the no-bundled-codex-cli docs, empty core fallback policy, and Codex plugin output-last-message resume path. Public docs: docs/gateway/cli-backends.md. (docs/gateway/cli-backends.md:303, 8c802aa68351)
  • Fix provenance for supported Codex route migration: GitHub commit history identifies a0f3557 as removing the bundled codex-cli backend and migrating legacy codex-cli refs/runtime pins to the Codex app-server runtime; GitHub compare shows v2026.6.6 is ahead of that commit with it as merge base. (a0f35574d047)

Likely related people:

  • steipete: Authored the current-main commit that removed the bundled codex-cli backend and migrated legacy codex-cli refs to the Codex app-server runtime, which supersedes this branch’s core direct-runner target. (role: feature owner and migration author; confidence: high; commits: a0f35574d047, 34f7d78449da, 28eb4cfa12e5; files: src/agents/cli-backends.ts, docs/gateway/cli-backends.md, extensions/codex/src/node-cli-sessions.ts)
  • mbelinky: Authored the node-backed Codex CLI session binding commit that uses --output-last-message in the Codex plugin path now shipped on main. (role: recent Codex plugin contributor; confidence: high; commits: a5c1956ca17a; files: extensions/codex/src/node-cli-sessions.ts, extensions/codex/src/conversation-binding.ts, extensions/codex/src/command-handlers.ts)
  • obviyus: Recent commits touched the CLI runner/parser behavior around commentary classification and output handling, which is adjacent to the JSONL fallback risk in this PR. (role: recent CLI parser and runner contributor; confidence: medium; commits: 0c4fc0a2e3b3, 817a0910f35e, db576c4a2d2e; files: src/agents/cli-output.ts, src/agents/cli-runner/execute.ts, docs/gateway/cli-backends.md)

Codex review notes: model internal, reasoning high; reviewed against c78f9376d929; fix evidence: release v2026.6.6, commit a0f35574d047.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels May 20, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 20, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jun 6, 2026
@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 6, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jun 7, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. labels Jun 14, 2026
@clawsweeper

clawsweeper Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

@clawsweeper clawsweeper Bot closed this Jun 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Enhancement: finalize codex-cli replies from --output-last-message artifact instead of relying on stdout

3 participants