Raven-1/docs-site/docs/protocol-backends.md
Zuyi Zhou 89a24c5769
fix(*): a command the host denies stays denied once it is handed to a sub-agent (#698)
## Summary

A host deny rule bound the host's own tool calls and nothing it
dispatched.
The host answered every `session/request_permission` from an ACP
sub-agent
with the most permissive option (`raven/acp_client/permissions.py`), and
a
product launcher rendered its own config without the host's permissions
(Raven-Code pins `mode: ask` and carries no rules). Measured end to end
before this change: with `permissions.tools.exec {"curl *": "deny"}` and
`tools.exec.extraDenyPatterns ["\\bcurl\\b"]` on the host, a curl handed
to
Raven-Code asked the host, was answered "Allow for this session", and
hit a
loopback sink.

Refusals now travel, on both sides, because a refusal needs nobody to
answer:

- **Launcher side.** `product_render.write_rendered` merges the host's
`deny`
entries of `permissions.tools` and `tools.exec.extraDenyPatterns` into
every
product render (strictest wins; a product exec tier written as one
string
becomes the `*` fallback beside the host's patterns; a pattern that does
not
compile is left behind, as the host's own live reader leaves it). Every
launcher and the scaffold end in that call, and a test pins that. This
is
  the half that matters for raven's own products: a call their own gate
  allows never produces a request the host could refuse.
- **Host side.** The approver reads the command a request names
  (`toolCall.rawInput.command`, as sent and unquoted, and every codex
  `commandActions` entry) against the host's builtin deny list with
`extraDenyPatterns` and its `deny` rules, read live, and answers a match
with the agent's reject option (cancel only when none was offered). A
check
  that raises refuses. A parse error is not a refusal. This also covers
  third-party agents, for what they ask about.
- **Server side.** Raven's own ACP broker now sends a shell call's
command as
`rawInput.command` (redacted like the title), so a raven host can read
it.

- **Logs.** Both approver log lines (the INFO refusal, and the DEBUG
approval, which logged the agent's own title) go through the ACP
redactor,
since the command is the sub-agent's to author and the log is retained.
The
redactor moves from `raven/acp/redact.py` to `raven/security/redact.py`
(content unchanged but one docstring paragraph), because
`raven.acp_client`
  may not import `raven.acp`, and one table beats a second copy.

Deliberately not changed: the ask tier and the mode. What no deny rule
names
is still approved, as before; routing the ask tier to the host's human
is a
separate decision. A rule added on the host reaches an already running
raven
product at its next launch (the host-side check is live, the render is
not).
Agents launched with a never-ask setting never send a request, so only
their
own configuration binds them. Docs (permissions, protocol backends, both
languages) and the `Unattended Approval` entry in `CONTEXT.md` say this.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

Head 703c7ceaf, rebased onto main 3a463d6cd (`git range-diff` shows both
commits `=` against the reviewed 4f8e0af95; the head is linear again,
the two
"Update branch" merge commits are gone). At this head: the six focused
suites
480 passed, the e2e 2 passed, `git diff --check` clean, `make
lint-imports`
10 kept. The full suite was run at the same two commits on earlier
bases:
25878 passed / 109 skipped at ca5e5dc15 (shown below), 25881 passed /
110
skipped at 4f8e0af95, diff coverage 100% at both. Main's newer commits
touch
`CONTEXT.md` in a different entry and none of the other files here:

```
uv run pytest -q tests/test_subagent_acp.py tests/test_acp_redact.py tests/test_acp_permissions.py tests/test_acp_server.py tests/test_config_product_render.py tests/test_agents_code_launcher.py
  480 passed
uv run pytest -q -n0 -m integration tests/integration/test_subagent_host_deny_e2e.py
  2 passed   (control run hits the sink; denied run does not, reply names the deny rule)
COLORTERM=truecolor make coverage   (fresh worktree at ca5e5dc15)
  25878 passed, 109 skipped in 619s
COVERAGE_BASE_REF=origin/main make coverage-diff
  Diff coverage: 100.00% (120/120 executable changed lines)
uv run --frozen --python 3.12 --extra dev ruff check raven evolver agents plugins-dist tests scripts   -> All checks passed
uv run --frozen --python 3.12 --extra dev ruff format --check raven evolver agents plugins-dist tests scripts   -> 2084 files already formatted
make lint-imports   -> 10 kept, 0 broken
make lint-deps && make lint-types   -> no issues / All checks passed
git diff --check origin/main...HEAD   -> clean
PYTHONPATH=. uv run --frozen --python 3.12 --extra dev python scripts/check_source_language.py origin/main...HEAD   -> exit 0
make check-commits; make check-pr-title; COMMIT_RANGE=origin/main...HEAD make check-large-files   -> pass
```

Revert-to-red, one production file at a time restored to origin/main
(the
focused suites plus the e2e where it applies; measured on the first
commit
before the rebases, which touched none of these files):

| reverted | unit | e2e |
|---|---|---|
| raven/config/product_render.py | 12 failed | 1 failed (sink not hit:
the host approver refused it, reply "User denied this action"; only the
wording assertion fails) |
| raven/acp_client/permissions.py | 2 failed, 14 errors | - |
| raven/acp/permissions.py | 2 failed | - |
| all three | 15 failed, 14 errors | 2 errors |

The first row is the two halves covering each other: with the launcher
half
reverted the host half still stops the command. For the second commit,
each
log line's redaction reverted alone turns
`test_the_logged_refusal_and_approval_carry_no_credential` red (1 failed
each).

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

## Risk

User-visible: an ACP sub-agent (Raven products, Claude Code, codex) now
has a
command refused when it matches the host's deny rules or the builtin
catastrophe list, where it used to run. Hosts with no deny rules see no
difference except the builtin list. Rollback: revert this commit.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

---------

Co-authored-by: Claude (claude-opus-5-5) <noreply@anthropic.com>
2026-09-23 17:46:08 +08:00

7.7 KiB

Protocol and Backend Integration

Start here when implementing an adapter, backend, or protocol client. For operator configuration use Agent Integrations or Channels and Messaging. Protocol methods and deployment limits are documented in Agent Protocols.

Choose the extension point

Requirement Extend Do not confuse it with
Another local agent speaks ACP already An ACP roster row/preset A new transport implementation
A CLI has a nonstandard transcript CLI configuration and, when needed, a parser An ACP server
A remote service accepts chat completions OpenAI-compatible agent configuration A local tool-capable backend
A remote agent publishes an Agent Card A2A client/server integration A roster entry with kind: a2a
A messaging platform needs a bot A channel adapter A sub-agent backend
A service provides tools/resources MCP An agent-to-agent task protocol
A product needs custom turn behaviour Plugin/participant A fork of the shared Agent Loop

Prefer an existing backend kind where it expresses the behaviour. Backend kinds are a closed, validated set; adding a custom string to a plugin manifest does not register a new backend.

Respect runtime contracts

The Assembly Root is raven/core/runtime.py:build_runtime. Runtime consumers depend on contracts; entrances and product adapters assemble or translate work. Keep the Kernel independent of CLI, RPC, ACP, and product code.

Contract or surface Source
Sub-agent execution raven/contracts/subagent_backend.py
Tool execution raven/contracts/tool.py
Channels and login raven/contracts/channel.py, re-exported by raven/channels/contract.py
Turn input, events, scheduling raven/spine/
Product UI wire schema rpc-schema/openrpc.json
Backend row validation raven/config/schema.py
Backend construction raven/agent/subagent/backends/__init__.py

Use CONTEXT-MAP.md and CONTEXT.md for canonical names. A backend session, host conversation, A2A task, and DAG node id have different lifetimes; mapping them explicitly prevents results or credentials crossing conversations.

Implement a sub-agent backend

SubagentBackend.run receives task text and keyword-only context including task_id, workspace, executor, session_key, instance, provider, model, mcps, mcp_grant, mode, authored_task, and on_delta. Use the actual Protocol signature rather than a copied subset.

The contract returns final text and raises on failure. The manager owns announcements, the shared semaphore, and rate limits. Do not create a second dispatch budget inside the backend or return a success-looking sentence when no final answer was produced.

Implement and test:

  • Start/readiness versus per-task timeout as separate operations.
  • Native session id binding and resumption, if supported.
  • Local-file access as a real property, not inferred from the agent name.
  • Explicit MCP selection and credential scope; no implicit secret sharing.
  • streams/on_delta only when actual transport events provide deltas.
  • Cancellation, process cleanup, output truncation, and nonzero exit handling.

Adding a backend kind requires coordinated schema, construction, capability, configuration-write, and regression-test changes. It is not currently a generic third-party plugin registration point. A parser-only change can often stay in raven/agent/subagent/backends/transcript.py with fixtures.

Integrate ACP safely

For an ACP client, negotiate before assuming optional features. Drive requests and notifications concurrently while a prompt is pending; a client that stops reading cannot answer permission or elicitation requests. Keep stdout protocol-only and continuously drain child stderr.

Test initialize, session creation, prompt updates, final stop reason, load/resume, cancellation, unknown capabilities, and malformed frames. Do not advertise methods that only return “not implemented.” Model/mode changes apply to the appropriate session and next turn, not every session sharing a connection.

Per-session MCP is especially sensitive when connections are pooled. A capability declaration does not by itself prove isolation between sessions; Raven has a separate sessionMcp policy for that reason. Verify simultaneous sessions with different server selections. Also test unanswered permission requests and client disconnects.

The packaged schema fixtures and tests in tests/test_acp_schema.py help check frame shapes. The current outbound client auto-approves offered permission options, except that a request whose toolCall.rawInput.command the host's deny rules refuse is answered with a reject option; integrations must disclose that trust model, not promise interactive human review.

Integrate A2A safely

Use the protocol SDK's request and response shapes. Raven's current binding is A2A 1.0 JSON-RPC, not the older slash-named method form. Streaming events have StreamResponse envelopes; non-streaming send has SendMessageResponse. Read task status text as well as message and artifact text.

Test the public card separately from authenticated RPC and optional extended cards. Match credentials to the intended origin; test off-origin interfaces and redirects without sending credentials elsewhere. Never expose internal tracebacks to peers.

Test a real local client/server round-trip with a stubbed turn, not only a hand-written JSON fixture on each side. This catches envelope disagreements. The task store is currently in memory; do not claim durable resumption or push notifications. Question routing differs between standalone and gateway hosting, as described in the protocol guide.

Add a messaging adapter

An adapter lives under raven/channels/adapters/<name>/. Its spec.py exports a ChannelSpec with display name, lazy factory, capabilities, and a config schema. Discovery scans these packages; do not import an optional platform SDK merely to enumerate channels.

The host owns channel socket fields (enabled, allow_from, workspace). The spec declares adapter-specific fields and secret/required markers. dispense_channel_config provides the admitted view to the factory; CLI and UI configuration should use that same declaration rather than a second field list.

Implement start, stop, and send and route inbound messages through Intake. Apply sender/group checks before downloading untrusted attachments or performing reactions. Preserve routing metadata and conversation identity; the gateway wires submission and outbound delivery.

Declare only capabilities you implement. Interactive login requires SupportsLogin; streaming requires the corresponding protocol, and the channel capability proof checks those claims. File attachment delivery needs real sends and error handling, not a flag alone. The current gateway channel outlet remains non-streaming.

Test allowed/denied senders, group policy, media handling, missing credentials, reconnect/shutdown, and outbound failures without connecting a real account. Then perform an explicitly authorized live-account acceptance test separately.

Verification and handoff

Representative repository checks:

uv run pytest tests/test_subagent_third_party.py tests/test_acp_schema.py tests/test_a2a_interop.py -q
uv run pytest tests/test_channels_contract.py tests/test_channels_registry.py tests/test_channels_intake.py tests/test_channels_outlet.py -q

Run the specific adapter/backend tests too, plus the repo's lint and import contracts for code changes. Report exactly which vendor versions, operations, and hosting surfaces were exercised. A mocked test is not a live authentication test. Do not include credentials, QR data, or raw private transcripts in fixtures.