Skip to content

Commit f3accc7

Browse files
authored
feat(plugins): add before agent finalize hook (#71765)
1 parent 727e0e0 commit f3accc7

24 files changed

Lines changed: 522 additions & 27 deletions
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
f5236ba3f34837485d1e319262d4d73ecd46ea8890d3f4c26a069834f376b796 config-baseline.json
2-
484b36513ecb4a13cc945c3916fbe5ac712b5e0ab2c4ffa2dc811758da4ec7a6 config-baseline.core.json
1+
15a3740b57d0c95f0c0963c1d0eff6d85ecdb8cb03960b4763e847f8a24551c0 config-baseline.json
2+
3c39a3a2008ce938886b600e9429a71921c1f9b00c64a16801f47d6d8d2ad7a8 config-baseline.core.json
33
7cd9c908f066c143eab2a201efbc9640f483ab28bba92ddeca1d18cc2b528bc3 config-baseline.channel.json
4-
17eb3f8887193579ff32e35f9bd520ba2bd6049e52ab18855c5d41fcbf195d83 config-baseline.plugin.json
4+
9e131d7734f8b9cc9e7f8af6cc6b6dc81c9971dc551fadbe66fb0d682173f32d config-baseline.plugin.json

‎docs/automation/hooks.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,11 @@ Each event includes: `type`, `action`, `sessionKey`, `timestamp`, `messages` (pu
126126

127127
**Compaction events**: `session:compact:before` includes `messageCount`, `tokenCount`. `session:compact:after` adds `compactedCount`, `summaryLength`, `tokensBefore`, `tokensAfter`.
128128

129+
`command:stop` observes the user issuing `/stop`; it is cancellation/command
130+
lifecycle, not an agent-finalization gate. Plugins that need to inspect a
131+
natural final answer and ask the agent for one more pass should use the typed
132+
plugin hook `before_agent_finalize` instead. See [Plugin hooks](/plugins/hooks).
133+
129134
## Hook discovery
130135

131136
Hooks are discovered from these directories, in order of increasing override precedence:

‎docs/cli/plugins.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,8 @@ For runtime hook debugging:
219219
from a module-loaded inspection pass.
220220
- `openclaw gateway status --deep --require-rpc` confirms the reachable Gateway,
221221
service/process hints, config path, and RPC health.
222-
- Non-bundled conversation hooks (`llm_input`, `llm_output`, `agent_end`) require
222+
- Non-bundled conversation hooks (`llm_input`, `llm_output`,
223+
`before_agent_finalize`, `agent_end`) require
223224
`plugins.entries.<id>.hooks.allowConversationAccess=true`.
224225

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

‎docs/gateway/configuration-reference.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ See [MCP](/cli/mcp#openclaw-as-an-mcp-client-registry) and
160160
- `plugins.entries.<id>.apiKey`: plugin-level API key convenience field (when supported by the plugin).
161161
- `plugins.entries.<id>.env`: plugin-scoped env var map.
162162
- `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.
163-
- `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`, and `agent_end`.
163+
- `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`.
164164
- `plugins.entries.<id>.subagent.allowModelOverride`: explicitly trust this plugin to request per-run `provider` and `model` overrides for background subagent runs.
165165
- `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.
166166
- `plugins.entries.<id>.config`: plugin-defined config object (validated by native OpenClaw plugin schema when available).

‎docs/plugins/codex-harness.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ These are in-process OpenClaw hooks, not Codex `hooks.json` command hooks:
3434
- `llm_input`, `llm_output`
3535
- `before_tool_call`, `after_tool_call`
3636
- `before_message_write` for mirrored transcript records
37+
- `before_agent_finalize` through Codex `Stop` relay
3738
- `agent_end`
3839

3940
Plugins can also register runtime-neutral tool-result middleware to rewrite
@@ -583,10 +584,10 @@ The Codex harness has three hook layers:
583584

584585
OpenClaw does not use project or global Codex `hooks.json` files to route
585586
OpenClaw plugin behavior. For the supported native tool and permission bridge,
586-
OpenClaw injects per-thread Codex config for `PreToolUse`, `PostToolUse`, and
587-
`PermissionRequest`. Other Codex hooks such as `SessionStart`,
588-
`UserPromptSubmit`, and `Stop` remain Codex-level controls; they are not exposed
589-
as OpenClaw plugin hooks in the v1 contract.
587+
OpenClaw injects per-thread Codex config for `PreToolUse`, `PostToolUse`,
588+
`PermissionRequest`, and `Stop`. Other Codex hooks such as `SessionStart` and
589+
`UserPromptSubmit` remain Codex-level controls; they are not exposed as
590+
OpenClaw plugin hooks in the v1 contract.
590591

591592
For OpenClaw dynamic tools, OpenClaw executes the tool after Codex asks for the
592593
call, so OpenClaw fires the plugin and middleware behavior it owns in the
@@ -622,6 +623,7 @@ Supported in Codex runtime v1:
622623
| Context engine lifecycle | Supported | Assemble, ingest or after-turn maintenance, and context-engine compaction coordination run for Codex turns. |
623624
| Dynamic tool hooks | Supported | `before_tool_call`, `after_tool_call`, and tool-result middleware run around OpenClaw-owned dynamic tools. |
624625
| Lifecycle hooks | Supported as adapter observations | `llm_input`, `llm_output`, `agent_end`, `before_compaction`, and `after_compaction` fire with honest Codex-mode payloads. |
626+
| Final-answer revision gate | Supported through the native hook relay | Codex `Stop` is relayed to `before_agent_finalize`; `revise` asks Codex for one more model pass before finalization. |
625627
| Native shell, patch, and MCP block or observe | Supported through the native hook relay | Codex `PreToolUse` and `PostToolUse` are relayed for committed native tool surfaces, including MCP payloads on Codex app-server `0.125.0` or newer. Blocking is supported; argument rewriting is not. |
626628
| Native permission policy | Supported through the native hook relay | Codex `PermissionRequest` can be routed through OpenClaw policy where the runtime exposes it. If OpenClaw returns no decision, Codex continues through its normal guardian or user approval path. |
627629
| App-server trajectory capture | Supported | OpenClaw records the request it sent to app-server and the app-server notifications it receives. |
@@ -635,7 +637,6 @@ Not supported in Codex runtime v1:
635637
| `tool_result_persist` for Codex-native tool records | That hook transforms OpenClaw-owned transcript writes, not Codex-native tool records. | Could mirror transformed records, but canonical rewrite needs Codex support. |
636638
| Rich native compaction metadata | OpenClaw observes compaction start and completion, but does not receive a stable kept/dropped list, token delta, or summary payload. | Needs richer Codex compaction events. |
637639
| Compaction intervention | Current OpenClaw compaction hooks are notification-level in Codex mode. | Add Codex pre/post compaction hooks if plugins need to veto or rewrite native compaction. |
638-
| Stop or final-answer gating | Codex has native stop hooks, but OpenClaw does not expose final-answer gating as a v1 plugin contract. | Future opt-in primitive with loop and timeout safeguards. |
639640
| Byte-for-byte model API request capture | OpenClaw can capture app-server requests and notifications, but Codex core builds the final OpenAI API request internally. | Needs a Codex model-request tracing event or debug API. |
640641

641642
## Tools, media, and compaction

‎docs/plugins/hooks.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ observation-only.
6464
- `before_prompt_build` — add dynamic context or system-prompt text before the model call
6565
- `before_agent_start` — compatibility-only combined phase; prefer the two hooks above
6666
- **`before_agent_reply`** — short-circuit the model turn with a synthetic reply or silence
67+
- **`before_agent_finalize`** — inspect the natural final answer and request one more model pass
6768
- `agent_end` — observe final messages, success state, and run duration
6869

6970
**Conversation observation**
@@ -185,7 +186,16 @@ bodies, or provider request IDs. These hooks include stable metadata such as
185186
`durationMs`/`outcome`, and `upstreamRequestIdHash` when OpenClaw can derive a
186187
bounded provider request-id hash.
187188

188-
Non-bundled plugins that need `llm_input`, `llm_output`, or `agent_end` must set:
189+
`before_agent_finalize` runs only when a harness is about to accept a natural
190+
final assistant answer. It is not the `/stop` cancellation path and does not
191+
run when the user aborts a turn. Return `{ action: "revise", reason }` to ask
192+
the harness for one more model pass before finalization, `{ action:
193+
"finalize", reason? }` to force finalization, or omit a result to continue.
194+
Codex native `Stop` hooks are relayed into this hook as OpenClaw
195+
`before_agent_finalize` decisions.
196+
197+
Non-bundled plugins that need `llm_input`, `llm_output`,
198+
`before_agent_finalize`, or `agent_end` must set:
189199

190200
```json
191201
{

‎docs/tools/acp-agents.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,12 @@ dynamic tools still execute through OpenClaw, while Codex-native tools such as
6565
shell/apply-patch execute inside Codex. For Codex-native tool events, OpenClaw
6666
injects a per-turn native hook relay so plugin hooks can block
6767
`before_tool_call`, observe `after_tool_call`, and route Codex
68-
`PermissionRequest` events through OpenClaw approvals. The v1 relay is
69-
deliberately conservative: it does not mutate Codex-native tool arguments,
70-
rewrite Codex thread records, or gate final answers/Stop hooks. Use explicit
71-
ACP only when you want the ACP runtime/session model. The embedded Codex support
72-
boundary is documented in the
68+
`PermissionRequest` events through OpenClaw approvals. Codex `Stop` hooks are
69+
relayed to OpenClaw `before_agent_finalize`, where plugins can request one more
70+
model pass before Codex finalizes its answer. The relay remains deliberately
71+
conservative: it does not mutate Codex-native tool arguments or rewrite Codex
72+
thread records. Use explicit ACP only when you want the ACP runtime/session
73+
model. The embedded Codex support boundary is documented in the
7374
[Codex harness v1 support contract](/plugins/codex-harness#v1-support-contract).
7475

7576
Natural-language triggers that should route to the ACP runtime:

‎docs/tools/plugin.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ do not run in live chat traffic, check these first:
223223
`openclaw gateway run` process.
224224
- Use `openclaw plugins inspect <id> --json` to confirm hook registrations and
225225
diagnostics. Non-bundled conversation hooks such as `llm_input`,
226-
`llm_output`, and `agent_end` need
226+
`llm_output`, `before_agent_finalize`, and `agent_end` need
227227
`plugins.entries.<id>.hooks.allowConversationAccess=true`.
228228
- For model switching, prefer `before_model_resolve`. It runs before model
229229
resolution for agent turns; `llm_output` only runs after a model attempt

‎extensions/codex/src/app-server/native-hook-relay.test.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,25 @@ describe("Codex native hook relay config", () => {
5959
],
6060
},
6161
],
62+
"hooks.Stop": [
63+
{
64+
matcher: null,
65+
hooks: [
66+
{
67+
type: "command",
68+
command:
69+
"openclaw hooks relay --provider codex --relay-id relay-1 --event before_agent_finalize",
70+
timeout: 7,
71+
async: false,
72+
statusMessage: "OpenClaw native hook relay",
73+
},
74+
],
75+
},
76+
],
6277
});
6378
expect(JSON.stringify(config)).not.toContain("timeoutSec");
6479
expect(config).not.toHaveProperty("hooks.SessionStart");
6580
expect(config).not.toHaveProperty("hooks.UserPromptSubmit");
66-
expect(config).not.toHaveProperty("hooks.Stop");
6781
});
6882

6983
it("includes only requested hook events", () => {
@@ -108,6 +122,7 @@ describe("Codex native hook relay config", () => {
108122
"hooks.PreToolUse": [],
109123
"hooks.PostToolUse": [],
110124
"hooks.PermissionRequest": [],
125+
"hooks.Stop": [],
111126
});
112127
});
113128
});
@@ -119,7 +134,7 @@ function createRelay(): NativeHookRelayRegistrationHandle {
119134
sessionId: "session-1",
120135
sessionKey: "agent:main:session-1",
121136
runId: "run-1",
122-
allowedEvents: ["pre_tool_use", "post_tool_use", "permission_request"],
137+
allowedEvents: ["pre_tool_use", "post_tool_use", "permission_request", "before_agent_finalize"],
123138
expiresAtMs: Date.now() + 1000,
124139
commandForEvent: (event) =>
125140
`openclaw hooks relay --provider codex --relay-id relay-1 --event ${event}`,

‎extensions/codex/src/app-server/native-hook-relay.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,16 @@ export const CODEX_NATIVE_HOOK_RELAY_EVENTS = [
88
"pre_tool_use",
99
"post_tool_use",
1010
"permission_request",
11+
"before_agent_finalize",
1112
] as const satisfies readonly NativeHookRelayEvent[];
1213

13-
type CodexHookEventName = "PreToolUse" | "PostToolUse" | "PermissionRequest";
14+
type CodexHookEventName = "PreToolUse" | "PostToolUse" | "PermissionRequest" | "Stop";
1415

1516
const CODEX_HOOK_EVENT_BY_NATIVE_EVENT: Record<NativeHookRelayEvent, CodexHookEventName> = {
1617
pre_tool_use: "PreToolUse",
1718
post_tool_use: "PostToolUse",
1819
permission_request: "PermissionRequest",
20+
before_agent_finalize: "Stop",
1921
};
2022

2123
export function buildCodexNativeHookRelayConfig(params: {
@@ -53,6 +55,7 @@ export function buildCodexNativeHookRelayDisabledConfig(): JsonObject {
5355
"hooks.PreToolUse": [],
5456
"hooks.PostToolUse": [],
5557
"hooks.PermissionRequest": [],
58+
"hooks.Stop": [],
5659
};
5760
}
5861

0 commit comments

Comments
 (0)