Skip to main content

ag_session/execution_graph/
node.rs

1//! Execution graph nodes with their execution profiles, dependencies,
2//! outputs, and input bindings.
3
4use ag_protocol::{ProtocolRequestProfile, TurnPrompt};
5use serde::{Deserialize, Serialize};
6
7use super::GraphContractError;
8use crate::{AgentDefinition, AgentSelection, EnvId, PermissionMode};
9
10/// An agent invocation template, independent of built-in workflow roles.
11#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
12pub struct GraphNode {
13    /// Captured model/provider, never resolved from mutable settings at
14    /// dispatch.
15    #[serde(with = "super::selection")]
16    pub agent: AgentSelection,
17    /// Complete captured instructions, independent of a role or catalog ID.
18    pub definition: AgentDefinition,
19    /// All gates must be satisfied before a new execution can be admitted.
20    pub dependencies: Vec<GraphDependency>,
21    /// Stable environment identity; paths are resolved by the host at
22    /// execution.
23    pub env_id: EnvId,
24    /// Context, response, effect, budget, and resource requirements.
25    pub execution: GraphExecutionProfile,
26    /// Identity unique within this graph and stable across its revisions.
27    pub id: String,
28    /// Named result slots resolved to exact references at attempt admission.
29    pub inputs: Vec<GraphInputBinding>,
30    /// Desired outcome, separate from the agent definition and attempt request.
31    pub objective: String,
32    /// Named outputs with protocol-owned schemas, not implicit conversation
33    /// replay.
34    pub outputs: Vec<GraphOutput>,
35    /// Captured initial request and workflow evidence, excluding bound results.
36    /// Hosts supply result bodies explicitly; this is not a template language.
37    pub request: TurnPrompt,
38}
39
40/// Requirements interpreted by a host before worker submission.
41///
42/// These values neither grant permissions nor configure a runtime directly.
43/// Worker-owned execution policy remains an independent ceiling. Unsupported
44/// requirements must be rejected rather than silently downgraded.
45#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
46pub struct GraphExecutionProfile {
47    /// Fresh utility context or isolated, resumable task conversation.
48    pub context: GraphContext,
49    /// Ordered host effects included in execution settlement.
50    pub post_processing: GraphPostProcessing,
51    /// Existing protocol schema to validate before publishing a result.
52    pub response_profile: ProtocolRequestProfile,
53    /// Host-owned shared provider-call budget, charged for retries and repairs.
54    /// `None` retains worker limits; it does not grant unlimited execution.
55    pub shared_budget_id: Option<String>,
56    /// Read sharing or exclusive access within the referenced environment.
57    pub workspace_access: GraphWorkspaceAccess,
58}
59
60impl GraphExecutionProfile {
61    /// Intersects node and definition restrictions with session permissions.
62    /// This value must still pass through worker/runtime enforcement.
63    pub fn permission_mode(
64        &self,
65        definition: &AgentDefinition,
66        session_mode: PermissionMode,
67    ) -> PermissionMode {
68        if self.workspace_access.is_read() {
69            return PermissionMode::ReadOnly;
70        }
71
72        definition.permission_mode(session_mode)
73    }
74
75    /// Checks execution-path compatibility without invoking a worker.
76    ///
77    /// # Errors
78    /// Rejects blank identities, session schemas on utility contexts, utility
79    /// schemas on task contexts, effects on fresh or read-only execution, and
80    /// background readers outside fresh utility contexts.
81    pub fn validate(&self) -> Result<(), GraphContractError> {
82        match &self.context {
83            GraphContext::Fresh => {
84                if self.response_profile == ProtocolRequestProfile::SessionTurn
85                    || self.post_processing != GraphPostProcessing::None
86                {
87                    return Err(GraphContractError::InvalidProfile(
88                        "fresh utilities require a utility schema and no session effects",
89                    ));
90                }
91            }
92            GraphContext::TaskConversation { task_id } => {
93                GraphContractError::require(task_id, "task_id")?;
94                if self.response_profile != ProtocolRequestProfile::SessionTurn {
95                    return Err(GraphContractError::InvalidProfile(
96                        "task conversations require the session-turn schema",
97                    ));
98                }
99            }
100        }
101
102        if self.workspace_access.is_read() && self.post_processing != GraphPostProcessing::None {
103            return Err(GraphContractError::InvalidProfile(
104                "shared readers cannot perform host mutation effects",
105            ));
106        }
107        if self.workspace_access == GraphWorkspaceAccess::BackgroundRead
108            && self.context != GraphContext::Fresh
109        {
110            return Err(GraphContractError::InvalidProfile(
111                "background readers require a fresh utility context",
112            ));
113        }
114        if let Some(budget_id) = &self.shared_budget_id {
115            GraphContractError::require(budget_id, "shared_budget_id")?;
116        }
117
118        Ok(())
119    }
120}
121
122/// Provider conversation lifetime and existing execution authority.
123#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
124pub enum GraphContext {
125    /// New context for each utility run; no provider continuation is shared.
126    Fresh,
127    /// Attempts reuse only this task's own captured assignment and history.
128    TaskConversation {
129        /// Existing or reserved task identity, unique among graph nodes.
130        task_id: String,
131    },
132}
133
134/// Host mutation effects, independent of model tools and response schema.
135#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
136pub enum GraphPostProcessing {
137    /// No commit, publication, or automatic remediation effects.
138    None,
139    /// Existing ordered session effects settle before execution succeeds.
140    SessionWorkflow,
141}
142
143/// Resource requirement within one Env, not a security sandbox.
144#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
145pub enum GraphWorkspaceAccess {
146    /// Read-only execution may share the Env with other readers.
147    SharedRead,
148    /// Read-only fresh utility that may overlap ordinary host work in the
149    /// Env, such as session turns and sync, but never graph writers. Use only
150    /// when observing a changing workspace is acceptable.
151    BackgroundRead,
152    /// Serialize against all other work in the Env, including readers.
153    /// Session/worker/definition restrictions can still deny writes.
154    ExclusiveWrite,
155}
156
157impl GraphWorkspaceAccess {
158    /// Whether this access forces read-only execution.
159    #[must_use]
160    pub fn is_read(self) -> bool {
161        matches!(self, Self::SharedRead | Self::BackgroundRead)
162    }
163}
164
165/// One prerequisite; multiple gates on one producer are permitted.
166#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
167pub struct GraphDependency {
168    /// Condition the host must establish from authoritative records.
169    pub gate: GraphCompletionGate,
170    /// Producing node in the same graph.
171    pub node_id: String,
172}
173
174/// Completion condition, distinct from desired-outcome task completion.
175#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
176pub enum GraphCompletionGate {
177    /// Successful authoritative execution including ordered post-processing,
178    /// with no unanswered clarification. A provider answer alone is
179    /// insufficient.
180    ExecutionSucceeded,
181    /// Exact output validated after successful, question-free settlement.
182    ResultValidated {
183        /// Declared output on the producing node.
184        output_name: String,
185    },
186    /// Explicit acceptance of an exact validated output version.
187    ResultAccepted {
188        /// Declared output on the producing node.
189        output_name: String,
190    },
191}
192
193impl GraphCompletionGate {
194    /// Named output needed by this gate, if any.
195    pub(super) fn output_name(&self) -> Option<&str> {
196        match self {
197            Self::ExecutionSucceeded => None,
198            Self::ResultValidated { output_name } | Self::ResultAccepted { output_name } => {
199                Some(output_name)
200            }
201        }
202    }
203}
204
205/// Named output containing one complete response under an existing schema.
206#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
207pub struct GraphOutput {
208    /// Output name unique on the producing node.
209    pub name: String,
210    /// Must match the producing execution's response schema.
211    pub schema: ProtocolRequestProfile,
212}
213
214/// A planned handoff; no attempt or result needs to exist when planning.
215#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
216pub struct GraphInputBinding {
217    /// Slot name unique on the consuming node.
218    pub name: String,
219    /// Declared output on the producer.
220    pub output_name: String,
221    /// Node in this graph, protected by a matching result dependency gate.
222    pub producer_node_id: String,
223}
224
225#[cfg(test)]
226#[path = "node_test.rs"]
227mod tests;