Skip to content

agent: hooks system + steering (picoclaw + nanobot parity) - #110

Merged
FMXExpress merged 1 commit into
mainfrom
claude/hooks-and-steering
Jun 1, 2026
Merged

FMXExpress merged 1 commit into
mainfrom
claude/hooks-and-steering

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

New PasClaw.Agent.Hooks unit ships TPasClawHook — the typed callback base class embedders subclass to observe, transform, or veto agent events. Plus Cfg.Hooks wiring in RunToolLoop that 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:

Virtual Purpose
BeforeTurn(var ContinueTurn, var Messages) Once per iteration before the LLM call. Mutate Hist in place, or set ContinueTurn := False to abort cleanly.
BeforeToolCall(call, var Cancel, var SyntheticResult) Approval gate. Cancel := True skips the real handler; SyntheticResult becomes the tool_result.
AfterToolResult(call, var ResultText, var ErrMsg, var SteeringMessage) Rewrite results inline AND inject a system note before the next LLM round (steering).
OnError(Stage, Msg) Observe failures (hsBeforeTurn, hsBeforeToolCall, hsDuringToolCall, hsAfterToolResult, hsProviderCall).

Hooks form an ordered list (registration order). Combine semantics:

  • BeforeTurn: ContinueTurn is sticky-false — one veto ends the chain
  • BeforeToolCall: Cancel is sticky-true — early deny wins
  • AfterToolResult: SteeringMessages from each hook concatenate with double-newline separators into one consolidated mrSystem entry
  • OnError: hook exceptions are swallowed so a buggy observer can't replace the real error
type
  TApprovalHook = class(TPasClawHook)
    procedure BeforeToolCall(const ToolCall: TToolCall;
                             var Cancel: Boolean;
                             var SyntheticResult: string); override;
  end;

Agent.RegisterHook(TApprovalHook.Create);

Plumbing

  • PasClaw.Tools.ToolLoop: Cfg.Hooks: TPasClawHookArray; TToolCallDispatch.Cancelled flag; workers + serial path short-circuit on cancelled slots; BeforeTurn fires inside the iteration before Provider.Chat; the batch dispatch loop got phased — Phase 1 fires OnToolCall + HooksBeforeToolCall, Phase 2 dispatches (parallel or serial), Phase 3 fires HooksAfterToolResult + OnToolResult + appends tool_result, Phase 4 appends one consolidated steering mrSystem entry when any hook contributed.
  • PasClaw.Agent: FHooks: TObjectList (owns + frees), RegisterHook(AHook: TPasClawHook) takes ownership, BuildHookArray converts to the array Cfg.Hooks expects, ChatHistory wires it on every call.

Verification

End-to-end 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 mechanics:

  • TBoomTool writes a sentinel BOOM_TOOL_HANDLER_RAN if its handler runs — asserts the veto really blocks dispatch
  • TApprovalHook.BeforeToolCall returns Cancel := True + SyntheticResult := "BLOCKED by approval policy" for boom_tool
  • TSteeringHook.AfterToolResult injects "Steering: after running this tool, also verify X"
  • Test asserts the synthetic result is in tool_result AND the steering message lands as mrSystem AND the boom-sentinel never appears
  • TAbortHook.BeforeTurn sets ContinueTurn := False; test confirms loop exits cleanly after one iteration

make smoke 11/11 green. README updated with a hooks + steering entry under Features.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

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

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

Copy link
Copy Markdown

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: 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".

Comment on lines +653 to +654
SetLength(Hist, Length(Hist) + 1);
Hist[High(Hist)] := MakeMessage(mrSystem, BatchSteering);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +251 to +253
procedure HooksOnError(const Hooks: TPasClawHookArray;
Stage: TPasClawHookStage;
const Msg: string);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Invoke registered error hooks

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 👍 / 👎.

@FMXExpress
FMXExpress merged commit 43d36d5 into main Jun 1, 2026
FMXExpress added a commit that referenced this pull request Jun 1, 2026
hooks: fix PR #110 review — steering via SystemPrompt + wire OnError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants