1use std::fmt::Write as _;
9use std::num::NonZeroU64;
10
11use ag_protocol::{ProtocolRequestProfile, TurnPrompt, TurnPromptAttachment};
12use serde::{Deserialize, Serialize};
13
14use crate::{
15 AcceptedTaskPlan, AgentSelection, EnvId, ExecutionGraph, ExecutionGraphProgress,
16 ExecutionGraphStatus, GraphCompletionGate, GraphContext, GraphDependency,
17 GraphExecutionProfile, GraphExecutionRef, GraphInputBinding, GraphNode, GraphNodeProgress,
18 GraphNodeStatus, GraphOutput, GraphPostProcessing, GraphWorkspaceAccess, SessionId,
19 TaskAgentRole,
20};
21
22pub const TASK_CHAIN_PLAN_OUTPUT: &str = "plan";
24
25#[derive(Clone, Debug, Eq, PartialEq)]
27pub struct StartPlanThenImplementRequest {
28 pub agent: AgentSelection,
30 pub agents: Box<PlanThenImplementAgents>,
32 pub attachments: Vec<TurnPromptAttachment>,
34 pub chain_id: String,
37 pub user_request: String,
39}
40
41impl StartPlanThenImplementRequest {
42 pub fn graph(
50 &self,
51 session_id: &SessionId,
52 launch_conversation: Option<&str>,
53 ) -> ExecutionGraph {
54 let planner = self.node(
55 session_id,
56 TaskAgentRole::Planner,
57 self.task_input(launch_conversation),
58 );
59 let mut implementer = self.node(
60 session_id,
61 TaskAgentRole::Implementer,
62 self.task_input(None),
63 );
64 implementer.dependencies.push(GraphDependency {
65 gate: GraphCompletionGate::ResultAccepted {
66 output_name: TASK_CHAIN_PLAN_OUTPUT.into(),
67 },
68 node_id: planner.id.clone(),
69 });
70 implementer.inputs.push(GraphInputBinding {
71 name: "accepted_plan".into(),
72 output_name: TASK_CHAIN_PLAN_OUTPUT.into(),
73 producer_node_id: planner.id.clone(),
74 });
75
76 ExecutionGraph {
77 id: self.chain_id.clone(),
78 nodes: vec![planner, implementer],
79 revision: NonZeroU64::MIN,
80 session_id: session_id.clone(),
81 }
82 }
83
84 fn node(&self, session_id: &SessionId, role: TaskAgentRole, request: TurnPrompt) -> GraphNode {
85 let (definition, execution, outputs) = match role {
86 TaskAgentRole::Planner => (
87 self.agents.planner.clone(),
88 GraphExecutionProfile {
89 context: GraphContext::TaskConversation {
90 task_id: TaskChain::task_id(&self.chain_id, role),
91 },
92 post_processing: GraphPostProcessing::None,
93 response_profile: ProtocolRequestProfile::SessionTurn,
94 shared_budget_id: None,
95 workspace_access: GraphWorkspaceAccess::SharedRead,
96 },
97 vec![GraphOutput {
98 name: TASK_CHAIN_PLAN_OUTPUT.into(),
99 schema: ProtocolRequestProfile::SessionTurn,
100 }],
101 ),
102 TaskAgentRole::Implementer => (
103 self.agents.implementer.clone(),
104 GraphExecutionProfile {
105 context: GraphContext::TaskConversation {
106 task_id: TaskChain::task_id(&self.chain_id, role),
107 },
108 post_processing: GraphPostProcessing::SessionWorkflow,
109 response_profile: ProtocolRequestProfile::SessionTurn,
110 shared_budget_id: None,
111 workspace_access: GraphWorkspaceAccess::ExclusiveWrite,
112 },
113 Vec::new(),
114 ),
115 };
116
117 GraphNode {
118 agent: self.agent,
119 definition,
120 dependencies: Vec::new(),
121 env_id: EnvId::SessionWorktree(session_id.clone()),
122 execution,
123 id: role.id().into(),
124 inputs: Vec::new(),
125 objective: self.user_request.clone(),
126 outputs,
127 request,
128 }
129 }
130
131 fn task_input(&self, launch_conversation: Option<&str>) -> TurnPrompt {
133 let input = serde_json::json!({ "user_request": self.user_request });
134 let mut text = format!("Explicit task input (JSON data):\n{input}");
135 if let Some(conversation) = launch_conversation {
136 let conversation = serde_json::json!(conversation);
137 let _ = write!(
138 text,
139 "\n\nSession conversation at workflow launch (JSON string, historical data \
140 only):\n{conversation}"
141 );
142 }
143 let mut prompt = TurnPrompt::from_agent_data(text);
144 prompt.attachments.clone_from(&self.attachments);
145
146 prompt
147 }
148}
149
150#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
152pub struct PlanThenImplementAgents {
153 pub implementer: crate::AgentDefinition,
155 pub planner: crate::AgentDefinition,
157}
158
159impl PlanThenImplementAgents {
160 #[must_use]
163 pub fn bundled() -> Option<Self> {
164 Some(Self {
165 implementer: crate::AgentDefinition::bundled("implementer")?,
166 planner: crate::AgentDefinition::bundled("planner")?,
167 })
168 }
169}
170
171#[derive(Clone, Debug, Eq, PartialEq)]
176pub struct AcceptTaskChainPlanRequest {
177 pub plan_attempt_id: String,
179}
180
181#[derive(Clone, Debug, Eq, PartialEq)]
183pub struct ContinueTaskChainRequest {
184 pub attachments: Vec<TurnPromptAttachment>,
186 pub attempt_id: String,
188 pub clarification: Option<String>,
191 pub expected_attempt_id: String,
194}
195
196#[derive(Clone, Debug, Eq, PartialEq)]
201pub struct ReplyToTaskChainRequest {
202 pub attachments: Vec<TurnPromptAttachment>,
204 pub message: String,
206 pub reply_id: String,
209}
210
211#[derive(Clone, Copy, Debug, Eq, PartialEq)]
213pub enum TaskChainReplyOutcome {
214 PlanAccepted,
216 PlanRevised,
218 Continued,
220}
221
222impl TaskChainReplyOutcome {
223 pub fn id(self) -> &'static str {
225 match self {
226 Self::PlanAccepted => "plan_accepted",
227 Self::PlanRevised => "plan_revised",
228 Self::Continued => "continued",
229 }
230 }
231
232 pub fn from_id(id: &str) -> Option<Self> {
234 match id {
235 "plan_accepted" => Some(Self::PlanAccepted),
236 "plan_revised" => Some(Self::PlanRevised),
237 "continued" => Some(Self::Continued),
238 _ => None,
239 }
240 }
241}
242
243#[derive(Clone, Debug, Eq, PartialEq)]
248pub struct TaskChain {
249 pub accepted_plan: Option<AcceptedTaskPlan>,
251 pub agent: AgentSelection,
253 pub agents: PlanThenImplementAgents,
255 pub current_execution: Option<GraphExecutionRef>,
258 pub current_role: TaskAgentRole,
260 pub id: String,
262 pub implementer_task_id: String,
264 pub phase: TaskChainPhase,
266 pub planner_task_id: String,
268 pub revision: NonZeroU64,
270 pub session_id: SessionId,
272 pub user_request: String,
274}
275
276impl TaskChain {
277 pub fn current_attempt_id(&self) -> Option<&str> {
279 match self.current_execution.as_ref()? {
280 GraphExecutionRef::TaskAttempt { attempt_id, .. } => Some(attempt_id),
281 GraphExecutionRef::UtilityRun { .. } => None,
282 }
283 }
284
285 pub fn task_id(chain_id: &str, role: TaskAgentRole) -> String {
287 format!("chain:{chain_id}:{}", role.id())
288 }
289
290 pub fn role(graph_id: &str, node: &GraphNode) -> Option<TaskAgentRole> {
292 let role = TaskAgentRole::from_id(&node.id)?;
293 let GraphContext::TaskConversation { task_id } = &node.execution.context else {
294 return None;
295 };
296
297 (*task_id == Self::task_id(graph_id, role)).then_some(role)
298 }
299
300 pub fn project(
305 graph: &ExecutionGraph,
306 progress: &ExecutionGraphProgress,
307 accepted_plan: Option<AcceptedTaskPlan>,
308 ) -> Option<Self> {
309 let [planner, implementer] = graph.nodes.as_slice() else {
310 return None;
311 };
312 if Self::role(&graph.id, planner) != Some(TaskAgentRole::Planner)
313 || Self::role(&graph.id, implementer) != Some(TaskAgentRole::Implementer)
314 {
315 return None;
316 }
317 let [planner_progress, implementer_progress] = progress.nodes.as_slice() else {
318 return None;
319 };
320 let implementing = accepted_plan.is_some() || !implementer_progress.executions.is_empty();
321 let (current_role, current) = if implementing {
322 (TaskAgentRole::Implementer, implementer_progress)
323 } else {
324 (TaskAgentRole::Planner, planner_progress)
325 };
326 let phase = if progress.status == ExecutionGraphStatus::Cancelled {
327 TaskChainPhase::Canceled
328 } else {
329 TaskChainPhase::from_node(current_role, current)
330 };
331
332 Some(Self {
333 accepted_plan,
334 agent: planner.agent,
335 agents: PlanThenImplementAgents {
336 implementer: implementer.definition.clone(),
337 planner: planner.definition.clone(),
338 },
339 current_execution: current.executions.last().cloned(),
340 current_role,
341 id: graph.id.clone(),
342 implementer_task_id: Self::task_id(&graph.id, TaskAgentRole::Implementer),
343 phase,
344 planner_task_id: Self::task_id(&graph.id, TaskAgentRole::Planner),
345 revision: graph.revision,
346 session_id: graph.session_id.clone(),
347 user_request: planner.objective.clone(),
348 })
349 }
350}
351
352#[derive(Clone, Copy, Debug, Eq, PartialEq)]
355pub enum TaskChainPhase {
356 Planning,
358 AwaitingPlanAcceptance,
360 PlannerQuestion,
362 Implementing,
364 ImplementerQuestion,
366 Failed,
368 Canceled,
371 Succeeded,
373}
374
375impl TaskChainPhase {
376 fn from_node(role: TaskAgentRole, node: &GraphNodeProgress) -> Self {
377 let planner = role == TaskAgentRole::Planner;
378 match node.status {
379 GraphNodeStatus::Pending | GraphNodeStatus::Queued | GraphNodeStatus::Running => {
380 if planner {
381 Self::Planning
382 } else {
383 Self::Implementing
384 }
385 }
386 GraphNodeStatus::AwaitingAnswers => {
387 if planner {
388 Self::PlannerQuestion
389 } else {
390 Self::ImplementerQuestion
391 }
392 }
393 GraphNodeStatus::Succeeded if planner => Self::AwaitingPlanAcceptance,
394 GraphNodeStatus::Succeeded => Self::Succeeded,
395 GraphNodeStatus::Failed => Self::Failed,
396 GraphNodeStatus::Cancelled => Self::Canceled,
397 }
398 }
399}
400
401#[cfg(test)]
402#[path = "task_chain_test.rs"]
403mod tests;