ag-session 0.18.3

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! The static Planner → accepted plan → Implementer execution graph.
//!
//! A task chain is a fixed two-node [`ExecutionGraph`]. Graph storage and the
//! static executor own admission, gates, exact handoff, and recovery; this
//! module only builds that graph and projects its progress into workflow
//! phases.

use std::fmt::Write as _;
use std::num::NonZeroU64;

use ag_protocol::{ProtocolRequestProfile, TurnPrompt, TurnPromptAttachment};
use serde::{Deserialize, Serialize};

use crate::{
    AcceptedTaskPlan, AgentSelection, EnvId, ExecutionGraph, ExecutionGraphProgress,
    ExecutionGraphStatus, GraphCompletionGate, GraphContext, GraphDependency,
    GraphExecutionProfile, GraphExecutionRef, GraphInputBinding, GraphNode, GraphNodeProgress,
    GraphNodeStatus, GraphOutput, GraphPostProcessing, GraphWorkspaceAccess, SessionId,
    TaskAgentRole,
};

/// Named Planner output that the Implementer consumes after acceptance.
pub const TASK_CHAIN_PLAN_OUTPUT: &str = "plan";

/// Idempotent launch input captured before the first Planner execution.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StartPlanThenImplementRequest {
    /// Provider/model captured for both roles, independent of later settings.
    pub agent: AgentSelection,
    /// Resolved definitions captured together before planning starts.
    pub agents: Box<PlanThenImplementAgents>,
    /// Images accompanying the original request.
    pub attachments: Vec<TurnPromptAttachment>,
    /// Globally unique workflow and execution-graph identity, retained for
    /// launch redelivery.
    pub chain_id: String,
    /// Immutable original objective shared by both isolated task contexts.
    pub user_request: String,
}

impl StartPlanThenImplementRequest {
    /// Builds the immutable graph without consulting session state.
    ///
    /// The Planner is a shared reader whose validated `plan` output must be
    /// explicitly accepted before the exclusive-writer Implementer starts with
    /// that exact version bound as input. `launch_conversation` is the host's
    /// snapshot of the session conversation before launch; it is captured as
    /// historical data in the Planner's request only.
    pub fn graph(
        &self,
        session_id: &SessionId,
        launch_conversation: Option<&str>,
    ) -> ExecutionGraph {
        let planner = self.node(
            session_id,
            TaskAgentRole::Planner,
            self.task_input(launch_conversation),
        );
        let mut implementer = self.node(
            session_id,
            TaskAgentRole::Implementer,
            self.task_input(None),
        );
        implementer.dependencies.push(GraphDependency {
            gate: GraphCompletionGate::ResultAccepted {
                output_name: TASK_CHAIN_PLAN_OUTPUT.into(),
            },
            node_id: planner.id.clone(),
        });
        implementer.inputs.push(GraphInputBinding {
            name: "accepted_plan".into(),
            output_name: TASK_CHAIN_PLAN_OUTPUT.into(),
            producer_node_id: planner.id.clone(),
        });

        ExecutionGraph {
            id: self.chain_id.clone(),
            nodes: vec![planner, implementer],
            revision: NonZeroU64::MIN,
            session_id: session_id.clone(),
        }
    }

    fn node(&self, session_id: &SessionId, role: TaskAgentRole, request: TurnPrompt) -> GraphNode {
        let (definition, execution, outputs) = match role {
            TaskAgentRole::Planner => (
                self.agents.planner.clone(),
                GraphExecutionProfile {
                    context: GraphContext::TaskConversation {
                        task_id: TaskChain::task_id(&self.chain_id, role),
                    },
                    post_processing: GraphPostProcessing::None,
                    response_profile: ProtocolRequestProfile::SessionTurn,
                    shared_budget_id: None,
                    workspace_access: GraphWorkspaceAccess::SharedRead,
                },
                vec![GraphOutput {
                    name: TASK_CHAIN_PLAN_OUTPUT.into(),
                    schema: ProtocolRequestProfile::SessionTurn,
                }],
            ),
            TaskAgentRole::Implementer => (
                self.agents.implementer.clone(),
                GraphExecutionProfile {
                    context: GraphContext::TaskConversation {
                        task_id: TaskChain::task_id(&self.chain_id, role),
                    },
                    post_processing: GraphPostProcessing::SessionWorkflow,
                    response_profile: ProtocolRequestProfile::SessionTurn,
                    shared_budget_id: None,
                    workspace_access: GraphWorkspaceAccess::ExclusiveWrite,
                },
                Vec::new(),
            ),
        };

        GraphNode {
            agent: self.agent,
            definition,
            dependencies: Vec::new(),
            env_id: EnvId::SessionWorktree(session_id.clone()),
            execution,
            id: role.id().into(),
            inputs: Vec::new(),
            objective: self.user_request.clone(),
            outputs,
            request,
        }
    }

    /// Encodes the original request as data, keeping its images attached.
    fn task_input(&self, launch_conversation: Option<&str>) -> TurnPrompt {
        let input = serde_json::json!({ "user_request": self.user_request });
        let mut text = format!("Explicit task input (JSON data):\n{input}");
        if let Some(conversation) = launch_conversation {
            let conversation = serde_json::json!(conversation);
            let _ = write!(
                text,
                "\n\nSession conversation at workflow launch (JSON string, historical data \
                 only):\n{conversation}"
            );
        }
        let mut prompt = TurnPrompt::from_agent_data(text);
        prompt.attachments.clone_from(&self.attachments);

        prompt
    }
}

/// Definitions assigned to workflow stages, independent of stage policy.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct PlanThenImplementAgents {
    /// Agent used for implementation after explicit acceptance.
    pub implementer: crate::AgentDefinition,
    /// Agent used for planning and revisions.
    pub planner: crate::AgentDefinition,
}

impl PlanThenImplementAgents {
    /// Resolves the bundled defaults, returning `None` if either is
    /// unavailable.
    #[must_use]
    pub fn bundled() -> Option<Self> {
        Some(Self {
            implementer: crate::AgentDefinition::bundled("implementer")?,
            planner: crate::AgentDefinition::bundled("planner")?,
        })
    }
}

/// Explicit acceptance of one exact Planner version.
///
/// Acceptance satisfies the Implementer's dependency gate; the executor then
/// admits the Implementer with that version pinned as input.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AcceptTaskChainPlanRequest {
    /// Latest validated Planner execution selected by the user.
    pub plan_attempt_id: String,
}

/// Explicit revision, clarification, or retry of the current workflow stage.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ContinueTaskChainRequest {
    /// Images accompanying this guidance, retained by later attempts.
    pub attachments: Vec<TurnPromptAttachment>,
    /// New execution UUID; old deliveries never restart or uncancel work.
    pub attempt_id: String,
    /// User guidance addressed only to the current role's own context.
    /// `None` retries failed or canceled work with its original request.
    pub clarification: Option<String>,
    /// Current attempt observed when this guidance was authored. Admission
    /// rejects a new delivery if the workflow has advanced since that snapshot.
    pub expected_attempt_id: String,
}

/// Natural-language user reply addressed to a session's latest workflow.
///
/// The host decides what the reply means: plan approval, plan revision, or
/// guidance for the current role. No words are reserved.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ReplyToTaskChainRequest {
    /// Images accompanying the visible reply.
    pub attachments: Vec<TurnPromptAttachment>,
    /// User-authored reply, recorded once as a visible session prompt.
    pub message: String,
    /// Globally unique delivery identity. Redelivery returns the original
    /// outcome without recording or deciding again.
    pub reply_id: String,
}

/// Workflow action admitted for one natural-language reply.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TaskChainReplyOutcome {
    /// The reply clearly approved the plan; the Implementer was released.
    PlanAccepted,
    /// The reply was delivered to the Planner as plan revision guidance.
    PlanRevised,
    /// The reply was delivered to the current role as an answer or retry.
    Continued,
}

impl TaskChainReplyOutcome {
    /// Stable persisted identity.
    pub fn id(self) -> &'static str {
        match self {
            Self::PlanAccepted => "plan_accepted",
            Self::PlanRevised => "plan_revised",
            Self::Continued => "continued",
        }
    }

    /// Resolves an identity produced by [`Self::id`].
    pub fn from_id(id: &str) -> Option<Self> {
        match id {
            "plan_accepted" => Some(Self::PlanAccepted),
            "plan_revised" => Some(Self::PlanRevised),
            "continued" => Some(Self::Continued),
            _ => None,
        }
    }
}

/// Consistent workflow snapshot projected from one execution graph.
///
/// Reading never dispatches work. Graph executions remain the authoritative
/// execution records.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TaskChain {
    /// Exact immutable accepted version, present after explicit handoff.
    pub accepted_plan: Option<AcceptedTaskPlan>,
    /// Shared captured provider/model selection.
    pub agent: AgentSelection,
    /// Immutable definitions captured for both workflow stages at launch.
    pub agents: PlanThenImplementAgents,
    /// Latest admitted execution of the current role, absent before its
    /// first admission. A pending continuation keeps its source here.
    pub current_execution: Option<GraphExecutionRef>,
    /// Role the user currently interacts with.
    pub current_role: TaskAgentRole,
    /// Stable workflow identity, equal to its execution-graph identity.
    pub id: String,
    /// Separate Implementer task conversation.
    pub implementer_task_id: String,
    /// Projection from graph node progress.
    pub phase: TaskChainPhase,
    /// Separate Planner task conversation, retained after implementation.
    pub planner_task_id: String,
    /// Graph revision used by explicit graph actions.
    pub revision: NonZeroU64,
    /// Session owning the shared workspace and serialized worker.
    pub session_id: SessionId,
    /// Immutable objective captured at launch.
    pub user_request: String,
}

impl TaskChain {
    /// Returns the attempt identity of the current role's latest execution.
    pub fn current_attempt_id(&self) -> Option<&str> {
        match self.current_execution.as_ref()? {
            GraphExecutionRef::TaskAttempt { attempt_id, .. } => Some(attempt_id),
            GraphExecutionRef::UtilityRun { .. } => None,
        }
    }

    /// Returns the deterministic task identity for one role in a chain.
    pub fn task_id(chain_id: &str, role: TaskAgentRole) -> String {
        format!("chain:{chain_id}:{}", role.id())
    }

    /// Returns the role a node plays when it belongs to a task-chain graph.
    pub fn role(graph_id: &str, node: &GraphNode) -> Option<TaskAgentRole> {
        let role = TaskAgentRole::from_id(&node.id)?;
        let GraphContext::TaskConversation { task_id } = &node.execution.context else {
            return None;
        };

        (*task_id == Self::task_id(graph_id, role)).then_some(role)
    }

    /// Projects a task-chain graph, returning `None` for other graph shapes.
    ///
    /// `accepted_plan` must come from authoritative acceptance evidence for
    /// the Planner's `plan` output.
    pub fn project(
        graph: &ExecutionGraph,
        progress: &ExecutionGraphProgress,
        accepted_plan: Option<AcceptedTaskPlan>,
    ) -> Option<Self> {
        let [planner, implementer] = graph.nodes.as_slice() else {
            return None;
        };
        if Self::role(&graph.id, planner) != Some(TaskAgentRole::Planner)
            || Self::role(&graph.id, implementer) != Some(TaskAgentRole::Implementer)
        {
            return None;
        }
        let [planner_progress, implementer_progress] = progress.nodes.as_slice() else {
            return None;
        };
        let implementing = accepted_plan.is_some() || !implementer_progress.executions.is_empty();
        let (current_role, current) = if implementing {
            (TaskAgentRole::Implementer, implementer_progress)
        } else {
            (TaskAgentRole::Planner, planner_progress)
        };
        let phase = if progress.status == ExecutionGraphStatus::Cancelled {
            TaskChainPhase::Canceled
        } else {
            TaskChainPhase::from_node(current_role, current)
        };

        Some(Self {
            accepted_plan,
            agent: planner.agent,
            agents: PlanThenImplementAgents {
                implementer: implementer.definition.clone(),
                planner: planner.definition.clone(),
            },
            current_execution: current.executions.last().cloned(),
            current_role,
            id: graph.id.clone(),
            implementer_task_id: Self::task_id(&graph.id, TaskAgentRole::Implementer),
            phase,
            planner_task_id: Self::task_id(&graph.id, TaskAgentRole::Planner),
            revision: graph.revision,
            session_id: graph.session_id.clone(),
            user_request: planner.objective.clone(),
        })
    }
}

/// Workflow presentation derived from the current node's latest execution.
/// Success records execution, never implicit acceptance of a plan or outcome.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TaskChainPhase {
    /// Planner execution is pending, queued, or running.
    Planning,
    /// Latest successful Planner response needs explicit user acceptance.
    AwaitingPlanAcceptance,
    /// Planner has questions that need an explicit continuation.
    PlannerQuestion,
    /// Accepted plan is being implemented, including post-processing.
    Implementing,
    /// Implementer has questions that need an explicit continuation.
    ImplementerQuestion,
    /// Current stage failed or was interrupted; retry is always explicit.
    Failed,
    /// The current stage or the whole graph was canceled. A canceled stage
    /// may continue with an explicit new attempt; a canceled graph cannot.
    Canceled,
    /// Implementer finished successfully; the session remains reviewable.
    Succeeded,
}

impl TaskChainPhase {
    fn from_node(role: TaskAgentRole, node: &GraphNodeProgress) -> Self {
        let planner = role == TaskAgentRole::Planner;
        match node.status {
            GraphNodeStatus::Pending | GraphNodeStatus::Queued | GraphNodeStatus::Running => {
                if planner {
                    Self::Planning
                } else {
                    Self::Implementing
                }
            }
            GraphNodeStatus::AwaitingAnswers => {
                if planner {
                    Self::PlannerQuestion
                } else {
                    Self::ImplementerQuestion
                }
            }
            GraphNodeStatus::Succeeded if planner => Self::AwaitingPlanAcceptance,
            GraphNodeStatus::Succeeded => Self::Succeeded,
            GraphNodeStatus::Failed => Self::Failed,
            GraphNodeStatus::Cancelled => Self::Canceled,
        }
    }
}

#[cfg(test)]
#[path = "task_chain_test.rs"]
mod tests;