Skip to main content

ag_session/
task_execution.rs

1//! Explicit role assignments and inputs for isolated task execution.
2
3use ag_protocol::TurnPromptAttachment;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7    AgentSelection, BuiltinAgentDefinition, DurableMessageVisibility, EnvId, SessionError,
8    SessionId,
9};
10
11/// Immutable role and provider/model selection assigned to one task.
12///
13/// A caller captures the selection once, before admission. A future chain can
14/// reuse that selection across its tasks without reading mutable session
15/// settings again. Permissions still resolve from the role and session at
16/// execution time; assignment never grants access.
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub struct TaskAgentAssignment {
19    /// Captured provider/model pair, independent of the role.
20    pub agent: AgentSelection,
21    /// Instructions and permission restriction used for every attempt.
22    pub definition: BuiltinAgentDefinition,
23}
24
25/// Durable identity of one task's conversation and runtime resources.
26///
27/// The host allocates `id` independently of caller-supplied task IDs and
28/// provider conversation IDs. It remains stable across attempts and process
29/// restarts. Provider continuation and replay history belong to this context,
30/// never the owning session's ordinary conversation. The session still owns
31/// scheduling, cancellation, and the shared workspace.
32#[derive(Clone, Debug, Eq, PartialEq)]
33pub struct TaskAgentContext {
34    /// Immutable role and captured model selection.
35    pub assignment: TaskAgentAssignment,
36    /// Host-allocated stable execution identity, not a provider conversation
37    /// ID.
38    pub id: String,
39    /// Owning session; task completion does not release its environment.
40    pub session_id: SessionId,
41    /// Task whose attempts may continue this context.
42    pub task_id: String,
43}
44
45impl TaskAgentContext {
46    /// Returns the session-owned environment shared by this context's attempts.
47    pub fn env_id(&self) -> EnvId {
48        EnvId::SessionWorktree(self.session_id.clone())
49    }
50}
51
52/// Caller-supplied, explicitly accepted plan for an implementation attempt.
53///
54/// The producing task and attempt identify the exact plan version. This is
55/// input provenance, not proof of acceptance: the host must verify acceptance
56/// before dispatch. The plan is task data, never application policy.
57#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
58pub struct AcceptedTaskPlan {
59    /// Attempt that produced this exact plan.
60    pub attempt_id: String,
61    /// Task that owns the producing attempt.
62    pub task_id: String,
63    /// Accepted plan body supplied explicitly to the implementer.
64    pub text: String,
65}
66
67/// Explicit input for a task's own conversation, excluding session replay.
68///
69/// Continuations retain this task's history only. The host must not copy the
70/// human transcript or another task's provider conversation into this input.
71#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
72pub struct TaskAgentInput {
73    /// Exact accepted plan required by an implementer; absent for a planner.
74    pub accepted_plan: Option<AcceptedTaskPlan>,
75    /// Images retained across attempts and handed off with an accepted plan.
76    #[serde(default, skip_serializing_if = "Vec::is_empty")]
77    pub attachments: Vec<TurnPromptAttachment>,
78    /// Clarification or retry guidance explicitly addressed to this task.
79    pub clarification: Option<String>,
80    /// Original user request, retained across this task's attempts.
81    pub user_request: String,
82}
83
84impl TaskAgentInput {
85    /// Validates required role inputs without asserting plan acceptance.
86    ///
87    /// # Errors
88    /// Returns an operation error for an empty request, missing implementer
89    /// plan, incomplete plan provenance, or a plan supplied to a planner.
90    pub fn validate(&self, definition: BuiltinAgentDefinition) -> Result<(), SessionError> {
91        if self.user_request.trim().is_empty() {
92            return Err(SessionError::Operation(
93                "Task user request is empty".to_string(),
94            ));
95        }
96
97        match (definition, &self.accepted_plan) {
98            (BuiltinAgentDefinition::Planner, None) => Ok(()),
99            (BuiltinAgentDefinition::Planner, Some(_)) => Err(SessionError::Operation(
100                "Planner input must not contain an accepted plan".to_string(),
101            )),
102            (BuiltinAgentDefinition::Implementer, None) => Err(SessionError::Operation(
103                "Implementer input requires an accepted plan".to_string(),
104            )),
105            (BuiltinAgentDefinition::Implementer, Some(plan)) => {
106                if plan.task_id.trim().is_empty()
107                    || plan.attempt_id.trim().is_empty()
108                    || plan.text.trim().is_empty()
109                {
110                    return Err(SessionError::Operation(
111                        "Accepted plan requires a task, producing attempt, and text".to_string(),
112                    ));
113                }
114
115                Ok(())
116            }
117        }
118    }
119}
120
121/// Explicit role-aware attempt, separate from legacy session-context tasks.
122///
123/// Identical redelivery includes the assignment and structured input. Once
124/// admitted, the task's role, selection, original request, and accepted plan
125/// are immutable; clarification and additional images may change in a new
126/// attempt. A host must reject conflicting assignments rather than changing an
127/// existing task's conversation or falling back to ordinary chat.
128///
129/// These contracts alone do not enable submission or dispatch.
130#[derive(Clone, Debug, Eq, PartialEq)]
131pub struct SubmitAgentTaskRequest {
132    /// Assignment captured before admission and retained across attempts.
133    pub assignment: TaskAgentAssignment,
134    /// Globally unique delivery identity; retries and continuations use new
135    /// IDs.
136    pub attempt_id: String,
137    /// Role-specific input supplied to the isolated conversation.
138    pub input: TaskAgentInput,
139    /// Desired outcome, immutable across this task's attempts.
140    pub objective: String,
141    /// Globally unique desired-outcome identity.
142    pub task_id: String,
143    /// Whether task views show the explicit input. Task input never enters
144    /// the ordinary session's transcript.
145    pub visibility: DurableMessageVisibility,
146}
147
148/// One response retained in an isolated task conversation.
149#[derive(Clone, Debug, Eq, PartialEq)]
150pub struct TaskAgentTurn {
151    /// Exact serialized protocol response, including clarification questions.
152    pub assistant_message: String,
153    /// Producing attempt; consult its durable status before accepting output.
154    pub attempt_id: String,
155    /// Explicit input supplied to this attempt.
156    pub input: TaskAgentInput,
157    /// Input tokens charged to the captured model.
158    pub input_tokens: u64,
159    /// Output tokens charged to the captured model.
160    pub output_tokens: u64,
161}
162
163/// Durable task conversation, independent of ordinary session messages.
164#[derive(Clone, Debug, Eq, PartialEq)]
165pub struct TaskAgentHistory {
166    /// Stable assignment and runtime identity shared by these attempts.
167    pub context: TaskAgentContext,
168    /// Original task input without attempt-specific clarification.
169    pub input: TaskAgentInput,
170    /// Responses in admitted attempt order; absence is not proof of failure.
171    pub turns: Vec<TaskAgentTurn>,
172}
173
174#[cfg(test)]
175#[path = "task_execution_test.rs"]
176mod tests;