Skip to content

Commit 1c42c77

Browse files
feat: add user input blocking lifecycle gates (#75035)
Summary: - The PR adds a `before_agent_run` plugin hook with pass/block decisions, redacted blocked-turn persistence, diagnostics/docs/changelog updates, and focused runner, gateway, session, and plugin tests. - Reproducibility: not applicable. as a feature PR rather than a current-main bug report. Current main lacks ` ... un`, while the PR head adds source coverage and copied live Gateway/WebChat log proof for the new behavior. Automerge notes: - PR branch already contained follow-up commit before automerge: fix: trim before agent hook PR scope - PR branch already contained follow-up commit before automerge: fix: keep before-agent blocks redacted - PR branch already contained follow-up commit before automerge: fix: keep runtime context out of model prompt - PR branch already contained follow-up commit before automerge: docs: refresh config baseline after rebase - PR branch already contained follow-up commit before automerge: fix: align blocked turn clients with redacted content - PR branch already contained follow-up commit before automerge: fix: remove out-of-scope client block UI changes Validation: - ClawSweeper review passed for head 767e46f. - Required merge gates passed before the squash merge. Prepared head SHA: 767e46f Review: #75035 (comment) Co-authored-by: Jesse Merhi <[email protected]> Co-authored-by: jesse-merhi <[email protected]> Co-authored-by: clawsweeper <274271284+clawsweeper[bot]@users.noreply.github.com>
1 parent 2915f45 commit 1c42c77

48 files changed

Lines changed: 2194 additions & 166 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ Docs: https://docs.openclaw.ai
109109
- Developer tooling: add checked-in VS Code Gateway debugging configs and an opt-in `OUTPUT_SOURCE_MAPS=1` source-map build path for breakpoints in TypeScript source. (#45710) Thanks @SwissArmyBud.
110110
- Managed proxy: add `proxy.loopbackMode` for Gateway loopback control-plane traffic, allowing operators to keep the default Gateway loopback bypass, force loopback Gateway traffic through the proxy, or block it. (#77018) Thanks @jesse-merhi.
111111
- Telegram/native commands: show the current thinking level above the `/think` level picker so users can see the active setting before changing it. (#78278) Thanks @obviyus.
112+
- Plugins/hooks: add a `before_agent_run` pass/block gate that can stop a user prompt before model submission while preserving a redacted transcript entry for the user, and clarify that raw conversation hooks require `hooks.allowConversationAccess=true`. (#75035) Thanks @jesse-merhi.
112113

113114
### Fixes
114115

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
5dd302a20b8a6347425617323d0ad7875f9b7631acd3ed3935cfaaf7708a32dd config-baseline.json
2-
d192d678668712b81cc2e76ddcb6420893ab5144944ccb830b290019d6a717a4 config-baseline.core.json
1+
da2ba9afd1062db1fafe81fb42e39db4ad65995a5e56caef4057a9954c2c386b config-baseline.json
2+
f860a7d43d3bd15379d8c3dfccbc6fcbf47b9bec8d8b67b29dd7313946905645 config-baseline.core.json
33
cd7c0c7fb1435bc7e59099e9ac334462d5ad444016e9ab4512aae63a238f78dc config-baseline.channel.json
4-
6871e789b74722e4ff2c877940dac256c232433ae26b305fc6ca782b90662097 config-baseline.plugin.json
4+
2fee9c16a60d074fac428b4ad14c38ad3ca7febefacfad819f741a820101326e config-baseline.plugin.json
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
ce3eef3355f00b88eba1dd54731f932a1ffff9dee64cb19402d7d89b2c363681 plugin-sdk-api-baseline.json
2-
28eb08edb11108d80ec5d5bd12c97108495b064a4d6dd5ca3ecc01d12c2d4c42 plugin-sdk-api-baseline.jsonl
1+
fe1d0d9bde4ab216a92e4fce8c01d699601c3f033f6449352382ff902b129a6f plugin-sdk-api-baseline.json
2+
15eb9a88276f066cddb645f072f57f25f1ff59174cf2277b6014ca2565dbe09a plugin-sdk-api-baseline.jsonl

‎docs/cli/plugins.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ For runtime hook debugging:
275275

276276
- `openclaw plugins inspect <id> --runtime --json` shows registered hooks and diagnostics from a module-loaded inspection pass. Runtime inspection never installs dependencies; use `openclaw doctor --fix` to clean legacy dependency state or recover missing downloadable plugins that are referenced by config.
277277
- `openclaw gateway status --deep --require-rpc` confirms the reachable Gateway, service/process hints, config path, and RPC health.
278-
- Non-bundled conversation hooks (`llm_input`, `llm_output`, `before_agent_finalize`, `agent_end`) require `plugins.entries.<id>.hooks.allowConversationAccess=true`.
278+
- Non-bundled conversation hooks (`llm_input`, `llm_output`, `before_model_resolve`, `before_agent_reply`, `before_agent_run`, `before_agent_finalize`, `agent_end`) require `plugins.entries.<id>.hooks.allowConversationAccess=true`.
279279

280280
Use `--link` to avoid copying a local directory (adds to `plugins.load.paths`):
281281

‎docs/gateway/configuration-reference.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ See [MCP](/cli/mcp#openclaw-as-an-mcp-client-registry) and
195195
- `plugins.entries.<id>.apiKey`: plugin-level API key convenience field (when supported by the plugin).
196196
- `plugins.entries.<id>.env`: plugin-scoped env var map.
197197
- `plugins.entries.<id>.hooks.allowPromptInjection`: when `false`, core blocks `before_prompt_build` and ignores prompt-mutating fields from legacy `before_agent_start`, while preserving legacy `modelOverride` and `providerOverride`. Applies to native plugin hooks and supported bundle-provided hook directories.
198-
- `plugins.entries.<id>.hooks.allowConversationAccess`: when `true`, trusted non-bundled plugins may read raw conversation content from typed hooks such as `llm_input`, `llm_output`, `before_agent_finalize`, and `agent_end`.
198+
- `plugins.entries.<id>.hooks.allowConversationAccess`: when `true`, trusted non-bundled plugins may read raw conversation content from typed hooks such as `llm_input`, `llm_output`, `before_model_resolve`, `before_agent_reply`, `before_agent_run`, `before_agent_finalize`, and `agent_end`.
199199
- `plugins.entries.<id>.subagent.allowModelOverride`: explicitly trust this plugin to request per-run `provider` and `model` overrides for background subagent runs.
200200
- `plugins.entries.<id>.subagent.allowedModels`: optional allowlist of canonical `provider/model` targets for trusted subagent overrides. Use `"*"` only when you intentionally want to allow any model.
201201
- `plugins.entries.<id>.config`: plugin-defined config object (validated by native OpenClaw plugin schema when available).

‎docs/plugins/hooks.md‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ observation-only.
104104
- `agent_turn_prepare` - consume queued plugin turn injections and add same-turn context before prompt hooks
105105
- `before_prompt_build` - add dynamic context or system-prompt text before the model call
106106
- `before_agent_start` - compatibility-only combined phase; prefer the two hooks above
107+
- **`before_agent_run`** - inspect the final prompt and session messages before model submission and optionally block the run
107108
- **`before_agent_reply`** - short-circuit the model turn with a synthetic reply or silence
108109
- **`before_agent_finalize`** - inspect the natural final answer and request one more model pass
109110
- `agent_end` - observe final messages, success state, and run duration
@@ -232,6 +233,22 @@ Use the phase-specific hooks for new plugins:
232233
`before_agent_start` remains for compatibility. Prefer the explicit hooks above
233234
so your plugin does not depend on a legacy combined phase.
234235

236+
`before_agent_run` runs after prompt construction and before any model input,
237+
including prompt-local image loading and `llm_input` observation. It receives
238+
the current user input as `prompt`, plus loaded session history in `messages`
239+
and the active system prompt. Return `{ outcome: "block", reason, message? }`
240+
to stop the run before the model can read the prompt. `reason` is internal;
241+
`message` is the user-facing replacement. The only supported outcomes are
242+
`pass` and `block`; unsupported decision shapes fail closed.
243+
244+
When a run is blocked, OpenClaw stores only the replacement text in
245+
`message.content` plus non-sensitive block metadata such as the blocking plugin
246+
id and timestamp. The original user text is not retained in transcript or future
247+
context. Internal block reasons are treated as sensitive and excluded from
248+
transcript, history, broadcast, log, and diagnostics payloads. Observability
249+
should use sanitized fields such as blocker id, outcome, timestamp, or a safe
250+
category.
251+
235252
`before_agent_start` and `agent_end` include `event.runId` when OpenClaw can
236253
identify the active run. The same value is also available on `ctx.runId`.
237254
Cron-driven runs also expose `ctx.jobId` (the originating cron job id) so
@@ -280,8 +297,9 @@ type BeforeAgentFinalizeRetry = {
280297
equivalent finalize decisions, and `maxAttempts` caps how many extra passes the
281298
host will allow before continuing with the natural final answer.
282299

283-
Non-bundled plugins that need `llm_input`, `llm_output`,
284-
`before_agent_finalize`, or `agent_end` must set:
300+
Non-bundled plugins that need raw conversation hooks (`before_model_resolve`,
301+
`before_agent_reply`, `llm_input`, `llm_output`, `before_agent_finalize`,
302+
`agent_end`, or `before_agent_run`) must set:
285303

286304
```json
287305
{

‎docs/tools/plugin.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -406,8 +406,9 @@ do not run in live chat traffic, check these first:
406406
containers, PID 1 may only be a supervisor; restart or signal the child
407407
`openclaw gateway run` process.
408408
- Use `openclaw plugins inspect <id> --runtime --json` to confirm hook registrations and
409-
diagnostics. Non-bundled conversation hooks such as `llm_input`,
410-
`llm_output`, `before_agent_finalize`, and `agent_end` need
409+
diagnostics. Non-bundled conversation hooks such as `before_model_resolve`,
410+
`before_agent_reply`, `before_agent_run`, `llm_input`, `llm_output`,
411+
`before_agent_finalize`, and `agent_end` need
411412
`plugins.entries.<id>.hooks.allowConversationAccess=true`.
412413
- For model switching, prefer `before_model_resolve`. It runs before model
413414
resolution for agent turns; `llm_output` only runs after a model attempt

‎extensions/diagnostics-otel/src/service.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -646,6 +646,34 @@ describe("diagnostics-otel service", () => {
646646
await service.stop?.(ctx);
647647
});
648648

649+
test("records hook-blocked run metrics with safe blocker originator", async () => {
650+
const service = createDiagnosticsOtelService();
651+
const ctx = createOtelContext(OTEL_TEST_ENDPOINT, { traces: true, metrics: true });
652+
await service.start(ctx);
653+
654+
emitDiagnosticEvent({
655+
type: "run.completed",
656+
runId: "run-1",
657+
provider: "openai",
658+
model: "gpt-5.4",
659+
outcome: "blocked",
660+
blockedBy: "policy-plugin",
661+
durationMs: 100,
662+
});
663+
await flushDiagnosticEvents();
664+
665+
expect(telemetryState.histograms.get("openclaw.run.duration_ms")?.record).toHaveBeenCalledWith(
666+
100,
667+
expect.objectContaining({
668+
"openclaw.outcome": "blocked",
669+
"openclaw.blocked_by": "policy-plugin",
670+
}),
671+
);
672+
expect(JSON.stringify(telemetryState)).not.toContain("matched secret prompt");
673+
674+
await service.stop?.(ctx);
675+
});
676+
649677
test("honors disabled traces when an OpenTelemetry SDK is preloaded", async () => {
650678
process.env.OPENCLAW_OTEL_PRELOADED = "1";
651679
const service = createDiagnosticsOtelService();

‎extensions/diagnostics-otel/src/service.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1665,6 +1665,9 @@ export function createDiagnosticsOtelService(): OpenClawPluginService {
16651665
if (evt.channel) {
16661666
attrs["openclaw.channel"] = evt.channel;
16671667
}
1668+
if (evt.blockedBy) {
1669+
attrs["openclaw.blocked_by"] = lowCardinalityAttr(evt.blockedBy, "unknown");
1670+
}
16681671
durationHistogram.record(evt.durationMs, attrs);
16691672
if (!tracesEnabled) {
16701673
return;
@@ -1673,6 +1676,9 @@ export function createDiagnosticsOtelService(): OpenClawPluginService {
16731676
"openclaw.outcome": evt.outcome,
16741677
};
16751678
addRunAttrs(spanAttrs, evt);
1679+
if (evt.blockedBy) {
1680+
spanAttrs["openclaw.blocked_by"] = lowCardinalityAttr(evt.blockedBy, "unknown");
1681+
}
16761682
if (evt.errorCategory) {
16771683
spanAttrs["openclaw.errorCategory"] = lowCardinalityAttr(evt.errorCategory, "other");
16781684
}

‎extensions/diagnostics-prometheus/src/service.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,37 @@ describe("diagnostics-prometheus service", () => {
4343
expect(rendered).not.toContain("session-should-not-export");
4444
});
4545

46+
it("records hook-blocked run metrics with safe blocker originator only", () => {
47+
const store = __test__.createPrometheusMetricStore();
48+
49+
__test__.recordDiagnosticEvent(
50+
store,
51+
{
52+
...baseEvent(),
53+
type: "run.completed",
54+
runId: "run-should-not-export",
55+
sessionKey: "session-should-not-export",
56+
provider: "openai",
57+
model: "gpt-5.4",
58+
channel: "slack",
59+
trigger: "message",
60+
durationMs: 250,
61+
outcome: "blocked",
62+
blockedBy: "policy-plugin",
63+
},
64+
trusted,
65+
);
66+
67+
const rendered = __test__.renderPrometheusMetrics(store);
68+
69+
expect(rendered).toContain(
70+
'openclaw_run_completed_total{blocked_by="policy-plugin",channel="slack",model="gpt-5.4",outcome="blocked",provider="openai",trigger="message"} 1',
71+
);
72+
expect(rendered).not.toContain("run-should-not-export");
73+
expect(rendered).not.toContain("session-should-not-export");
74+
expect(rendered).not.toContain("matched secret prompt");
75+
});
76+
4677
it("drops untrusted plugin-emitted diagnostic events", () => {
4778
const store = __test__.createPrometheusMetricStore();
4879

0 commit comments

Comments
 (0)