tandem-server 0.6.0

HTTP server for Tandem engine APIs
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
use super::*;

fn assert_no_channel_draft_confirmation_text(payload: &Value) {
    let rendered = serde_json::to_string(payload).expect("payload json");
    assert!(!rendered.contains("Reply `confirm` to create it"));
    assert!(!rendered.contains("Reply confirm to create it"));
    assert!(!rendered.contains("report to `same_chat`"));
    assert!(!rendered.contains("report to same_chat"));
    assert!(!rendered.contains("event-driven"));
}

#[tokio::test]
async fn channel_automation_draft_collects_previews_and_confirms() {
    let state = test_state().await;
    let app = app_router(state.clone());

    let start_req = Request::builder()
        .method("POST")
        .uri("/automations/channel-drafts")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "text": "Create an automation",
                "session_id": "session-channel-1",
                "thread_key": "discord:room-1",
                "channel_context": {
                    "source_platform": "discord",
                    "scope_kind": "room",
                    "scope_id": "room-1",
                    "reply_target": "room-1",
                    "sender": "alice"
                },
                "allowed_tools": ["websearch", "memory_store"],
                "allowed_mcp_servers": ["github"]
            })
            .to_string(),
        ))
        .expect("request");
    let start_resp = app.clone().oneshot(start_req).await.expect("response");
    assert_eq!(start_resp.status(), StatusCode::OK);
    let body = to_bytes(start_resp.into_body(), usize::MAX)
        .await
        .expect("body");
    let start_payload: Value = serde_json::from_slice(&body).expect("json");
    assert_eq!(
        start_payload
            .get("draft")
            .and_then(|draft| draft.get("status"))
            .and_then(Value::as_str),
        Some("collecting")
    );
    assert_eq!(
        start_payload
            .get("draft")
            .and_then(|draft| draft.get("question"))
            .and_then(|question| question.get("field"))
            .and_then(Value::as_str),
        Some("goal")
    );
    let draft_id = start_payload
        .get("draft")
        .and_then(|draft| draft.get("draft_id"))
        .and_then(Value::as_str)
        .expect("draft id")
        .to_string();

    let goal_req = Request::builder()
        .method("POST")
        .uri(format!("/automations/channel-drafts/{draft_id}/answer"))
        .header("content-type", "application/json")
        .body(Body::from(
            json!({ "answer": "Post a support summary here" }).to_string(),
        ))
        .expect("request");
    let goal_resp = app.clone().oneshot(goal_req).await.expect("response");
    assert_eq!(goal_resp.status(), StatusCode::OK);
    let body = to_bytes(goal_resp.into_body(), usize::MAX)
        .await
        .expect("body");
    let goal_payload: Value = serde_json::from_slice(&body).expect("json");
    assert_eq!(
        goal_payload
            .get("draft")
            .and_then(|draft| draft.get("question"))
            .and_then(|question| question.get("field"))
            .and_then(Value::as_str),
        Some("schedule_hint")
    );

    let schedule_req = Request::builder()
        .method("POST")
        .uri(format!("/automations/channel-drafts/{draft_id}/answer"))
        .header("content-type", "application/json")
        .body(Body::from(json!({ "answer": "daily at 9am" }).to_string()))
        .expect("request");
    let schedule_resp = app.clone().oneshot(schedule_req).await.expect("response");
    assert_eq!(schedule_resp.status(), StatusCode::OK);
    let body = to_bytes(schedule_resp.into_body(), usize::MAX)
        .await
        .expect("body");
    let preview_payload: Value = serde_json::from_slice(&body).expect("json");
    assert_eq!(
        preview_payload
            .get("draft")
            .and_then(|draft| draft.get("status"))
            .and_then(Value::as_str),
        Some("preview_ready")
    );
    assert!(preview_payload
        .get("message")
        .and_then(Value::as_str)
        .is_some_and(|message| message.contains("Reply `confirm`")));

    let pending_req = Request::builder()
        .method("GET")
        .uri("/automations/channel-drafts/pending?channel=discord&scope_id=room-1&sender=alice")
        .body(Body::empty())
        .expect("request");
    let pending_resp = app.clone().oneshot(pending_req).await.expect("response");
    assert_eq!(pending_resp.status(), StatusCode::OK);
    let body = to_bytes(pending_resp.into_body(), usize::MAX)
        .await
        .expect("body");
    let pending_payload: Value = serde_json::from_slice(&body).expect("json");
    assert_eq!(
        pending_payload.get("count").and_then(Value::as_u64),
        Some(1)
    );

    let confirm_req = Request::builder()
        .method("POST")
        .uri(format!("/automations/channel-drafts/{draft_id}/confirm"))
        .body(Body::empty())
        .expect("request");
    let confirm_resp = app.clone().oneshot(confirm_req).await.expect("response");
    assert_eq!(confirm_resp.status(), StatusCode::OK);
    let body = to_bytes(confirm_resp.into_body(), usize::MAX)
        .await
        .expect("body");
    let confirm_payload: Value = serde_json::from_slice(&body).expect("json");
    assert_eq!(
        confirm_payload
            .get("draft")
            .and_then(|draft| draft.get("status"))
            .and_then(Value::as_str),
        Some("applied")
    );
    let automation = confirm_payload.get("automation").expect("automation");
    assert_eq!(
        automation.get("status").and_then(Value::as_str),
        Some("active")
    );
    assert_eq!(
        automation
            .get("schedule")
            .and_then(|schedule| schedule.get("type"))
            .and_then(Value::as_str),
        Some("cron")
    );
    assert_eq!(
        automation
            .get("schedule")
            .and_then(|schedule| schedule.get("cron_expression"))
            .and_then(Value::as_str),
        Some("0 0 9 * * * *")
    );
    assert_eq!(
        automation
            .get("metadata")
            .and_then(|metadata| metadata.get("created_from"))
            .and_then(Value::as_str),
        Some("channel_automation_draft")
    );
    assert_eq!(
        automation
            .get("metadata")
            .and_then(|metadata| metadata.get("channel_context"))
            .and_then(|context| context.get("source_platform"))
            .and_then(Value::as_str),
        Some("discord")
    );
    assert_eq!(
        automation
            .get("agents")
            .and_then(Value::as_array)
            .and_then(|agents| agents.first())
            .and_then(|agent| agent.get("mcp_policy"))
            .and_then(|policy| policy.get("allowed_servers"))
            .and_then(Value::as_array)
            .map(|servers| servers.contains(&Value::String("github".to_string()))),
        Some(true)
    );
}

#[tokio::test]
async fn channel_automation_draft_start_fails_closed_when_workflow_drafts_disabled() {
    let state = test_state().await;
    let app = app_router(state);

    let start_req = Request::builder()
        .method("POST")
        .uri("/automations/channel-drafts")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "text": "What time does sponsor booth setup start, and when must it be finished?",
                "session_id": "session-channel-disabled",
                "thread_key": "telegram:topic-disabled",
                "workflow_planner_enabled": false,
                "strict_kb_grounding": false,
                "factual_question": true,
                "explicit_workflow_intent": false,
                "channel_context": {
                    "source_platform": "telegram",
                    "scope_kind": "topic",
                    "scope_id": "topic-disabled",
                    "reply_target": "topic-disabled",
                    "sender": "alice"
                }
            })
            .to_string(),
        ))
        .expect("request");
    let start_resp = app.clone().oneshot(start_req).await.expect("response");
    assert_eq!(start_resp.status(), StatusCode::OK);
    let body = to_bytes(start_resp.into_body(), usize::MAX)
        .await
        .expect("body");
    let payload: Value = serde_json::from_slice(&body).expect("json");
    assert_no_channel_draft_confirmation_text(&payload);
    assert_eq!(payload.get("blocked").and_then(Value::as_bool), Some(true));
    assert_eq!(
        payload.get("block_reason").and_then(Value::as_str),
        Some("workflow_drafting_disabled")
    );
    assert_eq!(
        payload
            .get("draft")
            .and_then(|draft| draft.get("status"))
            .and_then(Value::as_str),
        Some("cancelled")
    );
}

#[tokio::test]
async fn channel_automation_draft_answer_fails_closed_for_strict_kb_factual_question() {
    let state = test_state().await;
    let app = app_router(state);

    let start_req = Request::builder()
        .method("POST")
        .uri("/automations/channel-drafts")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "text": "Create a workflow that sends a sponsor setup reminder every event morning.",
                "session_id": "session-channel-strict",
                "thread_key": "telegram:topic-strict",
                "workflow_planner_enabled": true,
                "strict_kb_grounding": true,
                "factual_question": false,
                "explicit_workflow_intent": true,
                "channel_context": {
                    "source_platform": "telegram",
                    "scope_kind": "topic",
                    "scope_id": "topic-strict",
                    "reply_target": "topic-strict",
                    "sender": "alice"
                }
            })
            .to_string(),
        ))
        .expect("request");
    let start_resp = app.clone().oneshot(start_req).await.expect("response");
    assert_eq!(start_resp.status(), StatusCode::OK);
    let body = to_bytes(start_resp.into_body(), usize::MAX)
        .await
        .expect("body");
    let start_payload: Value = serde_json::from_slice(&body).expect("json");
    let draft_id = start_payload
        .get("draft")
        .and_then(|draft| draft.get("draft_id"))
        .and_then(Value::as_str)
        .expect("draft id")
        .to_string();

    let answer_req = Request::builder()
        .method("POST")
        .uri(format!("/automations/channel-drafts/{draft_id}/answer"))
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "answer": "What time does sponsor booth setup start, and when must it be finished?",
                "workflow_planner_enabled": true,
                "strict_kb_grounding": true,
                "factual_question": true,
                "explicit_workflow_intent": false
            })
            .to_string(),
        ))
        .expect("request");
    let answer_resp = app.clone().oneshot(answer_req).await.expect("response");
    assert_eq!(answer_resp.status(), StatusCode::OK);
    let body = to_bytes(answer_resp.into_body(), usize::MAX)
        .await
        .expect("body");
    let answer_payload: Value = serde_json::from_slice(&body).expect("json");
    assert_no_channel_draft_confirmation_text(&answer_payload);
    assert_eq!(
        answer_payload.get("block_reason").and_then(Value::as_str),
        Some("strict_kb_factual_question")
    );
    assert_eq!(
        answer_payload
            .get("draft")
            .and_then(|draft| draft.get("status"))
            .and_then(Value::as_str),
        Some("cancelled")
    );

    let pending_req = Request::builder()
        .method("GET")
        .uri("/automations/channel-drafts/pending?channel=telegram&scope_id=topic-strict&sender=alice")
        .body(Body::empty())
        .expect("request");
    let pending_resp = app.clone().oneshot(pending_req).await.expect("response");
    assert_eq!(pending_resp.status(), StatusCode::OK);
    let body = to_bytes(pending_resp.into_body(), usize::MAX)
        .await
        .expect("body");
    let pending_payload: Value = serde_json::from_slice(&body).expect("json");
    assert_eq!(
        pending_payload.get("count").and_then(Value::as_u64),
        Some(0)
    );
}

#[tokio::test]
async fn channel_automation_draft_can_cancel_preview() {
    let state = test_state().await;
    let app = app_router(state);

    let start_req = Request::builder()
        .method("POST")
        .uri("/automations/channel-drafts")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "text": "Create an automation that posts a daily summary here every day",
                "channel_context": {
                    "source_platform": "telegram",
                    "scope_kind": "topic",
                    "scope_id": "topic-1",
                    "reply_target": "topic-1",
                    "sender": "bob"
                }
            })
            .to_string(),
        ))
        .expect("request");
    let start_resp = app.clone().oneshot(start_req).await.expect("response");
    assert_eq!(start_resp.status(), StatusCode::OK);
    let body = to_bytes(start_resp.into_body(), usize::MAX)
        .await
        .expect("body");
    let start_payload: Value = serde_json::from_slice(&body).expect("json");
    assert_eq!(
        start_payload
            .get("draft")
            .and_then(|draft| draft.get("status"))
            .and_then(Value::as_str),
        Some("preview_ready")
    );
    let draft_id = start_payload
        .get("draft")
        .and_then(|draft| draft.get("draft_id"))
        .and_then(Value::as_str)
        .expect("draft id");

    let cancel_req = Request::builder()
        .method("POST")
        .uri(format!("/automations/channel-drafts/{draft_id}/cancel"))
        .body(Body::empty())
        .expect("request");
    let cancel_resp = app.clone().oneshot(cancel_req).await.expect("response");
    assert_eq!(cancel_resp.status(), StatusCode::OK);
    let body = to_bytes(cancel_resp.into_body(), usize::MAX)
        .await
        .expect("body");
    let cancel_payload: Value = serde_json::from_slice(&body).expect("json");
    assert_eq!(
        cancel_payload
            .get("draft")
            .and_then(|draft| draft.get("status"))
            .and_then(Value::as_str),
        Some("cancelled")
    );

    let confirm_req = Request::builder()
        .method("POST")
        .uri(format!("/automations/channel-drafts/{draft_id}/confirm"))
        .body(Body::empty())
        .expect("request");
    let confirm_resp = app.clone().oneshot(confirm_req).await.expect("response");
    assert_eq!(confirm_resp.status(), StatusCode::CONFLICT);
}

/// GOV-B2c: confirming a channel automation draft from an agent context is
/// rejected by creation governance, and the draft is not applied. In the
/// non-premium build all agent creation is refused; the premium engine instead
/// applies per-agent quota/capability rules, so this hard-rejection assertion is
/// scoped to the non-premium build.
#[cfg(not(feature = "premium-governance"))]
#[tokio::test]
async fn channel_automation_draft_confirm_rejects_agent_context() {
    let state = test_state().await;
    let app = app_router(state.clone());

    let start_req = Request::builder()
        .method("POST")
        .uri("/automations/channel-drafts")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "text": "Create an automation",
                "session_id": "session-b2c",
                "thread_key": "discord:room-b2c",
                "channel_context": {
                    "source_platform": "discord",
                    "scope_kind": "room",
                    "scope_id": "room-b2c",
                    "reply_target": "room-b2c",
                    "sender": "alice"
                },
                "allowed_tools": ["websearch"],
                "allowed_mcp_servers": []
            })
            .to_string(),
        ))
        .expect("request");
    let start_resp = app.clone().oneshot(start_req).await.expect("response");
    assert_eq!(start_resp.status(), StatusCode::OK);
    let start_payload: Value = serde_json::from_slice(
        &to_bytes(start_resp.into_body(), usize::MAX)
            .await
            .expect("body"),
    )
    .expect("json");
    let draft_id = start_payload
        .get("draft")
        .and_then(|draft| draft.get("draft_id"))
        .and_then(Value::as_str)
        .expect("draft id")
        .to_string();

    for answer in ["Post a support summary here", "daily at 9am"] {
        let req = Request::builder()
            .method("POST")
            .uri(format!("/automations/channel-drafts/{draft_id}/answer"))
            .header("content-type", "application/json")
            .body(Body::from(json!({ "answer": answer }).to_string()))
            .expect("request");
        let resp = app.clone().oneshot(req).await.expect("response");
        assert_eq!(resp.status(), StatusCode::OK);
    }

    // Confirm from an agent context: creation governance must reject it.
    let confirm_req = Request::builder()
        .method("POST")
        .uri(format!("/automations/channel-drafts/{draft_id}/confirm"))
        .header("x-tandem-request-source", "agent")
        .header("x-tandem-agent-id", "agent-b2c")
        .body(Body::empty())
        .expect("request");
    let confirm_resp = app.clone().oneshot(confirm_req).await.expect("response");
    // The confirm is routed through creation governance and rejected. In the
    // non-premium build, agent-authored creation is a premium feature, so the
    // engine returns NOT_IMPLEMENTED rather than applying the draft.
    assert_eq!(confirm_resp.status(), StatusCode::NOT_IMPLEMENTED);
    assert!(!confirm_resp.status().is_success());

    // The draft must remain unapplied and no automation should have been created.
    let pending_req = Request::builder()
        .method("GET")
        .uri("/automations/channel-drafts/pending?channel=discord&scope_id=room-b2c&sender=alice")
        .body(Body::empty())
        .expect("request");
    let pending_resp = app.clone().oneshot(pending_req).await.expect("response");
    assert_eq!(pending_resp.status(), StatusCode::OK);
    let pending_payload: Value = serde_json::from_slice(
        &to_bytes(pending_resp.into_body(), usize::MAX)
            .await
            .expect("body"),
    )
    .expect("json");
    assert_eq!(
        pending_payload.get("count").and_then(Value::as_u64),
        Some(1)
    );
}