gadk-engine 0.5.6

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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// 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.

//! Instruction request processor and session-state templating.

use std::sync::{Arc, LazyLock};

use futures::future::BoxFuture;
use gadk_agent::tool_util::append_instructions;
use gadk_agent::{Agent, AgentError, InvocationContext};
use gadk_artifact::ArtifactError;
use gadk_model::LlmRequest;
use gadk_session::{Event, SessionError};
use serde_json::Value;

use crate::llm::{
    flow::Flow,
    processors::{go_sprint, wrap_err},
    state::{LlmAgentState, reveal},
};

const APP_PREFIX: &str = "app:";
const USER_PREFIX: &str = "user:";
const TEMP_PREFIX: &str = "temp:";

/// The regex to find placeholders like {variable} or {artifact.file_name}.
#[allow(clippy::expect_used)] // constant pattern, cannot fail
static PLACEHOLDER: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r"\{+[^{}]*\}+").expect("valid placeholder regex"));

/// A placeholder directly after one of these bytes is literal text ("${x}", "\{x}").
const LITERAL_PLACEHOLDER_PREFIXES: &[u8] = b"$\\";

/// Appends the root agent's global instruction, then this agent's instruction, to the request.
pub(crate) fn instructions_request_processor<'a>(
    ctx: &'a InvocationContext,
    req: &'a mut LlmRequest,
    _f: &'a Flow,
) -> BoxFuture<'a, Result<Vec<Event>, AgentError>> {
    Box::pin(async move {
        let agent = ctx.agent();
        let Some(state) = reveal(&*agent) else {
            return Ok(Vec::new());
        };
        // The root agent, falling back to the agent
        // itself.
        let root = root_agent(ctx, &agent);
        let root_state = reveal(&*root).unwrap_or(state);
        append_global_instructions(ctx, req, root_state)
            .await
            .map_err(|e| wrap_err("failed to append global instructions", e))?;
        append_agent_instructions(ctx, req, state)
            .await
            .map_err(|e| wrap_err("failed to append instructions", e))?;
        Ok(Vec::new())
    })
}

/// Walks parent links by name until none; no parent map → the agent
/// itself.
fn root_agent(ctx: &InvocationContext, agent: &Arc<dyn Agent>) -> Arc<dyn Agent> {
    match ctx.parent_map() {
        Some(pm) => pm.root_agent(agent),
        None => agent.clone(),
    }
}

/// Appends the agent's instruction. The provider result is not templated.
async fn append_agent_instructions(
    ctx: &InvocationContext,
    req: &mut LlmRequest,
    state: &LlmAgentState,
) -> Result<(), AgentError> {
    if let Some(provider) = &state.cfg.instruction_provider {
        let mut instruction = provider(ctx.as_readonly().clone())
            .await
            .map_err(|e| wrap_err("failed to evaluate instruction provider", e))?;
        // The live task_completed suffix wraps the provider, as in
        // adk-python's _append_instruction (the provider's text is not templated).
        instruction.push_str(state.instruction_suffix.read().as_str());
        append_instructions(req, &[instruction.as_str()]);
        return Ok(());
    }
    // The configured instruction plus any live suffix; the empty check and state
    // injection run on the combined string.
    let instruction = state.instruction();
    if instruction.is_empty() {
        return Ok(());
    }
    let inst = inject_session_state(ctx, &instruction)
        .await
        .map_err(|e| wrap_err("failed to inject session state into instruction", e))?;
    append_instructions(req, &[inst.as_str()]);
    Ok(())
}

/// Appends the global instruction. The provider result is not
/// templated.
async fn append_global_instructions(
    ctx: &InvocationContext,
    req: &mut LlmRequest,
    state: &LlmAgentState,
) -> Result<(), AgentError> {
    if let Some(provider) = &state.cfg.global_instruction_provider {
        let instruction = provider(ctx.as_readonly().clone())
            .await
            .map_err(|e| wrap_err("failed to evaluate global instruction provider", e))?;
        append_instructions(req, &[instruction.as_str()]);
        return Ok(());
    }
    if state.cfg.global_instruction.is_empty() {
        return Ok(());
    }
    let inst = inject_session_state(ctx, &state.cfg.global_instruction)
        .await
        .map_err(|e| wrap_err("failed to inject session state into global instruction", e))?;
    append_instructions(req, &[inst.as_str()]);
    Ok(())
}

/// Populates values in an instruction
/// template from the context.
pub(crate) async fn inject_session_state(
    ctx: &InvocationContext,
    template: &str,
) -> Result<String, AgentError> {
    let mut out = String::with_capacity(template.len());
    let mut last = 0;
    for m in PLACEHOLDER.find_iter(template) {
        let (start, end) = (m.start(), m.end());
        // Leave literal placeholders in place; they are copied with the surrounding text.
        if start > 0 && LITERAL_PLACEHOLDER_PREFIXES.contains(&template.as_bytes()[start - 1]) {
            continue;
        }
        out.push_str(&template[last..start]);
        out.push_str(&replace_match(ctx, m.as_str()).await?);
        last = end;
    }
    out.push_str(&template[last..]);
    Ok(out)
}

/// Resolves one `{...}` placeholder: an artifact, or a session state value.
pub(crate) async fn replace_match(ctx: &InvocationContext, m: &str) -> Result<String, AgentError> {
    // Strip the braces, then surrounding whitespace.
    let var = m.trim_matches(|c| c == '{' || c == '}').trim();
    let (var, optional) = match var.strip_suffix('?') {
        Some(v) => (v, true),
        None => (var, false),
    };
    if let Some(file) = var.strip_prefix("artifact.") {
        let Some(arts) = ctx.artifacts() else {
            return Err(AgentError::other("artifact service is not initialized"));
        };
        return match arts.load(file).await {
            Ok(resp) => Ok(resp
                .part
                .map(|p| artifact_text(file, &p))
                .unwrap_or_default()),
            Err(e) if optional && is_artifact_not_found(&e) => Ok(String::new()),
            Err(e) => Err(wrap_err(format!("failed to load artifact {file}"), e)),
        };
    }
    if !is_valid_state_name(var) {
        // Return the original string if not a valid name.
        return Ok(m.to_owned());
    }
    let session = ctx.session();
    match session.state().get(var) {
        // A null value → "".
        Ok(Value::Null) => Ok(String::new()),
        // Any other value is displayed with `go_sprint`.
        Ok(v) => Ok(go_sprint(&v)),
        Err(SessionError::StateKeyNotExist) if optional => Ok(String::new()),
        // Unwrapped: the session error is returned as is.
        Err(e) => Err(AgentError::Session(e)),
    }
}

/// Renders a loaded artifact for an instruction. A text artifact can come back as inline data
/// rather than as text (the GCS artifact service stores a text part as a text/plain object and
/// loads it back as bytes). Inline data goes
/// through adk-python's `as_safe_part_for_llm` checks, in the same order:
///
/// 1. Inline data whose MIME type Gemini accepts inline (image/*, audio/*, video/*,
///    application/pdf, apart from the SVG and XML image types) is never decoded.
/// 2. Otherwise it is decoded when its MIME type is text/* or one of adk-python's
///    `_TEXT_LIKE_MIME_TYPES`, or its name has a .csv, .txt, .json or .xml extension.
///
/// Anything else renders as the part's text (empty for binary data). Invalid UTF-8 becomes one
/// U+FFFD per run of invalid bytes.
pub(crate) fn artifact_text(name: &str, part: &gadk_genai::Part) -> String {
    let Some(blob) = &part.inline_data else {
        return part.text.clone();
    };
    let mime_type = normalize_mime_type(&blob.mime_type);
    if is_gemini_inline_mime_type(&mime_type) {
        return part.text.clone();
    }
    if is_text_like_mime_type(&mime_type) || has_text_file_extension(name) {
        return to_valid_utf8(&blob.data);
    }
    part.text.clone()
}

/// The lowercase media type without parameters such as charset.
fn normalize_mime_type(mime_type: &str) -> String {
    let media_type = mime_type.split_once(';').map_or(mime_type, |(m, _)| m);
    media_type.trim().to_lowercase()
}

/// Whether Gemini accepts the MIME type inline (adk-python `_is_inline_mime_type_supported`).
fn is_gemini_inline_mime_type(mime_type: &str) -> bool {
    match mime_type {
        "image/svg" | "image/svg+xml" | "image/xml" => false,
        "application/pdf" => true,
        m => m.starts_with("image/") || m.starts_with("audio/") || m.starts_with("video/"),
    }
}

/// A MIME type adk-python decodes as text.
fn is_text_like_mime_type(mime_type: &str) -> bool {
    mime_type.starts_with("text/")
        || matches!(
            mime_type,
            "application/csv"
                | "application/json"
                | "application/svg+xml"
                | "application/xml"
                | "image/svg"
                | "image/svg+xml"
                | "image/xml"
        )
}

/// Whether the name's extension (the suffix from the final dot of the final
/// slash-separated element) is a text one.
fn has_text_file_extension(name: &str) -> bool {
    let base = name.rsplit('/').next().unwrap_or(name);
    let ext = base.rfind('.').map_or("", |i| &base[i..]);
    matches!(
        ext.to_lowercase().as_str(),
        ".csv" | ".txt" | ".json" | ".xml"
    )
}

/// Lossy UTF-8 decode: each run of invalid bytes becomes one U+FFFD.
fn to_valid_utf8(data: &[u8]) -> String {
    let mut out = String::with_capacity(data.len());
    let mut in_invalid_run = false;
    for chunk in data.utf8_chunks() {
        if !chunk.valid().is_empty() {
            out.push_str(chunk.valid());
            in_invalid_run = false;
        }
        if !chunk.invalid().is_empty() && !in_invalid_run {
            out.push('\u{FFFD}');
            in_invalid_run = true;
        }
    }
    out
}

/// Whether the error is, or wraps, an artifact-not-found error.
fn is_artifact_not_found(e: &AgentError) -> bool {
    // `AgentError::Artifact` is `#[error(transparent)]`, which forwards `source()` to the inner
    // ArtifactError's own source, so a chain walk never yields the ArtifactError itself; check
    // the direct variant first.
    if matches!(e, AgentError::Artifact(ArtifactError::NotFound)) {
        return true;
    }
    // Wrapped forms. `AgentError::Other` has no `source()`, so start from its payload.
    let mut cur: Option<&(dyn std::error::Error + 'static)> = match e {
        AgentError::Other(inner) | AgentError::Workflow(inner) => Some(&**inner),
        other => Some(other),
    };
    while let Some(err) = cur {
        if matches!(
            err.downcast_ref::<ArtifactError>(),
            Some(ArtifactError::NotFound)
        ) {
            return true;
        }
        if matches!(
            err.downcast_ref::<AgentError>(),
            Some(AgentError::Artifact(ArtifactError::NotFound))
        ) {
            return true;
        }
        cur = err.source();
    }
    false
}

/// Whether `s` is a valid identifier (Python `str.isidentifier()`).
///
/// Letters and digits are `char::is_alphabetic` and `char::is_numeric`, which are slightly
/// broader than Unicode categories L and Nd for rare scripts (Other_Alphabetic, Nl/No).
/// `char::is_numeric` are slightly broader for rare scripts (Other_Alphabetic, Nl/No).
fn is_identifier(s: &str) -> bool {
    let mut chars = s.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !(first.is_alphabetic() || first == '_') {
        return false;
    }
    chars.all(|c| c.is_alphabetic() || c.is_numeric() || c == '_')
}

/// Whether `var` is a valid state name: an identifier, optionally prefixed by `app:`, `user:` or
/// `temp:`.
fn is_valid_state_name(var: &str) -> bool {
    let parts: Vec<&str> = var.split(':').collect();
    match parts.as_slice() {
        [_] => is_identifier(var),
        [prefix, name] => {
            let prefix = format!("{prefix}:");
            [APP_PREFIX, USER_PREFIX, TEMP_PREFIX].contains(&prefix.as_str()) && is_identifier(name)
        }
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use gadk_agent::InvocationContext;
    use gadk_session::{CreateRequest, InMemorySessionService, SessionService};
    use pretty_assertions::assert_eq;
    use serde_json::json;

    use super::*;

    #[tokio::test]
    async fn literal_dollar_brace_is_kept() {
        let svc = InMemorySessionService::new();
        let sess = svc
            .create(CreateRequest {
                app_name: "a".into(),
                user_id: "u".into(),
                session_id: Some("s".into()),
                state: json!({"x": "X", "y": 1.5}).as_object().cloned(),
            })
            .await
            .unwrap();
        let ctx = InvocationContext::builder()
            .session(sess)
            .build_invocation();
        assert_eq!(
            inject_session_state(&ctx, "${x} \\{x} {x} {y} { x }")
                .await
                .unwrap(),
            "${x} \\{x} X 1.5 X"
        );
    }

    #[test]
    fn state_names() {
        assert!(is_valid_state_name("user:name"));
        assert!(is_valid_state_name("_a1"));
        assert!(!is_valid_state_name("1a"));
        assert!(!is_valid_state_name("bad:name"));
        assert!(!is_valid_state_name("a:b:c"));
        assert!(!is_valid_state_name(""));
    }

    use std::sync::Arc;

    use gadk_model::LlmRequest;

    use crate::llm::flow::Flow;
    use crate::llm::state::reveal;
    use crate::llm::{InstructionProvider, LlmAgentConfig, agent as llm_agent};

    /// The system-instruction text the processor builds for `agent` over a session with `x = "X"`.
    async fn system_instruction_for(agent: Arc<dyn gadk_agent::Agent>) -> String {
        let svc = InMemorySessionService::new();
        let sess = svc
            .create(CreateRequest {
                app_name: "a".into(),
                user_id: "u".into(),
                session_id: Some("s".into()),
                state: json!({"x": "X"}).as_object().cloned(),
            })
            .await
            .unwrap();
        let ctx = InvocationContext::builder()
            .session(sess)
            .agent(agent)
            .build_invocation();
        let mut req = LlmRequest::default();
        instructions_request_processor(&ctx, &mut req, &Flow::default())
            .await
            .unwrap();
        req.config
            .and_then(|c| c.system_instruction)
            .map(|si| si.parts.iter().map(|p| p.text.as_str()).collect::<String>())
            .unwrap_or_default()
    }

    /// Go appends the live suffix to State.Instruction, and appendInstructions runs the empty check
    /// and InjectSessionState on the combined string.
    #[tokio::test]
    async fn live_instruction_suffix_is_part_of_the_templated_instruction() {
        let a = llm_agent::new(LlmAgentConfig {
            name: "a".into(),
            instruction: "Hello".into(),
            ..Default::default()
        })
        .unwrap();
        reveal(&*a)
            .unwrap()
            .instruction_suffix
            .write()
            .push_str("\nvalue {x}");
        assert_eq!(system_instruction_for(a).await, "Hello\nvalue X");
    }

    /// An empty instruction with a suffix is not empty (Go: "" + suffix).
    #[tokio::test]
    async fn live_instruction_suffix_alone_is_appended() {
        let a = llm_agent::new(LlmAgentConfig {
            name: "a".into(),
            ..Default::default()
        })
        .unwrap();
        reveal(&*a)
            .unwrap()
            .instruction_suffix
            .write()
            .push_str("\nsuffix");
        assert_eq!(system_instruction_for(a).await, "\nsuffix");
    }

    /// Go dd39c80a: State.Instruction is ignored with a provider, but the live suffix wraps the
    /// provider's output.
    #[tokio::test]
    async fn live_instruction_suffix_is_appended_to_an_instruction_provider() {
        let provider: InstructionProvider =
            Arc::new(|_ctx| Box::pin(async { Ok::<_, AgentError>("from provider".to_string()) }));
        let a = llm_agent::new(LlmAgentConfig {
            name: "a".into(),
            instruction: "Hello".into(),
            instruction_provider: Some(provider),
            ..Default::default()
        })
        .unwrap();
        reveal(&*a)
            .unwrap()
            .instruction_suffix
            .write()
            .push_str("\nsuffix");
        assert_eq!(system_instruction_for(a).await, "from provider\nsuffix");
    }
}