Skip to main content

ag_session/
task_execution.rs

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