Skip to content

Tools: per-result output truncation cache + TUI /stats overlay - #176

Merged
FMXExpress merged 2 commits into
mainfrom
claude/tool-output-cache
Jun 8, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/tool-output-cache

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Borrows two patterns from mksglu/context-mode and wires them onto the existing PasClaw plumbing:

  1. Per-result tool output truncation — RunToolLoop diverts oversize tool outputs into a process-lifetime cache and replaces the in-context body with a head/tail snippet plus a handle the model can dereference. context-mode's "56 KB Playwright snapshot → 299 B" pattern, in a 250-LOC shape that fits the existing tool registry.
  2. TUI /stats overlay — read-only modal that shows where the session's context budget is going (tokens, turns, truncations, bytes saved, per-tool call counts). Pairs with Port PicoClaw to Delphi Object Pascal (Phase 1) #1 so operators can see the savings.

#1 — Tool output truncation

  • New PasClaw.Tools.OutputCache unit owns the lock-protected store + truncation logic + the tool_output_get(handle, offset, len) tool handler. Process-lifetime in-memory (no SQLite); handles are valid until pasclaw exits, which is the window the agent loop actually needs.
  • New TToolLoopConfig.ToolOutputCap (default 0 = off). When > 0, the tool-result append site in RunToolLoop runs Dispatches[j].ResultText through StashAndMaybeTruncate before MakeToolResult. Errors stay verbatim — they're already short and the head/tail split would just obscure what went wrong.
  • New TToolLoopResult.Truncations + TruncatedBytesSaved so callers (TUI /stats, gateway response metrics) can show what was saved.
  • New TConfig.ToolOutputCap JSON option ("tool_output_cap": 8192), wired through Cmd.Agent.MakeLoopCfg + Cmd.TUI.StartTurn + both TToolLoopConfig sites in PasClaw.Gateway.Server.
  • tool_output_get registers conditionally on Cfg.ToolOutputCap > 0 — no point advertising a tool that would only ever return "no handle".
  • NewBuiltinRegistry gained an EnableOutputCache: Boolean parameter (default False) for the same gating; Cmd.TUI / Cmd.Gateway / Cmd.Serve use the inline if Cfg.ToolOutputCap > 0 then RegisterOutputCacheTool(Reg) form.

#2 — /stats overlay

  • New TTUI.FStats* accumulators (turn count, TUsageInfo, truncations, bytes saved, parallel name[]/count[] arrays for per-tool tallies) rolled up in PollLoopWorker right after ApplyLoopResultTo.
  • New DrawStatsOverlay modal — centred box modeled on DrawThemeMenu, shows session/tokens/truncated/cache/tool-calls rows. Top 8 tools rendered with a "... N more" footer for the tail.
  • New OpenStatsOverlay and a HandleKey intercept that dismisses on any key — read-only, no Up/Dn / Enter / Esc selection semantics.
  • Mutual exclusion with the existing theme + model overlays: opening one closes the others.
  • Tool-call names walked off Loop.FinalMessages[i].ToolCalls[k].Func.Name so we catch every call across iterations, not just the last assistant response's. Runs on the main thread (no need for the OnToolCall callback + cross-thread sync the worker would have needed).

Tests

src/tests/output_cache_tests.pas covers:

  • pass-through under cap (no handle stashed, identical bytes)
  • pass-through when cap = 0 (legacy verbatim behavior, regardless of size)
  • truncation notice shape (handle/elided/head/tail, replacement smaller than original)
  • full round-trip via FetchStashedOutput (bytes-for-bytes match)
  • slice fetch math (offset clamping ≥ 0, len = -1 = "to end", past-end empty without error, len > remaining clamps)
  • unknown / empty handle errors (caller sees the reason)
  • multi-entry cache stats accumulation

make test runs the new suite alongside the existing 10; all green.

Test plan

  • make builds cleanly (FPC, mode delphi)
  • make test — all 11 suites green
  • Manual: set "tool_output_cap": 4096 in ~/.pasclaw/config.json, run pasclaw tui, ask the model to recursively grep something noisy. Confirm: tool result message shows truncation notice; model can call tool_output_get to read more; /stats shows truncated N output(s), saved K bytes.
  • Manual: same with cap absent / 0 — confirm legacy verbatim output (no notice, no handle, truncated none (set tool_output_cap to enable) in /stats).
  • Manual: open /stats while a turn is in flight — confirm it draws on top of the chat pane without breaking the spinner.

Generated by Claude Code

Borrows two patterns from mksglu/context-mode and wires them onto
the existing PasClaw plumbing.

Tool output truncation. New PasClaw.Tools.OutputCache holds full
tool outputs in a process-lifetime, lock-protected store keyed by
short handle. When Cfg.ToolOutputCap > 0 and a successful tool
result exceeds the cap, RunToolLoop replaces the in-context body
with `[tool output truncated: N bytes, handle=...]` plus a head
and tail snippet — the model dereferences via the auto-registered
`tool_output_get(handle, offset, len)` tool when it needs the
rest. Errors stay verbatim regardless of cap (they're short and
the head/tail split would just obscure the failure). 0 = off
(legacy verbatim) so the default config keeps current behavior;
operators opt in via "tool_output_cap" in config.json. Wired
through Cmd.Agent / Cmd.TUI / Cmd.Gateway / Cmd.Serve plus
Gateway.Server's two TToolLoopConfig sites. Stats land on
TToolLoopResult.Truncations + TruncatedBytesSaved for the TUI
to surface.

/stats overlay. New TUI slash command opens a read-only modal
showing: per-session token totals (in/out, plus cache r/w when
non-zero), turn count + wall-clock elapsed, truncation count +
bytes saved, OutputCache handles held + bytes, and per-tool
call counts (top 8 rendered, "... N more" footer for the tail).
Accumulators sit on TTUI as plain fields, rolled up in
PollLoopWorker right after ApplyLoopResultTo. Mutual exclusion
with the theme/model overlays: opening /stats closes them and
vice versa. Any key dismisses.

Tests. output_cache_tests covers: pass-through under cap, off
when cap=0, truncation notice shape (handle/elided/head/tail),
slice fetch math (offset clamping, len-1, past-end empty),
unknown/empty handle errors, multi-entry stats accumulation.

@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: f572071526

ℹ️ 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".

LoopCfg.OnToolResult := nil;
LoopCfg.CompactEnabled := True;
LoopCfg.CompactOpts := DefaultCompactOptions;
LoopCfg.ToolOutputCap := FCfg.ToolOutputCap;

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 Register the cache tool before enabling truncation

In component-server usage (TPasClawServer), the gateway registry is built in src/pkg/agent/PasClaw.Agent.pas without registering tool_output_get, while this line still enables truncation from FCfg.ToolOutputCap. With tool_output_cap > 0, an oversized tool result is replaced with a handle, but the provider tool list has no dereference tool, so the model cannot fetch the elided bytes. The CLI gateway/serve paths register RegisterOutputCacheTool, but the component gateway path does not, so either register it there too or avoid setting the cap unless the registry contains the tool.

Useful? React with 👍 / 👎.

TPasClawAgent.EnsureRegistry and TPasClawServer.PrepareServer build
the registry in PasClaw.Agent.pas without registering
tool_output_get, but Gateway.Server still forwards
FCfg.ToolOutputCap into LoopCfg. With the cap on via this path,
truncated tool results carry a handle the model has no way to
dereference -- the tool list is missing the lookup.

Same fix shape as the four CLI paths in PR #176: register
RegisterOutputCacheTool conditionally on FConfig.ToolOutputCap > 0
so the gate and the registration stay paired.
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