Skip to content

feat(plugins): let plugins gate the final model provider request - #193550

Merged
VACInc merged 18 commits into
openclaw:mainfrom
VACInc:feat/before-model-request
Nov 18, 2026
Merged

VACInc merged 18 commits into
openclaw:mainfrom
VACInc:feat/before-model-request

Conversation

@VACInc

@VACInc VACInc commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Summary

High Level TLDR

Plugins can add context and gate a run before the prompt is built, but nothing lets a plugin see or change the exact request body that is about to go to the model provider. This adds before_model_request, an awaited, fail-closed policy hook on the embedded runner's provider transport. A handler gets the final provider payload plus a detached copy of the model-facing history (with host sender metadata) and can return a replacement payload, for example with untrusted text withheld or quarantined, or with credentials (API keys, tokens, passwords, private keys) that leaked into tool output or context redacted before they leave the Gateway. If a handler throws or times out, the request is not sent.

CLI runtimes too. CLI-backed runtimes such as claude-cli own their provider requests, so the hook now also runs where OpenClaw hands text to the CLI: once per CLI turn dispatch and once per input steered into a live CLI turn. There the event has runtime: "cli" and payload: { prompt, prependContext?, appendContext? }, and messages ends with the current user row including its input provenance. Before this, a subagent completion from an untrusted agent reached a CLI-backed agent as the prompt itself and no plugin could screen or withhold it.

Compaction too. Compaction resends older history to a model, so a value a plugin redacted on a turn could still leave in a compaction summary request. Embedded compaction requests (the summary call and server-side compaction) now pass the same gate, marked requestKind: "compaction" (turns are "turn"). The hook still only changes the outgoing request, never stored history; the docs now say so and point redaction of stored content at tool_result_persist / before_message_write.

Side questions too. A /btw side question and a plugin session fork (api.runtime.subagent.forkSession) resend the conversation to the model, but they built their own provider request without the gate, so a plugin that redacts or blocks content could be bypassed by asking a side question. Since main started letting forks replay the parent's saved request, a fork resent the parent's history exactly as it was before the gate. Every side-question request (embedded lightweight path, embedded fork, and CLI side questions) now passes the same gate, marked requestKind: "side_question", and a handler that throws fails the side question. A fork still replays the parent's saved request first and then gates its own request once, so a handler that rewrites the same input the same way sends the parent's exact cached prefix.

The hook is opt-in: it is off by default for every plugin, bundled ones included, and only runs after the operator sets plugins.entries.<id>.hooks.allowModelRequest: true. Without that, the registration is ignored and the Gateway logs one startup warning naming the key to flip.

What Problem This Solves

A prompt-injection scanner or data-loss policy plugin cannot enforce anything on the bytes that actually reach the model. before_prompt_build and before_agent_run run before provider onPayload transforms, tool-loop follow-up calls, and transport retries, and llm_input is observe-only. Content added after those hooks (tool results in later loop iterations, provider/config payload rewrites) never passes through a policy gate.

User Impact

Plugin authors can register api.on("before_model_request", handler) to inspect, rewrite, or withhold the final embedded provider request, once the operator opts that plugin in with plugins.entries.<id>.hooks.allowModelRequest: true. Nothing changes for installs with no handler registered: the transformer returns the payload as-is without copying messages or awaiting anything.

Why This Change Was Made

  • Owner: wrapStreamFnWithProviderPromptState already owns the post-onPayload request body (it hashes it for context-retry admission). The gate runs there, right after provider onPayload transforms. For transports that use host request encoding, it runs at encode time instead, including encode-only retries. The replacement is what gets hashed, recorded, encoded, and sent, so retry admission and the wire bytes agree.
  • Hook runner: registered as a modifying hook. Handlers run in priority order and each sees the previous replacement. Added to the runner's fail-closed policy set (like before_agent_run / before_channel_ingress) with a 10 s default timeout. An aborted turn rechecks its signal after the hook, so it cannot send late.
  • Tool surface, model, and Access program are fixed: a replacement may rewrite content but not tools, tool_choice, toolConfig, functions, function_call, model, or access_programs (top level or under config). These fields are snapshotted in their JSON wire form before any handler runs and compared against the effective payload on every return path, so an in-place edit to event.payload (including one followed by returning nothing) fails the request just like a changed replacement. Tool, provider-hosted tool, model, and Access-program authorization (for example code-mode web_search filtering, or the admitted cyber program) is settled before this hook, and hosted tools have no later local gate.
  • Authority after the await: the gate rechecks the run's abort signal right after the handler. The existing managed-fetch egress guard (withGuardedFetchBeforeRequest) still revalidates access-program authority at HTTP egress, after the hook has finished.
  • Context: the hook gets the same agent hook context as other embedded hooks (buildEmbeddedAgentHookContext: agent, session, run, channel and sender fields) plus modelProviderId / modelId.
  • Explicit opt-in: new config key plugins.entries.<id>.hooks.allowModelRequest (boolean, default off for all origins, unlike allowConversationAccess, which bundled plugins get by default). registerTypedHook checks it first: when it is not true, the registration is dropped with one registry warning, typed hook "before_model_request" ignored: it is off by default; set plugins.entries.<id>.hooks.allowModelRequest=true to enable it. The Gateway startup diagnostics logger (server-plugin-bootstrap.ts) prints it, and openclaw plugins inspect <id> lists it. Registration is the single owner of typed hooks, so an ignored handler never reaches the runner and the transport fast path (hasHooks) stays free. Schema (Zod, strict boolean), normalization, help text, label, and the generated config baseline are updated. No global switch: per-plugin opt-in already means nothing runs unless an operator turns it on, and plugins.entries.<id>.enabled or removing the key turns it off.
  • Permissions: the opt-in does not replace the existing gates. Metadata sets conversationAccess: true and promptInjection: true, so non-bundled plugins need allowConversationAccess, and allowPromptModification: false blocks registration, same as before_prompt_build. Added to the harness WORKSPACE_EFFECT_HOOKS list with the other in-turn agent callbacks.
  • Typing: PluginHookBeforeModelRequestEvent / Result are added to the typed handler map, so api.on infers them, and exported from openclaw/plugin-sdk/plugin-entry next to the before_channel_ingress event/result types, so plugin authors can name them. They live in a leaf src/plugins/hook-model.types.ts (no import back into hook-types.ts, so there is no cycle). That file also holds the model hook metadata, and hook-model.ts holds the model hook runner bindings, so hook-types.ts and hooks.ts do not grow past their line caps. llm_input / llm_output incognito suppression is unchanged.
  • CLI runtimes: the CLI owns its wire request and tool loop, so the gate sits at the last text OpenClaw controls. executePreparedCliRun runs it after history reseed, resume context and plugin input text transforms, before image paths, node placement and process start (including each recovery retry), and rechecks run currency after the await. createSteeredCliMessageInjection runs it before input enters a live plugin-owned turn (the path a subagent completion takes into a busy session), with the steered row (provenance included) last in messages. The gate is built per run in runPreparedCliAgentOwned (src/agents/cli-runner/model-request-hook.ts) and carried on PreparedCliRunContext.beforeModelRequest; it is absent for isolated completions and control operations such as compaction. CLI side questions build their own gate (below). A replacement may rewrite text only: anything but { prompt: string, prependContext?: string, appendContext?: string } fails the dispatch, as do a throw or timeout (CLI not started; steered input refused). The system prompt, images and the CLI's own tool results are out of scope. The event gains runtime: "embedded" | "cli" on both paths.
  • Compaction: every embedded compaction model call (the safeguard/default summary via summarizeCompactionHistory -> generateSummary, and attemptServerEndpointCompaction) runs on the compaction session's own streamFn, which prepareCompactionSessionAgent builds and which previously had no gate. The gate is now installed there with wrapStreamFnWithProviderPromptState + createModelRequestTransformer(context, "compaction"), at the same depth as on a turn: right after stream resolution, inside the provider text transforms and applyExtraParamsToAgent wrappers, so it sees the final shaped payload and also gates encode-only transports. Hook context: agent, session key/id, workspace, message provider, trigger, modelProviderId / modelId, contextTokenBudget. Fail-closed as on turns: a throw or timeout fails that compaction request. The event gains requestKind: "turn" | "compaction" (CLI dispatch and steered input are "turn"); documented as extensible, unknown kinds should be treated as turns.
  • Side questions and session forks: resolveSideQuestionStream (src/agents/btw-stream.ts), the one stream owner for both embedded side-question paths, wraps the resolved stream with the gate before the message transform, provider and applyExtraParamsToAgent wrappers, the depth used on turns and compaction. On the fork path the fork's own onPayload (parent-request replay, tool_choice: none) is an outer payload hook, so it runs first and the gate sees the final fork body. The saved parent request stays the pre-gate body on purpose: the fork matches it item by item against its rebuilt history, and replay only happens when every parent item matches, so an item a parent handler edited in place is never replayed and gated a second time. runCliBtwSideQuestion sets PreparedCliRunContext.beforeModelRequest with createCliModelRequestGate(..., requestKind: "side_question"); messages is the sanitized history the prompt was built from plus the question row. Hook context: runId (the side run), agent, session key/id, workspace, channel and sender fields, modelProviderId / modelId. The compaction and side-question wrappers share one helper, wrapStreamFnWithModelRequestGate, which returns the stream unchanged when no handler is registered (this also removes the always-on request hashing the compaction wrapper added for installs without a handler).
  • Stored history is out of scope by design: the hook gates bytes leaving the Gateway; messages stays a detached copy. Keeping a secret out of the transcript (and so out of every later request) is the job of the existing write-time hooks tool_result_persist and before_message_write; docs now state this next to the scope list and in the security page.
  • Docs: docs/plugins/hooks/prompt-and-session.md#final-model-request-policy, plus catalog, timeout, permission, and "choose a hook" rows; docs/gateway/security/prompt-injection.md#screening-the-final-model-request covers request and credential screening with a config and redacting-handler example.
Security considerations
  • This is a strong hook: a registered handler sees full conversation content and can replace the provider request. It needs the explicit allowModelRequest opt-in plus the same two registration permissions as before_prompt_build. Trusted plugins only.
  • A handler cannot change the tool surface (see above), so prompt-modification permission cannot restore a denied provider-hosted tool such as web_search.
  • Fail-closed by design: a crashing or hanging scanner blocks the model call instead of silently sending unscanned content. A plugin that wants outage passthrough must catch its own errors and return nothing (documented).
  • messages is a structuredClone, so handlers cannot mutate session history through the event. Sender trust must come from host metadata (__openclaw.senderIsOwner), not message text (documented).
  • Still runs for incognito sessions, as other policy hooks do. llm_input / llm_output observations stay suppressed there.
  • Embedded compaction requests are gated (requestKind: "compaction"). With agents.defaults.compaction.mode: "default" explicitly set, the agent session's own in-turn compaction can also run; it uses the turn's already-gated streamFn, so it is gated but reported as requestKind: "turn". The shipped default (safeguard) disables that path.
  • Side questions and session forks are gated (requestKind: "side_question") on embedded and CLI runtimes.
  • Not covered (documented): tool results a CLI reads inside its own loop, isolated completions and control operations, external harnesses such as Codex (including their own side questions), turns that run on cloud workers (the Gateway's worker inference executor builds those provider requests without this gate), compaction a CLI runtime runs itself, custom transports that bypass both onPayload and host encoding, and provider-hosted tool results that never return to the client.

Request path matrix

Path that sends conversation content to a model Result Where
Embedded turn, each tool-loop call, transport and encode-only retries Gated, turn attempt-stream-settle.ts transport wrapper
Embedded in-turn agent-session compaction (compaction.mode: "default") Gated as turn (uses the turn's stream) same
Memory flush turns, subagent runs Gated as turns (they are embedded or CLI runs) same / CLI runner
Embedded compaction summary, server-side compaction, compaction fallback routes and retries Gated, compaction prepareCompactionSessionAgent, once per candidate route
/btw side question, embedded lightweight path Gated, side_question (new) resolveSideQuestionStream
/btw with tools denied and api.runtime.subagent.forkSession (session fork, replays the parent's saved request) Gated, side_question (new); replay first, gate once resolveSideQuestionStream + runEmbeddedSessionFork
CLI turn dispatch and steered CLI input Gated, turn executePreparedCliRun, createSteeredCliMessageInjection
CLI /btw side question Gated, side_question (new) runCliBtwSideQuestion
Codex or another plugin harness, including its runSideQuestion Out of scope: the harness owns its request documented
Turns on cloud workers (Gateway worker inference executor) Out of scope for this PR: separate request owner documented
Isolated completions, plugin llm.complete, control operations, compaction a CLI runs itself, tool results inside a CLI's own loop Out of scope: no session history from OpenClaw, or the CLI owns it documented

Real behavior proof

Provider-I/O proof: the real embedded transport owner (prepareEmbeddedAttemptTransport) runs with the real OpenAI Responses transport, and the transport host's model fetch is replaced by a local capture, so the assertions run on the exact HTTP request body. A before_model_request handler is registered:

pnpm exec vitest run src/agents/embedded-agent-runner/provider-prompt-state.test.ts \
  src/agents/embedded-agent-runner/model-request-hook.test.ts \
  src/plugins/hooks.before-model-request.test.ts \
  test/embedded-agent-attempt-stream-transport.test.ts

 ✓ hooks.before-model-request.test.ts > awaits replacements in priority order
 ✓ hooks.before-model-request.test.ts > does not send the original when a policy hook fails
 ✓ model-request-hook.test.ts > dispatches final payload with detached provenance and the correct session
 ✓ model-request-hook.test.ts > leaves the request intact when the plugin is absent
 ✓ provider-prompt-state.test.ts > final model request gate > awaits one gate after provider transforms (encoded=false)
 ✓ provider-prompt-state.test.ts > final model request gate > awaits one gate after provider transforms (encoded=true)
 ✓ provider-prompt-state.test.ts > final model request gate > gates encode-only retries and stops an aborted request after the gate
 ✓ embedded-agent-attempt-stream-transport.test.ts > sends the before_model_request replacement with run context
 ✓ embedded-agent-attempt-stream-transport.test.ts > gates the final OpenAI Responses request at provider I/O (withhold)
 ✓ embedded-agent-attempt-stream-transport.test.ts > gates the final OpenAI Responses request at provider I/O (hosted-tool)
 ✓ embedded-agent-attempt-stream-transport.test.ts > gates the final OpenAI Responses request at provider I/O (throw)
 ✓ model-request-hook.test.ts > rejects replacements that change the provider tool surface

Observed at provider I/O: with withhold, the HTTP body carries [withheld] and not the original user text. With hosted-tool, a replacement that appends { type: "web_search" } ends the turn with must not change the provider tool surface and no HTTP request is made. With throw, the turn errors with the handler's failure and no HTTP request is made. In-process: order is provider onPayload → gate → send, the handler's replacement is the body that is hashed and sent, encode-only retries are gated each time, an abort after the gate prevents the send, a throwing handler rejects the request, and edits to event.messages do not reach the session.

Red checks: with the tool-surface check disabled, the hosted-tool case fails (expected 'stop' to be 'error'). With the transport wiring removed (base attempt-stream-settle.ts), the transport test fails with expected { input: [ 'outside' ] } to deeply equal { input: [ 'withheld' ] }. The other new tests fail on base because the hook and its runner method do not exist. The protected-field snapshot (head 8687f8c) adds model-request-hook.test.ts cases for an in-place tools.push({ type: "web_search" }) with and without a returned payload, and for replacements that change model or access_programs.cyber; with the previous comparison (post-handler, replacement-only, tools only) both new cases fail, and with the snapshot they pass. The real OpenAI Responses transport test (test/embedded-agent-attempt-stream-transport.test.ts, "gates the final OpenAI Responses request at provider I/O") adds in-place-tool (handler pushes web_search onto event.payload.tools and returns nothing) and model (replacement sets model: "other-model") modes: both end with stopReason: "error" and zero captured fetches; against the previous hook implementation both fail with expected 'stop' to be 'error' (the request was sent).

CLI proof through the real CLI runner (runPreparedCliAgent → executePreparedCliRun → process supervisor, with the real hook runner and a registered before_model_request handler; the supervisor spawn is captured so assertions run on the exact argv the CLI would get):

pnpm exec vitest run src/agents/cli-runner.model-request-hook.test.ts

 ✓ screens the CLI turn once and sends the replacement prompt
 ✓ leaves the CLI prompt alone when no plugin is allowed the hook
 ✓ does not start the CLI when the hook times out
 ✓ does not start the CLI when the hook returns a non-text payload
 ✓ screens input steered into a live CLI turn

Observed: the handler runs once per turn with runtime: "cli", the original prompt, the current user row carrying provenance: { kind: "inter_session", sourceSessionKey: "agent:<untrusted>:subagent:..." }, and context with agentId, sessionKey, modelProviderId, modelId; the spawned argv carries [held] and not the original handback text. With no registered handler the argv carries the original prompt. A 20 ms hook timeout or a { prompt: 1 } replacement rejects the run and the CLI is never spawned. Steered input: the injection receives the replacement text and context, not the original. Red check: with src/agents/cli-runner.ts at the previous head, the turn, timeout and malformed-payload cases fail (hook never called, CLI spawned with the original text).

Opt-in proof on a real Gateway built from this branch (isolated state dir, loopback port, no model credentials, no model calls), with a local plugin whose register only calls api.on("before_model_request", ...) and allowConversationAccess: true:

# hooks: { allowConversationAccess: true }   (allowModelRequest unset)
openclaw gateway run --allow-unconfigured --port <free> --bind loopback --auth none
[gateway] [plugins] typed hook "before_model_request" ignored: it is off by default; set plugins.entries.model-request.hooks.allowModelRequest=true to enable it (plugin=model-request, source=<plugin>/index.cjs)
[gateway] http server listening (2 plugins: memory-core, model-request; 4.4s)

# hooks: { allowConversationAccess: true, allowModelRequest: true }
[gateway] http server listening (2 plugins: memory-core, model-request; 3.4s)      (no warning)

openclaw plugins inspect model-request --runtime --json
  off: typedHooks [] , diagnostics ["typed hook \"before_model_request\" ignored: ... allowModelRequest=true to enable it"]
  on:  typedHooks ["before_model_request"], diagnostics []

# hooks: { allowModelRequest: "yes" }
OpenClaw config is invalid
  - plugins.entries.model-request.hooks.allowModelRequest: Invalid input: expected boolean, received string (allowed: true, false)

Opt-in unit proof (src/plugins/loader-model-request-permission.test-support.ts, run through loader.test.ts with the real loader): unset and false register nothing and emit exactly one warning naming the key; true registers the hook; true without allowConversationAccess is still blocked by the conversation-access gate; true with allowPromptModification: false is still blocked by the prompt gate. Red check: forcing the resolver to allow always fails the unset and false cases. Schema and normalization: config-misc.test.ts accepts true and rejects the string "true"; config-state.test.ts keeps a boolean and drops a non-boolean.

Live proof with a real Gateway, a real model, and a scanner plugin registered on this hook is not in this PR. Also not shown: Access revocation or account reassignment while a handler is awaited (this PR does not change prepareEmbeddedAccessProgramGuard), and a latest-stable upgrade run; the only config addition is the new optional boolean allowModelRequest, so existing plugin entries load unchanged. It will follow on a deployment running this branch.

Compaction gate proof (src/agents/embedded-agent-runner/compaction-session-agent.test.ts, real prepareCompactionSessionAgent, real hook runner, mocked transport + a payload-shaping wrapper standing in for applyExtraParamsToAgent): a handler receives requestKind: "compaction", the session hook context, and the payload after provider/config shaping ({ input: "API_TOKEN=fixture-value", shaped: true }), and the transport sends its replacement (API_TOKEN=[REDACTED]); with no handler the payload is sent unchanged. Red check: removing the new wrapper from prepareCompactionSessionAgent fails the first case (handler never called, secret sent). model-request-hook.test.ts asserts requestKind defaults to "turn" and passes "compaction" through.

Side-question proof (head 6f2b0a9):

pnpm exec vitest run src/agents/btw.model-request-hook.test.ts src/agents/embedded-agent-runner/session-fork.test.ts

 ✓ before_model_request on side questions > gates the embedded side question request (block=false)
 ✓ before_model_request on side questions > gates the embedded side question request (block=true)
 ✓ before_model_request on side questions > gates the prompt a CLI side question hands to its runtime
 ✓ session-fork.test.ts > gates the fork's own request once and keeps the parent's gated prefix
 ✓ session-fork.test.ts > does not send a fork the request gate withholds

Observed:

  • btw.model-request-hook.test.ts runs the real runBtwSideQuestion -> resolveSideQuestionStream with a registered redacting handler. The transcript holds a synthetic credential line. The body the provider stream receives carries the redacted value and not the original. The handler sees runtime: "embedded", requestKind: "side_question", the question as the last message, and context agentId, sessionKey, sessionId, modelProviderId, modelId. With a throwing handler the side question rejects and the provider stream never gets a body.
  • CLI side question: the prepared CLI run handed to executePreparedCliRun carries the gate. The prompt it returns is redacted, and the handler sees runtime: "cli", requestKind: "side_question" and the question row last. That executePreparedCliRun sends what the gate returns, and does not start the CLI when it throws, is the existing CLI proof above.
  • Fork, through the real OpenAI Responses transport with only the network fetch captured: the parent turn goes through the turn gate and records its saved request as a run does; the fork then replays it and passes its own gate. The fork's wire input minus the question equals the parent's wire input byte for byte (redacted once, not twice, so the cached prefix holds), no original credential is on the wire, and the handler saw ["turn", "side_question"]. With a handler that throws on side questions the fork rejects and no fetch happens.

Red check: with the gate call removed from resolveSideQuestionStream and the CLI side-question gate disabled, all three btw.model-request-hook.test.ts cases fail (handler never called, credential sent).

What was not tested

  • No live Gateway run with a real provider in this PR (see above). The opt-in gate was proven on a real Gateway startup without model calls.
  • openclaw doctor does not show the opt-in warning: doctor does not load plugin runtimes for this check, and the same is true for the existing conversation-access registration warnings. Startup logs and plugins inspect do show it.
  • The timeout path was not exercised directly. It uses the shared modifying-hook timeout plus the fail-closed policy, and the thrown-error path is tested.
  • Locally, src/agents/harness/ suites that spawn supervised child processes failed with service child cleanup identity lost: native owner closed without kernel descendant extinction. The same suites fail the same way on the base commit, so it is a local process-supervision environment limit, not this change. CI is the reference for them.
  • CLI: the turn path is proven with a codex-cli-shaped arg backend; the claude-cli plugin-owned transport consumes the same gated prompt / promptContext values and its steering path is covered by the steered-input test, but no claude-cli process ran in tests. Live claude-cli proof follows on deployment.
  • Locally, src/agents/cli-runner/bundle-mcp*.test.ts (MCP config projection) and execute-plugin.steering.test.ts fail; bundle-mcp.test.ts and execute-plugin.steering.test.ts fail the same way on the previous head (57b5ec1), so they are a local environment limit, not this change. CI is the reference.
  • Compaction: no live compaction against a real provider with a scanner plugin. The gate placement relative to provider/config wrappers is proven with a stand-in wrapper, not each provider's real onPayload.
  • Side questions: no live /btw or forkSession run against a real provider with a scanner plugin; proof is the real side-question owner with a captured provider stream, and the real Responses transport with a captured fetch for the fork. Codex-harness side questions and cloud-worker turns stay ungated (documented above).
  • Benchmark (before/after, same host, vitest, one gate call per provider request over a 200-message, ~100 KB OpenAI Responses-shaped body, 3 warmups then 10 samples x 300 requests, median): side question with no handler, old head (no gate) 0.1 µs vs new head 0.1 µs (the stream is returned unchanged; one hasHooks lookup per side question). Compaction with no handler: old head's always-on wrapper 554 µs per request, new head none. With a handler: 618 µs per side-question request with a pass-through handler, 681 µs with a JSON-rewriting one (request hashing, history structuredClone, dispatch). Not measured: an end-to-end /btw latency on a live Gateway.
  • Plugin SDK surface budget (pnpm plugin-sdk:surface:check, run by check:changed because plugin-entry.ts changed) fails, but it fails the same way on current main without this PR (public entrypoints 163 > 162, exports 3888 > 3867, wildcard re-exports 1 > 0). This PR adds the two type exports (3888 -> 3890). The budget is not raised here.
  • No separate reviewer: the readiness and review passes for this update were done by the author; no external review agent was available.

Stable-to-candidate upgrade proof — 6a4a6cc8daba

In an isolated profile, the published npm [email protected] CLI wrote a plugin entry with hooks.allowConversationAccess: true and no allowModelRequest. A pre-existing fixture plugin registered only its before_agent_run hook. The rebuilt PR CLI read the same file and plugin without migration or re-enrollment. Redacted terminal results:

stable     config validate                                 valid
stable     plugins inspect <fixture> --runtime --json       loaded; hooks=[before_agent_run]; diagnostics=[]
candidate  config validate                                 valid
candidate  plugins inspect <fixture> --runtime --json       loaded; hooks=[before_agent_run]; diagnostics=[]
config SHA-256 before / after                              identical

This supersedes the earlier note that upgrading existing settings had not been tested. It proves existing plugin settings and runtime registration, not an authenticated external model call. The provider-policy suite now uses Google's existing public transport export. The extension-boundary suite (13), provider-wire suite (12), and remaining core-hook tests (5) passed, as did the session-identity ratchet. No guard or allowance was relaxed.

Evidence — November 18

Head d06d3971eb77, integrated with main e93a426be329 without rewriting the PR branch.

  • Captured Google Gemini and Interactions requests after private video preparation: allow preserves the bytes, rewrite changes the outgoing bytes, and deny sends no HTTP request. With no policy registered the original path is unchanged. A denied Gemini fallback does not send a second request.
  • Protected native Mistral toolChoice and Interactions generation_config.tool_choice; edits fail before provider I/O. Added regressions for native V2 compaction on the foreground stream and a fork replaying the parent's saved request from current main.
  • Final targeted run: 332 tests passed (12 provider-policy, 198 plugin registration, 122 Gemini transport). Additional runner/compaction/fork, CLI, and Interactions suites passed locally. No live provider credentials or billing were involved.
  • Core and root test typechecks, SDK export registration/surface, changed-file lint/format, and test-line budget passed. api.on supplies the typed callback without expanding the public SDK barrel.
  • Independent Codex autoreview of the full base-to-head diff: no P0/P1 findings. Local ClawSweeper’s review process exited before returning a verdict; hosted review and GitHub CI are separate gates.

Verification (earlier revisions)

  • Targeted + hook suites: 5 files, 102 tests pass (provider-prompt-state, model-request-hook, hooks.before-model-request, embedded-agent-attempt-stream-transport, hooks.phase-hooks).

  • Adjacent suites: src/plugins/hooks.phase-hooks.test.ts, attempt-session-runtime-prepare.test.ts, model-request-body.test.ts pass.

  • tsgo core and core-test / root-test shards: clean.

  • oxlint on changed files: clean. Formatter: applied. Line-cap, madge import-cycle, import-cycle, and assertion SAFETY ratchets: pass.

  • Opt-in suites: loader.test.ts (198 tests), config-state.test.ts, config-misc.test.ts, schema.tiers.test.ts, plus the hook suites above, all pass. pnpm tsgo:core clean; oxlint and oxfmt clean on changed files; pnpm config:docs:check OK after pnpm config:docs:gen; base config schema check OK.

  • Test-lines ratchet: config/test-lines-allocations/before-model-request.txt allocates the 563 added test lines (289 for the hook, 44 for the opt-in gate, 47 for the protected-field snapshot cases, 183 for CLI runtimes), since this is a new hook with its own tests.

  • CLI extension (head dc1267b): src/agents/cli-runner suites (1006 pass; only the pre-existing local failures above), cli-runner.model-request-hook, hooks.before-model-request, embedded model-request-hook, reply-tool-authority.worker pass. tsgo:core, tsgo:test:src, tsgo:test:root clean; oxlint (incl. max-lines) and oxfmt clean on changed files; import-cycle and madge checks 0 cycles; config:docs:check OK after config:docs:gen; format:docs:check clean. Autoreview (Claude engine, P0-P1) on the CLI delta: scoped-clean.

  • Compaction follow-up (head deac31b): 29 compaction/hook suites, 317 tests pass (compact*, compaction*, cli-runner.model-request-hook, hooks.before-model-request, model-request-hook, new compaction-session-agent). tsgo:core and core-test shards clean; oxlint / oxfmt clean on changed files; line-cap, max-lines, import-cycle and madge checks pass; format:docs:check clean; test-lines allocation raised to 682 (+119 for the compaction gate tests). Autoreview (Codex gpt-6.1-sol, standard tier, P0-P1) on the compaction delta: scoped-clean.

  • Docs: pnpm format:docs:check and pnpm check:docs (markdownlint, MDX, link audit, config examples) pass with the prompt-injection screening section.

  • Side-question update (head 6f2b0a9, rebased onto current main because the generated config baseline conflicted; only docs/.generated/config-baseline.sha256 was regenerated, every other PR line is unchanged): 21 files, 559 tests pass (btw*, btw.model-request-hook (new), session-fork, model-request-hook, compaction-session-agent, compaction-session-execution.*, provider-prompt-state, cli-runner.model-request-hook, hooks.before-model-request, embedded-agent-attempt-stream-transport, server-plugin-subagent-runtime.fork, loader, hooks.phase-hooks, config-misc, config-state, reply-tool-authority.worker). pnpm check:changed: typecheck (core, core tests, extensions, test root), lint, format, import cycles, line caps, config docs baseline and the production and script unused-export scans pass; the production scan no longer reports createCliModelRequestGate (now called by CLI side questions) or the two hook types (now exported from plugin-entry). Two check:changed rows fail on current main without this PR: the Plugin SDK surface budget (see above) and the full-tree unused-export scan, which reports two exports in ui/ test-support files this PR does not touch. Test-lines ratchet: OK (net +905, allowance 400, allocation 693).

@clawsweeper

clawsweeper Bot commented Nov 5, 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 docs Improvements or additions to documentation agents Agent runtime and tooling size: M labels Nov 5, 2026
@VACInc
VACInc force-pushed the feat/before-model-request branch from 4d59619 to 169cade Compare November 5, 2026 15:18
@clawsweeper clawsweeper Bot added the clawsweeper:intake:feature Preliminary submission classification; full source review pending. label Nov 5, 2026
@VACInc
VACInc force-pushed the feat/before-model-request branch from 169cade to a44cf9a Compare November 5, 2026 15:32
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 5, 2026
@clawsweeper

clawsweeper Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Adds an opt-in plugin hook that can rewrite or block outgoing embedded model requests and text handed to CLI runtimes.

Example: A trusted scanner encounters API_TOKEN=fixture-value in an outgoing model request.

  • Before: Existing prompt hooks cannot reliably redact content added later in the tool loop or transport preparation.
  • After: before_model_request can replace it with API_TOKEN=[REDACTED] or reject the request before dispatch.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful and supported by real Gateway/model evidence, focused transport regressions, and stable-upgrade verification; no actionable patch defect was identified.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Discussion output exercises public webhook intake through isolated Gateways and real local models for embedded and CLI rewrite/deny cases; provider-I/O tests support Google media, retry, compaction, and fork coverage, and the exercised production owners are unchanged at the reviewed head.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Complete
User problem: Policy plugins cannot reliably inspect and withhold the final outgoing content after tool-loop additions and provider payload transformations.
Reason: The maintainer-authored proposal supplies a missing generic extension boundary with explicit permissions and documented coverage limits.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR adds a useful missing policy boundary. No actionable defects were found in the pinned diff; current-head CI is still running.

Priority: P2
Reviewed head: bbc6fc2b2087d98231237c8d8ae5724bf2bfccf4

Before merge

None.

Findings

None.

Agent review details

How this fits together

The hook connects plugin registration permissions to the embedded provider encoder and CLI input boundary, receiving prepared request content and returning replacement content or an error.

flowchart LR
  A[Operator configuration] --> B[Hook registration]
  B --> D[Final request policy]
  C[Prepared model request] --> D
  D --> E[Transport encoder or CLI dispatch]
  E --> F[Model runtime]
  D --> G[Blocked request]
Loading

Technical review

Best possible solution:

Keep one permission-gated policy operation in the existing hook runner, with transport-specific adapters at final encoding and CLI dispatch.

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

Current-main source establishes the missing final-request hook, and supplied Gateway output demonstrates the new behavior; this read-only review did not execute the product.

Is this the best way to solve the issue?

The patch uses the existing registration, modifying-hook, request-identity, and encoding owners; separate CLI and embedded adapters reflect their different dispatch contracts.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 14b9fc3c8d94.

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 69809d7 adds src/agents/embedded-agent-runner/provider-prompt-state.ts:176 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 69809d7a9427; files: src/agents/embedded-agent-runner/provider-prompt-state.ts)
  • Ayaan Zaidi: Raw commit d2ca84f adds src/agents/embedded-agent-runner/provider-prompt-state.ts:226 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d2ca84fb7b67; files: src/agents/embedded-agent-runner/provider-prompt-state.ts)
  • Josh Avant: Raw commit e07de4c adds src/agents/embedded-agent-runner/provider-prompt-state.ts:117 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e07de4c56159; files: src/agents/embedded-agent-runner/provider-prompt-state.ts)

PR surface

Source +577, Tests +1067, Docs +178, Generated 0, Other +1. Total +1823 across 54 files. Added test files: 7.

View PR surface stats
Area Files Added Removed Net
Source 32 650 73 +577
Tests 14 1074 7 +1067
Docs 5 182 4 +178
Config 0 0 0 0
Generated 2 3 3 0
Other 1 1 0 +1
Total 54 1910 87 +1823

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
New configuration surface 1 optional per-plugin boolean hooks.allowModelRequest defaults off, including for bundled plugins, and existing configuration was exercised through a stable-to-candidate upgrade.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: A useful plugin capability with limited opt-in scope; existing installations retain their behavior.
  • merge-risk: 🚨 compatibility: The PR introduces a typed plugin hook and transport SDK export; the maintainer-authored direction, default-off permission, documentation, and upgrade evidence address the intentional contract expansion.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • 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-11-05T16:26:13.840Z sha 53db7f1 :: needs real behavior proof before merge. :: [P1] Snapshot the tool surface before invoking handlers | [P1] Preserve the admitted model and Access program in replacements
  • reviewed 2026-11-05T18:06:45.354Z sha 0d8a697c77edd2dca547f57d726c098f8ffaa7c3 :: needs real behavior proof before merge. :: [P1] Snapshot the tool surface before invoking handlers | [P1] Preserve the admitted model and Access program in replacements | [P3] Point operators to diagnostics that show the ignored hook
  • reviewed 2026-11-05T19:36:03.596Z sha 607b66dff5b6c6811cba7c32f6c112eb100b622e :: needs real behavior proof before merge. :: [P1] Snapshot the tool surface before invoking handlers | [P1] Preserve the admitted model and Access program in replacements | [P3] Point operators to diagnostics that show the ignored hook
  • reviewed 2026-11-05T20:36:26.511Z sha cfe5642c51a92a1757dcd5e10480300d2df3c09c :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-06T20:52:16.626Z sha de4aecb :: needs real behavior proof before merge. :: [P2] Preserve provider-native tool-choice fields in the snapshot
  • reviewed 2026-11-18T02:33:33.390Z sha d06d397 :: blocked before merge. :: none
  • reviewed 2026-11-18T02:42:18.032Z sha d06d397 :: needs changes before merge. :: [P2] [P2] Move Google transport coverage behind the plugin boundary
  • reviewed 2026-11-18T02:53:31.814Z sha 6a4a6cc :: needs maintainer review before merge. :: none

Reviewed November 17, 2026, 10:52 PM ET / November 18, 2026, 03:52 UTC (Revision 10).

@VACInc
VACInc force-pushed the feat/before-model-request branch from a44cf9a to 53db7f1 Compare November 5, 2026 16:00
@VACInc

VACInc commented Nov 5, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 5, 2026
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: L and removed size: M labels Nov 5, 2026
@VACInc
VACInc force-pushed the feat/before-model-request branch from f6adbcf to 0d8a697 Compare November 5, 2026 17:23
@VACInc

VACInc commented Nov 5, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added the security Security documentation label Nov 5, 2026
@VACInc

VACInc commented Nov 5, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@VACInc

VACInc commented Nov 5, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. 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. labels Nov 18, 2026
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Real Gateway + CLI input-policy proof — 6a4a6cc8daba

Four fresh, isolated Gateway instances built from the exact reviewed commit. Each received one synthetic external event through the public webhook endpoint, in a new session, with external delivery disabled. A locally installed, opted-in scanner either replaced a marker or threw. Both backends used real Qwen2.5-0.5B-Instruct Q4_K_M weights with llama.cpp b12494. No provider credentials, hosted inference, or changes to the branch.

Redacted terminal results (counts at the receiving HTTP or executable boundary, not a count of hook callbacks):

cli      deny    terminal=error receiver_calls=0
cli      rewrite terminal=ok    receiver_calls=1  original=absent replacement=present generated_text=yes
embedded deny    terminal=error receiver_calls=0
embedded rewrite terminal=ok    receiver_calls=1  original=absent replacement=present generated_text=yes

The embedded receiver recorded the full request and forwarded its bytes unchanged to the model server; the successful stream contained generated text. The CLI backend recorded the prompt at process entry and invoked the native llama-completion binary, which generated text and exited 0. The two denials completed in the expected error state, with no provider POST or CLI dispatch. This demonstrates input rewrite and denial; neither test edits model output. It tests one real backend per boundary, not every hosted provider or CLI's private internal calls.

The exact-stamped build also re-read the config produced by published stable 2026.11.5: config valid, existing before_agent_run hook loaded, diagnostics empty, config hash unchanged. This supersedes the older no-live-run note for these four cases. Separate from product proof: the Discord capture and plugin handover failures both reproduced on the unchanged CI base (3460f6178601); neither is being counted as passed.

Reconcile the generated manifest for the model input hook with the upstream plugin schema changes. No authored hook changes.

Co-authored-by: VACInc <[email protected]>
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Nov 18, 2026
@VACInc
VACInc merged commit 2b7950c into openclaw:main Nov 18, 2026
239 of 247 checks passed
vincentkoc pushed a commit that referenced this pull request Nov 18, 2026
Apply hosted file-count bounds during weighted balancing instead of slicing already-balanced stripes into stranded tails. Preserve the 77-row hourly nondist cap, runner and worker limits, time budgets, and complete selected inventory.

The scheduled manifest reproduced 78 > 77 after inventory growth in #200967. Expanded GitHub/hybrid regressions and all 174 focused planner tests pass; Codex autoreview is clean. check:changed passes except unrelated main unused exports attributed to #200533, #193550, #198455, and #200817.
RomneyDa added a commit that referenced this pull request Nov 18, 2026
…llback model (#200801)

Root cause: `src/agents/cli-runner.ts:410` (main 91614b5) handles a refused CLI stream (`CLI JSONL output exceeded …`) by keeping the first-turn session and rethrowing, but never applies the existing rule that a turn which already ran tools must not be replayed on another model (`cli-runner.ts:466-472`, from #162567). The executor also rethrew the refusal without the run's tool facts, so model fallback sent the same user message to the fallback model, which ran the completed tools again.

Fixes #200744

## What Problem This Solves

A long Claude CLI turn can edit files and run commands, then produce more output than OpenClaw will parse. OpenClaw refuses that output and, when a fallback model is configured, hands the same request to the fallback model. That model starts from scratch and repeats the work on top of half-applied changes, while queued messages wait behind it. Thanks @jzmudzinski for the detailed report (a 54-minute turn replayed this way).

## User Impact

User impact: when a `claude-cli` turn that already ran a tool hits the stream output limit, the run stops with the limit error instead of replaying the request on another model, so finished tool actions are not repeated. A turn that hits the limit before running any tool still falls back as before.

## Why This Change Was Made

OpenClaw already refuses to fall back after tool effects when a CLI turn ends with an empty answer. The output-limit refusal never reached that check, because the refused output did not carry the run's tool summary. The executor now attaches the tool summary and accepted session spawns to the refused output, and the runner applies the same stop to both failures. The refused first turn's native session is still kept for the next message (#192838 unchanged).

The issue also suggests a new failover reason for output budgets. This keeps the existing reason and uses the existing fallback stop, so failover reasons and their consumers stay unchanged.

Fix by @fede-kamel (d2169a3), kept as is; on top: a merge of current `main` and a shorter regression test.

## Evidence

Real Gateway, real Claude Code 2.1.322 as the `claude-cli` backend, built `dist/`, isolated state. Claude Code talks to a local Anthropic Messages fixture; the fallback `stub/stub` is a local OpenAI-compatible fixture that starts the request from scratch. The turn runs `exec` once (appends a line to a marker file) through the Gateway's MCP, then streams 10 MiB of reply text.

| Build | Result | `exec` runs |
| --- | --- | --- |
| `main` 91614b5, run 1 and 2 | output refused, fallback `stub/stub` runs `exec` again and answers | **2**, **2** |
| this PR, run 1 and 2 | output refused, run fails with `CLI JSONL output exceeded 8388608 characters`, fallback never called | **1**, **1** |
| this PR, no tool before the overflow | output refused, fallback to `stub/stub` as before | 0 from Claude Code |

Regression test: `execute.output-limit.test.ts` › "stops model fallback when a turn that already ran a tool exceeds the output limit" fails on `main` (`expected false to be true`) and passes here; the existing first-turn refusal test now also checks that a refusal without tools records no stop.

Gateway and fixture logs: #200801 (comment)

Merge danger: two-way door. Reverting restores the old fallback behavior; nothing is written or migrated. Blast radius: `claude-cli` turns that hit the output limit after running a tool now end with the error instead of falling back.

Release adaptation: the unchanged shared fallback-stop policy lives in the existing CLI exit-error owner instead of the already-full orchestrator, keeping the 700-line limit intact without exemptions. Both refusal and empty-answer callers use that single policy. Added a 29-line regression allocation. Backported to release/2026.11.6 from baseline 309067b under Dallin's explicit intake authorization.

Companion audit through 9e917f0: later same-path commit 2b7950c (#193550) adds a model-request hook and is not a prerequisite; no later #200801 mention. Existing refusal/session continuity, finalized tool tracking, accepted-spawn evidence, and fallback-stop consumer are present.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit fea4a9d)
Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 19, 2026
…nclaw#193550)

* feat(plugins): add before_model_request final provider request hook

* feat(plugins): make before_model_request opt-in via hooks.allowModelRequest

* docs(security): document before_model_request screening, including credentials

* fix(plugins): snapshot protected request fields before before_model_request handlers

Handlers receive the payload by reference, so an in-place edit (or a void
return) bypassed the tool-surface comparison. Snapshot tools, model, and
access_programs before dispatch and validate the effective payload on every
path. Point operators to startup logs and plugins inspect --runtime --json
for the ignored-registration diagnostic.

* test: allocate test lines for protected-field snapshot cases

* test: prove in-place tool edits and model replacements stop before provider I/O

* feat(plugins): run before_model_request on CLI runtimes

CLI-backed runtimes such as claude-cli own their provider requests, so the
hook never saw what OpenClaw handed them: a subagent completion from an
untrusted agent reached the CLI as the prompt with no plugin able to screen
or withhold it.

The hook now also runs where OpenClaw hands text to a CLI: once per turn
dispatch (after history reseed, resume context and input text transforms,
before image paths) and once per input steered into a live CLI turn. The
event carries runtime "cli" and payload { prompt, prependContext?,
appendContext? }; messages end with the current user row, including its
input provenance. Same opt-in, timeout and fail-closed policy as embedded
runs: a failure or a malformed replacement stops the dispatch.

* chore: document CLI payload record assertion invariant

* feat(plugins): gate embedded compaction requests with before_model_request

Compaction summary and server-side compaction requests resend older
history, so they now pass the same final request gate as turns, at the
same depth after provider and config payload shaping. The event gains
requestKind (turn | compaction). Docs state that the hook changes only
the outgoing request and point redaction of stored history at
tool_result_persist / before_message_write.

* test: allocate compaction gate test lines

* test: keep real exports in compaction gate test mocks

* feat(plugins): gate side questions and session forks with before_model_request

* feat(plugin-sdk): export before_model_request hook event and result types

* fix: accept an uninitialized hook runner on CLI requests

Co-authored-by: VACInc <[email protected]>

* test: verify retry denial and cancellation at provider I/O

Keep callback types inferred through the existing plugin registration API.

Co-authored-by: VACInc <[email protected]>

* test: verify model request policy through the public Google transport

Use the published transport facade and reserve generation naming for session identity. Drop the redundant request-kind helper test; real provider and fork coverage remains.

Co-authored-by: VACInc <[email protected]>

---------

Co-authored-by: VACInc <[email protected]>
Co-authored-by: roboclaw-bot <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 19, 2026
…1002)

Apply hosted file-count bounds during weighted balancing instead of slicing already-balanced stripes into stranded tails. Preserve the 77-row hourly nondist cap, runner and worker limits, time budgets, and complete selected inventory.

The scheduled manifest reproduced 78 > 77 after inventory growth in openclaw#200967. Expanded GitHub/hybrid regressions and all 174 focused planner tests pass; Codex autoreview is clean. check:changed passes except unrelated main unused exports attributed to openclaw#200533, openclaw#193550, openclaw#198455, and openclaw#200817.
RomneyDa added a commit that referenced this pull request Nov 19, 2026
Release adaptation: omit the new before_model_request gate regression from #201497 because its complete feature #193550 (2b7950c) is absent on this release. Keep the transport shaping regression; do not import an unrelated 54-file plugin feature to satisfy a mismatched test. Simplify the prepared alias registration-key comparison while preserving the generation-registry exemption and exact captured resolver.

Follow-up disposition: missing gate test is not compaction behavior proof; source extraction and exact replay tests provide the retained boundary coverage. PostgreSQL service qualification remains environment-blocked.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 3045afdafff9a3a21b48732b6c49711fb5fc9b71)
RomneyDa added a commit that referenced this pull request Nov 19, 2026
Apply hosted file-count bounds during weighted balancing instead of slicing already-balanced stripes into stranded tails. Preserve the 77-row hourly nondist cap, runner and worker limits, time budgets, and complete selected inventory.

The scheduled manifest reproduced 78 > 77 after inventory growth in #200967. Expanded GitHub/hybrid regressions and all 174 focused planner tests pass; Codex autoreview is clean. check:changed passes except unrelated main unused exports attributed to #200533, #193550, #198455, and #200817.

Backport to beta.2 preparation; exact reviewed adapted patch. Focused parent proof: 35 tests; nine-file type-aware lint; 18-file format. Tooling typecheck retains the same two pre-existing cron UI errors as baseline. No release qualification.

(cherry picked from commit af50b8e)
(cherry picked from commit c7ccc5e)
Co-authored-by: Vincent Koc <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: google gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security Security documentation size: XL 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.

2 participants