Skip to main content

polyc_agent/
handoff.rs

1//! Handoff (sub-agent transfer) primitive for the agent turn loop.
2//!
3//! # Why a reserved tool name, not a wire message
4//!
5//! Two clean designs exist for "the parent wants to spawn a child agent":
6//!
7//!   1. A first-class wire message — e.g. a new `AgentResponse` oneof variant
8//!      the planner emits. The control plane sees the variant on the response
9//!      stream and reacts.
10//!   2. A reserved *tool name* the model can call from inside the standard
11//!      function-calling loop. The tool executor recognises the name, doesn't
12//!      execute anything, and surfaces it as a structured break-out of
13//!      `run_turn`.
14//!
15//! We pick **(2) reserved tool name** (`HANDOFF_TOOL_NAME`) because:
16//!
17//!   * It rides the existing provider function-calling shape (every modern
18//!     provider models "call function X with JSON args"). No new channel is
19//!     needed, no provider integration is touched.
20//!   * It keeps the agent crate the single authority on the turn loop — the
21//!     handoff is "the model asked to delegate", uniformly across providers.
22//!   * Convergent with prior-art agent SDKs that advertise handoffs to the
23//!     model as tools (turning the choice of delegation into a function the
24//!     planner can reason about with the rest of its toolbox).
25//!
26//! Wire-level surfacing happens upstream in the control plane: when
27//! `run_turn` returns a [`TurnResult`](crate::TurnResult) with a populated
28//! [`TurnResult::handoff`](crate::TurnResult), the control plane emits a
29//! signed [`polyc_proto::proto::polychrome::handoff::v1::Handoff`] event
30//! into the *parent* conversation's journal, creates a child `Conversation`
31//! resource, and suspends the parent until a
32//! `polyc_proto::proto::polychrome::handoff::v1::HandoffReturn` event
33//! lands.
34
35use polyc_llm::{Message as LlmMessage, ToolSpec};
36
37/// The reserved tool name the model emits to request a sub-agent handoff.
38///
39/// Any [`crate::ToolExecutor`] implementation that mixes user tools with the
40/// handoff primitive must avoid using this name for a real tool — the runtime
41/// short-circuits the name before [`crate::ToolExecutor::execute`] is invoked.
42pub const HANDOFF_TOOL_NAME: &str = "__handoff_to";
43
44/// JSON-schema spec for the handoff tool. Provided alongside the user's tool
45/// specs so the model knows the shape of `handoff_to(child_agent_id, ...)`.
46/// Use [`handoff_tool_spec`] to obtain it.
47#[must_use]
48pub fn handoff_tool_spec() -> ToolSpec {
49    // Handoff is a control-plane delegation handled by the harness's own
50    // suspend/resume path, not the HITL spend gate; leave it ungated and
51    // un-annotated (neither read-only nor destructive in the tool sense).
52    ToolSpec::new(
53        HANDOFF_TOOL_NAME,
54        "Delegate the current task to a child sub-agent. The current turn suspends; the \
55             child runs in its own isolated conversation with the carried context; the child's \
56             final message is returned to this conversation on the next turn. Use sparingly — \
57             handoffs are expensive (cold-start a sandbox). `child_agent_id` selects the \
58             planner; `reason` is recorded for operator visibility; `max_carry` bounds how many \
59             of the most recent messages the child sees (default 5).",
60        serde_json::json!({
61            "type": "object",
62            "properties": {
63                "child_agent_id": {
64                    "type": "string",
65                    "description": "Identifier of the child agent / planner to spawn."
66                },
67                "reason": {
68                    "type": "string",
69                    "description": "Short rationale for the delegation."
70                },
71                "max_carry": {
72                    "type": "integer",
73                    "minimum": 0,
74                    "description": "How many of the most recent messages from this conversation to inject as the child's initial transcript. Default 5."
75                }
76            },
77            "required": ["child_agent_id"]
78        }),
79    )
80}
81
82/// Parsed `__handoff_to` arguments, surfaced as
83/// [`crate::TurnResult::handoff`].
84///
85/// The control plane consumes this to:
86///   1. Slice the parent's transcript per [`HandoffRequest::carried_context`]
87///      (the agent crate has already done the slicing).
88///   2. Sign-and-write a `Handoff` event to the parent's eventlog partition.
89///   3. Create the child `Conversation` resource.
90#[derive(Debug, Clone)]
91pub struct HandoffRequest {
92    /// Tool-call id the provider assigned to the `__handoff_to` call. Echoed
93    /// back to the provider on the parent's *next* turn as the `tool_result`
94    /// id, so the function-calling loop on the parent's resumed turn sees a
95    /// matched call → result pair (otherwise the provider rejects the turn
96    /// for a dangling call).
97    pub call_id: String,
98    /// The model's chosen child agent identifier.
99    pub child_agent_id: String,
100    /// Optional free-form reason captured for operator visibility.
101    pub reason: String,
102    /// Sliding-window cap on the carried transcript. The runtime applies it
103    /// against the *current* turn's transcript when packaging the handoff.
104    pub max_carry: usize,
105    /// The pre-sliced carried transcript — the last `max_carry` messages of
106    /// the parent's transcript at the moment of the handoff call. Stored as
107    /// llm messages; the control plane maps them to wire `Message`s on the
108    /// way into the `Handoff` event payload.
109    pub carried_context: Vec<LlmMessage>,
110}
111
112/// Default carried-context window when the model omits `max_carry`.
113///
114/// Kept small — the child gets a fresh sandbox / new sliding window, so
115/// dragging in the parent's full context defeats the isolation a handoff is
116/// for. A future variant accepts a per-handoff `input_filter` predicate (a
117/// projection from the parent's transcript to the child's seed).
118pub const DEFAULT_MAX_CARRY: usize = 5;
119
120/// Parse the JSON arguments of a `__handoff_to` tool call into a structured
121/// [`HandoffRequest`].
122///
123/// `transcript_so_far` is the parent's *current* turn messages — the runtime
124/// slices the tail per `max_carry` (or [`DEFAULT_MAX_CARRY`] when absent)
125/// into `carried_context`.
126///
127/// Returns `None` if `args_json` doesn't parse or the required
128/// `child_agent_id` is missing — the runtime then treats the call as a
129/// no-op and lets the loop continue (so a malformed call doesn't deadlock
130/// the turn).
131#[must_use]
132pub fn parse_handoff_args(
133    call_id: &str,
134    args_json: &str,
135    transcript_so_far: &[LlmMessage],
136) -> Option<HandoffRequest> {
137    let v: serde_json::Value = serde_json::from_str(args_json).ok()?;
138    let child_agent_id = v.get("child_agent_id")?.as_str()?.to_owned();
139    if child_agent_id.is_empty() {
140        return None;
141    }
142    let reason = v
143        .get("reason")
144        .and_then(serde_json::Value::as_str)
145        .unwrap_or("")
146        .to_owned();
147    // Clamp max_carry to the actual transcript length so the slice never
148    // panics; a malicious model asking for u64::MAX still produces a sane
149    // slice (the whole transcript).
150    #[allow(clippy::cast_possible_truncation)]
151    let raw_max_carry = v
152        .get("max_carry")
153        .and_then(serde_json::Value::as_u64)
154        .map_or(DEFAULT_MAX_CARRY, |n| n as usize);
155    let max_carry = raw_max_carry.min(transcript_so_far.len());
156    let start = transcript_so_far.len().saturating_sub(max_carry);
157    let carried_context = transcript_so_far[start..].to_vec();
158    Some(HandoffRequest {
159        call_id: call_id.to_owned(),
160        child_agent_id,
161        reason,
162        max_carry,
163        carried_context,
164    })
165}
166
167#[cfg(test)]
168mod tests {
169    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
170
171    use polyc_llm::Message as LlmMessage;
172
173    use super::*;
174
175    fn transcript(n: usize) -> Vec<LlmMessage> {
176        (0..n)
177            .map(|i| {
178                if i % 2 == 0 {
179                    LlmMessage::user(format!("u{i}"))
180                } else {
181                    LlmMessage::assistant(format!("a{i}"))
182                }
183            })
184            .collect()
185    }
186
187    #[test]
188    fn parses_minimum_required_args() {
189        let t = transcript(10);
190        let h = parse_handoff_args("c-1", r#"{"child_agent_id":"researcher"}"#, &t).unwrap();
191        assert_eq!(h.child_agent_id, "researcher");
192        assert_eq!(h.max_carry, DEFAULT_MAX_CARRY);
193        assert_eq!(h.carried_context.len(), DEFAULT_MAX_CARRY);
194        assert_eq!(h.call_id, "c-1");
195    }
196
197    #[test]
198    fn slices_last_n_messages() {
199        let t = transcript(10);
200        let h = parse_handoff_args(
201            "c-2",
202            r#"{"child_agent_id":"x","max_carry":3,"reason":"because"}"#,
203            &t,
204        )
205        .unwrap();
206        assert_eq!(h.max_carry, 3);
207        assert_eq!(h.carried_context.len(), 3);
208        assert_eq!(h.reason, "because");
209        // The tail of the transcript.
210        let last_text = match h.carried_context.last().unwrap().content.first().unwrap() {
211            polyc_llm::Content::Text(s) => s.clone(),
212            _ => panic!("expected text"),
213        };
214        assert_eq!(last_text, "a9");
215    }
216
217    #[test]
218    fn clamps_max_carry_to_transcript_length() {
219        let t = transcript(2);
220        let h = parse_handoff_args("c", r#"{"child_agent_id":"x","max_carry":1000}"#, &t).unwrap();
221        assert_eq!(h.max_carry, 2, "clamped to len");
222        assert_eq!(h.carried_context.len(), 2);
223    }
224
225    #[test]
226    fn rejects_missing_child_agent_id() {
227        let t = transcript(2);
228        assert!(parse_handoff_args("c", r#"{"reason":"x"}"#, &t).is_none());
229    }
230
231    #[test]
232    fn rejects_empty_child_agent_id() {
233        let t = transcript(2);
234        assert!(parse_handoff_args("c", r#"{"child_agent_id":""}"#, &t).is_none());
235    }
236
237    #[test]
238    fn rejects_garbage_json() {
239        let t = transcript(2);
240        assert!(parse_handoff_args("c", "not-json", &t).is_none());
241    }
242
243    #[test]
244    fn empty_transcript_yields_empty_carry() {
245        let h = parse_handoff_args("c", r#"{"child_agent_id":"x"}"#, &[]).unwrap();
246        assert_eq!(h.max_carry, 0);
247        assert!(h.carried_context.is_empty());
248    }
249
250    #[test]
251    fn handoff_tool_spec_has_required_field() {
252        let spec = handoff_tool_spec();
253        assert_eq!(spec.name, HANDOFF_TOOL_NAME);
254        let required = spec
255            .schema_json
256            .get("required")
257            .and_then(|v| v.as_array())
258            .cloned()
259            .unwrap_or_default();
260        assert!(required.iter().any(|v| v == "child_agent_id"));
261    }
262}