Repository navigation
fix(plugins): let hooks see the verified paired device that sent a turn - #200664
Conversation
A turn sent over a device-authenticated Gateway connection carries the connection's verified device id only internally (ApprovalReviewerDeviceId, used to route approvals). Plugin hooks get senderId, which for an operator client is its declared client id, so a guard plugin cannot tell the user's own paired phone from any client that declares the same name. Expose that id read-only: requesterDeviceId on the agent hook context (user turns only, like senderId) and deviceId on the before_tool_call requester. Both come from the run's existing approvalReviewerDeviceId, which is set only from client.connect.device.id after the handshake verified the device signature and that the id matches its public key; chat.send params are a closed schema and cannot supply it.
|
🦞👀 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. |
|
Codex review: blocked before merge. What this changesExpose the originating Gateway connection’s verified device ID in agent and tool hook contexts. Example: Two paired phones both identify their client as openclaw-ios.
Review scores
ProductKind: Feature · Worth it: Needs a maintainer decision · Fix scope: Partial Merge readiness⛔ Blocked before merge - 1 item remains This PR supplies useful device identity that current main lacks, but CLI prompt hooks still omit it and the public SDK addition needs an owner decision. Priority: P2 Decision needed
Before merge
Findings
Tests
Agent review detailsHow this fits togetherThe Gateway admits a device-authenticated turn, carries its existing approval reviewer device ID into the agent run, and projects that identity into plugin hook contexts. flowchart LR
A[Paired client] --> B[Gateway device verification]
B --> C[Admitted run]
C --> D[Agent hook context]
C --> E[Tool requester context]
D --> F[Plugin hooks]
E --> F
Technical reviewBest possible solution: Approve the optional SDK shape and complete device propagation through the existing CLI prompt-context owner without introducing another identity source. Do we have a high-confidence way to reproduce the issue? Current-main source demonstrably drops device identity before hook delivery, and the contributor supplies matching Gateway observations; no target code was executed during this read-only review. Is this the best way to solve the issue? Reusing the admitted approval reviewer device ID is the smallest suitable approach, but the CLI prompt-context projection must join the same contract. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 5e6bbeddb9fb. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +20, Tests +67, Docs +7. Total +94 across 12 files. Added test files: 1. 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 (1 earlier review cycle)
Reviewed November 17, 2026, 1:17 PM ET / 18:17 UTC (Revision 2). |
…runtime Turns that run on the Codex app-server runtime built their agent hook context without the verified device id, so before_prompt_build and agent_end had no requesterDeviceId there even though tool hooks had requester.deviceId.
9b69b6a to
80af2ee
Compare
|
Added a run with a real model to the Evidence section. On @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
CLI backend turns built their before_prompt_build context from the channel and memory projections only, so a device-aware plugin saw no requesterDeviceId there. Take it from the shared identity projection, which keeps the user-trigger rule. Also update the MCP grant-transfer expectation for the requester device id, and drop the gateway-client-identity case that only re-tested an unchanged projection.
|
Fixed the CLI prompt-build gap in abe48fb. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Steering keeps the run's approval device, so hooks kept reporting the first device after a second device or a device-less source injected input. The injection owner now records each accepted human input's device by run, and hook dispatch withholds the device unless all of it came from the reported device. Adds a device allowlist example to the tool policy docs. Co-authored-by: obviyus <[email protected]>
Co-authored-by: Garry Tan <[email protected]> Co-authored-by: obviyus <[email protected]>
Co-authored-by: Garry Tan <[email protected]> Co-authored-by: obviyus <[email protected]>
Co-authored-by: obviyus <[email protected]>
Co-authored-by: Garry Tan <[email protected]> Co-authored-by: obviyus <[email protected]>
|
Thanks @garrytan, merged in 74e5127. Plugins can now gate hooks on the paired device that sent a turn. I pushed a small maintainer fix before landing:
I checked it end to end on an isolated Gateway with two paired devices, including an allowlist plugin. The scenario table is in the PR body. |
…rn (openclaw#200664) Related: openclaw#189600, openclaw#187952, openclaw#177713 ## What Problem This Solves A plugin hook can't tell which paired device sent a turn. The gateway already knows: every `chat.send` from a paired operator device runs with `ApprovalReviewerDeviceId` set from the connection's verified device (`client.connect.device.id`), and exec approvals are bound to it. But neither the agent hook context nor the tool requester context exposes it. What hooks do see, `senderId`, names the kind of client (for example `openclaw-ios`), not the device, so two phones running the same app look identical to a plugin. A plugin that wants to allow or refuse a turn based on which paired device sent it has no field to read. ## User Impact Plugins get the verified device id for turns a paired device sends: - agent hooks (`before_agent_run`, `before_prompt_build`, `agent_end`, …): `ctx.requesterDeviceId` - tool hooks (`before_tool_call`, …): `ctx.requester.deviceId` Both are optional and read-only. Both are set only from the authenticated connection, never from request params (`chat.send` still rejects unknown properties), and only for user-triggered turns. A device-less client (shared token, no device identity) gets neither field. Nothing changes for plugins that don't read them. ## Why This Change Was Made The id already exists on the run (`approvalReviewerDeviceId`, threaded into the embedded attempt for approval binding). This change copies it onto the two hook contexts at the points where they're built. It doesn't add a new source or a new trust decision: - `src/plugins/hook-agent-context.types.ts` / `hook-agent-context.ts`: `requesterDeviceId?` on `PluginHookAgentContext`, set by `buildAgentHookContextIdentityFields` from `approvalReviewerDeviceId` under the same `trigger === "user"` (or unset) rule that already governs `senderId` and `chatId`. - `src/agents/harness/hook-context.ts`: passes the attempt's `requesterDeviceId` through. - `extensions/codex/src/app-server/run-attempt-context.ts`: the Codex app-server runtime builds its own agent hook context, so it sets `requesterDeviceId` from the attempt's `approvalReviewerDeviceId` too. The shared builder still applies the user-trigger rule. - `src/agents/cli-runner/prepare-hook-context.ts`: CLI backend turns build their `before_prompt_build` context separately, so it takes `requesterDeviceId` from the shared identity projection (same user-trigger rule). The CLI's other hooks already used that projection. - `src/plugins/hook-tool-context.types.ts` / `src/agents/harness/host-requester.ts`: `readonly deviceId?` on the tool requester, set from `attempt.approvalReviewerDeviceId`. - Docs: `docs/plugins/hooks/tool-policy.md` and `docs/plugins/hooks/prompt-and-session.md`. - Tests: `src/plugins/hook-agent-context.test.ts`, `extensions/codex/src/app-server/run-attempt.auth-context.test.ts` (the Codex prompt and compaction hooks carry the id on a user turn and drop it on cron), a case in `src/agents/cli-runner/prepare.test.ts` (the CLI prompt-build hook receives it), and new `src/agents/harness/host-requester.test.ts`. `prepare-mcp.test-support.ts`'s grant-transfer case now expects `deviceId` on the tool requester. **How this relates to openclaw#189600.** That PR gives tool factories `toolContext.requesterProfile`, the verified Gateway *profile* (the person) behind an admitted Control UI turn, with a liveness check. This one gives hooks the verified *device* behind any paired device's turn, phones and native apps included, which have no profile and no Control UI session. They answer different questions (which person, which device) at different layers (tool factory, hooks), they touch none of the same files, and either can land first. If maintainers would rather have one requester-identity object, `deviceId` fits next to `requesterProfile` without changing this PR's meaning. Accepted edge cases: - Only user-triggered turns carry the id, the same as `senderId`. Cron, heartbeat and other system-triggered runs don't. - A run a plugin starts with `api.runtime.subagent.run` carries the id only when it's started inside the paired device's gateway-method request. That's when the in-process `agent` dispatch uses the device's connection. A run started from the plugin's own detached context runs as the plugin and carries none, which is correct: no device asked for it. - The id is the device that sent the turn. It isn't a person; for that, see openclaw#189600. ## Evidence **Real gateway with a real model.** Source build of this PR's head (80af2ee). The model was `openai/gpt-5.4-mini`, which runs on the Codex app-server runtime. Clients were OpenClaw's own `GatewayClient`, and a probe plugin logged every hook's context. Device ids are cut to 8 characters: | Case | `before_prompt_build` / `agent_end` | `before_tool_call` (every tool the model called) | |---|---|---| | a: paired device `openclaw-ios`/ui sends `chat.send` | `requesterDeviceId c74f633c…`, `senderId openclaw-ios` | `requester.deviceId c74f633c…` | | c: second paired device, same client id and display name | `requesterDeviceId 03d163a…` (its own) | `requester.deviceId 03d163a…` | | d: device-less `cli` (shared token) | no `requesterDeviceId`, `senderId cli` | no `requester.deviceId`, including on `device_probe_tool` | This run found a gap in this PR's first head (9449852). On the Codex runtime, tool hooks had the id but `before_prompt_build` and `agent_end` didn't, because that runtime builds its own agent hook context. The second commit fixes it. With the first commit's tree restored, the extended Codex test fails (`expected … to match object … requesterDeviceId: 'device-a'`). The stub-model runs below use the embedded runtime (`openai-completions` provider) and cover the request-param and pairing cases. Real gateway, source build of this change (6e198d5, before the rebase) against its parent on main (30c2ded), with a probe plugin that logs both hook contexts, OpenClaw's own `GatewayClient` and a local OpenAI-compatible stub model. No provider keys were set, and device ids are cut to 8 characters: | Case | This head | Base (30c2ded) | |---|---|---| | Paired device (`openclaw-ios`/ui) sends `chat.send` | `before_agent_run`: `requesterDeviceId bc313985…`; `before_tool_call` (`dispatch_action` and the inner plugin tool): `requester.deviceId bc313985…` | `senderId openclaw-ios` only; no device id anywhere | | Same device adds `requesterDeviceId` or `approvalReviewerDeviceId` to `chat.send` | `INVALID_REQUEST … unexpected property` (closed schema), no run | same | | Second device with the same client id and display name | sees its own id (`cc3b699f…`), never the first's | n/a | | Device-less client (`cli`, shared token) | no `requesterDeviceId`, no `requester.deviceId` | same | `grep -rl requesterDeviceId dist` finds nothing in the base build. The same change, backported onto 2026.11.4, was also run with a plugin whose gateway method starts `subagent.run` inside the device's request. The id was on every hook of the run, including hooks that fired after the device's socket had closed, and the run finished normally. Checks on this PR's head (abe48fb, on main d4684da): - Tests: 19 test files that touch the requester device or hook contexts (hook-agent-context, host-requester, Codex run-attempt.auth-context, native-hook-relay and dynamic-tools, CLI prepare, tool-authority and reliability, embedded attempt tool context, before-tool-call approval policy, plugin tool context, reply authority and others) pass, except one Codex `dynamic-tools` case ("bounds high-cardinality validation errors") that fails the same way on main d4684da. The new hook-agent-context, Codex and CLI assertions each fail with main's production line. - `pnpm tsgo:core` and `pnpm tsgo:extensions` pass. - oxlint and oxfmt are clean on the changed files, `git diff --check` is clean, and `check:test-lines-ratchet` passes (+49 net test lines, within the 400 allowance). - The local Codex autoreview (`--mode branch --engine codex --max-priority P2`) found nothing on the first commit. - On the change before the rebase (6e198d5), every `lint:tmp:*` script, `check:max-lines-ratchet`, `check:assertion-safety`, `check:test-timeout-race-ratchet` and `config:docs:check`/`config:schema:check` also passed. - Plugin SDK API diff: additive optional fields only (`PluginHookAgentContext.requesterDeviceId`, `PluginHookToolRequesterContext.deviceId`). Not run: the full test suite locally (CI covers it), the CLI runner path with a real model, and a real phone app. ## Maintainer fix **Bug found in review:** steering from device B into device A's active run kept reporting device A to hooks. A device allowlist then authorized B's input as A. **Fix:** - `src/plugins/hook-requester-device.ts` records the device of every human input accepted into a run. Hook dispatch withholds the device unless all input came from that device. A missing device is acceptable; a wrong device is not. - Talk steering (`talk.client.steer`) carries the verified caller device, so a client that steers its own run keeps its device. - Sync hooks (`tool_result_persist`, `before_message_write`) carry no device and are not projected. - Pure hook-selection helpers moved to `src/plugins/hook-registration-select.ts` to keep `hooks.ts` within the line cap. - Docs: steering caveat and a device allowlist example. **Real Gateway proof** (isolated Gateway, real model, two paired devices A and B, probe plugin logging the device each hook sees): | Scenario | Device the hook sees | |---|---| | `chat.send` from A | A | | B steers into A's run, before fix | A (wrong) | | B steers into A's run, after fix | none | | A steers its own run | A | | Collect from A and B | separate runs, each its own device | | Restart resume | none | | Revoke A mid-run | run cancelled, `agent_end` shows A | | Subagent / `sessions_send` / `tools.invoke` from B | none | | Allowlist plugin (allow A only) | A's run reaches `session_status`; B's run is blocked at `dispatch_action` | Checked from source only: retries and fallback reuse the same runId and input; compaction keeps the runId; cron and side questions carry no device; MCP HTTP grants carry the device and runId. Regression tests (red before, green after): `src/auto-reply/reply/message-injection-requester-device.test.ts`, `src/agents/cli-runner/prepare-hook-context.test.ts`, `src/talk/agent-run-control.test.ts`. Co-authored-by: Ayaan Zaidi <[email protected]>
…run reports (#201503) Related: #200664, #152204 ## What Problem This Solves When an `exec` call goes to the background (`yieldMs`), its completion later runs as its own agent turn, with `trigger: "event"` and `inputProvenance: { kind: "internal_system", sourceTool: "exec" }`. Plugin hooks on that run have no field naming the turn that started the command. `senderId`, `chatId` and `requesterDeviceId` (#200664) are set only for `trigger: "user"`, so they're absent here. The trace can't be used to recover the starter either. When the session is busy, the completion runs after the turn that was running when the command finished, and its trace is that turn's trace. A plugin that follows the trace gets the wrong turn. ## User Impact A plugin that applies a rule per requester, such as gating a tool call on who asked for it, has two bad options on a completion run today. It can treat every completion as unknown, which blocks legitimate follow-up work, or it can guess, which can attribute the work to whoever happened to be talking at the time. With this change, hooks on that run get `ctx.execRequestOwners`, which names the turn that started the command. Nothing changes for plugins that don't read the field. ## Why This Change Was Made The host already keeps this ownership. The completion run inherits the starting request's exec owners in `src/infra/exec-request-context.ts`. This change exposes a read-only copy of those records on the hook context and adds no new bookkeeping: - `readInheritedExecRequestOwners(runId)` returns one frozen `{ runId, sessionKey?, sessionId?, ownerDeviceId? }` entry per inherited owner. `runId` is the run that called the tool, not a later continuation. Owners the run created for its own request are left out. The function returns `undefined`, never an empty array, when the run continues no other request or the run id isn't the current run. - `buildAgentHookContextIdentityFields` takes `runId` and always adds the field, whatever the trigger. So every agent hook context built through it gets the field without per-builder edits. The CLI runner's prepared hook context passes it along. - The Codex harness needs no change of its own: its prompt, lifecycle and compaction hooks go through the shared `buildAgentHookContext`, which calls the same identity builder, and its dynamic tools go through the shared `before_tool_call` wrapper. No plugin SDK export is added. - `before_tool_call` gets the same field through `PluginHookToolContext`. - The field comes only from the host's exec records, and the array and its entries are frozen. It is ancestry metadata only: the type doc says it grants the run none of the starter's authority or approvals. ## Evidence Head: 30f0284. The first commit adds the field. The second follows the first review: it removes the Codex projection and the SDK export, and routes the tests through the shared builder. **Real model, real exec, busy session.** I built this head's package with `node scripts/package-openclaw-for-docker.mjs` (`OpenClaw 2026.11.5 (30f0284)`) and ran a loopback gateway with `openai/gpt-5.4-mini`. A small plugin logs each hook's `ctx`, and a paired-device operator client sends `chat.send`. Device ids are masked to their last 4 characters. 1. Run A: "Use the exec tool to run exactly: sleep 30; echo a-done -- set yieldMs to 1000 so it keeps running in the background…". The model called `exec`, the command yielded, and run A ended. 2. Run B, sent once A had ended: "Use the exec tool to run exactly: sleep 40; echo b-done -- in the foreground…". This kept the session busy while A's command finished. 3. When B ended, the completion ran as its own turn (`trigger: "event"`, `sourceTool: "exec"`): ``` 23:50:03 before_agent_run real-b-… user owners=ABSENT 23:50:47 agent_end real-b-… user owners=ABSENT 23:50:48 before_prompt_build 528f2655… event exec owners=[{"runId":"real-a-…","sessionKey":"agent:main:real-busy2","sessionId":"70c717a4","ownerDeviceId":"..73f0"}] 23:50:48 before_agent_run 528f2655… event exec owners=[same] 23:50:52 before_agent_finalize 528f2655… event owners=[same] 23:50:52 agent_end 528f2655… event owners=[same] trace ids: run A …595ca, run B …bbb48, completion …bbb48 ``` The completion's trace is run B's, and `execRequestOwners` names run A, the run that started the command. The field is absent on A's and B's own hooks. **Mock model, more cases** (first head 318096f; the agent hook path is the same at this head). With an OpenAI-shaped mock that calls `exec` with `yieldMs: 1000`: - idle: the completion names its starter on before_prompt_build, before_agent_run, before_tool_call, before_agent_finalize and agent_end; - busy: same result as the real-model run; - two overlapping execs: two completion runs, each naming its own starter. **Unit tests** (`src/plugins/hook-agent-context.test.ts`, 5 new). They cover idle, two overlapping execs, the busy-session case, before_tool_call matching the agent hooks, and absence outside a run. - On base a4be1ae with the source changes reverted, 5 fail. The idle, overlap and busy tests fail on the missing field through the existing `buildAgentHookContextIdentityFields` (for example `expected {} to deeply equal { execRequestOwners: [ … ] }`). The other two fail because the tool-context helper is missing. - On this head, 11 pass. **Checks on this head:** - `pnpm tsgo:core` and `pnpm tsgo:extensions` pass. - `oxlint` and `oxfmt --check` are clean on the changed files. - `check:test-lines-ratchet`, `check:max-lines-ratchet`, `check:assertion-safety`, `lint:tmp:export-name-collisions` and `lint:tmp:tsgo-core-boundary` pass. - `pnpm plugin-sdk:api:diff --base a4be1ae --head HEAD` exits 0 (digest `efb88881`). The change is one optional context field, with no new function export. - On the first head, every other `lint:tmp:*` script passed, along with `lint:kysely`, `check:database-worker-ratchet`, `check:test-timeout-race-ratchet`, `check:temp-path-guardrails`, `check:database-first-legacy-stores` and `git diff --check`. The second commit touches only the four files above. ## Accepted edge cases - `after_tool_call` and hooks outside agent runs (`reply_payload_sending`, `message_sending`, `before_dispatch`) don't carry the field. The real run shows this. - `ownerDeviceId` is left out when the starting connection had no verified paired device, for example a shared-token client with no device identity. - One completion run that drains two owners returns two entries. The unit test covers this, but in the real run the two overlapping execs completed as two separate runs. - The subagent-session heartbeat wake (trigger `heartbeat`, `sourceTool: "exec"`), the CLI runner and the Codex harness reach the same shared builders and are covered by types and unit tests. I didn't run them end to end. ## Maintainer fix Three repairs before landing: 1. **Wrong device after steering.** If device B steered the run that started a command, the completion still reported `ownerDeviceId: A`. The existing #200664 projection in `src/plugins/hook-requester-device.ts` now covers `execRequestOwners` too: an owner's device is dropped once its run held input from another source. One owner, no second store. Regression test: `message-injection-requester-device.test.ts` fails at `30f0284` and passes after. 2. **Run-id comparisons.** `readInheritedExecRequestOwners` compared run ids, which the session-identity ratchet forbids (`exec-request-context.ts` 28 > 24). The turn now records `continues`, which the event-run owner (`runAgentTurnWithOutcome`) sets. 3. **Own owners reported as ancestry.** A run that re-enters with its own captured owners also passes owners. With the flag tied to the presence of owners, every user run named itself. The flag is now set only at the event-run call site. Regression test in `hook-agent-context.test.ts`: fails at `fa32ed0` and passes after. **Gateway E2E** (dist build at `fb2cbaf`, two paired devices A and B, probe plugin logging `ctx.execRequestOwners`, real `openai/gpt-5.4-mini` turns): | Scenario | Completion run sees | |---|---| | A starts `sleep 15` in the background, session idle | `[{runId: A's run, ownerDeviceId: A}]` | | A starts `sleep 30` in the background, B runs a 25 s turn, completion lands after B | `[{runId: A's run, ownerDeviceId: A}]` (not B's run) | | B steers A's run, and that run starts the background command | `[{runId: A's run}]`, device withheld | | Ordinary user runs (A and B) | no `execRequestOwners` | Co-authored-by: Ayaan Zaidi <[email protected]>
…run reports (openclaw#201503) Related: openclaw#200664, openclaw#152204 ## What Problem This Solves When an `exec` call goes to the background (`yieldMs`), its completion later runs as its own agent turn, with `trigger: "event"` and `inputProvenance: { kind: "internal_system", sourceTool: "exec" }`. Plugin hooks on that run have no field naming the turn that started the command. `senderId`, `chatId` and `requesterDeviceId` (openclaw#200664) are set only for `trigger: "user"`, so they're absent here. The trace can't be used to recover the starter either. When the session is busy, the completion runs after the turn that was running when the command finished, and its trace is that turn's trace. A plugin that follows the trace gets the wrong turn. ## User Impact A plugin that applies a rule per requester, such as gating a tool call on who asked for it, has two bad options on a completion run today. It can treat every completion as unknown, which blocks legitimate follow-up work, or it can guess, which can attribute the work to whoever happened to be talking at the time. With this change, hooks on that run get `ctx.execRequestOwners`, which names the turn that started the command. Nothing changes for plugins that don't read the field. ## Why This Change Was Made The host already keeps this ownership. The completion run inherits the starting request's exec owners in `src/infra/exec-request-context.ts`. This change exposes a read-only copy of those records on the hook context and adds no new bookkeeping: - `readInheritedExecRequestOwners(runId)` returns one frozen `{ runId, sessionKey?, sessionId?, ownerDeviceId? }` entry per inherited owner. `runId` is the run that called the tool, not a later continuation. Owners the run created for its own request are left out. The function returns `undefined`, never an empty array, when the run continues no other request or the run id isn't the current run. - `buildAgentHookContextIdentityFields` takes `runId` and always adds the field, whatever the trigger. So every agent hook context built through it gets the field without per-builder edits. The CLI runner's prepared hook context passes it along. - The Codex harness needs no change of its own: its prompt, lifecycle and compaction hooks go through the shared `buildAgentHookContext`, which calls the same identity builder, and its dynamic tools go through the shared `before_tool_call` wrapper. No plugin SDK export is added. - `before_tool_call` gets the same field through `PluginHookToolContext`. - The field comes only from the host's exec records, and the array and its entries are frozen. It is ancestry metadata only: the type doc says it grants the run none of the starter's authority or approvals. ## Evidence Head: 30f0284. The first commit adds the field. The second follows the first review: it removes the Codex projection and the SDK export, and routes the tests through the shared builder. **Real model, real exec, busy session.** I built this head's package with `node scripts/package-openclaw-for-docker.mjs` (`OpenClaw 2026.11.5 (30f0284)`) and ran a loopback gateway with `openai/gpt-5.4-mini`. A small plugin logs each hook's `ctx`, and a paired-device operator client sends `chat.send`. Device ids are masked to their last 4 characters. 1. Run A: "Use the exec tool to run exactly: sleep 30; echo a-done -- set yieldMs to 1000 so it keeps running in the background…". The model called `exec`, the command yielded, and run A ended. 2. Run B, sent once A had ended: "Use the exec tool to run exactly: sleep 40; echo b-done -- in the foreground…". This kept the session busy while A's command finished. 3. When B ended, the completion ran as its own turn (`trigger: "event"`, `sourceTool: "exec"`): ``` 23:50:03 before_agent_run real-b-… user owners=ABSENT 23:50:47 agent_end real-b-… user owners=ABSENT 23:50:48 before_prompt_build 528f2655… event exec owners=[{"runId":"real-a-…","sessionKey":"agent:main:real-busy2","sessionId":"70c717a4","ownerDeviceId":"..73f0"}] 23:50:48 before_agent_run 528f2655… event exec owners=[same] 23:50:52 before_agent_finalize 528f2655… event owners=[same] 23:50:52 agent_end 528f2655… event owners=[same] trace ids: run A …595ca, run B …bbb48, completion …bbb48 ``` The completion's trace is run B's, and `execRequestOwners` names run A, the run that started the command. The field is absent on A's and B's own hooks. **Mock model, more cases** (first head 318096f; the agent hook path is the same at this head). With an OpenAI-shaped mock that calls `exec` with `yieldMs: 1000`: - idle: the completion names its starter on before_prompt_build, before_agent_run, before_tool_call, before_agent_finalize and agent_end; - busy: same result as the real-model run; - two overlapping execs: two completion runs, each naming its own starter. **Unit tests** (`src/plugins/hook-agent-context.test.ts`, 5 new). They cover idle, two overlapping execs, the busy-session case, before_tool_call matching the agent hooks, and absence outside a run. - On base fc26a47 with the source changes reverted, 5 fail. The idle, overlap and busy tests fail on the missing field through the existing `buildAgentHookContextIdentityFields` (for example `expected {} to deeply equal { execRequestOwners: [ … ] }`). The other two fail because the tool-context helper is missing. - On this head, 11 pass. **Checks on this head:** - `pnpm tsgo:core` and `pnpm tsgo:extensions` pass. - `oxlint` and `oxfmt --check` are clean on the changed files. - `check:test-lines-ratchet`, `check:max-lines-ratchet`, `check:assertion-safety`, `lint:tmp:export-name-collisions` and `lint:tmp:tsgo-core-boundary` pass. - `pnpm plugin-sdk:api:diff --base fc26a47 --head HEAD` exits 0 (digest `efb88881`). The change is one optional context field, with no new function export. - On the first head, every other `lint:tmp:*` script passed, along with `lint:kysely`, `check:database-worker-ratchet`, `check:test-timeout-race-ratchet`, `check:temp-path-guardrails`, `check:database-first-legacy-stores` and `git diff --check`. The second commit touches only the four files above. ## Accepted edge cases - `after_tool_call` and hooks outside agent runs (`reply_payload_sending`, `message_sending`, `before_dispatch`) don't carry the field. The real run shows this. - `ownerDeviceId` is left out when the starting connection had no verified paired device, for example a shared-token client with no device identity. - One completion run that drains two owners returns two entries. The unit test covers this, but in the real run the two overlapping execs completed as two separate runs. - The subagent-session heartbeat wake (trigger `heartbeat`, `sourceTool: "exec"`), the CLI runner and the Codex harness reach the same shared builders and are covered by types and unit tests. I didn't run them end to end. ## Maintainer fix Three repairs before landing: 1. **Wrong device after steering.** If device B steered the run that started a command, the completion still reported `ownerDeviceId: A`. The existing openclaw#200664 projection in `src/plugins/hook-requester-device.ts` now covers `execRequestOwners` too: an owner's device is dropped once its run held input from another source. One owner, no second store. Regression test: `message-injection-requester-device.test.ts` fails at `30f0284` and passes after. 2. **Run-id comparisons.** `readInheritedExecRequestOwners` compared run ids, which the session-identity ratchet forbids (`exec-request-context.ts` 28 > 24). The turn now records `continues`, which the event-run owner (`runAgentTurnWithOutcome`) sets. 3. **Own owners reported as ancestry.** A run that re-enters with its own captured owners also passes owners. With the flag tied to the presence of owners, every user run named itself. The flag is now set only at the event-run call site. Regression test in `hook-agent-context.test.ts`: fails at `fa32ed0` and passes after. **Gateway E2E** (dist build at `fb2cbaf`, two paired devices A and B, probe plugin logging `ctx.execRequestOwners`, real `openai/gpt-5.4-mini` turns): | Scenario | Completion run sees | |---|---| | A starts `sleep 15` in the background, session idle | `[{runId: A's run, ownerDeviceId: A}]` | | A starts `sleep 30` in the background, B runs a 25 s turn, completion lands after B | `[{runId: A's run, ownerDeviceId: A}]` (not B's run) | | B steers A's run, and that run starts the background command | `[{runId: A's run}]`, device withheld | | Ordinary user runs (A and B) | no `execRequestOwners` | Co-authored-by: Ayaan Zaidi <[email protected]>
Related: #189600, #187952, #177713
What Problem This Solves
A plugin hook can't tell which paired device sent a turn. The gateway already knows: every
chat.sendfrom a paired operator device runs withApprovalReviewerDeviceIdset from the connection's verified device (client.connect.device.id), and exec approvals are bound to it. But neither the agent hook context nor the tool requester context exposes it. What hooks do see,senderId, names the kind of client (for exampleopenclaw-ios), not the device, so two phones running the same app look identical to a plugin. A plugin that wants to allow or refuse a turn based on which paired device sent it has no field to read.User Impact
Plugins get the verified device id for turns a paired device sends:
before_agent_run,before_prompt_build,agent_end, …):ctx.requesterDeviceIdbefore_tool_call, …):ctx.requester.deviceIdBoth are optional and read-only. Both are set only from the authenticated connection, never from request params (
chat.sendstill rejects unknown properties), and only for user-triggered turns. A device-less client (shared token, no device identity) gets neither field. Nothing changes for plugins that don't read them.Why This Change Was Made
The id already exists on the run (
approvalReviewerDeviceId, threaded into the embedded attempt for approval binding). This change copies it onto the two hook contexts at the points where they're built. It doesn't add a new source or a new trust decision:src/plugins/hook-agent-context.types.ts/hook-agent-context.ts:requesterDeviceId?onPluginHookAgentContext, set bybuildAgentHookContextIdentityFieldsfromapprovalReviewerDeviceIdunder the sametrigger === "user"(or unset) rule that already governssenderIdandchatId.src/agents/harness/hook-context.ts: passes the attempt'srequesterDeviceIdthrough.extensions/codex/src/app-server/run-attempt-context.ts: the Codex app-server runtime builds its own agent hook context, so it setsrequesterDeviceIdfrom the attempt'sapprovalReviewerDeviceIdtoo. The shared builder still applies the user-trigger rule.src/agents/cli-runner/prepare-hook-context.ts: CLI backend turns build theirbefore_prompt_buildcontext separately, so it takesrequesterDeviceIdfrom the shared identity projection (same user-trigger rule). The CLI's other hooks already used that projection.src/plugins/hook-tool-context.types.ts/src/agents/harness/host-requester.ts:readonly deviceId?on the tool requester, set fromattempt.approvalReviewerDeviceId.docs/plugins/hooks/tool-policy.mdanddocs/plugins/hooks/prompt-and-session.md.src/plugins/hook-agent-context.test.ts,extensions/codex/src/app-server/run-attempt.auth-context.test.ts(the Codex prompt and compaction hooks carry the id on a user turn and drop it on cron), a case insrc/agents/cli-runner/prepare.test.ts(the CLI prompt-build hook receives it), and newsrc/agents/harness/host-requester.test.ts.prepare-mcp.test-support.ts's grant-transfer case now expectsdeviceIdon the tool requester.How this relates to #189600. That PR gives tool factories
toolContext.requesterProfile, the verified Gateway profile (the person) behind an admitted Control UI turn, with a liveness check. This one gives hooks the verified device behind any paired device's turn, phones and native apps included, which have no profile and no Control UI session. They answer different questions (which person, which device) at different layers (tool factory, hooks), they touch none of the same files, and either can land first. If maintainers would rather have one requester-identity object,deviceIdfits next torequesterProfilewithout changing this PR's meaning.Accepted edge cases:
senderId. Cron, heartbeat and other system-triggered runs don't.api.runtime.subagent.runcarries the id only when it's started inside the paired device's gateway-method request. That's when the in-processagentdispatch uses the device's connection. A run started from the plugin's own detached context runs as the plugin and carries none, which is correct: no device asked for it.Evidence
Real gateway with a real model. Source build of this PR's head (80af2ee). The model was
openai/gpt-5.4-mini, which runs on the Codex app-server runtime. Clients were OpenClaw's ownGatewayClient, and a probe plugin logged every hook's context. Device ids are cut to 8 characters:before_prompt_build/agent_endbefore_tool_call(every tool the model called)openclaw-ios/ui sendschat.sendrequesterDeviceId c74f633c…,senderId openclaw-iosrequester.deviceId c74f633c…requesterDeviceId 03d163ad…(its own)requester.deviceId 03d163ad…cli(shared token)requesterDeviceId,senderId clirequester.deviceId, including ondevice_probe_toolThis run found a gap in this PR's first head (9449852). On the Codex runtime, tool hooks had the id but
before_prompt_buildandagent_enddidn't, because that runtime builds its own agent hook context. The second commit fixes it. With the first commit's tree restored, the extended Codex test fails (expected … to match object … requesterDeviceId: 'device-a').The stub-model runs below use the embedded runtime (
openai-completionsprovider) and cover the request-param and pairing cases.Real gateway, source build of this change (6e198d5, before the rebase) against its parent on main (5fb2315), with a probe plugin that logs both hook contexts, OpenClaw's own
GatewayClientand a local OpenAI-compatible stub model. No provider keys were set, and device ids are cut to 8 characters:openclaw-ios/ui) sendschat.sendbefore_agent_run:requesterDeviceId bc313985…;before_tool_call(dispatch_actionand the inner plugin tool):requester.deviceId bc313985…senderId openclaw-iosonly; no device id anywhererequesterDeviceIdorapprovalReviewerDeviceIdtochat.sendINVALID_REQUEST … unexpected property(closed schema), no runcc3b699f…), never the first'scli, shared token)requesterDeviceId, norequester.deviceIdgrep -rl requesterDeviceId distfinds nothing in the base build.The same change, backported onto 2026.11.4, was also run with a plugin whose gateway method starts
subagent.runinside the device's request. The id was on every hook of the run, including hooks that fired after the device's socket had closed, and the run finished normally.Checks on this PR's head (abe48fb, on main bb45ba9):
dynamic-toolscase ("bounds high-cardinality validation errors") that fails the same way on main bb45ba9. The new hook-agent-context, Codex and CLI assertions each fail with main's production line.pnpm tsgo:coreandpnpm tsgo:extensionspass.git diff --checkis clean, andcheck:test-lines-ratchetpasses (+49 net test lines, within the 400 allowance).--mode branch --engine codex --max-priority P2) found nothing on the first commit.lint:tmp:*script,check:max-lines-ratchet,check:assertion-safety,check:test-timeout-race-ratchetandconfig:docs:check/config:schema:checkalso passed.PluginHookAgentContext.requesterDeviceId,PluginHookToolRequesterContext.deviceId).Not run: the full test suite locally (CI covers it), the CLI runner path with a real model, and a real phone app.
Maintainer fix
Bug found in review: steering from device B into device A's active run kept reporting device A to hooks. A device allowlist then authorized B's input as A.
Fix:
src/plugins/hook-requester-device.tsrecords the device of every human input accepted into a run. Hook dispatch withholds the device unless all input came from that device. A missing device is acceptable; a wrong device is not.talk.client.steer) carries the verified caller device, so a client that steers its own run keeps its device.tool_result_persist,before_message_write) carry no device and are not projected.src/plugins/hook-registration-select.tsto keephooks.tswithin the line cap.Real Gateway proof (isolated Gateway, real model, two paired devices A and B, probe plugin logging the device each hook sees):
chat.sendfrom Aagent_endshows Asessions_send/tools.invokefrom Bsession_status; B's run is blocked atdispatch_actionChecked from source only: retries and fallback reuse the same runId and input; compaction keeps the runId; cron and side questions carry no device; MCP HTTP grants carry the device and runId.
Regression tests (red before, green after):
src/auto-reply/reply/message-injection-requester-device.test.ts,src/agents/cli-runner/prepare-hook-context.test.ts,src/talk/agent-run-control.test.ts.