Repository navigation
Tools: per-result output truncation cache + TUI /stats overlay - #176
Conversation
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.
There was a problem hiding this comment.
💡 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; |
There was a problem hiding this comment.
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.
Summary
Borrows two patterns from mksglu/context-mode and wires them onto the existing PasClaw plumbing:
RunToolLoopdiverts 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./statsoverlay — 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
PasClaw.Tools.OutputCacheunit owns the lock-protected store + truncation logic + thetool_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.TToolLoopConfig.ToolOutputCap(default 0 = off). When > 0, the tool-result append site inRunToolLooprunsDispatches[j].ResultTextthroughStashAndMaybeTruncatebeforeMakeToolResult. Errors stay verbatim — they're already short and the head/tail split would just obscure what went wrong.TToolLoopResult.Truncations+TruncatedBytesSavedso callers (TUI/stats, gateway response metrics) can show what was saved.TConfig.ToolOutputCapJSON option ("tool_output_cap": 8192), wired throughCmd.Agent.MakeLoopCfg+Cmd.TUI.StartTurn+ bothTToolLoopConfigsites inPasClaw.Gateway.Server.tool_output_getregisters conditionally onCfg.ToolOutputCap > 0— no point advertising a tool that would only ever return "no handle".NewBuiltinRegistrygained anEnableOutputCache: Booleanparameter (default False) for the same gating;Cmd.TUI/Cmd.Gateway/Cmd.Serveuse the inlineif Cfg.ToolOutputCap > 0 then RegisterOutputCacheTool(Reg)form.#2 —
/statsoverlayTTUI.FStats*accumulators (turn count,TUsageInfo, truncations, bytes saved, parallelname[]/count[]arrays for per-tool tallies) rolled up inPollLoopWorkerright afterApplyLoopResultTo.DrawStatsOverlaymodal — centred box modeled onDrawThemeMenu, shows session/tokens/truncated/cache/tool-calls rows. Top 8 tools rendered with a "... N more" footer for the tail.OpenStatsOverlayand aHandleKeyintercept that dismisses on any key — read-only, no Up/Dn / Enter / Esc selection semantics.Loop.FinalMessages[i].ToolCalls[k].Func.Nameso 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.pascovers:FetchStashedOutput(bytes-for-bytes match)len = -1= "to end", past-end empty without error,len > remainingclamps)make testruns the new suite alongside the existing 10; all green.Test plan
makebuilds cleanly (FPC, mode delphi)make test— all 11 suites green"tool_output_cap": 4096in~/.pasclaw/config.json, runpasclaw tui, ask the model to recursively grep something noisy. Confirm: tool result message shows truncation notice; model can calltool_output_getto read more;/statsshowstruncated N output(s), saved K bytes.truncated none (set tool_output_cap to enable)in/stats)./statswhile a turn is in flight — confirm it draws on top of the chat pane without breaking the spinner.Generated by Claude Code