Skip to content

Commit 29cfd19

Browse files
authored
fix(memory): honor turn tool policy during automatic recall (#126482)
* fix(memory): bind prompt recall to turn tool policy * test(plugins): update hook contract inventory * fix(memory): bind recall to active run lifecycle * docs(plugins): define prompt authority contract * test(plugins): track prompt authority type guard * fix(plugins): revalidate prompt authority per handler
1 parent 53bd316 commit 29cfd19

32 files changed

Lines changed: 1226 additions & 415 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ extensions/acpx/src/service.ts 2
1111
extensions/acpx/src/state.ts 1
1212
extensions/active-memory/config.ts 4
1313
extensions/active-memory/doctor-contract-api.ts 3
14-
extensions/active-memory/index.ts 7
14+
extensions/active-memory/index.ts 6
1515
extensions/active-memory/query.ts 2
1616
extensions/active-memory/session.ts 4
1717
extensions/active-memory/transcript-result.ts 2

‎docs/plugins/hooks.md‎

Lines changed: 73 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,14 @@ observation side effects.
5757

5858
`api.on(name, handler, opts?)` accepts:
5959

60-
| Option | Effect |
61-
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
62-
| `matcher` | Non-empty list of canonical OpenClaw tool ids handled by `before_tool_call` or `after_tool_call`, such as `exec`, `apply_patch`, or `spawn_agent`. Omit to match all tools. Empty lists, wildcards, blanks, and provider-specific aliases are invalid. |
63-
| `priority` | Ordering; higher runs first. |
64-
| `registrationId` | Stable identity for one registration inside a plugin. Skill evaluators use it as `evaluatorId`; otherwise the plugin id is used. |
65-
| `timeoutMs` | Per-hook await budget. When it expires, OpenClaw stops awaiting that handler and moves on. It does not cancel the handler or its side effects. Omit to use the runner's default per-hook timeout. |
66-
| `eligibleTriggers` | For `before_agent_reply` only, limits host dispatch to one or more of `cron`, `heartbeat`, or `user`. |
60+
| Option | Effect |
61+
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
62+
| `matcher` | Non-empty list of canonical OpenClaw tool ids handled by `before_tool_call` or `after_tool_call`, such as `exec`, `apply_patch`, or `spawn_agent`. Omit to match all tools. Empty lists, wildcards, blanks, and provider-specific aliases are invalid. |
63+
| `priority` | Ordering; higher runs first. |
64+
| `registrationId` | Stable identity for one registration inside a plugin. Skill evaluators use it as `evaluatorId`; otherwise the plugin id is used. |
65+
| `timeoutMs` | Per-hook await budget. When it expires, OpenClaw stops awaiting that handler and moves on. It does not cancel the handler or its side effects. Omit to use the runner's default per-hook timeout. |
66+
| `eligibleTriggers` | For `before_agent_reply` only, limits host dispatch to one or more of `cron`, `heartbeat`, or `user`. |
67+
| `requiresToolAuthority` | For `before_prompt_build` only, runs the handler after the host finalizes the current turn's tool surface and supplies ephemeral `ctx.toolAuthority`. Use this for context retrieval that must follow tool policy. |
6768

6869
Trigger eligibility is enforced by the host before it invokes the handler. A
6970
hook registered with `eligibleTriggers: ["heartbeat", "cron"]` is therefore
@@ -135,16 +136,16 @@ observation-only.
135136

136137
**Agent turn**
137138

138-
| Hook | Purpose |
139-
| ------------------------------- | ---------------------------------------------------------------------------------------- |
140-
| `before_model_resolve` | Override provider or model before session messages load |
141-
| `agent_turn_prepare` | Consume queued plugin turn injections and add same-turn context before prompt hooks |
142-
| `before_prompt_build` | Add prompt context or narrow the current turn's submitted tool surface |
143-
| **`before_agent_run`** | Inspect the final prompt and session messages before model submission; can block the run |
144-
| **`before_agent_reply`** | Short-circuit the model turn with a synthetic reply or silence |
145-
| **`before_agent_finalize`** | Inspect the natural final answer and request one more model pass |
146-
| `agent_end` | Observe final messages, success state, and run duration |
147-
| `heartbeat_prompt_contribution` | Add heartbeat-only context for background monitor and lifecycle plugins |
139+
| Hook | Purpose |
140+
| ------------------------------- | ----------------------------------------------------------------------------------------------------------- |
141+
| `before_model_resolve` | Override provider or model before session messages load |
142+
| `agent_turn_prepare` | Consume queued plugin turn injections and add same-turn context before prompt hooks |
143+
| `before_prompt_build` | Add prompt context, narrow the current turn's submitted tools, or perform authorized post-policy enrichment |
144+
| **`before_agent_run`** | Inspect the final prompt and session messages before model submission; can block the run |
145+
| **`before_agent_reply`** | Short-circuit the model turn with a synthetic reply or silence |
146+
| **`before_agent_finalize`** | Inspect the natural final answer and request one more model pass |
147+
| `agent_end` | Observe final messages, success state, and run duration |
148+
| `heartbeat_prompt_contribution` | Add heartbeat-only context for background monitor and lifecycle plugins |
148149

149150
**Conversation observation**
150151

@@ -577,10 +578,65 @@ Use the phase-specific hooks for new plugins:
577578
dynamic tools are thread-scoped and Codex `turn/start` has no tool-surface
578579
override; use the embedded or Copilot runtime when a plugin requires this
579580
policy.
581+
- `before_prompt_build` with `{ requiresToolAuthority: true }`: runs in a
582+
second, post-policy phase. Use it when prompt enrichment reads data through
583+
a tool-backed capability and the same turn must be allowed to call that
584+
tool. See [Authorized prompt enrichment](#authorized-prompt-enrichment).
580585
- `heartbeat_prompt_contribution`: runs only for heartbeat turns and returns
581586
`prependContext` or `appendContext`. Intended for background monitors that
582587
need to summarize current state without changing user-initiated turns.
583588

589+
### Authorized prompt enrichment
590+
591+
Register `before_prompt_build` with `requiresToolAuthority: true` when a plugin
592+
must verify the finalized per-turn tool policy before retrieving context:
593+
594+
```typescript
595+
api.on(
596+
"before_prompt_build",
597+
async (event, ctx) => {
598+
const authority = ctx.toolAuthority;
599+
if (!authority?.allows("memory_search")) {
600+
return;
601+
}
602+
603+
const recalledContext = await recallForPrompt(event.prompt);
604+
authority.assertActive();
605+
return { prependContext: recalledContext };
606+
},
607+
{ requiresToolAuthority: true },
608+
);
609+
```
610+
611+
The host excludes this handler from the ordinary prompt-build phase. After all
612+
ordinary hooks and tool restrictions settle, a supported runtime invokes it
613+
with `ctx.toolAuthority` bound to that exact active turn and finalized tool
614+
surface. Embedded, CLI, Copilot, and Codex runtimes support this phase. If a
615+
runtime cannot prove the authority, it skips the handler.
616+
617+
Treat `toolAuthority` as an ephemeral capability:
618+
619+
- `allows(toolName)` checks a canonical tool id against the finalized surface
620+
and also verifies that the capability is still active.
621+
- `assertActive()` rejects after abort, cancellation, run replacement,
622+
lifecycle rotation, or hook dispatch completion. Call it after awaited work
623+
and before committing plugin-owned side effects.
624+
- `fingerprint` is opaque cache-partitioning input. It is not a bearer token or
625+
authorization proof; never persist, transmit, or compare it as authority.
626+
- Return only `prependContext` or `appendContext` from this phase. It cannot
627+
replace the system prompt or change `toolsAllow` after policy has settled.
628+
629+
The host revalidates authority after each awaited handler and discards stale
630+
enrichment. A retained `toolAuthority` object fails closed after dispatch.
631+
632+
This option requires a host that implements the post-policy phase. Published
633+
plugins must set `package.json` `openclaw.compat.pluginApi` to a range beginning
634+
with the first OpenClaw version they build against for this contract. Older
635+
hosts skip incompatible packages during discovery and reject incompatible
636+
installs or updates. Do not publish a package that uses this option while
637+
claiming compatibility with an older plugin API; an older host may otherwise
638+
treat an unknown option as an ordinary pre-policy hook.
639+
584640
`before_agent_run` runs after prompt construction and before any model input,
585641
including prompt-local image loading and `llm_input` observation. It receives
586642
the current user input as `prompt`, plus loaded session history in `messages`

0 commit comments

Comments
 (0)