Repository navigation
hooks: fix PR #113 review — preserve history mrSystem + catch provider exceptions - #114
Conversation
…ions Two Codex P2 findings on PR #113, both legitimate. P2 #1 — In-history system messages silently disappear when steering first folds into LiveOptions.SystemPrompt. A direct RunToolLoop embedder (not via TPasClawAgent) who puts policy as mrSystem in Hist with Cfg.Options.SystemPrompt = '' would see their policy vanish the moment an AfterToolResult hook returned a non-empty SteeringMessage. PR #113 set LiveOptions.SystemPrompt to the steering text alone; the next Provider.Chat then dropped every in-history mrSystem (both OpenAI and Anthropic builders do this whenever the option slot is populated). Net: the embedder's policy was gone, replaced by just the steering note. Fix: new DrainHistorySystem helper. On every steering fold, extract all mrSystem entries from Hist (in order), concatenate their content with blank-line separators, and prepend that to whatever's about to land in LiveOptions.SystemPrompt. Hist is rewritten in place to skip the drained entries so they don't get re-folded on subsequent passes (idempotent). The next round ships: SystemPrompt = (existing prompt) + (history mrSystem content) + (accumulated steering) and Hist no longer carries any mrSystem the builder would drop. P2 #2 — Provider Chat exceptions bypass HooksOnError. When Cfg.Provider.Chat or a fallback's Chat raises (Indy EIdSocketError on a wedged TLS handshake, builder parse error, OOM in CollapseSSE), execution leaves RunToolLoop before reaching the post-walk HooksOnError check. Audit hooks never get notified. Fix: wrap both the primary Chat call and each fallback Chat call in try/except. On exception: log, build a synthetic Resp with StatusCode := -1 and Content := "EClass: message", continue to the next provider attempt. The existing post-walk HooksOnError (now widened in PR #112 to fire on status <= 0) sees -1 and fires; the hook gets the exception text in the message because the post-walk Format now includes Resp.Content when populated: before: 'provider returned status=-1' after : 'provider returned status=-1: Exception: TLS handshake refused' No exception propagates out of RunToolLoop — embedders that prefer hard failures can still wrap their Run call. Verified with a focused two-part test (built + run + removed): === Test 1: in-history mrSystem preserved on steering fold === PASS — policy + steering both in SystemPrompt, no stray mrSystem === Test 2: raised provider exception fires OnError + no propagation === PASS — OnError fired: provider returned status=-1: Exception: simulated provider raise all PR #113 review-fix tests passed. make clean && make smoke 11/11 green. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9b48010e37
ℹ️ 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".
| LogWarn('provider Chat raised: %s: %s', [E.ClassName, E.Message]); | ||
| Resp := Default(TLLMResponse); | ||
| Resp.StatusCode := -1; | ||
| Resp.Content := E.ClassName + ': ' + E.Message; |
There was a problem hiding this comment.
Keep provider exception details out of assistant content
When a provider raises after all fallbacks are exhausted, storing EClass: message in Resp.Content makes the exception flow through the normal successful-response path: the empty-tool-call branch returns True, and public consumers expose Loop.Content directly (for example, PasClaw.Gateway.Server.pas:1721-1725 returns an OpenAI-compatible HTTP 200 response and PasClaw.Channels.Discord.pas:242-243 posts it to the channel). This can leak internal parser, socket, or provider details to users while reporting the failed call as a completed assistant turn. Keep the exception text in a separate diagnostic value for HooksOnError, or return an explicit failure after the hook fires; the identical fallback assignment at line 573 needs the same treatment.
Useful? React with 👍 / 👎.
| otherwise see their policy disappear the first time | ||
| steering fires. (Codex P2 on PR #113.) Idempotent — once | ||
| drained, subsequent passes find no mrSystem to fold. } | ||
| HistSystem := DrainHistorySystem(Hist); |
There was a problem hiding this comment.
Preserve drained policies when hooks reset steering
When a direct RunToolLoop embedder uses an in-history mrSystem policy and follows the documented ephemeral-steering behavior at lines 761-762 by resetting SystemPrompt in BeforeTurn, this destructive drain removes the only durable copy of that policy. After the first tool batch contributes steering, the policy is moved out of Hist; on the next turn the reset clears the folded prompt, so the provider receives neither the original policy nor the steering text. Keep the drained policy separate from the mutable steering portion, or restore it when rebuilding SystemPrompt.
Useful? React with 👍 / 👎.
…mrSystem Codex P2 on PR #116: Gemini's BuildRequest concatenated Options.SystemPrompt AND every in-history mrSystem into systemInstruction. PR #114's steering fold copies in-history mrSystem into SystemPrompt non-destructively (so the policy stays recoverable after ephemeral-steering resets), which means both copies reach Gemini and the policy ships twice per request. OpenAI and Anthropic builders already drop in-history mrSystem when SystemPrompt is set, so they're unaffected. Fix: match the OpenAI / Anthropic precedence rule in Gemini's BuildRequest. When Options.SystemPrompt is non-empty, that wins and in-history mrSystem is skipped; when SystemPrompt is empty, in-history mrSystem entries fold into Sys as before (behavior preserved for embedders that route policy purely through Hist). before: Sys := Options.SystemPrompt; for i := 0 to High(Messages) do if (Messages[i].Role = mrSystem) ... then Sys := Sys + sLineBreak + Messages[i].Content; after: Sys := Options.SystemPrompt; if Sys = '' then { only fold mrSystem when SystemPrompt unset } for i := 0 to High(Messages) do if (Messages[i].Role = mrSystem) ... then Sys := Sys + sLineBreak + Messages[i].Content; Tiny side change: exposed BuildRequest in the interface section so a focused unit-level test can verify the dedup without spinning up an HTTPS round-trip. The function was already documented and stable internally; this just makes it reachable to test fixtures. Verified end-to-end with a four-case probe (built + run + removed, not committed) — counts occurrences of a sentinel policy string in the JSON body that BuildRequest emits: A: SystemPrompt+mrSystem same content expected=1 got=1 B: empty SystemPrompt, mrSystem in Hist expected=1 got=1 C: SystemPrompt only, no mrSystem expected=1 got=1 D: SystemPrompt set, different mrSystem skipped expected=1 got=1 Case A is the regression that PR #116's review caught. Case B verifies the pre-existing behavior didn't regress when SystemPrompt is empty. Case D confirms a DIFFERENT in-history mrSystem is correctly suppressed when SystemPrompt is set — matches OpenAI's "already added above" precedence. make clean && make smoke 11/11 green. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
hooks: fix PR #114 review — exception out-of-band + non-destructive policy copy
Summary
Two Codex P2 findings on the merged PR #113, both legitimate.
P2 #1 — In-history
mrSystemmessages silently disappear on first steering foldA direct
RunToolLoopembedder (not viaTPasClawAgent) who puts their policy asmrSysteminHistwithCfg.Options.SystemPrompt = ''saw their policy vanish the moment anAfterToolResulthook returned a non-emptySteeringMessage. PR #113 setLiveOptions.SystemPromptto the steering text alone; the nextProvider.Chatthen dropped every in-historymrSystem(both OpenAI and Anthropic builders do this whenever the option slot is populated). Net: the embedder's policy was gone, replaced by just the steering note.Fix: new
DrainHistorySystem(var Hist): stringhelper. On every steering fold, extract allmrSystementries fromHist(in order), concatenate their content with blank-line separators, and prepend that to whatever's about to land inLiveOptions.SystemPrompt.Histis rewritten in place to skip the drained entries so they don't get re-folded on subsequent passes (idempotent). The next round ships:and
Histno longer carries anymrSystemthe builder would drop.P2 #2 — Provider Chat exceptions bypass HooksOnError
When
Cfg.Provider.Chator a fallback'sChatraises (IndyEIdSocketErroron a wedged TLS handshake, builder parse error, OOM inCollapseSSE), execution leftRunToolLoopbefore reaching the post-walkHooksOnErrorcheck. Audit hooks never got notified.Fix: wrap both the primary Chat call and each fallback Chat call in try/except. On exception: log, build a synthetic
RespwithStatusCode := -1andContent := "EClass: message", continue to the next provider attempt. The existing post-walkHooksOnError(widened in PR #112 to fire on status ≤ 0) sees-1and fires; the hook now gets the exception text in the message because the post-walk Format includesResp.Contentwhen populated:No exception propagates out of
RunToolLoop— embedders that prefer hard failures can still wrap theirRuncall.Verification
Test 1 asserts the in-history policy text appears in
Loop.FinalSystemPrompt, the steering text also appears there, and nomrSystementry leaks intoLoop.FinalMessages(because in-history mrSystem gets dropped by provider builders, that would be a silent regression).Test 2 uses a
TRaiseProviderwhoseChatalways raises. Asserts thatRunToolLoopreturns without propagating the exception and the audit hook recorded the exception text viaHooksOnError.make clean && make smoke11/11 green.https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code