Skip to content

refactor(gateway): check agent runtime authority once at request start - #201697

Merged
obviyus merged 8 commits into
mainfrom
refactor/check-once-runtime-guard
Nov 19, 2026
Merged

obviyus merged 8 commits into
mainfrom
refactor/check-once-runtime-guard

Conversation

@obviyus

@obviyus obviyus commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

What problem this solves

An agent run's Gateway requests re-checked the run's authority many times while one request ran. The checks ran before the queue, at handler start, inside handlers (cron, secrets, sessions.create, message send, themes, ui.command, MCP events) and again on every response. When the run's authority closed partway through, a request that had already started was refused with agent runtime authority is no longer active. On the WebSocket path the Gateway also closed the whole client connection (4001). An effect that had already committed could then be reported as a failure.

The repo's rule (AGENTS.md, "Choose good compromises") is to check authority one time, when work starts. Revocation applies to the next request, and a started request may finish.

Change

  • One check, at the shared pre-dispatch admission owner authorizeGatewayRequestPreDispatch. Both WebSocket and in-process requests pass through it. A request whose run authority is already closed when it starts is refused (INVALID_REQUEST) with a message that names the next step: "This agent run has ended, so it cannot start new Gateway requests. Start a new turn to retry." No production code matched on the old text.
  • authorizeGatewayRequestPreDispatch is also called mid-request by withSessionTurnAuthority, for example when sessions.files.get re-authorizes before publishing a host read. That call passes admitted: true, so the run check runs only at request start. The other callers each start a request or a tool operation, and they keep the check.
  • Deleted: createAgentRuntimeAuthorityGuard, assertActiveAgentRuntimeAuthority, hasActiveAgentRuntimeAuthority, the dispatch-level re-checks, the response-time re-checks and the 4001 connection close on runtime authority.
  • resolveSessionRuntimeAuthority keeps its caller and participant assertions. Those are separate chains with their own PRs. It no longer checks runtime authority.
  • Gateway computer cleanup after a run ends had two owners. The Gateway already retires the run's desktop execution on run closure (gatewayComputerService.revokeRunAuthority, server-core-runtime.ts). The tool also sent computer.invoke __close_execution with the ended run's identity through a captured binding (bindGatewayComputerCleanup). That binding is deleted. The gateway host treats the run-ended close as done, because the Gateway owns it and an ended run cannot start new requests. Closes during a live run, and paired-node closes, are unchanged.
  • The message-action turn-capability check is kept as on base, without the run check. It moved out of the run validator into isMessageActionTurnCurrent (one owner). The run validator still calls it. server-methods/agent-runtime-authority.ts keeps one assertion that message actions compose first, with the base refusal text. A revoked turn still stops a pending channel read, download or send from returning or caching a result. That re-check is its own check-once chain.
  • The caller-only message-action authorize() (session mutation, action and delivery assertions) stays at the same points as on base. Its run check is gone.
  • Every other assertion that shared those guards (session mutation, client authority, request authority, owner, participant) is unchanged. poll moved unchanged to send-poll.ts, and the startup-agent helpers moved unchanged to request-authorization-startup.ts (line caps).

User impact

A Gateway request that an agent run has started now finishes and returns its real result, even if the run's authority closes meanwhile. A new request from a closed run is still refused when it starts.

Evidence

Proof tier: source (ocx test, ocx src).

  • New regression test: an agent-runtime client whose authority is released after the handler starts still gets its response. Refusal of an identity that is already invalid at start is covered with the new wording.
  • Focused tests across every touched handler and its consumers (33 files, including the four channel read-authority integration suites): pass after repairs. The rerun files pass: send.test.ts 70, matrix-channel-read-authority 13, server.agent-runtime-authority-proof 13.
  • pnpm tsgo: pass. pnpm check:lifetime-check-ratchet: pass, with no per-file growth. Format check: clean.
  • Local Gateway (ocx src, scripted model, Code Mode on): a parent spawns a subagent and ends its turn. The child's Code Mode guest crashes while a shell exec is still running, and the child then calls a Gateway-backed tool (sessions_search). The call succeeds, and no refusal is logged.
  • Deleted tests pinned the removed behavior: refusing or suppressing delivery after the run's authority closes mid-request, and the 4001 close. One of them (retains reset across parent closure) was checked before deletion: plugin host cleanup still runs on /reset with the matching session key. The test failed only at its no-delivery-after-revoke assertion. One earlier run of that case ended before its pause point. That did not reproduce in a logged rerun.

Unchanged on purpose (separate check-once PRs): the message-action turn-capability re-check, the exec and plugin approval checks (exec-approval.ts, nodes.invoke-authority.ts), the caller and participant assertions (resolveSessionRuntimeAuthority keeps them), and client authority (hasCurrentClientAuthority).

- Check run authority one time in authorizeGatewayRequestPreDispatch, shared by
  WebSocket and in-process requests; the refusal names the next step.
- Delete the mid-request re-checks: createAgentRuntimeAuthorityGuard,
  assertActiveAgentRuntimeAuthority, hasActiveAgentRuntimeAuthority, the dispatch
  and response-time re-checks, and the 4001 close on runtime authority.
- Keep caller, participant, session-mutation and client-authority assertions.
- Move the startup-agent helpers to request-authorization-startup.ts (line cap).
- Delete tests that pinned refusal after the run's authority closed mid-request;
  add a regression that a started request still gets its response.
@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 08484ecde4355cecc6038ff740d26e22b7007428
  • Maintainer: @obviyus
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/agent-runtime-approval-authority.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server-methods.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server-methods/agent-runtime-authority.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server-methods/request-authorization-startup.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server-methods/request-authorization.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server-methods/secrets.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/gateway/server-plugin-in-process-authority.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server/ws-connection/authenticated-request-dispatch.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/session-runtime-authority.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

…admitted request

- withSessionTurnAuthority re-authorizes session access mid-request (for example
  sessions.files.get before publishing a host read). Pass admitted: true so the
  run-authority check stays at request start only.
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 19, 2026
@clawsweeper

clawsweeper Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR checks agent runtime authority at Gateway request admission and removes repeated checks during handlers and response delivery.

Example: An agent's Gateway request starts while authorized, then its run ends before the response arrives.

  • Before: The request can report an authority error and close its WebSocket with code 4001.
  • After: The started request returns its actual result; a subsequent request from the ended run is refused.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The direction and shared owner are sound, but the central runtime scenario remains unproven and exact-head CI exposes a caller-refusal regression and incomplete consumer updates.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 4 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A started Gateway operation can report failure after completing an effect because its agent run ends before response delivery.
Reason: The maintainer-authored direction matches the repository's explicit check-once policy and avoids misleading outcomes without introducing configuration or public APIs.

Merge readiness

⛔ Needs changes before merge - 4 items remain

Keep open: this maintainer-authored PR follows the approved admission-only direction, but it loses a structured caller-authority refusal and leaves several consumer tests inconsistent with the change.

Priority: P2
Reviewed head: 7cff44ffc157bf832de3de6b4c51883287b5f5b4

Before merge

  • Preserve structured refusals from the retained caller assertion (P2) - When client authority becomes false while explicit-recipient routing is pending, assertAdmissionCurrent throws an ordinary Error. Removing the runtime wrapper and rethrowing here loses its previous INVALID_REQUEST response handling: direct callers now receive a rejected promise, and WebSocket dispatch treats it as a handler failure. Exact-head CI reproduces this in the existing routing-custody test, whose expectation this PR changes. Translate the retained caller refusal into the existing structured authorization error without restoring runtime-liveness rechecks.
  • Update Teams read expectations for admitted runtime completion (P2) - Removing the response-time runtime fence makes the existing turn-token and run-response cases complete successfully, but this consumer still requires rejection. Both cases fail in exact-head CI. Update those runtime-retirement expectations to the new contract while preserving the separate plugin-retirement refusals.
  • Update the cron policy test's mid-request revocation case (P2) - The 'revoked before commit' scenario revokes delegated runtime authority after the operation starts, then still expects cron.update, cron.remove, and cron.run to be denied. The PR intentionally removes that commit-time check, and exact-head CI fails at this assertion. Move this scenario out of the denied table and assert the authorized operation's result; retain the other scope-denial cases.
  • Expect the retained scheduled-source refusal in the retry test (P2) - After removal of the runtime wrapper, immediate scheduled-source revocation still stops the Discord 429 retry, but its error is now 'Scheduled source permission revoked.' This assertion still requires the removed runtime-authority wording and fails in exact-head CI. Assert the scheduled-source refusal while keeping the one-request and zero-accepted-write checks.

Findings

  • [P2] Preserve structured refusals from the retained caller assertion — src/gateway/server-methods/agent-run-handler.ts:74
  • [P2] Update Teams read expectations for admitted runtime completion — test/msteams-read-authority.integration.test.ts:859
  • [P2] Update the cron policy test's mid-request revocation case — src/gateway/server-methods/cron.gateway-policy.integration.test.ts:353-354

Tests

  • Missing end-to-end proof: Supply redacted Gateway output showing a request admitted before its own runtime authority closes still returning its real result, followed by refusal of a new request from that ended run; the new regression's base-failing result is also unshown.
Agent review details

How this fits together

Gateway dispatch receives authenticated WebSocket and in-process requests, authorizes their principals, invokes method handlers, and returns results or structured refusals.

flowchart TD
  A[WebSocket request] --> C[Shared request admission]
  B[In-process request] --> C
  C --> D[Runtime authority check]
  D --> E[Method handler]
  E --> F[Response delivery]
Loading

Technical review

Best possible solution:

Keep shared runtime admission and the removed rechecks, restore typed caller-refusal handling, and complete the affected consumer-test cutover.

Do we have a high-confidence way to reproduce the issue?

Current-main source shows repeated runtime checks during handling and response delivery; the PR's dispatcher regression exercises the changed contract, but this review ran no reproduction.

Is this the best way to solve the issue?

The shared admission owner is the smallest coherent solution, and moving existing startup helpers preserves their ownership without adding state or a parallel authorization path.

Full review comments:

  • [P2] Preserve structured refusals from the retained caller assertion — src/gateway/server-methods/agent-run-handler.ts:74
    When client authority becomes false while explicit-recipient routing is pending, assertAdmissionCurrent throws an ordinary Error. Removing the runtime wrapper and rethrowing here loses its previous INVALID_REQUEST response handling: direct callers now receive a rejected promise, and WebSocket dispatch treats it as a handler failure. Exact-head CI reproduces this in the existing routing-custody test, whose expectation this PR changes. Translate the retained caller refusal into the existing structured authorization error without restoring runtime-liveness rechecks.
    Confidence: 0.99
  • [P2] Update Teams read expectations for admitted runtime completion — test/msteams-read-authority.integration.test.ts:859
    Removing the response-time runtime fence makes the existing turn-token and run-response cases complete successfully, but this consumer still requires rejection. Both cases fail in exact-head CI. Update those runtime-retirement expectations to the new contract while preserving the separate plugin-retirement refusals.
    Confidence: 0.99
  • [P2] Update the cron policy test's mid-request revocation case — src/gateway/server-methods/cron.gateway-policy.integration.test.ts:353-354
    The 'revoked before commit' scenario revokes delegated runtime authority after the operation starts, then still expects cron.update, cron.remove, and cron.run to be denied. The PR intentionally removes that commit-time check, and exact-head CI fails at this assertion. Move this scenario out of the denied table and assert the authorized operation's result; retain the other scope-denial cases.
    Confidence: 0.99
  • [P2] Expect the retained scheduled-source refusal in the retry test — test/cli-message-authority.integration.test.ts:992
    After removal of the runtime wrapper, immediate scheduled-source revocation still stops the Discord 429 retry, but its error is now 'Scheduled source permission revoked.' This assertion still requires the removed runtime-authority wording and fails in exact-head CI. Assert the scheduled-source refusal while keeping the one-request and zero-accepted-write checks.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 0c3f2a4ea2b3.

Provenance checked

  • Repeated runtime-authority guards changes intended behavior with a stated reason (73a9eed: The admitted-run context work established delegated runtime authority checks; later caller-retirement work composed independent caller assertions with that guard.)
  • Session runtime authority changes intended behavior with a stated reason (fd2a6ca: Preserve requester identity at execution admission; this PR removes runtime-liveness revalidation while retaining caller and participant assertions.)
  • Reset and input effects after runtime closure changes intended behavior with a stated reason (fix(gateway): stop input effects after caller authority closes #150640: Prevent fresh reset-followup, input, media, and confirmation effects after delegated caller closure while preserving committed outcomes.)
  • Startup request preparation keeps the original intent (0015e4a: Wait for agent preparation before scoped reads; the extracted startup module retains the existing preparation behavior.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source -231, Tests -1056, Other -1. Total -1288 across 51 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 30 247 478 -231
Tests 20 223 1279 -1056
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 51 470 1758 -1288

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P2: The change addresses incorrect Gateway outcomes during agent-run retirement, with focused correctness and consumer-validation repairs remaining.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: The change addresses incorrect Gateway outcomes during agent-run retirement, with focused correctness and consumer-validation repairs remaining.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 19, 2026, 2:47 AM ET / 07:47 UTC.

- Remove the slack test's reset of the deleted afterGatewayMirror hook.
- Teams gateway reads no longer fence on a run or turn closing mid-read; keep the
  plugin-retirement stages there and all stages on the tool route.
- Prune the session-identity allowlist after the deleted guards.
- The Gateway already retires a run's desktop execution on run closure
  (gatewayComputerService.revokeRunAuthority). Delete the tool's second cleanup
  path, bindGatewayComputerCleanup, which sent computer.invoke with the ended
  run's identity and is now refused at request start.
- The gateway host treats the run-ended close as done; live-run and paired-node
  closes are unchanged.
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Nov 19, 2026
- Restore the caller-only message-action authorize() (session mutation, action and
  delivery assertions) at the same points as before, without the run check; its
  refusal says message action authority, not agent runtime authority.
- Keep the structured INVALID_REQUEST when client authority closes during agent routing.
- Restore turn-capability cases in the channel read-authority suites; drop only
  cases that release the run's own authority mid-request.
- Narrow cron, requester-cron, sessions.create and role tests that pinned mid-request
  run revocation; the role test now proves the next request uses the new role.
- Move the poll handler unchanged to send-poll.ts (line cap); prune baselines.
…he run check

- Move the turn-token check out of the agent runtime validator into
  isMessageActionTurnCurrent; the validator calls it after its run checks.
- Message actions assert the caller's turn first, so a revoked turn still blocks a
  pending ordinary channel read or download from returning or caching a result.
- Remove the Slack and Teams fixture guards so those suites exercise production;
  send fixtures mint real turn capabilities.
…untime-guard

# Conflicts:
#	src/agents/tools/sessions-list-privacy.test.ts
- Keep the message-action turn assertion in server-methods/agent-runtime-authority.ts
  with its base refusal text; message actions compose it first. No run check.
- isMessageActionTurnCurrent takes a structural identity, breaking the import cycle
  with agent-runtime-identity-token.
- Drop the cron scratch row that called the handler past request start; the start
  check is covered in request-authorization tests. Relax a CLI wording assertion.
@obviyus
obviyus merged commit 26a5f73 into main Nov 19, 2026
150 of 151 checks passed
@obviyus
obviyus deleted the refactor/check-once-runtime-guard branch November 19, 2026 11:43
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 20, 2026
openclaw#201697)

Problem: an agent run's Gateway requests re-checked the run's authority many times while one request ran: before the queue, at handler start, inside cron, secrets, sessions.create, message, themes, ui.command and MCP event handlers, and on every response. When the run's authority closed partway through, a started request was refused with "agent runtime authority is no longer active". On WebSocket the client connection was also closed (4001), and a committed effect could be reported as a failure.

Fix: run authority is checked once, in the shared pre-dispatch owner `authorizeGatewayRequestPreDispatch`, which WebSocket and in-process requests both pass through. A request from a run that already ended is refused with a message that names the next step. Session authorization inside an already admitted request (`withSessionTurnAuthority`) skips that check. The run guard helpers, the dispatch and response-time re-checks, and the 4001 close are deleted. The message-action turn-capability check and the caller-only message-action fences stay as on base, without the run check; they are separate check-once chains. Gateway computer cleanup after a run ends now has one owner: the Gateway retires the run's desktop execution on run closure, and the tool no longer sends a second close with the ended run's identity. Caller, participant, session-mutation and client-authority assertions are unchanged.

User impact: a Gateway request that an agent run has started finishes and returns its real result even if the run's authority closes meanwhile. A new request from a closed run is refused at start.

Proof: focused tests for every touched handler and consumer, including the channel read-authority suites; new regressions (a started request keeps its response; an ended run is refused at start but not inside an admitted request); tsgo and test types; the lifetime-check, line-cap, session-identity and mock-export ratchets; a local Gateway run where a subagent's Code Mode crash is followed by a successful Gateway-backed tool call; ocx build --dts plus a packed install smoke on the merged head.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
#201697)

(cherry picked from commit 26a5f73)

Release adaptation: Keep existing stable admission and read-result fences; the authenticated dispatcher only stops replacing outcomes of started write handlers already governed by the method layer.

Companion audit: No direct later PR/SHA follow-up. Do not import the broad runtime/request authorization redesign or its changed blanket read-response contract.

Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts security-sensitive-changed size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant