Skip to main content

adk_surface/workflow/
mod.rs

1//! The workflow observer and debugger (spec 3.3 §6.1 `workflow`, §12 developer track): a
2//! graph agent's runs, steps and forks, for the web home's Runs tab.
3//!
4//! [`Workflows`] reads what adk-graph records in every checkpoint — the run, each step's nodes
5//! with their status, duration and writes, a fork's lineage — and the effect log of governed
6//! nodes. Reading changes nothing: rewinding to a step loads one checkpoint by id (S-I1).
7//!
8//! | What | Where |
9//! |---|---|
10//! | A graph's nodes, edges and channels | [`Workflows::graphs`] |
11//! | A session's latest run: status, node states, steps, lineage, forks | [`Workflows::run`] |
12//! | Every run of a session, from records only | [`Workflows::runs`] |
13//! | One step: its nodes, "What changed", what a fork from it would do | [`Workflows::step`] |
14//! | A fork from a completed step, with edits, into a new session of the caller | [`Workflows::fork`] |
15//! | Card hints for a governed node's decision | [`CardHints`] for [`Workflows`] |
16//! | High risk for a node that spends money | [`Workflows::approval_router`] |
17//!
18//! A decision a graph waits on is the inbox entry, drawn as every other card and answered with
19//! the engine's `decide` command (S-I1, S-I2): the observer only links to it. Its card says
20//! where it came from — "From the invoice-run workflow · Open in Runs" — never offers
21//! **Always allow**, and marks money for a node that spends it.
22//!
23//! Every value shown passes secret redaction, the host's hidden keys
24//! ([`Workflows::hide_keys`]) and a size cap; values are never logged. Developer panels may
25//! use technical words (spec 3.3 §8); the cards stay plain.
26//!
27//! # Example
28//!
29//! ```rust,no_run
30//! use std::sync::Arc;
31//! use adk_core::{ApprovalPolicy, ApproverSelector, InMemoryApprovalStore, StoreApprovalService};
32//! use adk_surface::workflow::Workflows;
33//!
34//! # fn example(graph: Arc<adk_graph::agent::GraphAgent>, runner: Arc<adk_runner::Runner>) {
35//! let workflows = Workflows::new("adk-rust").graph(graph).hide_keys(["apiKey"]);
36//! // Calls of a node that spends money are high risk on every surface.
37//! let approvals = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new())).with_router(
38//!     workflows.approval_router(ApprovalPolicy::new([ApproverSelector::group("owner")])),
39//! );
40//! let workflows = workflows.runner(runner);
41//! # let _ = (approvals, workflows);
42//! # }
43//! ```
44
45mod project;
46mod values;
47mod view;
48pub mod words;
49
50use std::collections::{BTreeMap, BTreeSet};
51use std::sync::{Arc, Mutex};
52
53use adk_core::{
54    AdkError, Agent, ApprovalCall, ApprovalRequest, ApprovalRisk, ApprovalRoute, ApprovalRouter,
55    ApprovalState, Content, ErrorCategory, ErrorComponent, RequestContext, RunConfig, SessionId,
56    ToolOrigin, UserId,
57};
58use adk_graph::agent::{GraphAgent, session_thread_id};
59use adk_graph::checkpoint::Checkpointer;
60use adk_graph::node::{ExecutionConfig, NodeContext};
61use adk_graph::record::{NodeRecord, NodeStatus};
62use adk_graph::shape::{GovernedShape, GraphShape};
63use adk_graph::state::Checkpoint;
64use adk_graph::time_travel::{ForkError, ForkSpec};
65use adk_runner::Runner;
66use adk_session::{CreateRequest, DeleteRequest, GetRequest, ListRequest, SessionService};
67use async_trait::async_trait;
68use chrono::{DateTime, FixedOffset, Utc};
69use futures::StreamExt;
70use serde_json::json;
71
72use crate::engine::SurfaceEngine;
73use crate::error::{Result, SurfaceError};
74use crate::hints::{CardHint, CardHints};
75use crate::model::{CardDetail, Reversibility};
76use crate::origin::{Caller, SurfaceKind};
77use project::{Context, Found, Saved, StepInputs};
78use values::Display;
79
80pub use view::{
81    Change, ChannelValue, EdgeView, EffectView, ForkOutcome, ForkPoint, ForkRequest, ForkSummary,
82    GraphView, GraphsResponse, NodeDecision, NodeDetail, NodeRun, NodeState, NodeView, RunLineage,
83    RunStatus, RunStep, RunSummary, RunsResponse, StateChange, StepDetail, StepState, WorkflowRun,
84};
85
86/// The audit action of a fork made on the web home (spec 3.3 §11, §12).
87pub const SURFACE_AUDIT_WORKFLOW_FORK: &str = "surface.workflow.fork";
88
89/// The audit action of a fork's run started from the web home, with the fork or later
90/// (spec 3.3 §11, §12).
91pub const SURFACE_AUDIT_WORKFLOW_START: &str = "surface.workflow.start";
92
93/// The largest value one fork edit may set, in bytes of compact JSON.
94pub const FORK_VALUE_LIMIT: usize = 64 * 1024;
95
96/// The most sessions of a person read to find a run's forks.
97const FORK_SCAN_LIMIT: usize = 500;
98
99/// The workflow observer over a host's graph agents (spec 3.3 §12). Cheap to clone.
100///
101/// # Example
102///
103/// ```rust,no_run
104/// use std::sync::Arc;
105/// use adk_surface::workflow::Workflows;
106///
107/// # fn example(graph: Arc<adk_graph::agent::GraphAgent>, runner: Arc<adk_runner::Runner>) {
108/// let workflows = Workflows::new("adk-rust").graph(graph).runner(runner);
109/// assert_eq!(workflows.graphs().len(), 1);
110/// # }
111/// ```
112#[derive(Clone)]
113pub struct Workflows {
114    inner: Arc<Inner>,
115}
116
117#[derive(Clone)]
118struct Inner {
119    app: String,
120    graphs: Vec<Arc<GraphAgent>>,
121    runner: Option<Arc<Runner>>,
122    sessions: Option<Arc<dyn SessionService>>,
123    display: Display,
124    hidden: Vec<String>,
125    offset: FixedOffset,
126    /// The threads of forks whose run this observer started and that have not ended.
127    starting: Arc<Mutex<BTreeSet<String>>>,
128}
129
130impl std::fmt::Debug for Workflows {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        f.debug_struct("Workflows")
133            .field("app", &self.inner.app)
134            .field(
135                "graphs",
136                &self.inner.graphs.iter().map(|graph| graph.name().to_string()).collect::<Vec<_>>(),
137            )
138            .finish_non_exhaustive()
139    }
140}
141
142impl Workflows {
143    /// An observer for the graph agents a runner of application `app` runs (spec 3.3 §12).
144    pub fn new(app: impl Into<String>) -> Self {
145        Self {
146            inner: Arc::new(Inner {
147                app: app.into(),
148                graphs: Vec::new(),
149                runner: None,
150                sessions: None,
151                display: Display::default(),
152                hidden: Vec::new(),
153                offset: *chrono::Local::now().offset(),
154                starting: Arc::default(),
155            }),
156        }
157    }
158
159    fn change(mut self, change: impl FnOnce(&mut Inner)) -> Self {
160        change(Arc::make_mut(&mut self.inner));
161        self
162    }
163
164    /// Observes `graph`, a graph agent with a checkpointer that the host's runner runs.
165    #[must_use]
166    pub fn graph(self, graph: Arc<GraphAgent>) -> Self {
167        self.change(|inner| inner.graphs.push(graph))
168    }
169
170    /// Starts a fork's run through `runner`, the runner whose root agent is the graph.
171    #[must_use]
172    pub fn runner(self, runner: Arc<Runner>) -> Self {
173        self.change(|inner| inner.runner = Some(runner))
174    }
175
176    /// Reads and creates sessions through `sessions`; the runner's when unset.
177    #[must_use]
178    pub fn sessions(self, sessions: Arc<dyn SessionService>) -> Self {
179        self.change(|inner| inner.sessions = Some(sessions))
180    }
181
182    /// Shows the values of these state keys, at any depth, as `[hidden]`.
183    #[must_use]
184    pub fn hide_keys(self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
185        self.change(|inner| {
186            inner.hidden.extend(keys.into_iter().map(Into::into));
187            inner.display = Display::new(inner.hidden.iter().cloned());
188        })
189    }
190
191    /// Shows times at `offset` east of UTC instead of the host's time zone.
192    #[must_use]
193    pub fn utc_offset(self, offset: FixedOffset) -> Self {
194        self.change(|inner| inner.offset = offset)
195    }
196
197    /// The application whose sessions this observer reads.
198    pub fn app_name(&self) -> &str {
199        &self.inner.app
200    }
201
202    /// Every graph agent observed, with its nodes, edges and channels.
203    pub fn graphs(&self) -> Vec<GraphView> {
204        self.inner
205            .graphs
206            .iter()
207            .map(|agent| {
208                project::graph_view(
209                    agent.name(),
210                    agent.description(),
211                    &agent.graph().shape(),
212                    agent.graph().state_channels(),
213                )
214            })
215            .collect()
216    }
217
218    fn session_service(&self) -> Result<Arc<dyn SessionService>> {
219        if let Some(sessions) = &self.inner.sessions {
220            return Ok(Arc::clone(sessions));
221        }
222        match &self.inner.runner {
223            Some(runner) => Ok(Arc::clone(runner.session_service())),
224            None => Err(SurfaceError::unsupported("the workflow observer without sessions")),
225        }
226    }
227
228    /// Refuses a session that is not the caller's (S-I8): it answers as not found.
229    async fn owned(&self, user: &str, session: &str) -> Result<()> {
230        let got = self
231            .session_service()?
232            .get(GetRequest {
233                app_name: self.inner.app.clone(),
234                user_id: user.to_string(),
235                session_id: session.to_string(),
236                num_recent_events: Some(0),
237                after: None,
238            })
239            .await;
240        match got {
241            Ok(_) => Ok(()),
242            Err(error) if error.category == ErrorCategory::NotFound => {
243                Err(SurfaceError::not_found(format!("session '{session}'")))
244            }
245            Err(error) => Err(SurfaceError::Source(error)),
246        }
247    }
248
249    fn thread(&self, user: &str, session: &str) -> String {
250        session_thread_id(&self.inner.app, user, session)
251    }
252
253    /// The graph `name` names, else the one with checkpoints on `thread`, else the only one.
254    async fn graph_for(&self, thread: &str, name: Option<&str>) -> Result<&Arc<GraphAgent>> {
255        if let Some(name) = name {
256            return self
257                .inner
258                .graphs
259                .iter()
260                .find(|agent| agent.name() == name)
261                .ok_or_else(|| SurfaceError::not_found(format!("workflow '{name}'")));
262        }
263        for agent in &self.inner.graphs {
264            if checkpointer(agent)?.load(thread).await.map_err(source)?.is_some() {
265                return Ok(agent);
266            }
267        }
268        self.inner.graphs.first().ok_or_else(|| SurfaceError::not_found("a workflow"))
269    }
270
271    /// The session's checkpoints, oldest first, with their records read.
272    async fn saved(agent: &GraphAgent, thread: &str) -> Result<Vec<Saved>> {
273        Ok(checkpointer(agent)?
274            .list(thread)
275            .await
276            .map_err(source)?
277            .into_iter()
278            .map(Saved::new)
279            .collect())
280    }
281
282    /// Every run of `session`, from the checkpoints' records only (spec 3.3 §12).
283    ///
284    /// # Errors
285    ///
286    /// Returns `surface.not_found` for a session that is not the caller's (S-I8), or for a
287    /// workflow `graph` does not name; the checkpointer's error otherwise.
288    pub async fn runs(
289        &self,
290        caller: &Caller,
291        session: &str,
292        graph: Option<&str>,
293    ) -> Result<RunsResponse> {
294        let user = caller.user_id();
295        self.owned(user, session).await?;
296        let thread = self.thread(user, session);
297        let agent = self.graph_for(&thread, graph).await?;
298        let saved = Self::saved(agent, &thread).await?;
299        let shape = agent.graph().shape();
300        let channels = agent.graph().state_channels();
301        let context = self.context(session, &thread, agent.name(), &shape, &channels);
302        let found = Found::default();
303        Ok(RunsResponse {
304            session_id: session.to_string(),
305            graph: agent.name().to_string(),
306            thread_id: thread.clone(),
307            runs: project::summaries(&context, &saved),
308            lineage: project::lineage(&context, &saved, &found),
309            removed_before: project::removed_before(&saved),
310        })
311    }
312
313    fn context<'a>(
314        &'a self,
315        session: &'a str,
316        thread: &'a str,
317        graph: &'a str,
318        shape: &'a GraphShape,
319        channels: &'a [String],
320    ) -> Context<'a> {
321        Context {
322            session,
323            thread,
324            graph,
325            shape,
326            channels,
327            offset: self.inner.offset,
328            display: &self.inner.display,
329        }
330    }
331
332    /// The latest run of `session`, as the Runs tab shows it (spec 3.3 §12): each node's
333    /// state, the steps, the lineage and forks, and the decision each waiting node waits on,
334    /// matched in the inbox by origin and node.
335    ///
336    /// # Errors
337    ///
338    /// Returns `surface.not_found` for a session that is not the caller's (S-I8), or for a
339    /// workflow `graph` does not name; the checkpointer's or the source's error otherwise.
340    pub async fn run(
341        &self,
342        engine: &SurfaceEngine,
343        caller: &Caller,
344        session: &str,
345        graph: Option<&str>,
346    ) -> Result<WorkflowRun> {
347        let user = caller.user_id();
348        self.owned(user, session).await?;
349        let thread = self.thread(user, session);
350        let agent = self.graph_for(&thread, graph).await?;
351        let checkpoints = checkpointer(agent)?;
352        let saved = Self::saved(agent, &thread).await?;
353        let shape = agent.graph().shape();
354        let channels = agent.graph().state_channels();
355
356        let mut found = Found {
357            starting: self.is_starting(&thread),
358            waiting: self.waiting(engine, caller, session, agent.name()).await?,
359            stopped: engine.source().stopped().await.unwrap_or(false),
360            forks: self.forks(checkpoints.as_ref(), user, session, &thread).await,
361            ..Found::default()
362        };
363        let newest = saved.last().map(|saved| &saved.checkpoint);
364        if let Some(lineage) = newest.and_then(|newest| newest.lineage().ok().flatten()) {
365            let (started, inherited) = parent_facts(checkpoints.as_ref(), &lineage).await;
366            found.parent_run_started = started;
367            found.inherited = inherited;
368            found.parent_session = session_of_thread(&self.inner.app, user, &lineage.parent);
369        }
370        if newest.is_some_and(Checkpoint::is_paused) && found.waiting.is_empty() {
371            found.question = self.question(user, session).await;
372        }
373        let context = self.context(session, &thread, agent.name(), &shape, &channels);
374        Ok(project::run_view(&context, &saved, found))
375    }
376
377    /// One step of `session`, from the checkpoint `checkpoint` (spec 3.3 §12): its nodes,
378    /// "What changed" since the checkpoint before it, its state, and what a fork from it would
379    /// do. Reading it changes nothing.
380    ///
381    /// # Errors
382    ///
383    /// Returns `surface.not_found` for a session that is not the caller's, or a checkpoint that
384    /// is not of the session's thread (S-I8); the checkpointer's error otherwise.
385    pub async fn step(
386        &self,
387        engine: &SurfaceEngine,
388        caller: &Caller,
389        session: &str,
390        checkpoint: &str,
391    ) -> Result<StepDetail> {
392        let user = caller.user_id();
393        self.owned(user, session).await?;
394        let thread = self.thread(user, session);
395        let agent = self.graph_for(&thread, None).await?;
396        let checkpoints = checkpointer(agent)?;
397        let target = checkpoints
398            .load_by_id(checkpoint)
399            .await
400            .map_err(source)?
401            .filter(|found| found.thread_id == thread)
402            .ok_or_else(|| SurfaceError::not_found(format!("checkpoint '{checkpoint}'")))?;
403        let previous = checkpoints
404            .list_page(&thread, Some(target.version), 1)
405            .await
406            .map_err(source)?
407            .into_iter()
408            .next();
409        // What a fork from here would do is what the rest of this run did: a later run of the
410        // session, started by a later message, is not part of it.
411        let mut later: Vec<Saved> = checkpoints
412            .list(&thread)
413            .await
414            .map_err(source)?
415            .into_iter()
416            .filter(|later| later.version > target.version)
417            .map(Saved::new)
418            .collect();
419        let run = target
420            .run_record()
421            .ok()
422            .flatten()
423            .or_else(|| later.iter().find_map(|later| later.run.clone()));
424        later.retain(|later| {
425            later.run.as_ref().map(|r| &r.run_id) == run.as_ref().map(|r| &r.run_id)
426        });
427        let root = target.lineage().ok().flatten().map_or_else(|| thread.clone(), |l| l.root);
428        let effects =
429            adk_graph::governed::effect_log(checkpoints.as_ref(), &root).await.map_err(source)?;
430        let shape = agent.graph().shape();
431        let channels = agent.graph().state_channels();
432
433        // Each governed node's call, at this checkpoint's state, in short.
434        let context_state =
435            NodeContext::new(target.state.clone(), ExecutionConfig::new(&thread), target.step);
436        let calls: BTreeMap<String, String> = shape
437            .nodes
438            .iter()
439            .filter(|node| node.governed.is_some())
440            .filter_map(|node| {
441                let args = agent.graph().node(&node.name)?.call_args(&context_state)?;
442                Some((node.name.clone(), project::call_summary(&args)?))
443            })
444            .collect();
445
446        let saved = Saved::new(target);
447        let decisions = self.decisions(engine, caller, session, agent.name(), &saved).await?;
448        let context = self.context(session, &thread, agent.name(), &shape, &channels);
449        Ok(project::step_detail(
450            &context,
451            &saved,
452            StepInputs {
453                previous: previous.as_ref(),
454                later: &later,
455                effects: &effects,
456                decisions,
457                calls,
458            },
459        ))
460    }
461
462    /// The newest checkpoint version of `session`'s thread, which the Runs tab's feed watches;
463    /// `None` before the first checkpoint.
464    ///
465    /// # Errors
466    ///
467    /// Returns `surface.not_found` for a session that is not the caller's (S-I8).
468    pub async fn version(&self, caller: &Caller, session: &str) -> Result<Option<u64>> {
469        let user = caller.user_id();
470        self.owned(user, session).await?;
471        let thread = self.thread(user, session);
472        let agent = self.graph_for(&thread, None).await?;
473        Ok(checkpointer(agent)?.load(&thread).await.map_err(source)?.map(|newest| newest.version))
474    }
475
476    /// Forks `session` at the completed checkpoint `request.from` into a new session of the
477    /// caller, with `request.set` written over whole channels, and starts it when
478    /// `request.start` is set (spec 3.3 §12).
479    ///
480    /// | Refused | With |
481    /// |---|---|
482    /// | A paired device, or any surface but the web home | `403 surface.not_here` |
483    /// | A session that is not the caller's, or a checkpoint not of its thread | `404 surface.not_found` (S-I8) |
484    /// | A decision of the session waits | `409 workflow.decision_waiting`: "Answer the waiting decision first" |
485    /// | A pause, a step with nothing after it, an edit of a key the graph does not declare, a value over [`FORK_VALUE_LIMIT`] | `400` with the fork's `fork.*` code |
486    ///
487    /// The original thread is never written; a governed call the fork makes unchanged is
488    /// answered from its record. While Stop all is on the fork is made and not started.
489    /// The fork is recorded as [`SURFACE_AUDIT_WORKFLOW_FORK`] with the session, the
490    /// checkpoint, the fork's session, the edited keys and the caller's surface and origin.
491    ///
492    /// # Errors
493    ///
494    /// As the table says, and the stores' errors.
495    pub async fn fork(
496        &self,
497        engine: &SurfaceEngine,
498        caller: &Caller,
499        session: &str,
500        request: ForkRequest,
501    ) -> Result<ForkOutcome> {
502        if caller.device.is_some() || caller.surface != SurfaceKind::Web {
503            return Err(SurfaceError::NotHere(
504                "a fork is made on the web home's Runs tab, not from a paired device or another \
505                 surface"
506                    .into(),
507            ));
508        }
509        let user = caller.user_id();
510        self.owned(user, session).await?;
511        if engine.source().waiting_on_decision(user, session).await?
512            || !engine.session_decisions(caller, session).await?.is_empty()
513        {
514            return Err(SurfaceError::Source(AdkError::new(
515                ErrorComponent::Server,
516                ErrorCategory::Conflict,
517                "workflow.decision_waiting",
518                words::ANSWER_THE_WAITING_DECISION_FIRST,
519            )));
520        }
521        if let Some((key, _)) =
522            request.set.iter().find(|(_, value)| value.to_string().len() > FORK_VALUE_LIMIT)
523        {
524            return Err(refused(
525                "fork.too_large",
526                format!("'{key}' is too large; a fork sets at most {FORK_VALUE_LIMIT} bytes a key"),
527            ));
528        }
529        let thread = self.thread(user, session);
530        let agent = self.graph_for(&thread, None).await?;
531        let checkpoints = checkpointer(agent)?;
532        // An edit starts from the value the step showed: a hidden or redacted part keeps the
533        // value it stands for, and a value too large to show is not edited here.
534        let forked_from = checkpoints
535            .load_by_id(&request.from)
536            .await
537            .map_err(source)?
538            .filter(|found| found.thread_id == thread)
539            .ok_or_else(|| SurfaceError::not_found(format!("checkpoint '{}'", request.from)))?;
540        let mut set = BTreeMap::new();
541        for (key, value) in request.set {
542            match self.inner.display.edited(&key, &value, forked_from.state.get(&key)) {
543                Ok(Some(value)) => {
544                    set.insert(key, value);
545                }
546                Ok(None) => {}
547                Err(refusal) => return Err(refused(refusal.code(), refusal.text(&key))),
548            }
549        }
550        let start = request.start && !engine.source().stopped().await.unwrap_or(false);
551        if start && self.inner.runner.is_none() {
552            return Err(SurfaceError::unsupported("starting a fork without a runner"));
553        }
554        let fork_session = format!("s-{}", &uuid::Uuid::new_v4().simple().to_string()[..8]);
555        let fork_thread = self.thread(user, &fork_session);
556        let spec = ForkSpec { from: request.from.clone(), new_thread_id: fork_thread.clone(), set };
557        let handle = agent.graph().time_travel(&thread).map_err(source)?;
558        let fork = handle.fork(spec).await.map_err(fork_refused)?;
559        let sessions = self.session_service()?;
560        let created = sessions
561            .create(CreateRequest {
562                app_name: self.inner.app.clone(),
563                user_id: user.to_string(),
564                session_id: Some(fork_session.clone()),
565                state: Default::default(),
566            })
567            .await;
568        if let Err(error) = created {
569            // A fork without its session is unreachable; it is removed.
570            if let Err(cleanup) = checkpoints.delete(&fork_thread).await {
571                tracing::warn!(error = %cleanup, "a fork whose session failed could not be removed");
572            }
573            return Err(SurfaceError::Source(error));
574        }
575        let edited: Vec<String> =
576            fork.lineage().ok().flatten().map(|lineage| lineage.edited).unwrap_or_default();
577        let recorded = engine
578            .record(
579                caller,
580                SURFACE_AUDIT_WORKFLOW_FORK,
581                json!({
582                    "sessionId": session,
583                    "from": request.from,
584                    "forkSessionId": fork_session,
585                    "edited": edited,
586                }),
587            )
588            .await;
589        if let Err(error) = recorded {
590            // A fork the audit does not hold is not left to be started (spec 3.3 §11).
591            let deleted = sessions
592                .delete(DeleteRequest {
593                    app_name: self.inner.app.clone(),
594                    user_id: user.to_string(),
595                    session_id: fork_session.clone(),
596                })
597                .await;
598            if let Err(cleanup) = deleted {
599                tracing::warn!(error = %cleanup, "an unrecorded fork's session could not be removed");
600            }
601            if let Err(cleanup) = checkpoints.delete(&fork_thread).await {
602                tracing::warn!(error = %cleanup, "an unrecorded fork could not be removed");
603            }
604            return Err(error);
605        }
606        tracing::info!(
607            session.id = %session,
608            fork.session_id = %fork_session,
609            fork.edited = edited.len(),
610            "forked a workflow run"
611        );
612        let (started, text) = if start {
613            match self.start_turn(engine, caller, &fork_session, &request.from).await {
614                Ok(()) => (true, words::FORKED),
615                Err(error) => {
616                    // The fork exists and is recorded; it is started from its run.
617                    tracing::warn!(fork.session_id = %fork_session, error = %error, "a fork could not start");
618                    (false, words::FORKED_NOT_STARTED)
619                }
620            }
621        } else if request.start {
622            (false, words::FORKED_STOPPED)
623        } else {
624            (false, words::FORKED)
625        };
626        Ok(ForkOutcome {
627            session_id: fork_session,
628            thread_id: fork_thread,
629            from: request.from,
630            edited,
631            started,
632            text: text.to_string(),
633        })
634    }
635
636    /// Starts a fork made and not started, such as one made while everything was stopped.
637    ///
638    /// # Errors
639    ///
640    /// Returns `403 surface.not_here` from a paired device or another surface,
641    /// `404 surface.not_found` for a session that is not the caller's, `409 workflow.stopped`
642    /// while everything is stopped, and `400 workflow.started` for a run that already started.
643    pub async fn start(
644        &self,
645        engine: &SurfaceEngine,
646        caller: &Caller,
647        session: &str,
648    ) -> Result<ForkOutcome> {
649        if caller.device.is_some() || caller.surface != SurfaceKind::Web {
650            return Err(SurfaceError::NotHere(
651                "a fork is started on the web home's Runs tab".into(),
652            ));
653        }
654        let user = caller.user_id();
655        self.owned(user, session).await?;
656        let thread = self.thread(user, session);
657        let agent = self.graph_for(&thread, None).await?;
658        let newest = checkpointer(agent)?.load(&thread).await.map_err(source)?;
659        // A fork not started is its first checkpoint alone: a lineage and no run, and no run
660        // of it under way.
661        let lineage = match newest {
662            Some(newest)
663                if newest.run_record().ok().flatten().is_none() && !self.is_starting(&thread) =>
664            {
665                newest.lineage().ok().flatten()
666            }
667            _ => None,
668        }
669        .ok_or_else(|| refused("workflow.started", "this run already started"))?;
670        if engine.source().stopped().await.unwrap_or(false) {
671            return Err(SurfaceError::Source(AdkError::new(
672                ErrorComponent::Server,
673                ErrorCategory::Conflict,
674                "workflow.stopped",
675                words::FORKED_STOPPED,
676            )));
677        }
678        self.start_turn(engine, caller, session, &lineage.parent_checkpoint).await?;
679        Ok(ForkOutcome {
680            session_id: session.to_string(),
681            thread_id: thread,
682            from: lineage.parent_checkpoint,
683            edited: lineage.edited,
684            started: true,
685            text: words::FORKED.to_string(),
686        })
687    }
688
689    /// Whether a run of `thread` this observer started is still under way.
690    fn is_starting(&self, thread: &str) -> bool {
691        self.inner.starting.lock().map(|starting| starting.contains(thread)).unwrap_or(false)
692    }
693
694    /// Runs a turn of the fork `session` with no message, as the caller: the graph continues
695    /// from its newest checkpoint. The start is recorded as [`SURFACE_AUDIT_WORKFLOW_START`],
696    /// and a second start while the run is under way is refused.
697    async fn start_turn(
698        &self,
699        engine: &SurfaceEngine,
700        caller: &Caller,
701        session: &str,
702        from: &str,
703    ) -> Result<()> {
704        let runner = self
705            .inner
706            .runner
707            .as_ref()
708            .ok_or_else(|| SurfaceError::unsupported("starting a fork without a runner"))?;
709        let user =
710            UserId::new(caller.user_id()).map_err(|e| SurfaceError::Invalid(e.to_string()))?;
711        let id = SessionId::new(session).map_err(|e| SurfaceError::Invalid(e.to_string()))?;
712        let thread = self.thread(caller.user_id(), session);
713        let claimed = self
714            .inner
715            .starting
716            .lock()
717            .map(|mut starting| starting.insert(thread.clone()))
718            .unwrap_or(false);
719        if !claimed {
720            return Err(refused("workflow.started", "this run already started"));
721        }
722        let release = Release { starting: Arc::clone(&self.inner.starting), thread };
723        engine
724            .record(
725                caller,
726                SURFACE_AUDIT_WORKFLOW_START,
727                json!({ "sessionId": session, "from": from }),
728            )
729            .await?;
730        let context = RequestContext {
731            user_id: caller.user_id().to_string(),
732            scopes: caller.groups.clone(),
733            metadata: Default::default(),
734        };
735        let config = RunConfig { request_context: Some(context), ..runner.run_config().clone() };
736        let mut stream =
737            runner.run_with_config(user, id, Content::new("user"), Some(config)).await?;
738        let session = session.to_string();
739        tokio::spawn(async move {
740            // The run is under way until its stream ends.
741            let _release = release;
742            while let Some(event) = stream.next().await {
743                if let Err(error) = event {
744                    tracing::warn!(session.id = %session, error = %error, "a fork's run failed");
745                    break;
746                }
747            }
748        });
749        Ok(())
750    }
751
752    /// The pending decision each node of `graph` waits on in `session`, by node.
753    async fn waiting(
754        &self,
755        engine: &SurfaceEngine,
756        caller: &Caller,
757        session: &str,
758        graph: &str,
759    ) -> Result<BTreeMap<String, String>> {
760        let origin = origin_of(graph);
761        let mut requests: Vec<ApprovalRequest> = engine
762            .source()
763            .requests(caller, Some(session), true)
764            .await?
765            .into_iter()
766            .filter(|request| {
767                request.state == ApprovalState::Pending
768                    && request.scope.session_id == session
769                    && request.origin.as_ref().is_some_and(|known| known.source == origin)
770            })
771            .collect();
772        requests.sort_by_key(|request| request.created_at);
773        // A node inside a subgraph waits as the subgraph's node of this graph.
774        Ok(requests
775            .into_iter()
776            .map(|request| {
777                let node = self
778                    .governed_node(request.origin.as_ref(), &request.tool_name)
779                    .and_then(|(_, found)| found.path.first().cloned())
780                    .unwrap_or(request.tool_name);
781                (node, request.id)
782            })
783            .collect())
784    }
785
786    /// The decision each governed node of a step waited on, and what became of it.
787    async fn decisions(
788        &self,
789        engine: &SurfaceEngine,
790        caller: &Caller,
791        session: &str,
792        graph: &str,
793        saved: &Saved,
794    ) -> Result<BTreeMap<String, NodeDecision>> {
795        let governed: Vec<&NodeRecord> = saved
796            .steps
797            .iter()
798            .flat_map(|step| &step.nodes)
799            .filter(|node| node.effect_key.is_some() && node.status != NodeStatus::Recorded)
800            .collect();
801        if governed.is_empty() {
802            return Ok(BTreeMap::new());
803        }
804        let origin = origin_of(graph);
805        let requests: Vec<ApprovalRequest> = engine
806            .source()
807            .requests(caller, Some(session), false)
808            .await?
809            .into_iter()
810            .filter(|request| {
811                request.scope.session_id == session
812                    && request.origin.as_ref().is_some_and(|known| known.source == origin)
813            })
814            .collect();
815        let mut decisions = BTreeMap::new();
816        for node in governed {
817            let ended = node.started_at
818                + chrono::Duration::milliseconds(i64::try_from(node.duration_ms).unwrap_or(0))
819                + chrono::Duration::seconds(5);
820            let Some(request) = requests
821                .iter()
822                .filter(|request| request.tool_name == node.node && request.created_at <= ended)
823                .max_by_key(|request| request.created_at)
824            else {
825                continue;
826            };
827            let waiting = request.state == ApprovalState::Pending;
828            let at =
829                request.created_at.with_timezone(&self.inner.offset).format("%H:%M").to_string();
830            let text = if waiting {
831                words::asked_at(&at)
832            } else {
833                match engine.decision(caller, &request.id).await {
834                    Ok(card) => card.decided.map_or(card.status_text, |decided| decided.text),
835                    Err(_) => words::asked_at(&at),
836                }
837            };
838            decisions
839                .insert(node.node.clone(), NodeDecision { id: request.id.clone(), waiting, text });
840        }
841        Ok(decisions)
842    }
843
844    /// The forks of `thread`: the caller's other sessions whose lineage names it, newest first.
845    async fn forks(
846        &self,
847        checkpoints: &dyn Checkpointer,
848        user: &str,
849        session: &str,
850        thread: &str,
851    ) -> Vec<ForkSummary> {
852        let Ok(service) = self.session_service() else { return Vec::new() };
853        let listed = service
854            .list(ListRequest {
855                app_name: self.inner.app.clone(),
856                user_id: user.to_string(),
857                limit: Some(FORK_SCAN_LIMIT),
858                offset: None,
859            })
860            .await
861            .unwrap_or_default();
862        let mut forks = Vec::new();
863        for other in listed {
864            if other.id() == session {
865                continue;
866            }
867            let Ok(Some(newest)) = checkpoints.load(&self.thread(user, other.id())).await else {
868                continue;
869            };
870            let Some(lineage) = newest.lineage().ok().flatten().filter(|l| l.parent == thread)
871            else {
872                continue;
873            };
874            let at =
875                newest.run_record().ok().flatten().map_or(newest.created_at, |run| run.started_at);
876            forks.push(ForkSummary {
877                session_id: other.id().to_string(),
878                at,
879                at_text: at.with_timezone(&self.inner.offset).format("%H:%M").to_string(),
880                parent_step: lineage.parent_step,
881                text: words::fork_summary(lineage.parent_step, &lineage.edited),
882                edited: lineage.edited,
883            });
884        }
885        forks.sort_by_key(|fork| std::cmp::Reverse(fork.at));
886        forks
887    }
888
889    /// The question a paused node asked, from the session's latest graph interrupt event.
890    async fn question(&self, user: &str, session: &str) -> Option<String> {
891        let found = self
892            .session_service()
893            .ok()?
894            .get(GetRequest {
895                app_name: self.inner.app.clone(),
896                user_id: user.to_string(),
897                session_id: session.to_string(),
898                num_recent_events: Some(20),
899                after: None,
900            })
901            .await
902            .ok()?;
903        found.events().all().iter().rev().find_map(|event| {
904            let payload = adk_graph::interrupt::GraphInterruptPayload::from_event(event)?;
905            (payload.kind == "dynamic").then_some(payload.message).flatten()
906        })
907    }
908
909    /// The governed node `request` is for, when its origin is a graph observed here, with the
910    /// graph's name: a node of the graph, or of a subgraph inside it, whose declaration the
911    /// origin binds. When none matches exactly, such as after the graph changed, the node of
912    /// that name that spends money, else the first.
913    fn governed_node(
914        &self,
915        origin: Option<&ToolOrigin>,
916        node: &str,
917    ) -> Option<(String, GovernedShape)> {
918        let origin = origin?;
919        let agent =
920            self.inner.graphs.iter().find(|agent| origin.source == origin_of(agent.name()))?;
921        let candidates: Vec<GovernedShape> = agent
922            .graph()
923            .governed_shapes()
924            .into_iter()
925            .filter(|governed| governed.node.name == node)
926            .collect();
927        let binds = |governed: &&GovernedShape| {
928            serde_json::to_value(&governed.node).is_ok_and(|declaration| {
929                ToolOrigin::new(origin.source.clone(), &declaration, None).declaration_digest
930                    == origin.declaration_digest
931            })
932        };
933        let spends = |governed: &&GovernedShape| {
934            governed.node.governed.is_some_and(|governed| governed.spends_money)
935        };
936        let found = candidates
937            .iter()
938            .find(binds)
939            .or_else(|| candidates.iter().find(spends))
940            .or_else(|| candidates.first())?;
941        Some((agent.name().to_string(), found.clone()))
942    }
943
944    /// An approval router that keeps `fallback`'s route and raises the risk of a call from a
945    /// governed node that spends money to high, so chat, voice and the kernel's own routes
946    /// treat it as money (spec 3.3 §7.2, §7.4 rule 4).
947    ///
948    /// # Example
949    ///
950    /// ```rust
951    /// use adk_core::{ApprovalPolicy, ApproverSelector};
952    /// use adk_surface::workflow::Workflows;
953    ///
954    /// let router = Workflows::new("adk-rust")
955    ///     .approval_router(ApprovalPolicy::new([ApproverSelector::group("owner")]));
956    /// # let _ = router;
957    /// ```
958    pub fn approval_router(&self, fallback: impl ApprovalRouter + 'static) -> WorkflowRouter {
959        WorkflowRouter { workflows: self.clone(), fallback: Arc::new(fallback) }
960    }
961}
962
963/// Ends a fork's run under way when dropped: when its stream ends, or when it never started.
964struct Release {
965    starting: Arc<Mutex<BTreeSet<String>>>,
966    thread: String,
967}
968
969impl Drop for Release {
970    fn drop(&mut self) {
971        if let Ok(mut starting) = self.starting.lock() {
972            starting.remove(&self.thread);
973        }
974    }
975}
976
977/// The router [`Workflows::approval_router`] builds.
978pub struct WorkflowRouter {
979    workflows: Workflows,
980    fallback: Arc<dyn ApprovalRouter>,
981}
982
983impl std::fmt::Debug for WorkflowRouter {
984    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
985        f.debug_struct("WorkflowRouter").field("workflows", &self.workflows).finish_non_exhaustive()
986    }
987}
988
989impl ApprovalRouter for WorkflowRouter {
990    fn route(&self, call: &ApprovalCall) -> Option<ApprovalRoute> {
991        let mut route = self.fallback.route(call)?;
992        let money = self
993            .workflows
994            .governed_node(call.request.origin.as_ref(), &call.request.tool_name)
995            .is_some_and(|(_, found)| {
996                found.node.governed.is_some_and(|governed| governed.spends_money)
997            });
998        if money {
999            route.risk = route.risk.max(ApprovalRisk::High);
1000        }
1001        Some(route)
1002    }
1003}
1004
1005#[async_trait]
1006impl CardHints for Workflows {
1007    /// A governed node's card (spec 3.3 §7.1, §12): never **Always allow**, money for a node
1008    /// that spends it, "Can't be undone" for a non-idempotent one, and "From the invoice-run
1009    /// workflow · Open in Runs".
1010    async fn hint(&self, request: &ApprovalRequest) -> Option<CardHint> {
1011        let (graph, found) = self.governed_node(request.origin.as_ref(), &request.tool_name)?;
1012        let node = found.node;
1013        let mut hint = CardHint::new().without_always_allow().with_detail(
1014            CardDetail::new(words::from_the_workflow(&graph)).with_link(
1015                words::OPEN_IN_RUNS,
1016                format!("/ui/developer/runs/{}", path_segment(&request.scope.session_id)),
1017            ),
1018        );
1019        if node.governed.is_some_and(|governed| governed.spends_money) {
1020            hint = hint.spends_money();
1021        }
1022        if project::effect_of(&node) == Some(adk_core::ToolEffect::NonIdempotent) {
1023            hint = hint.with_reversibility(Reversibility::CantBeUndone);
1024        }
1025        Some(hint)
1026    }
1027}
1028
1029/// The origin a graph agent's governed calls carry.
1030fn origin_of(graph: &str) -> String {
1031    format!("graph:{graph}")
1032}
1033
1034fn checkpointer(agent: &GraphAgent) -> Result<Arc<dyn Checkpointer>> {
1035    agent.graph().checkpointer().cloned().ok_or_else(|| {
1036        SurfaceError::unsupported(format!(
1037            "observing '{}', a graph without a checkpointer",
1038            agent.name()
1039        ))
1040    })
1041}
1042
1043fn source(error: adk_graph::GraphError) -> SurfaceError {
1044    SurfaceError::Source(error.into())
1045}
1046
1047fn refused(code: &'static str, message: impl Into<String>) -> SurfaceError {
1048    SurfaceError::Source(AdkError::new(
1049        ErrorComponent::Server,
1050        ErrorCategory::InvalidInput,
1051        code,
1052        message.into(),
1053    ))
1054}
1055
1056/// A fork's refusal, in the words the fork dialog shows.
1057fn fork_refused(error: ForkError) -> SurfaceError {
1058    match error {
1059        ForkError::UnknownCheckpoint { id } | ForkError::OtherThread { id, .. } => {
1060            SurfaceError::not_found(format!("checkpoint '{id}'"))
1061        }
1062        ForkError::Paused { .. } => refused("fork.paused", words::FORK_FROM_THE_COMPLETED_STEP),
1063        ForkError::NothingToRun { .. } => {
1064            refused("fork.nothing_to_run", words::NOTHING_RUNS_AFTER_THE_LAST_STEP)
1065        }
1066        ForkError::UndeclaredChannel { key } => {
1067            refused("fork.undeclared_channel", format!("Not a channel of this graph: {key}"))
1068        }
1069        ForkError::UnknownKey { key } => {
1070            refused("fork.unknown_key", format!("Not a key of this checkpoint: {key}"))
1071        }
1072        ForkError::Checkpointer(error) => source(error),
1073        other => refused(other.code(), other.to_string()),
1074    }
1075}
1076
1077/// When the run a fork came from started, and the nodes it finished up to the fork.
1078async fn parent_facts(
1079    checkpoints: &dyn Checkpointer,
1080    lineage: &adk_graph::record::Lineage,
1081) -> (Option<DateTime<Utc>>, Vec<NodeRecord>) {
1082    let Ok(parent) = checkpoints.list(&lineage.parent).await else { return (None, Vec::new()) };
1083    let saved: Vec<Saved> = parent.into_iter().map(Saved::new).collect();
1084    let Some(at) =
1085        saved.iter().position(|saved| saved.checkpoint.checkpoint_id == lineage.parent_checkpoint)
1086    else {
1087        return (None, Vec::new());
1088    };
1089    let Some(run) = saved[at].run.clone() else { return (None, Vec::new()) };
1090    let mut done: BTreeMap<String, NodeRecord> = BTreeMap::new();
1091    for entry in saved[..=at].iter().filter(|entry| entry.run.as_ref() == Some(&run)) {
1092        for step in entry.steps.iter().filter(|step| step.step <= lineage.parent_step) {
1093            for node in &step.nodes {
1094                if matches!(node.status, NodeStatus::Done | NodeStatus::Recorded) {
1095                    done.insert(node.node.clone(), node.clone());
1096                }
1097            }
1098        }
1099    }
1100    (Some(run.started_at), done.into_values().collect())
1101}
1102
1103/// The session of `thread`, when it is a session of `user` in `app`.
1104fn session_of_thread(app: &str, user: &str, thread: &str) -> Option<String> {
1105    let prefix = session_thread_id(app, user, "");
1106    let encoded = thread.strip_prefix(&prefix)?;
1107    let decoded = encoded.replace("%3A", ":").replace("%25", "%");
1108    (session_thread_id(app, user, &decoded) == thread).then_some(decoded)
1109}
1110
1111/// `value` as one path segment: every byte but the unreserved ones percent-encoded.
1112fn path_segment(value: &str) -> String {
1113    value
1114        .bytes()
1115        .map(|byte| match byte {
1116            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
1117                (byte as char).to_string()
1118            }
1119            other => format!("%{other:02X}"),
1120        })
1121        .collect()
1122}
1123
1124#[cfg(test)]
1125mod tests {
1126    use super::*;
1127
1128    #[test]
1129    fn a_thread_names_its_session_only_for_its_own_user() {
1130        let thread = session_thread_id("adk-rust", "ana", "s:1%");
1131        assert_eq!(session_of_thread("adk-rust", "ana", &thread), Some("s:1%".to_string()));
1132        assert_eq!(session_of_thread("adk-rust", "bob", &thread), None);
1133    }
1134
1135    #[test]
1136    fn a_session_is_one_path_segment() {
1137        assert_eq!(path_segment("s-1/2 3"), "s-1%2F2%203");
1138    }
1139}