gadk-engine 0.5.7

The gadk runtime: LLM agent and flow, workflow agents and graphs, and the runner
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright 2026 Chris Olson
// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Drives an agent through a single-node root workflow (START -> agent node), sharing the agent
//! path's session/plugin/persist pipeline.

use std::collections::HashSet;
use std::sync::Arc;

use futures::StreamExt;
use gadk_agent::{
    Agent, AgentError, AgentType, EventStream, InvocationContext, Mode, PluginManager, RunConfig,
    Teardowns, run_limits,
};
use gadk_genai::{Content, FunctionResponse};
use gadk_session::{Event, Session};
use serde_json::{Map, Value};
use tokio_util::sync::CancellationToken;

use super::agent_node::new_agent_node;
use super::compaction::InvocationGuard;
use super::{Processed, RunOptions, RunnerInner, wrap};
use crate::artifacts::ScopedArtifacts;
use crate::llm::mode::with_bound_mode;
use crate::memory::ScopedMemory;
use crate::tool::utils::{function_calls, function_responses};
use crate::workflow::{Edge, Node, NodeStatus, RunState, START, Workflow, WorkflowOptions};

/// Whether `a` is an LLM agent.
pub(crate) fn is_llm_agent(a: &dyn Agent) -> bool {
    a.agent_state().agent_type == AgentType::LlmAgent
}

/// Wraps any agent as the node the node runtime drives.
pub(crate) fn build_runner_node(a: &Arc<dyn Agent>) -> Result<Arc<dyn Node>, AgentError> {
    Ok(new_agent_node(a.clone()))
}

/// The root workflow's name, `<app>/<agent>`: stable across turns and unique per agent.
fn root_workflow_name(app_name: &str, a: &dyn Agent) -> String {
    format!("{app_name}/{}", a.name())
}

impl RunnerInner {
    /// Builds the invocation context for a run; the agent path uses it too. An empty
    /// `invocation_id` mints a fresh one; `branch` is the agent path's route to a calling sub-agent
    /// (empty otherwise).
    #[allow(clippy::too_many_arguments)]
    pub(super) fn new_invocation_context(
        &self,
        stored: &Arc<dyn Session>,
        agent: Arc<dyn Agent>,
        msg: Option<Content>,
        cfg: &RunConfig,
        token: &CancellationToken,
        compaction: bool,
        plugins: Arc<PluginManager>,
        mut invocation_id: String,
        branch: String,
    ) -> InvocationContext {
        // One LLM-call budget for the whole invocation.
        let limiter = Arc::new(run_limits::LlmCallLimiter::new(
            run_limits::resolve_max_llm_calls(cfg.max_llm_calls),
        ));
        if invocation_id.is_empty() {
            invocation_id = format!("e-{}", self.platform.new_uuid());
        }
        let mut b = InvocationContext::builder()
            .session(stored.clone())
            .session_service(self.session_service.clone())
            .agent(agent)
            .invocation_id(invocation_id)
            .run_config(cfg.clone())
            .llm_call_limiter(limiter)
            .platform(self.platform.clone())
            // The caller resolved the plugin manager.
            .plugin_manager(plugins)
            .parent_map(self.parents.clone())
            .branch(branch)
            .cancellation_token(token.clone())
            // Started work a dropped component hands over; awaited before the after-run
            // callbacks (see `InvocationGuard`).
            .teardowns(Arc::new(Teardowns::new()));
        if let Some(m) = msg {
            b = b.user_content(m);
        }
        if let Some(svc) = &self.artifact_service {
            b = b.artifacts(Arc::new(ScopedArtifacts::new(
                svc.clone(),
                stored.app_name(),
                stored.user_id(),
                stored.id(),
            )));
        }
        if let Some(svc) = &self.memory_service {
            b = b.memory(Arc::new(ScopedMemory::new(
                svc.clone(),
                stored.app_name(),
                stored.user_id(),
            )));
        }
        // One compaction runtime for the whole invocation, shared by every context derived from it.
        // Live runs attach none.
        if compaction && let Some(cfg) = &self.compaction {
            b = crate::compaction::runtime::attach(
                b,
                crate::compaction::runtime::CompactionRuntime::new(
                    cfg.clone(),
                    Some(self.session_service.clone()),
                ),
            );
        }
        b.build_invocation()
    }
}

/// Wraps `agent_to_run` in a START -> node workflow and runs or resumes it.
#[allow(clippy::too_many_arguments)]
pub(super) fn run_node(
    inner: Arc<RunnerInner>,
    plugins: Arc<PluginManager>,
    stored: Arc<dyn Session>,
    agent_to_run: Arc<dyn Agent>,
    root_mode: Mode,
    msg: Option<Content>,
    cfg: RunConfig,
    opts: RunOptions,
) -> EventStream {
    Box::pin(async_stream::stream! {
        let node = match build_runner_node(&agent_to_run) {
            Ok(n) => n,
            Err(e) => { yield Err(e); return; }
        };
        // A synthetic START -> node workflow; the root wrapper keeps "app/agent@1" off event
        // paths.
        let edges = vec![Edge { from: START.clone(), to: node, route: None }];
        let wf = match Workflow::new(
            &root_workflow_name(&inner.app_name, &*agent_to_run),
            edges,
            WorkflowOptions { root_wrapper: true, ..Default::default() },
        ) {
            Ok(w) => w,
            Err(e) => { yield Err(wrap("failed to build node workflow", e)); return; }
        };

        let token = CancellationToken::new();
        let cancel_on_drop = token.clone().drop_guard();
        // The user content is the workflow's seed input. Answers to calls from several invocations
        // resume the first call's invocation here rather than being rejected.
        let (invocation_id, _) = resolve_invocation_id(Some(&*stored), msg.as_ref());
        let ictx = inner.new_invocation_context(
            &stored,
            agent_to_run.clone(),
            msg.clone(),
            &cfg,
            &token,
            true,
            plugins,
            invocation_id,
            String::new(),
        );
        // Binds the ROOT agent's placement on the context handed to the node run.
        let ictx = with_bound_mode(
            &ictx,
            inner.root_agent.name(),
            inner.root_agent.agent_state(),
            root_mode,
        );

        // Append the user message (also runs on_user_message), as the agent path does.
        let appended = inner
            .append_message_to_session(
                ictx.into_context(),
                &stored,
                msg.clone(),
                cfg.save_input_blobs_as_artifacts,
                opts.state_delta.clone(),
            )
            .await;
        let (ctx, user_event) = match appended {
            Ok(v) => v,
            Err(e) => { yield Err(e); return; }
        };
        // Compaction is pending before the user message is yielded, the after-run callbacks only
        // after it.
        let ictx = ctx.as_invocation().clone();
        let mut guard = InvocationGuard::new(inner.clone(), stored.clone(), ictx.clone());
        guard.cancel_on_drop(cancel_on_drop);
        if opts.yield_user_message && let Some(ev) = user_event {
            guard.at_yield(true);
            yield Ok(ev);
            guard.at_yield(false);
        }

        // Plugin lifecycle: defer after_run, run before_run, honor an early exit.
        guard.defer_after_run();
        let mut early = false;
        'run: {
            match inner.run_before_run_callback(&ictx).await {
                Err(e) => { guard.mark_failed(); guard.at_yield(true); yield Err(e); guard.at_yield(false); early = true; break 'run; }
                Ok(Some(ev)) => { guard.at_yield(true); yield Ok(ev); guard.at_yield(false); early = true; break 'run; }
                Ok(None) => {}
            }

            // Resume (HITL continuation) vs fresh run: the paused state comes from session history
            // (`None` for a fresh run).
            let state: Option<RunState> = match wf.reconstruct_run_state(&*stored, ictx.invocation_id()) {
                Ok(s) => s,
                Err(e) => {
                    guard.mark_failed();
                    guard.at_yield(true);
                    yield Err(wrap("failed to reconstruct workflow run state", e));
                    guard.at_yield(false);
                    early = true;
                    break 'run;
                }
            };
            let responses = build_resume_responses(msg.as_ref(), state.as_ref(), &*stored);
            let mut events: EventStream = match (responses.is_empty(), state) {
                (true, _) => wf.run(ictx.clone()),
                (false, Some(state)) => wf.resume(ctx.clone(), state, responses),
                // Resuming with no paused state yields nothing.
                (false, None) => Box::pin(futures::stream::empty()),
            };

            while let Some(item) = events.next().await {
                let mut event = match item {
                    Ok(ev) => ev,
                    Err(e) => { guard.mark_failed(); guard.at_yield(true); yield Err(e); guard.at_yield(false); continue; }
                };
                // Engine control events have no author; a later find_agent_to_run would warn
                // about the empty author.
                if event.author.is_empty() {
                    event.author = agent_to_run.name().to_string();
                }
                match inner.process_event(&ictx, &*stored, event).await {
                    Processed::Event(ev) => { guard.at_yield(true); yield Ok(*ev); guard.at_yield(false); }
                    Processed::PluginError(e) => { guard.mark_failed(); guard.at_yield(true); yield Err(e); guard.at_yield(false); }
                    Processed::AppendError(e) => { guard.mark_failed(); guard.at_yield(true); yield Err(e); guard.at_yield(false); early = true; break 'run; }
                }
            }
        }
        if early {
            guard.finish_early().await;
        } else {
            // Compact once every event of the invocation is persisted; the consumer drained the
            // stream, so a failure can still be reported.
            if let Some(e) = guard.compact_inline().await {
                guard.at_yield(true);
                yield Err(e);
                guard.at_yield(false);
            }
            guard.finish().await;
        }
    })
}

/// `msg`'s function responses that answer a still-pending interrupt (waiting in `state`, or an open
/// long-running call in history), keyed by interrupt ID. Empty for a fresh turn.
fn build_resume_responses(
    msg: Option<&Content>,
    state: Option<&RunState>,
    sess: &dyn Session,
) -> Map<String, Value> {
    let mut out = Map::new();
    let Some(msg) = msg else {
        return out;
    };
    let mut pending: HashSet<String> = HashSet::new();
    if let Some(state) = state {
        pending.extend(waiting_interrupt_ids(state));
    }
    pending.extend(open_long_running_call_ids(Some(sess)));
    if pending.is_empty() {
        return out;
    }
    for fr in function_responses(Some(msg)) {
        if fr.id.is_empty() || !pending.contains(&fr.id) {
            continue;
        }
        // Opaque payload; Workflow::resume validates it against any schema.
        out.insert(fr.id.clone(), decode_resume_response(fr));
    }
    out
}

/// Long-running call IDs in history without a matching function response.
fn open_long_running_call_ids(sess: Option<&dyn Session>) -> HashSet<String> {
    let mut open = HashSet::new();
    let Some(sess) = sess else {
        return open;
    };
    let mut answered = HashSet::new();
    for ev in sess.events() {
        open.extend(ev.long_running_tool_ids.iter().cloned());
        for fr in function_responses(ev.response.content.as_ref()) {
            if !fr.id.is_empty() {
                answered.insert(fr.id.clone());
            }
        }
    }
    open.retain(|id| !answered.contains(id));
    open
}

/// Decodes a resume response: `{"response": v}` (a string `v` is JSON-parsed when possible), else
/// `{"payload": v}`, else the whole map.
fn decode_resume_response(fr: &FunctionResponse) -> Value {
    if let Some(raw) = fr.response.get("response") {
        if let Value::String(s) = raw {
            return serde_json::from_str::<Value>(s).unwrap_or_else(|_| raw.clone());
        }
        return raw.clone();
    }
    if let Some(payload) = fr.response.get("payload") {
        return payload.clone();
    }
    Value::Object(fr.response.clone())
}

/// The non-empty interrupt IDs of every waiting node.
fn waiting_interrupt_ids(state: &RunState) -> HashSet<String> {
    state
        .nodes
        .values()
        .filter(|ns| ns.status == NodeStatus::Waiting)
        .flat_map(|ns| ns.interrupts.iter())
        .filter(|id| !id.is_empty())
        .cloned()
        .collect()
}

/// The invocation ID of the event holding the first answered call found in history, so a HITL
/// resume shares its pause's invocation (`""` for a fresh turn or when no answered call is in
/// history), and whether the answered calls belong to more than one invocation.
pub(super) fn resolve_invocation_id(
    sess: Option<&dyn Session>,
    msg: Option<&Content>,
) -> (String, bool) {
    let (Some(sess), Some(msg)) = (sess, msg) else {
        return (String::new(), false);
    };
    let mut id: Option<String> = None;
    let mut spans_invocations = false;
    for fr in function_responses(Some(msg)) {
        if fr.id.is_empty() {
            continue;
        }
        let Some(ev) = find_event_by_function_call_id(Some(sess), &fr.id) else {
            continue;
        };
        match &id {
            None => id = Some(ev.invocation_id),
            Some(first) if *first != ev.invocation_id => spans_invocations = true,
            Some(_) => {}
        }
    }
    (id.unwrap_or_default(), spans_invocations)
}

/// The most recent event carrying a function call with `id` (reverse scan).
fn find_event_by_function_call_id(sess: Option<&dyn Session>, id: &str) -> Option<Event> {
    let sess = sess?;
    if id.is_empty() {
        return None;
    }
    sess.events().into_iter().rev().find(|ev| {
        function_calls(ev.response.content.as_ref())
            .iter()
            .any(|fc| fc.id == id)
    })
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use serde_json::json;

    fn fr(response: Value) -> FunctionResponse {
        let Value::Object(m) = response else {
            unreachable!()
        };
        FunctionResponse {
            id: "c".into(),
            name: "ask".into(),
            response: m,
            ..Default::default()
        }
    }

    #[test]
    fn decode_resume_response_matches_go() {
        assert_eq!(
            decode_resume_response(&fr(json!({"response": "{\"a\":1}"}))),
            json!({"a": 1})
        );
        assert_eq!(
            decode_resume_response(&fr(json!({"response": "plain"}))),
            json!("plain")
        );
        assert_eq!(
            decode_resume_response(&fr(json!({"response": 3}))),
            json!(3)
        );
        assert_eq!(
            decode_resume_response(&fr(json!({"payload": "yes"}))),
            json!("yes")
        );
        assert_eq!(
            decode_resume_response(&fr(json!({"x": 1}))),
            json!({"x": 1})
        );
    }
}