Skip to main content

ag_session/execution_graph/
node.rs

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