Deliver `SubAgents` background task output as framed `<task_output>` data instead of in a `SystemPromptPart`

Merged
DO
1mo ago
+809-113

SubAgents delivered a background task's report as one SystemPromptPart, with the child agent's output inside it. Anthropic and OpenAI send that as native system or developer voice, so model-written output (and anything the child read, such as a web page or a file) reached the parent in the most trusted channel, behind a "do not follow instructions in the report" disclaimer. Its <task-output> wrapper was also unescaped, so the output could close it early.

[!WARNING]
Compatibility impact: DelegationTask.report() now returns a UserPromptPart instead of a SystemPromptPart, and the enqueue callable passed to DelegationTasks.receiving() now receives that UserPromptPart. The model sees the child's output as user-channel <task_output task_id="..." agent_name="..."> data, with outcome="..." added when the task didn't succeed, and nothing in system voice. Snapshot tests of message history after a background task report will change. Code that finds reports by looking for SystemPromptParts whose text contains Automated subagent task report will no longer find them.

Why this can ship in a minor release: Pydantic AI Harness is on 0.x, where the version policy allows API changes between minor releases. Untrusted output in system voice is a trust-boundary bug.

Migration: call is_task_report(part) from pydantic_ai_harness.subagents to find the report; it matches on metadata, not text. Update snapshots to the new shape: a UserPromptPart([TextContent('<task_output task_id="..." agent_name="...">\n...\n</task_output>', metadata={...})]), with outcome="failed" (or timeout, budget, cancelled, ...) in the open tag when the task didn't succeed. A custom receiving(enqueue=...) callable gets the part to enqueue, for example lambda part: ctx.enqueue(part).

  • Refs: audit item H8 (message history as world model, 2026-10-15): untrusted content never enters system voice.

What changed

  • Report shape (subagents/_tasks.py, _task_report.py). The report is the child's output alone: a UserPromptPart holding one TextContent, framed as <task_output task_id="..." agent_name="...">, with outcome="..." only when the task didn't succeed. This mirrors BackgroundTools results after #10548: no preamble, the frame's attributes carry identity, and only a failure gets an outcome. Nothing variable reaches system voice. That includes the agent name, which for a disk agent comes from its frontmatter. Attributes go through html.escape. Escaping. In the body, core's pydantic_ai._framing.neutralize_tags neutralizes the < of every opening or closing framing tag core writes (<system>, <context>, <context_diff>, <tool_result> and the rest), and a local rule does the same for task_output and the older task-output. Any case, spacing or attributes match, and so does a tag cut off at the end of the text. A longer name such as <systemic> is left alone. The private import is safe because the harness pins pydantic-ai-slim to the exact matching release. Switching to core's wrap() from the public pydantic_ai.framing API is the follow-up, after #10957 lands; a TODO in _task_report.py points there. Either way, the PR is strictly better than main, which puts the child's output unescaped in a SystemPromptPart, that is, in system voice.
  • Tag spelling. The frame is <task_output>, with an underscore, like core's tool_result and assistant_thinking framing tags. Histories saved before this change keep <task-output>. Nothing parses the tag back, because recognition goes by metadata, but closing-tag neutralization matches both spellings, and test_report_shape covers a forged hyphenated end tag.
  • No disclaimer or preamble. The acceptance receipt the parent gets when it launches the task already says a report will follow and isn't a result. The frame's tag and attributes say what the content is. An extra line before it would be either untagged user text or system voice.
  • Identified by metadata. The TextContent carries {'origin': 'pydantic-ai-harness.subagents.report.v1', 'task_id': ..., 'generation': ...}. The new public is_task_report(part) is a TypeGuard[UserPromptPart] that checks this metadata. clai2 needs it from the public API.
  • clai2 UI round trip. The output now travels in a UserPromptPart, so without changes clai2 would treat it as a prompt the user typed: /resume would print it as > <task_output ...> and count it as a turn, /rewind would offer it as a disabled [attachment] rewind point, and the web history would show it as a user message. turn_starts, render_history, build_rewind_menu and history_items now skip it.
  • Core UI adapters and ReinjectSystemPrompt. I checked the Vercel AI and AG-UI round trips. TextContent metadata isn't kept, as documented, so after a round trip the output comes back as plain user text, still framed with its task id, agent and outcome. In manage_system_prompt='server' mode, and with ReinjectSystemPrompt(replace_existing=True) in general, history SystemPromptParts are replaced. Before this PR that dropped the whole report, so the parent lost the child's result on its next turn. Now the report isn't a system part, so it survives. A new test pins this. With replace_existing=False, a report no longer counts as "a system prompt is present", so it no longer stops reinjection.
  • InputGuardrail skips task reports, but only ones the framework enqueued. It validates the user's prompt. A report-only continuation (agent.run(None) with DelegationReports(priority='asap')) has no prompt of its own, so the guard falls back to the last UserPromptPart in history. A task report now is one, so without this change the guard got the report's repr, and a replace() raised UserError. While scanning history it now skips task reports and guards the user's earlier prompt, as before this PR. The run's own prompt is always guarded, even when it carries a task report's metadata, since a caller can set any metadata (test_prompt_with_forged_task_report_metadata_is_guarded). A private _provenance.tagged_text holds the metadata check that BackgroundTools completions and task reports share, and the task report helpers live in _task_report.py, so guardrails doesn't import subagents.
  • Realtime sessions accept the report. RealtimeSession.enqueue() (and RunContext.enqueue() in a realtime session) accepted only str prompts and system parts, so DelegationTasks.receiving(enqueue=session.enqueue) raised UserError on the new report. It now accepts text-only TextContent items too and joins their text for the live input channel. A message of user prompt parts holding TextContent is recorded in history as those parts, so the metadata survives. Anything non-text is still rejected. The error message and the realtime docs (docs/realtime/overview.md, docs/realtime/tools.md) say what is accepted. Tests: test_session_enqueue_delivers_text_content_and_keeps_its_metadata, test_session_enqueue_rejects_text_content_mixed_with_media, and test_report_reaches_a_realtime_session_and_keeps_its_metadata with a real DelegationTask.report().
  • Docs: docs/harness/subagents.md and its README twin, the harness agent skill reference, and the clai2 reference.

Decisions

  • message_history is trusted as the caller's (DouweM). A review asked whether a caller could forge TextContent.metadata (origin='pydantic-ai-harness.subagents.report.v1') to make InputGuardrail skip a prompt. The run's own prompt is always guarded, whatever metadata it carries. Inside message_history, the metadata-based skip stays: history passed there is the caller's own, and keeping forged client history out is the UI adapters' job. Their loaders never put client metadata on message content. sanitize_messages alone keeps TextContent.metadata, so the docs don't recommend it for this. New tests in tests/test_vercel_ai.py and tests/test_ag_ui.py check that loading a client message carrying origin-like metadata in every slot never builds a TextContent with metadata. The InputGuardrail and SubAgents docs now say this. The Vercel AI loader does copy client metadata onto ModelRequest.metadata, which no harness check reads.

  • Underscore tags (DouweM). Every framing tag uses underscores, to match core's tool_result and assistant_thinking.

  • Cross-run prefix stability. #10936's append-only matrix (tests/harness/test_history_append_only.py) has a DelegationReports conversation: a background delegation settles between two runs, and its report reaches the second run from stored, serialized history. That conversation runs against this PR's report shape and checks that every request only appends to the previous one, and that the report reaches history once. This PR extends its check to assert that the delivered part is a task report framed as <task_output> data.

  • SlidingWindowCompaction treats every harness-origin part as harness data, not only task reports. This is deliberate. It is #10833's classification rule (content whose TextContent.metadata['origin'] starts with pydantic-ai-harness.), which SummarizingCompaction and RelevanceCompaction already apply. A review asked for exactly this alignment.

Not changed (follow-ups)

  • Compaction (with #10833, now merged). A task report travels in a UserPromptPart, so compaction could treat it as a user turn. #10833 renders harness-added user-channel content as <harness_data> in SummarizingCompaction, keeps it out of keep_user_messages, and never picks it as the first user message. The report's origin is under pydantic-ai-harness., so it is covered, and test_subagent_report_is_summarized_as_data_and_never_kept_as_a_user_turn pins this for a real report. This PR applies the same rule to SlidingWindowCompaction's first-user-message selection (_shared.find_first_user_message), leaves harness data out of the first request it preserves (an asap report delivered with the user's prompt shares that request, and would otherwise stay outside the window on every run) and moves the rule (harness_data_origin, is_harness_data) into _shared, so both strategies use one definition.

Verification

  • New regression assertions in tests/harness/subagents/test_tasks.py, run through real agent runs: the forged </task_output> / </TASK_OUTPUT > in child output is neutralized, no SystemPromptPart contains child output, attributes are escaped, a look-alike UserPromptPart without the metadata is not a report, and the output survives ReinjectSystemPrompt(replace_existing=True). A minimal "child output not in system voice" check fails against main's _tasks.py and passes here.
  • tests/clai2/test_tasks.py (all three timing cases) and tests/clai2/test_rewind.py fail without the clai2 changes and pass with them.
  • tests/harness/guardrails/test_input_guardrail.py::...::test_subagent_task_report_is_not_the_prompt runs a replace guard over a report-only continuation.
  • Targeted pytest for tests/harness/subagents/, tests/harness/guardrails/, tests/harness/background_tools/ and the touched clai2 test files, single-file Pyright on touched files, and Ruff all pass.

Checklist

  • No breaking changes in accordance with the version policy. (Harness 0.x; see the compatibility note above.)
  • Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver. (The API check doesn't cover harness, so there is no waiver.)
  • PR title is fit for the release changelog.

šŸ¤– Generated with Claude Code