ag_session/execution_graph/
proposal.rs1use std::num::NonZeroU64;
4
5use ag_protocol::{
6 GraphProposal, GraphProposalContext, GraphProposalGate, GraphProposalNode,
7 GraphProposalPostProcessing, GraphProposalWorkspaceAccess, ProtocolRequestProfile, TurnPrompt,
8 TurnPromptAttachment,
9};
10use serde::{Deserialize, Serialize};
11
12use super::{
13 ExecutionGraph, GraphCompletionGate, GraphContext, GraphDependency, GraphExecutionProfile,
14 GraphInputBinding, GraphNode, GraphOutput, GraphPostProcessing, GraphWorkspaceAccess,
15};
16use crate::{AgentDefinition, AgentSelection, EnvId, PermissionMode, SessionId};
17
18#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
20pub struct GraphProposalLimits {
21 pub bytes: usize,
23 pub edges: usize,
25 pub generations: u32,
27 pub generation_provider_calls: usize,
29 pub nodes: usize,
31 pub provider_calls: usize,
33}
34
35impl Default for GraphProposalLimits {
36 fn default() -> Self {
37 Self {
38 bytes: 65_536,
39 edges: 32,
40 generations: 3,
41 generation_provider_calls: 3,
42 nodes: 16,
43 provider_calls: 48,
44 }
45 }
46}
47
48pub struct GraphProposalResolution<'a> {
50 pub agent: AgentSelection,
52 pub answers: &'a [String],
54 pub definitions: &'a [AgentDefinition],
56 pub graph_id: &'a str,
58 pub limits: &'a GraphProposalLimits,
60 pub permission: PermissionMode,
62 pub request: &'a TurnPrompt,
65 pub revision_attachments: &'a [TurnPromptAttachment],
67 pub session_id: &'a SessionId,
69}
70
71impl GraphProposalResolution<'_> {
72 pub fn resolve(&self, proposal: &GraphProposal) -> Result<ExecutionGraph, String> {
79 if self.limits.generations == 0
80 || self.limits.generation_provider_calls == 0
81 || self.limits.provider_calls == 0
82 || self.request.text.trim().is_empty()
83 || serde_json::json!(proposal).to_string().len() > self.limits.bytes
84 || proposal.nodes.len() > self.limits.nodes
85 || proposal
86 .nodes
87 .iter()
88 .map(|node| node.dependencies.len())
89 .sum::<usize>()
90 > self.limits.edges
91 {
92 return Err("Graph proposal exceeds captured limits or has an empty request".into());
93 }
94 let mut request = self.request.clone();
95 request
96 .attachments
97 .extend_from_slice(self.revision_attachments);
98 if !self.answers.is_empty() {
99 request
100 .text
101 .push_str("\n\nComplete clarification answer history (JSON data):\n");
102 request
103 .text
104 .push_str(&serde_json::json!(self.answers).to_string());
105 }
106 let mut nodes = Vec::with_capacity(proposal.nodes.len());
107 for (index, node) in proposal.nodes.iter().enumerate() {
108 let definition = self
109 .definitions
110 .iter()
111 .find(|definition| definition.id == node.agent_id)
112 .ok_or_else(|| format!("Unavailable agent definition: {}", node.agent_id))?;
113 nodes.push(GraphNode {
114 agent: self.agent,
115 definition: definition.clone(),
116 dependencies: node
117 .dependencies
118 .iter()
119 .map(|dependency| GraphDependency {
120 gate: match &dependency.gate {
121 GraphProposalGate::ExecutionSucceeded {} => {
122 GraphCompletionGate::ExecutionSucceeded
123 }
124 GraphProposalGate::ResultValidated { output_name } => {
125 GraphCompletionGate::ResultValidated {
126 output_name: output_name.clone(),
127 }
128 }
129 GraphProposalGate::ResultAccepted { output_name } => {
130 GraphCompletionGate::ResultAccepted {
131 output_name: output_name.clone(),
132 }
133 }
134 },
135 node_id: dependency.node_id.clone(),
136 })
137 .collect(),
138 env_id: EnvId::SessionWorktree(self.session_id.clone()),
139 execution: self.profile(node, definition, index)?,
140 id: node.id.clone(),
141 inputs: node
142 .inputs
143 .iter()
144 .map(|input| GraphInputBinding {
145 name: input.name.clone(),
146 output_name: input.output_name.clone(),
147 producer_node_id: input.producer_node_id.clone(),
148 })
149 .collect(),
150 objective: node.objective.clone(),
151 outputs: node
152 .outputs
153 .iter()
154 .map(|output| GraphOutput {
155 name: output.name.clone(),
156 schema: output.schema,
157 })
158 .collect(),
159 request: request.clone(),
160 });
161 }
162 let graph = ExecutionGraph {
163 id: self.graph_id.into(),
164 nodes,
165 revision: NonZeroU64::MIN,
166 session_id: self.session_id.clone(),
167 };
168 graph.validate().map_err(|error| error.to_string())?;
169
170 Ok(graph)
171 }
172
173 fn profile(
174 &self,
175 node: &GraphProposalNode,
176 definition: &AgentDefinition,
177 index: usize,
178 ) -> Result<GraphExecutionProfile, String> {
179 let execution = &node.execution;
180 let workspace_access = match execution.workspace_access {
181 GraphProposalWorkspaceAccess::SharedRead => GraphWorkspaceAccess::SharedRead,
182 GraphProposalWorkspaceAccess::ExclusiveWrite => GraphWorkspaceAccess::ExclusiveWrite,
183 GraphProposalWorkspaceAccess::BackgroundRead => {
184 return Err("Background graph readers are unsupported".into());
185 }
186 };
187 if workspace_access == GraphWorkspaceAccess::ExclusiveWrite
188 && (definition.read_only || self.permission == PermissionMode::ReadOnly)
189 {
190 return Err("Graph proposal requests access beyond host or agent permissions".into());
191 }
192 let context = match execution.context {
193 GraphProposalContext::Fresh => {
194 if workspace_access != GraphWorkspaceAccess::SharedRead
195 || !matches!(
196 execution.response_profile,
197 ProtocolRequestProfile::UtilityPrompt
198 | ProtocolRequestProfile::FocusedReview
199 | ProtocolRequestProfile::ReviewMetadata
200 )
201 {
202 return Err("Unsupported graph utility profile".into());
203 }
204 GraphContext::Fresh
205 }
206 GraphProposalContext::TaskConversation => GraphContext::TaskConversation {
207 task_id: format!("{}:task:{index}", self.graph_id),
208 },
209 };
210
211 Ok(GraphExecutionProfile {
212 context,
213 post_processing: match execution.post_processing {
214 GraphProposalPostProcessing::None => GraphPostProcessing::None,
215 GraphProposalPostProcessing::SessionWorkflow => {
216 GraphPostProcessing::SessionWorkflow
217 }
218 },
219 response_profile: execution.response_profile,
220 shared_budget_id: Some(format!("{}:calls", self.graph_id)),
221 workspace_access,
222 })
223 }
224}
225
226#[cfg(test)]
227#[path = "proposal_test.rs"]
228mod tests;