← Back to Pull requests

[api][plan][python] Expose sub-agents to chat models as callable tools #1114

Closed
unknown closed this pull request without merging on Sep 24, 2026 08:57 UTC
View on GitHub
unknown unknown commented on Sep 10, 2026 02:49 UTC
Author

Linked issue: #1112

Purpose of change

A chat model can now delegate to a sub-agent by issuing a tool call. The setup declares each sub-agent it names as one callable under the reserved _subagent_ prefix; at execution a prefixed call is routed to that sub-agent and its result is handed back to the model. Which sub-agent to call, and with what arguments, becomes the model's decision — previously a sub-agent could only be invoked from action code.

A sub-agent the caller names but gives no usable input shape is rejected when the model sets up, and a delegation that fails tells the model why, so it can correct the call rather than repeat it blindly.

Runtime flow

open() walks the subagents argument after the tools and, for each name resolving to a SubagentSetup with a usable input schema, adds a metadata-only SubagentTool named _subagent_<name>. The model builds a function call against that schema. ToolCallAction reads the prefix off the callable name, resolves the AGENT resource once, and passes the model's arguments to submit(...).await() unchanged; the result is normalized to JSON-generic form and rendered as the tool-message content. In the batched tool-call path sub-agent calls are dispatched concurrently — every call is submitted before any is awaited, so the runs overlap like the batched tools instead of proceeding one by one. Python mirrors this in its setup and tool-call action.

Key decisions

The reserved prefix, not a distinct tool type, separates the namespaces: tool registration rejects _subagent_ at plan-construction, so a prefixed name can only address a sub-agent, and a tool and a sub-agent may share a resource name. No listing message is injected — every sub-agent description ends with a marker, so the model learns a callable is a delegation from its description alone.

SubagentTool is metadata-only (call() throws); dispatch resolves the AGENT resource at execution, keeping the sub-agent's own durable execution as the single source of the result and avoiding nested durable cursors. An input schema is derived from the declared input type through the same Jackson generator the ReAct output schema uses, then aligned to the cross-language form (object-level required, byte[] as string/binary) at every nesting level, matching each property on the name it carries in the schema rather than its Java field name, adding no dependency.

Behavioral Semantics

Interaction decisions

| subagents entry resolves to | Input schema | Offered to the model |
| --- | --- | --- |
| SubagentSetup, explicit schema | that schema | yes |
| SubagentSetup, input type rendering as an object | derived schema | yes |
| SubagentSetup, type rendering as no object / none | none | no — open() fails (checkState); job fails at setup |
| bridge handle (owned by the other language) | carries none | no — open() fails |
| a tool registered under the prefix | — | impossible — rejected at plan-construction |

At dispatch a _subagent_ name resolves in the AGENT namespace and a plain name in TOOL; a success returns normalized JSON content, and any failure returns an error carrying the reason.

Behavioral contracts

1. Each named sub-agent with a usable input schema is declared as exactly one callable _subagent_<name>, after the tool callables, carrying its description and schema.
2. A sub-agent with neither a schema nor a shape-bearing input type is rejected when the chat model sets up — open() fails through checkState — rather than dropped, so a declaration with no arguments for the model to build a call from surfaces immediately.
3. Every sub-agent description ends with the marker; an undescribed one gets a generic delegation description, and no separate listing message is injected.
4. The schema is the explicit one if declared, else derived from the input type; explicit wins.
5. A tool and a sub-agent may share a resource name; a callable name resolves to exactly one namespace.
6. A tool name must not carry the prefix — rejected at plan-construction, including a name an MCP server advertises.
7. A prefixed call hands the model's arguments over unchanged; injection stays tool-only.
8. A success is reported as JSON-generic content; a declared result type narrows it (extras ignored), an undeclared one takes it as it arrived.
9. A result JSON cannot express — including one that reaches back into itself — is refused with the path where it was found, and reported as a failed delegation, not dropped, stringified, or made a job failure. No fixed nesting cap is imposed: a deep-but-finite result still has a JSON form, so only a cycle, which has none, is refused; a result too deep to walk overflows and is folded into a failed delegation.
10. A failed delegation reaches the model with the reason.
11. Re-opening rebuilds the callables from scratch and does not duplicate them.
12. Java and Python decide alike on declaration, dispatch, and result handling, and derive the same input schema for the same declaration.
13. A resolved sub-agent delegation reports under a subagent metric scope keyed by the registered sub-agent name — numOfSubagentCallsSucceeded, numOfSubagentCallsFailed, and subagentCallLatencyMs from the Action-observed hand-off to result observation — rather than as a tool call; a _subagent_ name that resolves to no registered sub-agent stays a tool call and aggregates under tool=unknown, so the subagent scope is keyed only by names in the Agent plan and its cardinality stays bounded.

Failure behavior

Construction and plan-building raise; call-time failures are absorbed into the tool response.

  • Blank explicit input schema → IllegalArgumentException at construction.

  • An input type that cannot be rendered, including a self-referential one → IllegalArgumentException naming the remedy.

  • A subagents entry resolving to a bridge handle, a sub-agent with no schema and no shape-bearing input type, or a repeated callable name → open() fails (checkState), not silently dropped.

  • A tool under the reserved prefix, including one an MCP server advertises → raises at plan-construction.

  • At call time, an absent/non-SubagentSetup resource, an exception from submit/await, a failed result, a cyclic result, or a result too deep to normalize are each caught and returned as ToolResponse.error with the reason; the job continues. A StackOverflowError from a result nested deeper than the stack can walk is folded into the same failed delegation on both the serial and the batched path, rather than escaping as an Error that fails the job.

  • A sub-agent call whose durable execution is cancelled surfaces an InterruptedException, propagated the way the tool paths do, so no further chat call is driven off a cancelled delegation; the concurrent path also cancels every handle submitted but no longer awaited.
  • Tests

    The new suites run offline, with no live model or external agent. Java: BaseChatModelSetupSubagentTest, SubagentSetupTest, AgentPlanSubagentResourceTest, ToolResultUtilsTest, ToolCallActionSubagentTest; Python: the mirrored test_chat_model_subagents, test_subagent, test_agent_plan, test_tool_result_utils, test_tool_call_action_subagent. Every contract is pinned on both sides:

    | Contract | Java | Python |
    | --- | --- | --- |
    | 1 declared as one prefixed callable, after tools | ✅ | ✅ |
    | 2 no schema and no shape → rejected at open() | ✅ | ✅ |
    | 3 description marker; no listing message | ✅ | ✅ |
    | 4 explicit schema wins, else derived | ✅ | ✅ |
    | 5 tool and sub-agent share a name | ✅ | ✅ |
    | 6 tool under the prefix rejected (incl. MCP-advertised) | ✅ | ✅ |
    | 7 arguments handed over unchanged | ✅ | ✅ |
    | 8 result type narrows; undeclared as-is | ✅ | ✅ |
    | 9 non-JSON / cyclic result refused with its path; no depth cap | ✅ | ✅ |
    | 10 failed delegation carries the reason | ✅ | ✅ |
    | 11 re-open does not duplicate | ✅ | ✅ |
    | 12 Java and Python decide alike, same derived schema | ✅ | ✅ |
    | 13 sub-agent delegation reports under the subagent metric scope | ✅ | ✅ |

    Highest risk is result normalization (9): non-string map keys, non-finite numbers, a POJO inside a JSON tree, arrays walked by index, a cyclic result refused at its path, and a 200-deep acyclic result still normalized, each asserted on the path in the message where one applies. The derived input schema (12) is pinned whole on both sides — object-level required and each property's type/format, including a byte[]/bytes field rendered as string/binary, a nested object deriving its own required, and a property whose schema name differs from its Java field name (a @JsonProperty rename, or a getter with no field) — so a divergence fails a build rather than passing contract 12 while the schemas differ.

    Not verified: no test drives a live model or a real external sub-agent, so these pin what the framework declares, dispatches, and reports, never that a provider accepts the derived schema. A sub-agent owned by the other language is checked only up to the rejection at open(); cross-language delegation end-to-end is out of scope. Parallel-mode routing of a sub-agent beside tools, and each call id landing on its own result under the batch, are covered; concurrency timing is not.

    Implementation invariants (not caller-observable)

  • SubagentTool.getToolType() is FUNCTION and call() throws UnsupportedOperationException; the callable is never invoked through Tool.call().

  • getInputType()/getResultType()/getResourceType() are @JsonIgnore (behavior, not state); Python pins the same via test_the_declared_types_stay_out_of_the_plan_json and test_the_metadata_serializes_under_the_cross_language_keys.

  • A declared result type is read with FAIL_ON_UNKNOWN_PROPERTIES off, mirroring pydantic's ignore-extra, then re-checked for JSON compatibility because a declared type can still render an inexpressible field.

  • Result normalization tracks the containers on the current path in an identity-based set, so a cycle is refused while the walk still can and a diamond (one node reached by two distinct paths) stays legal; there is no depth counter.

  • resolveSubagent resolves and type-checks the AGENT resource once and carries the setup down, so a plain tool call never attempts an AGENT resolution.

  • A derived input schema is carried by the plan JSON; an explicit one is kept verbatim.

  • Python has no metric recorder of its own: report_execution_ crosses the pemja bridge to the Java recorder, so the Python action-level test pins the reported subagent lifecycle while outcome and latency aggregation is a Java-side concern.
  • API

    Additive, aligned across Java / Python / YAML, building on the AGENT resource type and SubagentSetup:

  • SubagentSetup gains getDescription(), getInputSchema(), getInputType(), getResultType() and the CALLABLE_NAME_PREFIX constant (_subagent_).

  • The chat-model setup takes a new subagents argument (Java/Python constructor + YAML subagents:): the AGENT resources it may delegate to.

  • ToolResultUtils (plan) normalizes a result; SubagentTool and InputSchemas are package-private, not public API.

  • Sub-agent delegations expose a subagent metric scope (numOfSubagentCallsSucceeded, numOfSubagentCallsFailed, subagentCallLatencyMs) keyed by the registered sub-agent name, alongside the existing tool and model_resource scopes; documented in monitoring.md.
  • Two things change for a caller who does nothing differently: a tool named _subagent_ is now rejected at plan-construction, including a name an MCP server advertises; and a repeated tool name now fails open() as a duplicate callable name, where it was previously accepted. Otherwise nothing changes unless the new subagents argument is set, and a plain tool call routes as before. A sub-agent owned by the other language cannot yet be exposed as a callable — declaring one fails open().

    Documentation

  • doc-needed

  • doc-not-needed

  • doc-included
  • doc-included for the operational metrics: monitoring.md documents the new subagent metric scope. The subagents chat-model argument and the sub-agent-as-tool flow remain doc-needed but deferred, matching the AGENT-resource change, to be documented once the internal sub-agent lands and the API stabilizes.

    Was this patch authored or co-authored using generative AI tooling?

  • Yes

  • No
  • Generated-by: Qoder 1.29.0 (Qwen3.8-Max)

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: weiqingy Review duration: 20528m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #1114"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 56.8% · Lower = rushed or shallow review
    56.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.5% · Safe to merge
    22.5%