greentic-runner-host 1.2.1

Host runtime shim for Greentic runner: config, pack loading, activity handling
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! Flow-execution A2A node (LOCKED ENCODING v1: `component == "a2a"`).
//!
//! A plain flow can ask an external A2A agent one question. The node carries
//! `agent`, `message` and an optional `output` state key in its
//! payload/config; the payload is the source of truth, exactly as
//! [`super::mcp_node`]'s `server`/`tool` are.
//!
//! ```text
//! nodes:
//!   ask_recipe:
//!     a2a:
//!       agent: 8d2f0c1e-recipe     # the admin row id, as the sidecar names it
//!       message: "{{ entry.text }}"
//!       output: recipe             # optional state key to bind the result under
//!     routing: [ ... ]
//! ```
//!
//! # This is the flow lane, and it reuses the worker lane whole
//!
//! Everything below the route record is [`greentic_aw_runtime::a2a_source`]:
//! the card fetch, the same-host rule, the per-call credential read, the
//! `SendMessage` exchange, the continuation, and — most importantly — the
//! rendering of a remote task's state into a value. Nothing here classifies an
//! outcome. `A2aToolCatalog::dispatch_in_conversation` is called verbatim, so
//! the rule **`reply` appears if and only if `status` is `completed`** is the
//! same rule in both lanes, pinned by one test
//! (`a2a_source::outcome::tests::only_a_completed_outcome_carries_a_reply`).
//!
//! What a flow node adds is only the two things a worker already had and a
//! flow did not: where the agents come from (this pack's own
//! `assets/a2a-routes.json`, never another pack's) and where the remote
//! context is remembered (below).
//!
//! # Five statuses, and a flow ROUTES on them
//!
//! A flow cannot stop mid-node to ask a human, so a remote agent that answers
//! `input-required` is not an error and must not read as an answer either.
//! The node's value always carries `status`, one of `completed`,
//! `input_required`, `working`, `failed` (the remote decided) or `error` (we
//! could not ask it) — so a `conditional_branch` on
//! `{{node.<id>.payload.status}}` is how a flow handles each one. Only
//! `completed` carries `reply`.
//!
//! # Continuation: one remote context per (tenant, env, session, agent)
//!
//! A worker keeps its remote `contextId` in `ConversationState`. A flow has no
//! such thing, so this node keeps the same [`A2aContinuations`] map — the type
//! itself, not a copy of its rules — in the flow's own durable state store
//! under prefix [`aw::CONTINUATION_PREFIX`], keyed by the session hint.
//!
//! The rule, stated so it can be relied on: **every call this session makes to
//! one agent continues the same remote conversation.** A flow that routes
//! `input_required` to a card, collects the answer and comes back to this node
//! therefore ANSWERS the remote's question instead of asking it again — which
//! is the only shape in which a flow can use `input-required` at all. Two
//! different sessions never share a context (the key differs, and
//! [`A2aContinuations::resume`] re-checks the tenant and env recorded in the
//! value itself).
//!
//! **A run with no session hint gets no continuation**, because there is no
//! conversation to belong to: such a call is its own context and nothing is
//! stored. Same when the runtime has no state store configured. Both are
//! degradations to "a fresh remote context", never a node failure.

use serde_json::Value;

/// The agent id an A2A node names, from its payload/config object (LOCKED
/// ENCODING v1). `None` when the key is absent, not a string, or blank, in
/// which case the caller falls back to the `operation` / `a2a:<agent_id>`
/// component-ref form.
pub(crate) fn agent_from_payload(payload: &Value) -> Option<String> {
    super::mcp_node::str_field(payload, "agent")
}

/// Whether the node asks the agent for its Adaptive Card as well as its text.
///
/// `card: true` in the payload (LOCKED ENCODING v1, optional). The string
/// `"true"` is accepted too, because a templated config value arrives as text.
/// Anything else, or the key's absence, is off: a flow that never opted in
/// sends the request it always did and its value gains no `card` key.
#[cfg_attr(not(feature = "agentic-worker"), allow(dead_code))]
pub(crate) fn wants_card(payload: &Value) -> bool {
    match payload.get("card") {
        Some(Value::Bool(on)) => *on,
        Some(Value::String(text)) => text.trim().eq_ignore_ascii_case("true"),
        _ => false,
    }
}

/// Metadata keys a card submit carries to name the NEXT card to navigate to.
///
/// They address nodes of the flow that rendered the card, so they are
/// meaningless to the remote agent and are removed from an answer before it is
/// sent (the remote would otherwise see the router's own node ids).
const NAVIGATION_KEYS: &[&str] = &["routeToCardId", "toCardId", "nextCardId"];

/// The key [`retarget_card_submits`] adds to every submit action's data, so a
/// flow can route on `response.a2aCardSubmit == "true"` when a button press
/// resumes a parked card instead of navigating (a routed card needs both: the
/// press may arrive either way). Not part of the answer; removed before it is
/// forwarded.
pub const CARD_SUBMIT_MARKER: &str = "a2aCardSubmit";

/// The answer a node forwards to its agent, from the payload's `answer` field
/// (typically `{{ in.input.metadata }}`, the fields a card submit carried).
///
/// Forwarded ONLY for a card submit this node's own card produced: the
/// metadata must carry `nextCardId`, which [`retarget_card_submits`] writes
/// into every submit action. An ordinary text turn's metadata (locale, a
/// routed turn's `routeToCardId` and prefill, provider extras) is not an answer
/// and must never reach the remote as one.
///
/// `None` unless it is a non-empty object once the navigation keys and empty
/// values are removed.
#[cfg_attr(not(feature = "agentic-worker"), allow(dead_code))]
pub(crate) fn answer_from_payload(payload: &Value) -> Option<Value> {
    let mut map = payload.get("answer")?.as_object()?.clone();
    if !map.contains_key("nextCardId") {
        return None;
    }
    for key in NAVIGATION_KEYS {
        map.remove(*key);
    }
    map.remove(CARD_SUBMIT_MARKER);
    map.retain(|_, value| !matches!(value, Value::Null) && value.as_str() != Some(""));
    (!map.is_empty()).then_some(Value::Object(map))
}

/// The node id the node's returned card should submit back to
/// (`card_submit_to` in the payload), when set.
#[cfg_attr(not(feature = "agentic-worker"), allow(dead_code))]
pub(crate) fn card_submit_target(payload: &Value) -> Option<String> {
    super::mcp_node::str_field(payload, "card_submit_to")
}

/// Point every `Action.Submit` of `card` at `node_id`.
///
/// The card is the REMOTE agent's, so its submit actions name the remote's own
/// nodes. Rendered by another flow they would navigate nowhere; this makes the
/// submit return to the node that asked, which then forwards the answer. Any
/// other navigation key is removed so the precedence cannot pick a stale one.
/// Returns whether any action was rewritten.
#[cfg_attr(not(feature = "agentic-worker"), allow(dead_code))]
pub(crate) fn retarget_card_submits(card: &mut Value, node_id: &str) -> bool {
    let mut changed = false;
    match card {
        Value::Object(map) => {
            if map.get("type").and_then(Value::as_str) == Some("Action.Submit") {
                let data = map
                    .entry("data")
                    .or_insert_with(|| Value::Object(Default::default()));
                if !data.is_object() {
                    *data = Value::Object(Default::default());
                }
                if let Some(data) = data.as_object_mut() {
                    for key in NAVIGATION_KEYS {
                        data.remove(*key);
                    }
                    data.insert("nextCardId".to_string(), Value::String(node_id.to_string()));
                    data.insert(CARD_SUBMIT_MARKER.to_string(), Value::Bool(true));
                    changed = true;
                }
            }
            for value in map.values_mut() {
                changed |= retarget_card_submits(value, node_id);
            }
        }
        Value::Array(items) => {
            for item in items {
                changed |= retarget_card_submits(item, node_id);
            }
        }
        _ => {}
    }
    changed
}

/// Parse an `a2a:<agent_id>` component ref, or a bare `<agent_id>` carried as
/// the node `operation`. Returns `None` for an empty id.
pub(crate) fn agent_from_ref(reference: &str) -> Option<String> {
    let id = reference.strip_prefix("a2a:").unwrap_or(reference).trim();
    (!id.is_empty()).then(|| id.to_string())
}

#[cfg(feature = "agentic-worker")]
pub mod aw {
    use std::sync::Arc;

    use chrono::Utc;
    use greentic_aw_runtime::TenantContext;
    use greentic_aw_runtime::a2a_source::{
        A2aCallOptions, A2aContinuations, A2aToolSource, CONTINUATION_IDLE_TTL_SECS,
        call_error_value,
    };
    use greentic_types::{StateKey, TenantCtx};
    use serde_json::Value;

    use crate::pack::PackRuntime;
    use crate::storage::DynStateStore;

    /// The state-store namespace the per-session continuation map lives in.
    ///
    /// Note both accessors below call the SYNCHRONOUS [`greentic_state::StateStore`]
    /// from inside an `async fn`, which is what the `state.get` / `state.set`
    /// nodes already do (`FlowEngine::execute_state_get`). Following that
    /// precedent keeps one story for flow-state access; moving this one call
    /// site onto `spawn_blocking` alone would make the two disagree without
    /// fixing anything.
    ///
    /// Deliberately NOT [`crate::storage::state::STATE_PREFIX`], which is what
    /// the `state.get` / `state.set` nodes write under: a flow author owns
    /// every key in that namespace, so sharing it would let an ordinary
    /// `state.set` overwrite — or read — this node's remote references.
    pub const CONTINUATION_PREFIX: &str = "runner-a2a";

    /// The store key one flow's continuations for one session live at. The
    /// tenant and env are not in it: [`greentic_state::fqn`] already scopes
    /// every key by both.
    ///
    /// The flow is a segment of its own so two flows in one session cannot
    /// land in one remote thread — see the module docs for why that is a
    /// correctness rule and not a confidentiality one.
    ///
    /// **The two segments cannot be confused**, even though a session hint
    /// carries `:` and may carry `/`: a `FlowId` is `[A-Za-z0-9._-]+`, so the
    /// flow segment can never contain the `/` that ends it. `execute_a2a`
    /// resolves the flow through `pack_for_flow` BEFORE building this key, so
    /// by here the id is one a loaded pack declared, and therefore one that
    /// parsed as a `FlowId`. Pinned by
    /// `tests::a_flow_id_can_never_contain_the_separator_that_ends_its_segment`.
    fn continuation_key(flow_id: &str, session_id: &str) -> StateKey {
        StateKey::new(format!("continuations/{flow_id}/{session_id}"))
    }

    /// The A2A agents THIS pack declares, or `None`.
    ///
    /// Scoped to the flow's own pack rather than to every pack the runtime
    /// loaded, which is the fail-closed reading of decision 4: a flow may ask
    /// only the agents its own `assets/a2a-routes.json` names. The worker lane
    /// unions a revision's packs because a worker's bindings are resolved
    /// against the whole unit; a flow node names one agent in one pack's flow.
    ///
    /// `None` for a pack with no sidecar, a sidecar declaring no agent, or
    /// `GREENTIC_AW_A2A=0` — the operator opt-out, which a pack must not be
    /// able to override.
    pub(crate) fn source_for_pack(
        pack: &Arc<PackRuntime>,
        tenant: &str,
        secrets: Option<crate::secrets::DynSecretsManager>,
        unit: Option<&str>,
    ) -> Option<Arc<A2aToolSource>> {
        crate::runner::a2a_pack_source::a2a_source_from_packs(
            std::slice::from_ref(pack),
            tenant,
            secrets,
            unit,
        )
    }

    /// Read this session's continuation map.
    ///
    /// Every failure — no store, no session, an unreadable entry, a blob this
    /// build cannot decode — yields an empty map, i.e. a fresh remote context.
    /// That is the safe direction: the cost is one new conversation with the
    /// remote agent, whereas failing the node would take down a call that has
    /// nothing wrong with it.
    fn load_continuations(
        store: Option<&DynStateStore>,
        state_ctx: Option<&TenantCtx>,
        flow_id: &str,
        session_id: Option<&str>,
    ) -> A2aContinuations {
        let (Some(store), Some(ctx), Some(session)) = (store, state_ctx, session_id) else {
            return A2aContinuations::default();
        };
        let key = continuation_key(flow_id, session);
        let stored = match store.get_json(ctx, CONTINUATION_PREFIX, &key, None) {
            Ok(value) => value,
            Err(error) => {
                tracing::warn!(
                    %error,
                    "a2a node could not read its continuation state; this call starts a fresh remote context"
                );
                return A2aContinuations::default();
            }
        };
        let Some(stored) = stored else {
            return A2aContinuations::default();
        };
        serde_json::from_value(stored).unwrap_or_else(|error| {
            tracing::warn!(
                %error,
                "a2a node could not decode its continuation state; this call starts a fresh remote context"
            );
            A2aContinuations::default()
        })
    }

    /// Write this session's continuation map back.
    ///
    /// The store TTL is refreshed to the continuation's own idle window, so a
    /// session that goes quiet does not leave a blob behind forever. It is a
    /// housekeeping measure and NOT the authority: expiry is decided by
    /// [`A2aContinuations::resume`] against the timestamp inside the value, so
    /// a backend that ignores TTLs still starts a fresh context after the same
    /// hour.
    ///
    /// A write failure is a `warn` and nothing else. The call has already
    /// happened; refusing the node afterwards would report a failure for work
    /// the remote agent really did, and the only consequence of a lost write
    /// is a fresh context next time.
    fn save_continuations(
        store: Option<&DynStateStore>,
        state_ctx: Option<&TenantCtx>,
        flow_id: &str,
        session_id: Option<&str>,
        continuations: &A2aContinuations,
    ) {
        let (Some(store), Some(ctx), Some(session)) = (store, state_ctx, session_id) else {
            return;
        };
        let value = match serde_json::to_value(continuations) {
            Ok(value) => value,
            Err(error) => {
                tracing::warn!(%error, "a2a node could not serialise its continuation state");
                return;
            }
        };
        let ttl = u32::try_from(CONTINUATION_IDLE_TTL_SECS).ok();
        if let Err(error) = store.set_json(
            ctx,
            CONTINUATION_PREFIX,
            &continuation_key(flow_id, session),
            None,
            &value,
            ttl,
        ) {
            tracing::warn!(
                %error,
                "a2a node could not persist its continuation state; the next call to this agent \
                 will start a fresh remote context"
            );
        }
    }

    /// Everything one `a2a` node dispatch needs that is not the message.
    ///
    /// A struct rather than eight parameters because half of them are
    /// `Option<&str>` and a transposed pair would compile into a node that
    /// talks to the right agent under the wrong tenant.
    pub struct A2aCall<'a> {
        /// The agents this flow's pack declares. `None` is the "not
        /// configured" refusal below.
        pub source: Option<&'a Arc<A2aToolSource>>,
        /// The flow's durable state store, for the continuation map.
        pub store: Option<&'a DynStateStore>,
        /// The scope that store is keyed by. `None` disables continuation.
        pub state_ctx: Option<&'a TenantCtx>,
        /// The flow this node belongs to. A segment of the continuation key,
        /// so two flows in one session never share a remote context.
        pub flow_id: &'a str,
        /// The session hint this run belongs to. `None` disables continuation.
        pub session_id: Option<&'a str>,
        /// The runtime tenant and env, for the credential scope and for the
        /// ownership check inside a stored continuation.
        pub tenant: &'a str,
        pub env: &'a str,
        /// The pack whose sidecar `source` was built from, named in the
        /// "not configured" refusal so an operator knows which pack to rebuild.
        pub pack_id: &'a str,
        /// Ask the agent for its Adaptive Card too (interop contract D10).
        pub want_card: bool,
        /// The card-submit answer to forward as a `data` part.
        pub answer: Option<Value>,
        /// The node the returned card's submit actions navigate back to.
        pub card_submit_to: Option<&'a str>,
    }

    /// Ask `agent_id` one question and return the value the node binds.
    ///
    /// Infallible by contract, like [`super::super::mcp_node::aw::invoke_with_secrets`]:
    /// an unconfigured pack, an unknown agent, a missing credential, an
    /// unreachable card and a transport failure all come back as a
    /// `status: "error"` value. The caller binds it as-is, so a flow routes on
    /// `status` whatever happened.
    ///
    /// `message` is handed to the catalogue untouched so
    /// `a2a_source`'s own `args_to_text` is the single converter from a node's
    /// JSON to the text an A2A agent receives — a string is sent verbatim,
    /// anything else as its JSON text, so no configured content is dropped.
    pub async fn invoke(call: A2aCall<'_>, agent_id: &str, message: &Value) -> Value {
        let Some(source) = call.source else {
            return call_error_value(
                agent_id,
                &format!(
                    "a2a is not available to this flow: pack '{}' declares no agents \
                     (no assets/a2a-routes.json, or GREENTIC_AW_A2A=0)",
                    call.pack_id
                ),
            );
        };

        let catalog = source.catalog().await;
        let tenant_ctx = TenantContext::new(call.tenant, call.env);
        let mut continuations =
            load_continuations(call.store, call.state_ctx, call.flow_id, call.session_id);
        let before = continuations.clone();

        let result = catalog
            .dispatch_in_conversation_with(
                agent_id,
                message,
                &tenant_ctx,
                &mut continuations,
                Utc::now(),
                A2aCallOptions {
                    want_card: call.want_card,
                    answer: call.answer.clone(),
                },
            )
            .await;
        let mut result = result;
        if let (Some(node_id), Some(card)) = (call.card_submit_to, result.get_mut("card")) {
            super::retarget_card_submits(card, node_id);
        }

        // Only on a change: an agent that neither opened nor closed anything
        // would otherwise make every turn of every flow a store write.
        if continuations != before {
            save_continuations(
                call.store,
                call.state_ctx,
                call.flow_id,
                call.session_id,
                &continuations,
            );
        }

        // Every failure travels as a value, and a node with no error route
        // still reports `ok: true` (see `a2a_node_output`), so without this an
        // operator sees a clean run whose agent was never asked. Mirrors the
        // MCP node's warn, and for the same reason.
        if let Some(error) = result.get("error") {
            // `status` is read out here rather than inside the macro: the
            // `tracing` macros bring their own `Value` trait into scope, so
            // `Value::as_str` there resolves to the wrong `Value`.
            let status = result
                .get("status")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("error");
            tracing::warn!(
                tenant = call.tenant,
                agent = agent_id,
                status,
                error = %error,
                "a2a node did not get an answer"
            );
        }
        result
    }

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

        #[test]
        fn the_continuation_namespace_is_not_the_one_flow_authors_write_to() {
            // A flow author owns every key under the `state.set` namespace. If
            // this node shared it, an ordinary `state.set` could overwrite a
            // remote task reference — or read one out.
            assert_ne!(CONTINUATION_PREFIX, crate::storage::state::STATE_PREFIX);
        }

        #[test]
        fn the_key_is_per_session_so_two_sessions_never_share_a_remote_context() {
            assert_ne!(
                continuation_key("support", "demo:web:c1:u1").as_str(),
                continuation_key("support", "demo:web:c2:u1").as_str()
            );
        }

        /// The coordinator's ruling: two flows in ONE session must not land in
        /// one remote thread. A correctness rule, not a confidentiality one —
        /// same tenant, same end user, same agent — but a billing flow whose
        /// question is answered conditioned on a support flow's turns is a
        /// wrong answer, and nothing the `input-required` loop needs survives
        /// across flows.
        #[test]
        fn the_key_is_per_flow_so_two_flows_in_one_session_never_share_a_remote_context() {
            assert_ne!(
                continuation_key("support", "demo:web:c1:u1").as_str(),
                continuation_key("billing", "demo:web:c1:u1").as_str()
            );
        }

        /// The key puts the flow first and the session last, so it is
        /// unambiguous only while a flow id cannot contain the `/` that ends
        /// its segment. `FlowId` forbids one; this is the ratchet on that
        /// assumption, so a relaxation upstream says so here rather than
        /// silently letting `("a/b", "c")` and `("a", "b/c")` collide.
        #[test]
        fn a_flow_id_can_never_contain_the_separator_that_ends_its_segment() {
            use std::str::FromStr;
            assert!(greentic_types::FlowId::from_str("a/b").is_err());
            assert!(greentic_types::FlowId::from_str("support.v2_1-a").is_ok());
        }

        /// With no store, no scope or no session there is nothing to read and
        /// nothing to write: the call is its own context and neither path may
        /// panic or error.
        #[test]
        fn without_a_session_there_is_no_continuation_and_nothing_is_stored() {
            let empty = load_continuations(None, None, "support", None);
            assert!(empty.is_empty());
            // A no-op rather than a panic; there is no store to observe.
            save_continuations(None, None, "support", None, &empty);
        }
    }
}

#[cfg(test)]
mod wants_card_tests {
    use super::wants_card;
    use serde_json::json;

    #[test]
    fn only_an_explicit_card_true_opts_in() {
        assert!(wants_card(&json!({"card": true})));
        assert!(wants_card(&json!({"card": "true"})));
        assert!(wants_card(&json!({"card": " TRUE "})));
        assert!(!wants_card(&json!({"card": false})));
        assert!(!wants_card(&json!({"card": "yes"})));
        assert!(!wants_card(&json!({"agent": "a"})));
        assert!(!wants_card(&json!(null)));
    }

    #[test]
    fn an_answer_drops_the_routers_navigation_keys_and_empty_values() {
        use super::answer_from_payload;
        let payload = json!({"answer": {
            "email": "a@b.co", "notes": "", "gone": null,
            "nextCardId": "ask_x", "routeToCardId": "y", "action": "submit",
            "a2aCardSubmit": true
        }});
        assert_eq!(
            answer_from_payload(&payload),
            Some(json!({"email": "a@b.co", "action": "submit"}))
        );
        assert_eq!(
            answer_from_payload(&json!({"answer": {"nextCardId": "x"}})),
            None
        );
        assert_eq!(answer_from_payload(&json!({"answer": "text"})), None);
        assert_eq!(answer_from_payload(&json!({})), None);
    }

    #[test]
    fn every_submit_action_in_a_remote_card_is_pointed_back_at_the_asking_node() {
        use super::retarget_card_submits;
        let mut card = json!({
            "type": "AdaptiveCard",
            "body": [{"type": "Input.Text", "id": "email"}],
            "actions": [
                {"type": "Action.Submit", "title": "Go",
                 "data": {"action": "go", "nextCardId": "remote_node", "toCardId": "z"}},
                {"type": "Action.Submit", "title": "Bare"},
                {"type": "Action.OpenUrl", "url": "https://x"}
            ]
        });
        assert!(retarget_card_submits(&mut card, "ask_signup"));
        assert_eq!(
            card["actions"][0]["data"],
            json!({"action": "go", "nextCardId": "ask_signup", "a2aCardSubmit": true})
        );
        assert_eq!(
            card["actions"][1]["data"],
            json!({"nextCardId": "ask_signup", "a2aCardSubmit": true})
        );
        assert!(card["actions"][2].get("data").is_none());
        let mut plain = json!({"type": "AdaptiveCard", "body": []});
        assert!(!retarget_card_submits(&mut plain, "n"));
    }
}