Repository navigation
feat(plugins): let plugins gate the final model provider request - #193550
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
4d59619 to
169cade
Compare
169cade to
a44cf9a
Compare
|
Codex review: needs maintainer review before merge. What this changesAdds 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.
Review scores
ProductKind: Feature · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe 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]
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +577, Tests +1067, Docs +178, Generated 0, Other +1. Total +1823 across 54 files. Added test files: 7. View PR surface stats
Preflight sourceSource 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
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (9 earlier review cycles; latest 8 shown)
Reviewed November 17, 2026, 10:52 PM ET / November 18, 2026, 03:52 UTC (Revision 10). |
a44cf9a to
53db7f1
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
f6adbcf to
0d8a697
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Real Gateway + CLI input-policy proof —
|
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]>
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
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.
…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]>
…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]>
…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.
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)
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]>
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-cliown 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 hasruntime: "cli"andpayload: { prompt, prependContext?, appendContext? }, andmessagesends with the current user row including its inputprovenance. 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 attool_result_persist/before_message_write.Side questions too. A
/btwside 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, markedrequestKind: "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_buildandbefore_agent_runrun before provideronPayloadtransforms, tool-loop follow-up calls, and transport retries, andllm_inputis 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 withplugins.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
wrapStreamFnWithProviderPromptStatealready owns the post-onPayloadrequest body (it hashes it for context-retry admission). The gate runs there, right after provideronPayloadtransforms. 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.fail-closedpolicy set (likebefore_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.tools,tool_choice,toolConfig,functions,function_call,model, oraccess_programs(top level or underconfig). 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 toevent.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-modeweb_searchfiltering, or the admittedcyberprogram) is settled before this hook, and hosted tools have no later local gate.withGuardedFetchBeforeRequest) still revalidates access-program authority at HTTP egress, after the hook has finished.buildEmbeddedAgentHookContext: agent, session, run, channel and sender fields) plusmodelProviderId/modelId.plugins.entries.<id>.hooks.allowModelRequest(boolean, default off for all origins, unlikeallowConversationAccess, which bundled plugins get by default).registerTypedHookchecks it first: when it is nottrue, 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, andopenclaw 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, andplugins.entries.<id>.enabledor removing the key turns it off.conversationAccess: trueandpromptInjection: true, so non-bundled plugins needallowConversationAccess, andallowPromptModification: falseblocks registration, same asbefore_prompt_build. Added to the harnessWORKSPACE_EFFECT_HOOKSlist with the other in-turn agent callbacks.PluginHookBeforeModelRequestEvent/Resultare added to the typed handler map, soapi.oninfers them, and exported fromopenclaw/plugin-sdk/plugin-entrynext to thebefore_channel_ingressevent/result types, so plugin authors can name them. They live in a leafsrc/plugins/hook-model.types.ts(no import back intohook-types.ts, so there is no cycle). That file also holds the model hook metadata, andhook-model.tsholds the model hook runner bindings, sohook-types.tsandhooks.tsdo not grow past their line caps.llm_input/llm_outputincognito suppression is unchanged.executePreparedCliRunruns 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.createSteeredCliMessageInjectionruns 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 inmessages. The gate is built per run inrunPreparedCliAgentOwned(src/agents/cli-runner/model-request-hook.ts) and carried onPreparedCliRunContext.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 gainsruntime: "embedded" | "cli"on both paths.summarizeCompactionHistory->generateSummary, andattemptServerEndpointCompaction) runs on the compaction session's ownstreamFn, whichprepareCompactionSessionAgentbuilds and which previously had no gate. The gate is now installed there withwrapStreamFnWithProviderPromptState+createModelRequestTransformer(context, "compaction"), at the same depth as on a turn: right after stream resolution, inside the provider text transforms andapplyExtraParamsToAgentwrappers, 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 gainsrequestKind: "turn" | "compaction"(CLI dispatch and steered input are"turn"); documented as extensible, unknown kinds should be treated as turns.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 andapplyExtraParamsToAgentwrappers, the depth used on turns and compaction. On the fork path the fork's ownonPayload(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.runCliBtwSideQuestionsetsPreparedCliRunContext.beforeModelRequestwithcreateCliModelRequestGate(..., requestKind: "side_question");messagesis 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).messagesstays 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 hookstool_result_persistandbefore_message_write; docs now state this next to the scope list and in the security page.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-requestcovers request and credential screening with a config and redacting-handler example.Security considerations
allowModelRequestopt-in plus the same two registration permissions asbefore_prompt_build. Trusted plugins only.web_search.messagesis astructuredClone, so handlers cannot mutate session history through the event. Sender trust must come from host metadata (__openclaw.senderIsOwner), not message text (documented).llm_input/llm_outputobservations stay suppressed there.requestKind: "compaction"). Withagents.defaults.compaction.mode: "default"explicitly set, the agent session's own in-turn compaction can also run; it uses the turn's already-gatedstreamFn, so it is gated but reported asrequestKind: "turn". The shipped default (safeguard) disables that path.requestKind: "side_question") on embedded and CLI runtimes.onPayloadand host encoding, and provider-hosted tool results that never return to the client.Request path matrix
turnattempt-stream-settle.tstransport wrappercompaction.mode: "default")turn(uses the turn's stream)compactionprepareCompactionSessionAgent, once per candidate route/btwside question, embedded lightweight pathside_question(new)resolveSideQuestionStream/btwwith tools denied andapi.runtime.subagent.forkSession(session fork, replays the parent's saved request)side_question(new); replay first, gate onceresolveSideQuestionStream+runEmbeddedSessionForkturnexecutePreparedCliRun,createSteeredCliMessageInjection/btwside questionside_question(new)runCliBtwSideQuestionrunSideQuestionllm.complete, control operations, compaction a CLI runs itself, tool results inside a CLI's own loopReal 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. Abefore_model_requesthandler is registered:Observed at provider I/O: with
withhold, the HTTP body carries[withheld]and not the original user text. Withhosted-tool, a replacement that appends{ type: "web_search" }ends the turn withmust not change the provider tool surfaceand no HTTP request is made. Withthrow, the turn errors with the handler's failure and no HTTP request is made. In-process: order is provideronPayload→ 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 toevent.messagesdo not reach the session.Red checks: with the tool-surface check disabled, the
hosted-toolcase fails (expected 'stop' to be 'error'). With the transport wiring removed (baseattempt-stream-settle.ts), the transport test fails withexpected { 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 (head8687f8c) addsmodel-request-hook.test.tscases for an in-placetools.push({ type: "web_search" })with and without a returned payload, and for replacements that changemodeloraccess_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") addsin-place-tool(handler pushesweb_searchontoevent.payload.toolsand returns nothing) andmodel(replacement setsmodel: "other-model") modes: both end withstopReason: "error"and zero captured fetches; against the previous hook implementation both fail withexpected '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 registeredbefore_model_requesthandler; the supervisor spawn is captured so assertions run on the exact argv the CLI would get):Observed: the handler runs once per turn with
runtime: "cli", the original prompt, the current user row carryingprovenance: { kind: "inter_session", sourceSessionKey: "agent:<untrusted>:subagent:..." }, and context withagentId,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: withsrc/agents/cli-runner.tsat 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
registeronly callsapi.on("before_model_request", ...)andallowConversationAccess: true:Opt-in unit proof (
src/plugins/loader-model-request-permission.test-support.ts, run throughloader.test.tswith the real loader): unset andfalseregister nothing and emit exactly one warning naming the key;trueregisters the hook;truewithoutallowConversationAccessis still blocked by the conversation-access gate;truewithallowPromptModification: falseis still blocked by the prompt gate. Red check: forcing the resolver to allow always fails theunsetandfalsecases. Schema and normalization:config-misc.test.tsacceptstrueand rejects the string"true";config-state.test.tskeeps 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 booleanallowModelRequest, 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, realprepareCompactionSessionAgent, real hook runner, mocked transport + a payload-shaping wrapper standing in forapplyExtraParamsToAgent): a handler receivesrequestKind: "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 fromprepareCompactionSessionAgentfails the first case (handler never called, secret sent).model-request-hook.test.tsassertsrequestKinddefaults to"turn"and passes"compaction"through.Side-question proof (head
6f2b0a9):Observed:
btw.model-request-hook.test.tsruns the realrunBtwSideQuestion->resolveSideQuestionStreamwith 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 seesruntime: "embedded",requestKind: "side_question", the question as the last message, and contextagentId,sessionKey,sessionId,modelProviderId,modelId. With a throwing handler the side question rejects and the provider stream never gets a body.executePreparedCliRuncarries the gate. The prompt it returns is redacted, and the handler seesruntime: "cli",requestKind: "side_question"and the question row last. ThatexecutePreparedCliRunsends what the gate returns, and does not start the CLI when it throws, is the existing CLI proof above.inputminus the question equals the parent's wireinputbyte 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
resolveSideQuestionStreamand the CLI side-question gate disabled, all threebtw.model-request-hook.test.tscases fail (handler never called, credential sent).What was not tested
openclaw doctordoes 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 andplugins inspectdo show it.src/agents/harness/suites that spawn supervised child processes failed withservice 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.codex-cli-shaped arg backend; theclaude-cliplugin-owned transport consumes the same gatedprompt/promptContextvalues 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.src/agents/cli-runner/bundle-mcp*.test.ts(MCP config projection) andexecute-plugin.steering.test.tsfail;bundle-mcp.test.tsandexecute-plugin.steering.test.tsfail the same way on the previous head (57b5ec1), so they are a local environment limit, not this change. CI is the reference.onPayload./btworforkSessionrun 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).hasHookslookup 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, historystructuredClone, dispatch). Not measured: an end-to-end/btwlatency on a live Gateway.pnpm plugin-sdk:surface:check, run bycheck:changedbecauseplugin-entry.tschanged) fails, but it fails the same way on currentmainwithout 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.Stable-to-candidate upgrade proof —
6a4a6cc8dabaIn an isolated profile, the published npm
[email protected]CLI wrote a plugin entry withhooks.allowConversationAccess: trueand noallowModelRequest. A pre-existing fixture plugin registered only itsbefore_agent_runhook. The rebuilt PR CLI read the same file and plugin without migration or re-enrollment. Redacted terminal results: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 maine93a426be329without rewriting the PR branch.toolChoiceand Interactionsgeneration_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.api.onsupplies the typed callback without expanding the public SDK barrel.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.tspass.tsgocore and core-test / root-test shards: clean.oxlinton 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:coreclean;oxlintandoxfmtclean on changed files;pnpm config:docs:checkOK afterpnpm config:docs:gen; base config schema check OK.Test-lines ratchet:
config/test-lines-allocations/before-model-request.txtallocates 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-runnersuites (1006 pass; only the pre-existing local failures above),cli-runner.model-request-hook,hooks.before-model-request, embeddedmodel-request-hook,reply-tool-authority.workerpass.tsgo:core,tsgo:test:src,tsgo:test:rootclean;oxlint(incl. max-lines) andoxfmtclean on changed files; import-cycle and madge checks 0 cycles;config:docs:checkOK afterconfig:docs:gen;format:docs:checkclean. 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, newcompaction-session-agent).tsgo:coreand core-test shards clean;oxlint/oxfmtclean on changed files; line-cap, max-lines, import-cycle and madge checks pass;format:docs:checkclean; test-lines allocation raised to 682 (+119 for the compaction gate tests). Autoreview (Codexgpt-6.1-sol, standard tier, P0-P1) on the compaction delta: scoped-clean.Docs:
pnpm format:docs:checkandpnpm check:docs(markdownlint, MDX, link audit, config examples) pass with the prompt-injection screening section.Side-question update (head
6f2b0a9, rebased onto currentmainbecause the generated config baseline conflicted; onlydocs/.generated/config-baseline.sha256was 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 reportscreateCliModelRequestGate(now called by CLI side questions) or the two hook types (now exported fromplugin-entry). Twocheck:changedrows fail on currentmainwithout this PR: the Plugin SDK surface budget (see above) and the full-tree unused-export scan, which reports two exports inui/test-support files this PR does not touch. Test-lines ratchet: OK (net +905, allowance 400, allocation 693).