Repository navigation
agent: hooks system + steering (picoclaw + nanobot parity) - #110
Conversation
New PasClaw.Agent.Hooks unit ships TPasClawHook — the typed
callback base class embedders subclass to observe, transform, or
veto agent events. Four virtuals, all no-op by default:
BeforeTurn(var ContinueTurn, var Messages)
Fires once per iteration before the LLM Chat call. Embedder
can mutate Hist in place or set ContinueTurn := False to
abort the loop with whatever content was last accumulated.
BeforeToolCall(call, var Cancel, var SyntheticResult)
Fires before each tool dispatch. Cancel := True skips the
actual handler; SyntheticResult becomes the tool_result the
model sees. Approval-gate pattern — combine with simple name
+ arg substring checks to reject sensitive tools, or with a
UI prompt for human-in-the-loop.
AfterToolResult(call, var ResultText, var ErrMsg, var SteeringMessage)
Fires after each tool dispatch (real or synthetic). ResultText
+ ErrMsg are var-params so a hook can redact / truncate /
convert soft errors. SteeringMessage is picoclaw's steering
pattern — when non-empty, the loop concatenates contributions
from all hooks in the batch and appends one mrSystem note to
history before the next LLM round-trip. Lets the embedder
say "based on the file you just read, also check X" without
restructuring the loop.
OnError(Stage, Msg)
Fires on caught failures. Stage indicates where (hsBeforeTurn,
hsBeforeToolCall, hsDuringToolCall, hsAfterToolResult,
hsProviderCall) so a hook can route to metrics / alerting.
Hooks form an ordered list (registration order). Helpers in the
new unit — HooksBeforeTurn / HooksBeforeToolCall /
HooksAfterToolResult / HooksOnError — encapsulate the combine
semantics: BeforeTurn's ContinueTurn is sticky-false (one veto
ends the chain), BeforeToolCall's Cancel is sticky-true (early
deny wins), AfterToolResult's SteeringMessages concatenate
with sLineBreak + sLineBreak separators, OnError swallows hook
exceptions so a buggy observer can't replace the real error.
PasClaw.Tools.ToolLoop:
+ Cfg.Hooks: TPasClawHookArray field
+ TToolCallDispatch.Cancelled flag, set when a BeforeToolCall
hook veto came in; workers + serial path both skip
DispatchOneToolCall for cancelled slots (synthetic result
already lives in ResultText)
+ BeforeTurn fires inside the iteration before Cfg.Provider.Chat;
returns False = clean exit
+ Phase 1 (pre-dispatch): OnToolCall event + HooksBeforeToolCall
per batch, main thread, array order
+ Phase 2 (dispatch): parallel/serial as before, but
Worker.Execute short-circuits on Cancelled
+ Phase 3 (post-dispatch): HooksAfterToolResult per call,
OnToolResult event, append tool_result. SteeringMessages
collected into BatchSteering.
+ Phase 4 (steering): if BatchSteering <> '' append one
mrSystem message with the concatenated steering text so the
next iteration's LLM call sees it
PasClaw.Agent (TPasClawAgent):
+ FHooks: TObjectList — owns + frees registered hooks
+ RegisterHook(AHook: TPasClawHook) — takes ownership
+ BuildHookArray helper — converts FHooks list into the
Cfg.Hooks array passed to RunToolLoop
+ ChatHistory wires Cfg.Hooks := BuildHookArray on every call
Verified end-to-end with a two-part test (built + run + removed,
not committed):
=== Test 1: veto + steering ===
PASS — vetoed, synthetic landed, steering injected
=== Test 2: BeforeTurn abort ===
PASS — aborted before first LLM call, iterations=1
all hook tests passed.
Test wired: TApprovalHook bans 'boom_tool', emits
"BLOCKED by approval policy"; TSteeringHook contributes
"Steering: after running this tool, also verify X";
TFakeProvider scripts a turn that calls boom_tool. Asserts that
(a) the real boom_tool handler never runs (would write the
sentinel "BOOM_TOOL_HANDLER_RAN" into history), (b) the synthetic
veto result is in tool_result, (c) the steering message lands as
mrSystem after the tool_result. TAbortHook test confirms the
loop returns cleanly after one iteration.
make smoke 11/11 green. README updated with a Hooks + steering
entry.
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: 581b05e790
ℹ️ 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".
| SetLength(Hist, Length(Hist) + 1); | ||
| Hist[High(Hist)] := MakeMessage(mrSystem, BatchSteering); |
There was a problem hiding this comment.
Deliver steering notes through the provider system prompt
When an AfterToolResult hook returns a steering message under the normal component configuration, this appends it as an in-history mrSystem message even though ChatHistory sets a non-empty Cfg.Options.SystemPrompt in PasClaw.Agent.pas:691-692. The OpenAI builder explicitly skips every in-history system message whenever that option is populated (PasClaw.Providers.OpenAI.pas:137-151), and the Anthropic builder always skips in-history system messages after preferring the option (PasClaw.Providers.Anthropic.pas:110-130). As a result, the advertised steering feature is silently invisible to the next model round for the default OpenAI and Anthropic paths. Merge the steering text into the live system prompt or otherwise pass it through a provider-visible channel.
Useful? React with 👍 / 👎.
| procedure HooksOnError(const Hooks: TPasClawHookArray; | ||
| Stage: TPasClawHookStage; | ||
| const Msg: string); |
There was a problem hiding this comment.
Registered hooks can override OnError, but the new dispatcher is never called: a repo-wide search for HooksOnError( finds only this declaration and implementation. Consequently, none of the documented stages (hsBeforeTurn, hsBeforeToolCall, hsDuringToolCall, hsAfterToolResult, or hsProviderCall) can ever reach an embedder's audit or telemetry hook, including worker exceptions caught in TToolCallWorker.Execute. Invoke this helper from the relevant failure paths.
Useful? React with 👍 / 👎.
hooks: fix PR #110 review — steering via SystemPrompt + wire OnError
Summary
New
PasClaw.Agent.Hooksunit shipsTPasClawHook— the typed callback base class embedders subclass to observe, transform, or veto agent events. PlusCfg.Hookswiring inRunToolLoopthat powers picoclaw's steering pattern. ~400 LOC across 5 files.API surface
Four virtuals on
TPasClawHook, all no-op by default — subclass and override only what you need:BeforeTurn(var ContinueTurn, var Messages)ContinueTurn := Falseto abort cleanly.BeforeToolCall(call, var Cancel, var SyntheticResult)Cancel := Trueskips the real handler;SyntheticResultbecomes thetool_result.AfterToolResult(call, var ResultText, var ErrMsg, var SteeringMessage)OnError(Stage, Msg)hsBeforeTurn,hsBeforeToolCall,hsDuringToolCall,hsAfterToolResult,hsProviderCall).Hooks form an ordered list (registration order). Combine semantics:
BeforeTurn:ContinueTurnis sticky-false — one veto ends the chainBeforeToolCall:Cancelis sticky-true — early deny winsAfterToolResult:SteeringMessages from each hook concatenate with double-newline separators into one consolidatedmrSystementryOnError: hook exceptions are swallowed so a buggy observer can't replace the real errorPlumbing
PasClaw.Tools.ToolLoop:Cfg.Hooks: TPasClawHookArray;TToolCallDispatch.Cancelledflag; workers + serial path short-circuit on cancelled slots; BeforeTurn fires inside the iteration beforeProvider.Chat; the batch dispatch loop got phased — Phase 1 firesOnToolCall+HooksBeforeToolCall, Phase 2 dispatches (parallel or serial), Phase 3 firesHooksAfterToolResult+OnToolResult+ appendstool_result, Phase 4 appends one consolidated steeringmrSystementry when any hook contributed.PasClaw.Agent:FHooks: TObjectList(owns + frees),RegisterHook(AHook: TPasClawHook)takes ownership,BuildHookArrayconverts to the arrayCfg.Hooksexpects,ChatHistorywires it on every call.Verification
End-to-end test (built + run + removed, not committed):
Test mechanics:
TBoomToolwrites a sentinelBOOM_TOOL_HANDLER_RANif its handler runs — asserts the veto really blocks dispatchTApprovalHook.BeforeToolCallreturnsCancel := True+SyntheticResult := "BLOCKED by approval policy"forboom_toolTSteeringHook.AfterToolResultinjects"Steering: after running this tool, also verify X"tool_resultAND the steering message lands asmrSystemAND the boom-sentinel never appearsTAbortHook.BeforeTurnsetsContinueTurn := False; test confirms loop exits cleanly after one iterationmake smoke11/11 green. README updated with a hooks + steering entry under Features.https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code