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