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 "additionalProperties": false
79 }),
80 )
81}
82
83/// Parsed `__handoff_to` arguments, surfaced as
84/// [`crate::TurnResult::handoff`].
85///
86/// The control plane consumes this to:
87/// 1. Slice the parent's transcript per [`HandoffRequest::carried_context`]
88/// (the agent crate has already done the slicing).
89/// 2. Sign-and-write a `Handoff` event to the parent's eventlog partition.
90/// 3. Create the child `Conversation` resource.
91#[derive(Debug, Clone)]
92pub struct HandoffRequest {
93 /// Tool-call id the provider assigned to the `__handoff_to` call. Echoed
94 /// back to the provider on the parent's *next* turn as the `tool_result`
95 /// id, so the function-calling loop on the parent's resumed turn sees a
96 /// matched call → result pair (otherwise the provider rejects the turn
97 /// for a dangling call).
98 pub call_id: String,
99 /// The model's chosen child agent identifier.
100 pub child_agent_id: String,
101 /// Optional free-form reason captured for operator visibility.
102 pub reason: String,
103 /// Sliding-window cap on the carried transcript. The runtime applies it
104 /// against the *current* turn's transcript when packaging the handoff.
105 pub max_carry: usize,
106 /// The pre-sliced carried transcript — the last `max_carry` messages of
107 /// the parent's transcript at the moment of the handoff call. Stored as
108 /// llm messages; the control plane maps them to wire `Message`s on the
109 /// way into the `Handoff` event payload.
110 pub carried_context: Vec<LlmMessage>,
111}
112
113/// Default carried-context window when the model omits `max_carry`.
114///
115/// Kept small — the child gets a fresh sandbox / new sliding window, so
116/// dragging in the parent's full context defeats the isolation a handoff is
117/// for. A future variant accepts a per-handoff `input_filter` predicate (a
118/// projection from the parent's transcript to the child's seed).
119pub const DEFAULT_MAX_CARRY: usize = 5;
120
121/// Parse the JSON arguments of a `__handoff_to` tool call into a structured
122/// [`HandoffRequest`].
123///
124/// `transcript_so_far` is the parent's *current* turn messages — the runtime
125/// slices the tail per `max_carry` (or [`DEFAULT_MAX_CARRY`] when absent)
126/// into `carried_context`.
127///
128/// Returns `None` if `args_json` doesn't parse or the required
129/// `child_agent_id` is missing — the runtime then treats the call as a
130/// no-op and lets the loop continue (so a malformed call doesn't deadlock
131/// the turn).
132#[must_use]
133pub fn parse_handoff_args(
134 call_id: &str,
135 args_json: &str,
136 transcript_so_far: &[LlmMessage],
137) -> Option<HandoffRequest> {
138 let v: serde_json::Value = serde_json::from_str(args_json).ok()?;
139 let child_agent_id = v.get("child_agent_id")?.as_str()?.to_owned();
140 if child_agent_id.is_empty() {
141 return None;
142 }
143 let reason = v
144 .get("reason")
145 .and_then(serde_json::Value::as_str)
146 .unwrap_or("")
147 .to_owned();
148 // Clamp max_carry to the actual transcript length so the slice never
149 // panics; a malicious model asking for u64::MAX still produces a sane
150 // slice (the whole transcript).
151 #[allow(clippy::cast_possible_truncation)]
152 let raw_max_carry = v
153 .get("max_carry")
154 .and_then(serde_json::Value::as_u64)
155 .map_or(DEFAULT_MAX_CARRY, |n| n as usize);
156 let max_carry = raw_max_carry.min(transcript_so_far.len());
157 let start = transcript_so_far.len().saturating_sub(max_carry);
158 let carried_context = transcript_so_far[start..].to_vec();
159 Some(HandoffRequest {
160 call_id: call_id.to_owned(),
161 child_agent_id,
162 reason,
163 max_carry,
164 carried_context,
165 })
166}
167
168#[cfg(test)]
169mod tests {
170 #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
171
172 use polyc_llm::Message as LlmMessage;
173
174 use super::*;
175
176 fn transcript(n: usize) -> Vec<LlmMessage> {
177 (0..n)
178 .map(|i| {
179 if i % 2 == 0 {
180 LlmMessage::user(format!("u{i}"))
181 } else {
182 LlmMessage::assistant(format!("a{i}"))
183 }
184 })
185 .collect()
186 }
187
188 #[test]
189 fn parses_minimum_required_args() {
190 let t = transcript(10);
191 let h = parse_handoff_args("c-1", r#"{"child_agent_id":"researcher"}"#, &t).unwrap();
192 assert_eq!(h.child_agent_id, "researcher");
193 assert_eq!(h.max_carry, DEFAULT_MAX_CARRY);
194 assert_eq!(h.carried_context.len(), DEFAULT_MAX_CARRY);
195 assert_eq!(h.call_id, "c-1");
196 }
197
198 #[test]
199 fn slices_last_n_messages() {
200 let t = transcript(10);
201 let h = parse_handoff_args(
202 "c-2",
203 r#"{"child_agent_id":"x","max_carry":3,"reason":"because"}"#,
204 &t,
205 )
206 .unwrap();
207 assert_eq!(h.max_carry, 3);
208 assert_eq!(h.carried_context.len(), 3);
209 assert_eq!(h.reason, "because");
210 // The tail of the transcript.
211 let last_text = match h.carried_context.last().unwrap().content.first().unwrap() {
212 polyc_llm::Content::Text(s) => s.clone(),
213 _ => panic!("expected text"),
214 };
215 assert_eq!(last_text, "a9");
216 }
217
218 #[test]
219 fn clamps_max_carry_to_transcript_length() {
220 let t = transcript(2);
221 let h = parse_handoff_args("c", r#"{"child_agent_id":"x","max_carry":1000}"#, &t).unwrap();
222 assert_eq!(h.max_carry, 2, "clamped to len");
223 assert_eq!(h.carried_context.len(), 2);
224 }
225
226 #[test]
227 fn rejects_missing_child_agent_id() {
228 let t = transcript(2);
229 assert!(parse_handoff_args("c", r#"{"reason":"x"}"#, &t).is_none());
230 }
231
232 #[test]
233 fn rejects_empty_child_agent_id() {
234 let t = transcript(2);
235 assert!(parse_handoff_args("c", r#"{"child_agent_id":""}"#, &t).is_none());
236 }
237
238 #[test]
239 fn rejects_garbage_json() {
240 let t = transcript(2);
241 assert!(parse_handoff_args("c", "not-json", &t).is_none());
242 }
243
244 #[test]
245 fn empty_transcript_yields_empty_carry() {
246 let h = parse_handoff_args("c", r#"{"child_agent_id":"x"}"#, &[]).unwrap();
247 assert_eq!(h.max_carry, 0);
248 assert!(h.carried_context.is_empty());
249 }
250
251 #[test]
252 fn handoff_tool_spec_has_required_field() {
253 let spec = handoff_tool_spec();
254 assert_eq!(spec.name, HANDOFF_TOOL_NAME);
255 let required = spec
256 .schema_json
257 .get("required")
258 .and_then(|v| v.as_array())
259 .cloned()
260 .unwrap_or_default();
261 assert!(required.iter().any(|v| v == "child_agent_id"));
262 // Strict schema — no undeclared arguments (matches `__delegate_to`,
263 // #1141).
264 assert_eq!(
265 spec.schema_json.get("additionalProperties"),
266 Some(&serde_json::json!(false))
267 );
268 }
269}