Skip to content

fix(agents): pin the session tool surface across turns - #176167

Merged
obviyus merged 7 commits into
mainfrom
feat/prompt-prefix-pin
Oct 19, 2026
Merged

obviyus merged 7 commits into
mainfrom
feat/prompt-prefix-pin

Conversation

@obviyus

@obviyus obviyus commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: the provider prompt cache misses completely on session-event turns, for example the exec-exit notification after a background exec. On real OpenAI that turn read 0 cached tokens, and the next turn missed part of its prefix again.

The tool block changed on that turn in three ways. Each one alone breaks the cached prefix:

  1. The turn builds fewer tools. It replays the producing turn's allowlist, which leaves out owner-only tools (automations, conversations_*).
  2. The descriptions of exec, process and sessions_send change, because they name sibling tools (applyToolAvailabilityDescriptions) and those siblings are missing.
  3. The provider-hosted web_search drops out of the request. The saved event allowlist holds only function tools, so the hosted tool's runtime gate saw no web_search entry.

Why This Change Was Made

#167698 already pins the system prompt per session in the transcript-backed prompt series. This extends the same owner to the tool block:

  • Pin the tool list. The session pins every tool definition it has sent (prepareSessionToolSurface, session-prompt-state.ts). A turn that builds fewer tools still sends the pinned definitions. A call to a tool this turn did not build is refused through gateAgentToolExecution (fix: prompt cache misses on completion, heartbeat and non-owner turns #175309), so authority is unchanged.
  • Pin descriptions. Within a pin, a tool keeps its pinned description while its parameters match. A new tool or a parameter change extends the pin once.
  • When a new pin starts. On a route or model change, compaction or reset, and when the tool policy config (tools, the agent's tools) changes, so configured removals leave the request. Only a digest of that config is stored.
  • Storage. The pin lives in the existing openclaw.system-prompt checkpoint entry. Routes without in-history prompt updates write a tools-only checkpoint. No schema change.
  • Permission refresh. It rebuilds the pinned surface from the current tool generation, so new executors replace revoked ones.
  • Hosted web_search. The saved session-event allowlist keeps it when the producing turn's full conversation policy allowed it (isConversationToolAllowed: profile, group, sender, sandbox, subagent and runtime caps). An event turn cannot gain web_search that its producer did not have.
  • Compaction. A checkpoint carries the pinned tools only when the pin's route and history match the snapshot, so compaction or a route change retires the pin, and the next attempt pins the current tools.
  • OPENCLAW_PROMPT_CACHE_ASSERT=1. It now also throws on tool-block changes within a session, except a pin change the pin declared, and names the turn (trigger, provenance, reply mode).

User Impact

Background and event turns reuse the cached prefix. No change to which tools a turn may run.

Evidence

Real OpenAI (gpt-6-sol, direct to api.openai.com) through the Gateway and a Telegram mock-user scenario: two user turns, image generation, a subagent spawn, a background exec, a system event and a closing user turn. Cached share of prompt tokens per request, from the Gateway's usage records:

Turn Before After
User turns 94–98% 92–98%
Image completion 98% 99%
Subagent completion 98% 98%
Exec-exit event 0% 95% (94% in a second run)
Turn after the event 85% 86%
Whole session 83.1% 87.5%

The first request of each session and each new subagent is cold (0%) on both sides.

Hosted-search authority at the final provider request (same real-OpenAI setup, request tool lists from OPENCLAW_DEBUG_MODEL_PAYLOAD=tools). The producing turn starts a background exec that sleeps 90 s. While it sleeps, the Gateway config gets tools.deny: ["web_search"] (hot reload):

Request Tools sent Hosted web_search
User turn and exec call, before the deny 52 sent
Exec-exit event, after the deny 39 not sent
Later user turns 53 not sent

A producer that sender policy denies search (tools.toolsBySender: {"*": {deny: ["web_search"]}}) sends 51 tools without hosted web_search on every request. That includes its exec-exit event, which reads 93.5% cached.

The queued event does not keep hosted search after a revocation. The policy change also starts a new pin, which costs one cache miss, as designed. The allowed case is the exec-exit row in the cache table above: 52 tools, web_search sent.

  • Unit tests (session-prompt-state.test.ts and others):

    • A background turn keeps the user turn's definitions and refuses a missing tool.

    • The pin survives a restart, a prompt-series restart during admission and a system-prompt-only checkpoint.

    • A route or policy change starts a new pin.

    • A sibling-only description change keeps the pinned text.

    • A permission refresh uses the new executors.

    • The assert admits one declared pin change.

    • The session-event allowlist keeps hosted web_search.

    • Compaction retires the pin instead of carrying it into the new history.

    • A checkpoint written before this change (no tools key) still restores the system-prompt series, and a new pin starts from it.

    • Hosted search: a producer whose policy denies web_search saves no web_search entry. A saved entry still yields to the current policy when the event turn sends its request (resolveWebSearchToolPolicy with tools.deny).

    Each test for a fix fails without that fix. The pre-change checkpoint test and the two hosted-search policy tests cover behavior that already holds.

  • E2E: compaction hot-reload passes on the final head. On the previous head, background-exec restart, session resume restart, restored-requester settle, heartbeat session routing, subagent current-requester and the SQLite flip proof all pass (14/14). Earlier commits on this branch also passed the compaction hot-reload, image-generation, silent-reply, chat-tools and approval suites. One test expectation changed (gateway-session-resume-restart): a stale exec call after recovery restricted the session is still refused and its effect still never happens. The refusal now comes from the pinned gate, so the wording differs.

  • Upgrade: pnpm test:docker:published-upgrade-survivor from the current latest ([email protected]) passes on this head (881 s, no failures). An earlier run from [email protected] passed as well (915 s). The lane installs the published release with seeded config, sessions and transcripts, then updates in place to this branch. The Gateway, config and stored state survive.

  • Harness fix: the SQLite flip-proof helper now skips compressed (event_zstd) transcript rows, which the larger checkpoint entry produces.

Merge danger

Two-way door for behavior: a revert stops pinning, and older code ignores the tools field in checkpoint entries. Blast radius: the tool block of every embedded-runner request, and the allowlist stored with background exec and session events.

@clawsweeper

clawsweeper Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Oct 18, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 18, 2026
@clawsweeper

clawsweeper Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR persists session tool definitions across turns while preserving current execution restrictions and hosted-search policy.

Example: A background exec finishes and triggers another turn in the same session.

  • Before: The exec-exit request changes its tool block and reads 0% cached prompt tokens in the supplied live run.
  • After: The request retains the pinned definitions and reads 95% cached prompt tokens; unavailable tools still refuse execution.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused repair with shipped-entry-point evidence, latest-stable upgrade coverage, and no open correctness finding; inherited CI failures have an explicit maintainer override.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied real-OpenAI Gateway scenario exercises background exec completion and records cache recovery; final provider tool lists demonstrate allowed hosted search, denied producers, and removal after policy revocation while the command is pending.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Automatic background-command continuations discard reusable prompt prefixes and increase provider token processing.
Reason: The maintainer-authored direction extends an established cache contract, and the supplied real-provider measurements show improvement on the affected turn.

Merge readiness

✅ Ready for maintainer review

This PR fixes the remaining session-event tool-prefix churn without restoring revoked executors. No actionable patch defect remains, and the maintainer’s documented inherited-CI override resolves the previous review’s outstanding request.

Priority: P2
Reviewed head: 378141de142f0bab95b343c8323095c83459acdf

Before merge

None.

Findings

None.

Agent review details

How this fits together

The embedded runner combines current tool executors with transcript-backed session definitions, then passes the resulting surface through tool adapters to provider requests.

flowchart TD
  A[Current conversation policy] --> B[Current tool assembly]
  B --> C[Session tool pin]
  D[Transcript checkpoint] --> C
  C --> D
  C --> E[Provider request]
  E --> F[Current executor or refusal]
Loading

Technical review

Best possible solution:

Keep the tool pin in the existing transcript-backed prompt owner, with current executors, explicit refusals, and policy-driven invalidation.

Do we have a high-confidence way to reproduce the issue?

Current main rebuilds the event tool surface from a narrower allowlist, and the supplied real-provider before/after results demonstrate the resulting cache miss; this review executed no target code.

Is this the best way to solve the issue?

The change follows the established stable-prefix contract and reuses both the prompt checkpoint owner and execution gate, with no unnecessary parallel policy owner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 9463f49a6d24.

Provenance checked

  • Transcript-backed prompt checkpoint and lifecycle keeps the original intent (46ab36a: Preserve prompt prefixes across refreshes and matching restarts while retiring them at route and compaction boundaries; subsequent prompt-cache work broadened this contract.)
  • Session-event allowlist and execution gating keeps the original intent (b326dc0: Keep definitions stable without exporting authority a turn cannot exercise; session-event cache misses were explicitly deferred.)
  • Permission refresh keeps the original intent (67433ff: Replace permission-bound tools during active runs and revoke old-generation executors before using refreshed capabilities.)
  • Prompt-cache assertion keeps the original intent (cee0906: Detect undeclared request-history changes while permitting changes declared by their lifecycle owners.)
  • SQLite recovery proof keeps the original intent (edde2c2: Verify committed conversation recovery after abrupt termination; handling compressed checkpoint rows preserves that proof.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 46ab36a adds src/agents/embedded-agent-runner/session-prompt-state.ts:234 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 46ab36a493ac; files: src/agents/embedded-agent-runner/session-prompt-state.ts)
  • Ayaan Zaidi: Raw commit b326dc0 adds src/agents/agent-tools.ts:579 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b326dc020122; files: src/agents/agent-tools.ts)
  • Vincent Koc: Raw commit c76646a adds src/agents/pi-embedded-runner/prompt-cache-observability.ts:45 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c76646adb135; files: src/agents/pi-embedded-runner/prompt-cache-observability.ts)

PR surface

Source +209, Tests +318, Other -1. Total +526 across 16 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 227 18 +209
Tests 8 332 14 +318
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 16 559 33 +526

Review metrics

Metric Value Why it matters
Production versus test growth Production +209 net LOC; tests and support +318 net LOC Growth implements pin persistence and invalidation within the existing owner, with distinct restart, compaction, refresh, policy, and rejection coverage.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Session-event cache misses increase provider work and cost without preventing the core conversation workflow.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (9 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-18T21:55:14.386Z sha 16d6a3f :: needs real behavior proof before merge. :: [P2] Rebuild the tool pin when compaction starts a new prompt series
  • reviewed 2026-10-18T22:46:27.590Z sha 619fb7f :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-18T23:14:07.384Z sha 619fb7f :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-18T23:26:25.755Z sha 619fb7f :: blocked before merge. :: none
  • reviewed 2026-10-18T23:33:52.796Z sha 619fb7f :: blocked before merge. :: none
  • reviewed 2026-10-19T01:45:06.774Z sha 619fb7f :: blocked before merge. :: none
  • reviewed 2026-10-19T03:51:46.838Z sha 378141d :: blocked before merge. :: none
  • reviewed 2026-10-19T04:56:45.600Z sha 378141d :: needs changes before merge. :: none

Reviewed October 19, 2026, 1:05 AM ET / 05:05 UTC (Revision 10).

@obviyus

obviyus commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 18, 2026
@obviyus

obviyus commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Oct 18, 2026
@clawsweeper clawsweeper Bot added the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Oct 19, 2026
@obviyus

obviyus commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: the red checks on this head come from main, not from this PR.

  • check-test-types: extensions/codex/src/app-server/native-subagent-monitor.parent-retention.test.ts(37,5): error TS2353 ... 'completionDeliveryRetryDelaysMs' does not exist in type 'MonitorOptions'. This PR does not touch that file. The same error reproduces on plain main at 35aa52a (this PR's base) with node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.extensions.test.json.
  • checks-node-changed: only test/gateway-session-resume-restart.e2e.test.ts fails, in its three "resumes a tombstoned delegated task in place" cases (restartRecoveryStatus: "tombstoned" missing). The file runs here because this PR edits one expectation in it. The same three cases fail the same way on plain main at 35aa52a, without this PR.
  • openclaw/ci-gate only aggregates the two jobs above.

CI run: https://github.com/openclaw/openclaw/actions/runs/39192319951. Every other required check passes.

@obviyus

obviyus commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 19, 2026
@obviyus
obviyus merged commit 1f7b2f1 into main Oct 19, 2026
156 of 160 checks passed
@obviyus

obviyus commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 1f7b2f1.

  • Bug: the exec-exit notification turn changed the tool block in three ways: missing owner-only tools, sibling-dependent descriptions, and a dropped hosted web_search. So it read 0 cached tokens on real OpenAI.
  • Fix: the session pins the tool definitions it has sent. Missing tools are refused at call time, pinned descriptions hold while parameters match, and the event allowlist keeps the producer's hosted-search decision.
  • Proof: the exec-exit turn went from 0% to 95% cached, and the whole session from 83.1% to 87.5%. Hosted search was proven at the final request for allowed, sender-denied and revoked. The upgrade from 2026.10.5 and 2026.10.3 passed. The red checks are inherited from main (see the override comment above).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant