Skip to main content

ag_session/
task_chain.rs

1//! A static Planner, explicit acceptance, and Implementer workflow.
2
3use crate::{
4    AcceptedTaskPlan, AgentSelection, BuiltinAgentDefinition, DurableMessageVisibility, SessionId,
5    SubmitAgentTaskRequest, TaskAgentAssignment, TaskAgentInput,
6};
7
8/// Idempotent launch input captured before the first Planner attempt.
9#[derive(Clone, Debug, Eq, PartialEq)]
10pub struct StartPlanThenImplementRequest {
11    /// Provider/model captured for both roles, independent of later settings.
12    pub agent: AgentSelection,
13    /// Globally unique workflow identity, retained for launch redelivery.
14    pub chain_id: String,
15    /// Globally unique initial Planner delivery identity.
16    pub planner_attempt_id: String,
17    /// Immutable original objective shared by both isolated task contexts.
18    pub user_request: String,
19}
20
21impl StartPlanThenImplementRequest {
22    /// Builds the exact first role request without consulting session state.
23    pub fn planner_request(&self) -> SubmitAgentTaskRequest {
24        SubmitAgentTaskRequest {
25            assignment: TaskAgentAssignment {
26                agent: self.agent,
27                definition: BuiltinAgentDefinition::Planner,
28            },
29            attempt_id: self.planner_attempt_id.clone(),
30            input: TaskAgentInput {
31                accepted_plan: None,
32                clarification: None,
33                user_request: self.user_request.clone(),
34            },
35            objective: self.user_request.clone(),
36            task_id: format!("chain:{}:planner", self.chain_id),
37            visibility: DurableMessageVisibility::Hidden,
38        }
39    }
40
41    /// Identifies the separate Implementer task reserved by this workflow.
42    pub fn implementer_task_id(&self) -> String {
43        format!("chain:{}:implementer", self.chain_id)
44    }
45}
46
47/// Explicit acceptance and initial implementation admission in one action.
48#[derive(Clone, Debug, Eq, PartialEq)]
49pub struct AcceptTaskChainPlanRequest {
50    /// New delivery identity for the first Implementer attempt.
51    pub attempt_id: String,
52    /// Exact latest Planner version selected by the user.
53    pub plan_attempt_id: String,
54}
55
56/// Explicit revision, clarification, or retry of the current workflow stage.
57#[derive(Clone, Debug, Eq, PartialEq)]
58pub struct ContinueTaskChainRequest {
59    /// New delivery identity; old deliveries never restart or uncancel work.
60    pub attempt_id: String,
61    /// User guidance addressed only to the current role's own context.
62    pub clarification: Option<String>,
63    /// Current attempt observed when this guidance was authored. Admission
64    /// rejects a new delivery if the workflow has advanced since that snapshot.
65    /// Identical redelivery retains its original anchor after later progress.
66    pub expected_attempt_id: String,
67}
68
69/// Natural-language user reply addressed to a session's latest workflow.
70///
71/// The host decides what the reply means: plan approval, plan revision, or
72/// guidance for the current role. No words are reserved.
73#[derive(Clone, Debug, Eq, PartialEq)]
74pub struct ReplyToTaskChainRequest {
75    /// User-authored reply, recorded once as a visible session prompt.
76    pub message: String,
77    /// Globally unique delivery identity. Redelivery returns the original
78    /// outcome without recording, deciding, or admitting work again.
79    pub reply_id: String,
80}
81
82/// Workflow action admitted for one natural-language reply.
83#[derive(Clone, Copy, Debug, Eq, PartialEq)]
84pub enum TaskChainReplyOutcome {
85    /// The reply clearly approved the plan; the Implementer was admitted.
86    PlanAccepted,
87    /// The reply was delivered to the Planner as plan revision guidance.
88    PlanRevised,
89    /// The reply was delivered to the current role as an answer or retry.
90    Continued,
91}
92
93impl TaskChainReplyOutcome {
94    /// Every outcome, in the order hosts look up delivery receipts.
95    pub const ALL: [Self; 3] = [Self::PlanAccepted, Self::PlanRevised, Self::Continued];
96
97    /// Derives the attempt identity admitted when one reply has this outcome.
98    pub fn attempt_id(self, reply_id: &str) -> String {
99        let action = match self {
100            Self::PlanAccepted => "implement",
101            Self::PlanRevised => "revise",
102            Self::Continued => "continue",
103        };
104
105        format!("reply:{reply_id}:{action}")
106    }
107}
108
109/// Consistent durable workflow snapshot; reading never dispatches work.
110#[derive(Clone, Debug, Eq, PartialEq)]
111pub struct TaskChain {
112    /// Exact immutable accepted version, present after explicit handoff.
113    pub accepted_plan: Option<AcceptedTaskPlan>,
114    /// Shared captured provider/model selection.
115    pub agent: AgentSelection,
116    /// Exact latest admitted request for the current stage, including IDs.
117    pub current_request: SubmitAgentTaskRequest,
118    /// Stable workflow identity.
119    pub id: String,
120    /// Separate Implementer task, reserved at launch.
121    pub implementer_task_id: String,
122    /// Projection from durable stage selection and operation-backed attempts.
123    pub phase: TaskChainPhase,
124    /// Separate Planner task, retained after implementation begins.
125    pub planner_task_id: String,
126    /// Session owning the shared workspace and serialized worker.
127    pub session_id: SessionId,
128    /// Immutable objective captured at launch.
129    pub user_request: String,
130}
131
132impl TaskChain {
133    /// Builds a new delivery to the current role while retaining its inputs.
134    pub fn continuation_request(
135        &self,
136        request: &ContinueTaskChainRequest,
137    ) -> SubmitAgentTaskRequest {
138        SubmitAgentTaskRequest {
139            attempt_id: request.attempt_id.clone(),
140            input: TaskAgentInput {
141                clarification: request.clarification.clone(),
142                ..self.current_request.input.clone()
143            },
144            ..self.current_request.clone()
145        }
146    }
147}
148
149/// Workflow presentation derived from the current attempt and saved response.
150/// Success records execution, never implicit acceptance of a plan or outcome.
151#[derive(Clone, Copy, Debug, Eq, PartialEq)]
152pub enum TaskChainPhase {
153    /// Planner attempt is queued or executing, including post-processing.
154    Planning,
155    /// Latest successful Planner response needs explicit user acceptance.
156    AwaitingPlanAcceptance,
157    /// Planner has questions that need an explicit continuation.
158    PlannerQuestion,
159    /// Accepted plan is being implemented, including post-processing.
160    Implementing,
161    /// Implementer has questions that need an explicit continuation.
162    ImplementerQuestion,
163    /// Current stage failed or was interrupted; retry is always explicit.
164    Failed,
165    /// Cancellation requested; an explicit new attempt may retry the stage.
166    Canceled,
167    /// Implementer finished successfully; the session remains reviewable.
168    Succeeded,
169}
170
171#[cfg(test)]
172#[path = "task_chain_test.rs"]
173mod tests;