greentic-flow-builder 0.4.0

Greentic Flow Builder — orchestrator that powers Adaptive Card design via the adaptive-card-mcp toolkit
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
//! Pack routes:
//!   POST /api/pack           — start a pack job (returns job ID)
//!   GET  /api/pack/{id}      — poll job progress
//!   GET  /api/pack/download  — download .gtpack file

use crate::orchestrate::cards2pack;
use crate::ui::state::{AppState, LogKind, PackJob, PackJobStatus, PackLogLine};
use axum::Json;
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::http::header;
use axum::response::IntoResponse;
use serde::Deserialize;
use serde_json::{Value, json};
use std::sync::Arc;

/// One flow entry sent from the UI. Card entries carry `card`; HTTP nodes
/// carry `type: "http"` + `config`. Keeping both shapes optional lets the
/// pack endpoint accept mixed card/http flows without a second schema.
#[derive(Deserialize)]
pub struct CardPair {
    pub id: String,
    #[serde(default)]
    pub card: Option<Value>,
    #[serde(default, rename = "type")]
    pub entry_type: Option<String>,
    #[serde(default)]
    pub config: Option<Value>,
}

#[derive(Deserialize)]
pub struct PackBody {
    pub name: String,
    pub cards: Vec<CardPair>,
    #[serde(default)]
    pub i18n: bool,
    #[serde(default)]
    pub langs: Option<Vec<String>>,
    #[serde(default)]
    pub strict: bool,
    #[serde(default)]
    pub verbose: bool,
    /// If true, also generate .gtbundle after .gtpack (runnable via gtc start).
    #[serde(default)]
    pub bundle: bool,
    /// Extension provider OCI references for the bundle.
    #[serde(default)]
    pub providers: Option<Vec<String>>,
}

/// Start a pack job. Writes cards to temp dir, spawns greentic-cards2pack
/// subprocess, captures stderr in background, returns job ID immediately.
pub async fn post_pack(
    State(state): State<Arc<AppState>>,
    Json(body): Json<PackBody>,
) -> impl IntoResponse {
    if body.cards.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": "no cards provided"})),
        )
            .into_response();
    }

    let job_id = format!("pack-{}", uuid_short());

    // Convert card pairs to the format prepare_cards expects. HTTP nodes are
    // surfaced as `{type: "http", config: ...}` so `extract_http_entries` can
    // separate them from regular Adaptive Card entries.
    let card_count = body.cards.len();
    let card_pairs: Vec<(String, Value)> = body
        .cards
        .into_iter()
        .map(|cp| {
            let value = if let Some(card) = cp.card {
                card
            } else if matches!(cp.entry_type.as_deref(), Some("http")) {
                json!({
                    "type": "http",
                    "config": cp.config.unwrap_or_else(|| json!({})),
                })
            } else {
                json!({})
            };
            (cp.id, value)
        })
        .collect();

    // Prepare cards on disk
    let prep = match cards2pack::prepare_cards(&body.name, &card_pairs) {
        Ok(p) => p,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": e.to_string()})),
            )
                .into_response();
        }
    };

    // Initialize job
    {
        let mut jobs = state.pack_jobs.lock().await;
        jobs.insert(
            job_id.clone(),
            PackJob {
                lines: vec![PackLogLine {
                    text: format!("Starting pack: {} ({} cards)", body.name, card_count),
                    kind: LogKind::Info,
                }],
                progress: 5,
                step: "Preparing workspace...".to_string(),
                status: PackJobStatus::Running,
                pack_path: None,
                workspace_path: None,
                download_url: None,
                filename: None,
                error: None,
            },
        );
    }

    // Build subprocess args
    let mut args = vec![
        "generate".to_string(),
        "--cards".to_string(),
        prep.cards_dir.display().to_string(),
        "--out".to_string(),
        prep.out_dir.display().to_string(),
        "--name".to_string(),
        body.name.clone(),
        "--default-flow".to_string(),
        prep.flow_name.clone(),
    ];
    if body.i18n {
        if let Some(langs) = body.langs.as_ref().filter(|l| !l.is_empty()) {
            args.extend([
                "--auto-translate".to_string(),
                "--langs".to_string(),
                langs.join(","),
            ]);
        }
    } else {
        args.push("--no-auto-i18n".to_string());
    }
    if body.strict {
        args.push("--strict".to_string());
    }
    if body.verbose {
        args.push("--verbose".to_string());
    }

    // Spawn subprocess in background. Move `prep` into the task so the
    // TempDir stays alive until the subprocess finishes reading from it.
    let state_clone = state.clone();
    let jid = job_id.clone();
    let pack_name = body.name.clone();
    let out_dir = prep.out_dir.clone();
    let post_opts = PostProcessOpts {
        build_bundle: body.bundle,
        providers: body.providers.clone(),
        http_entries: prep.http_entries.clone(),
    };

    tokio::spawn(async move {
        run_pack_subprocess(&state_clone, &jid, &args, &out_dir, &pack_name, &post_opts).await;
        prep.persist();
    });

    (StatusCode::OK, Json(json!({ "job_id": job_id }))).into_response()
}

/// Poll job progress.
pub async fn get_job(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    let jobs = state.pack_jobs.lock().await;
    match jobs.get(&id) {
        Some(job) => {
            let lines: Vec<Value> = job
                .lines
                .iter()
                .map(|l| json!({"text": l.text, "kind": l.kind.as_str()}))
                .collect();
            (
                StatusCode::OK,
                Json(json!({
                    "status": job.status.as_str(),
                    "progress": job.progress,
                    "step": job.step,
                    "lines": lines,
                    "pack_path": job.pack_path,
                    "workspace_path": job.workspace_path,
                    "download_url": job.download_url,
                    "filename": job.filename,
                    "error": job.error,
                })),
            )
                .into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(json!({"error": "job not found"})),
        )
            .into_response(),
    }
}

#[derive(Deserialize)]
pub struct DownloadQuery {
    pub path: String,
}

/// Serve a .gtpack file for download. Only allows files under /tmp/.
pub async fn get_download(Query(q): Query<DownloadQuery>) -> impl IntoResponse {
    let path = std::path::Path::new(&q.path);
    let valid_ext = path
        .extension()
        .is_some_and(|e| e == "gtpack" || e == "gtbundle");
    if !q.path.starts_with("/tmp/") || !valid_ext {
        return (StatusCode::FORBIDDEN, "Access denied").into_response();
    }
    match tokio::fs::read(path).await {
        Ok(bytes) => {
            let filename = path
                .file_name()
                .map(|f| f.to_string_lossy().to_string())
                .unwrap_or_else(|| "flow.gtpack".to_string());
            (
                StatusCode::OK,
                [
                    (header::CONTENT_TYPE, "application/octet-stream".to_string()),
                    (
                        header::CONTENT_DISPOSITION,
                        format!("attachment; filename=\"{filename}\""),
                    ),
                ],
                bytes,
            )
                .into_response()
        }
        Err(_) => (StatusCode::NOT_FOUND, "File not found").into_response(),
    }
}

// ── Subprocess runner ────────────────────────────────────────────
struct PostProcessOpts {
    build_bundle: bool,
    providers: Option<Vec<String>>,
    http_entries: Vec<crate::orchestrate::http_inject::HttpNodeEntry>,
}

async fn run_pack_subprocess(
    state: &Arc<AppState>,
    job_id: &str,
    args: &[String],
    out_dir: &std::path::Path,
    pack_name: &str,
    opts: &PostProcessOpts,
) {
    use tokio::io::{AsyncBufReadExt, BufReader};
    use tokio::process::Command;

    let mut cmd = Command::new("greentic-cards2pack");
    cmd.args(args)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped());

    let mut child = match cmd.spawn() {
        Ok(c) => c,
        Err(e) => {
            let mut jobs = state.pack_jobs.lock().await;
            if let Some(job) = jobs.get_mut(job_id) {
                job.status = PackJobStatus::Failed;
                job.error = Some(format!("Failed to spawn greentic-cards2pack: {e}"));
                job.progress = 0;
            }
            return;
        }
    };

    // Capture stderr line-by-line. Some tools use \r for in-place progress
    // (e.g. "[flow] Progress: 3/8\r[flow] Progress: 4/8"), so we split by
    // both \n (from BufReader) and \r within each line.
    let stderr = child.stderr.take();
    if let Some(stderr) = stderr {
        let mut reader = BufReader::new(stderr).lines();
        while let Ok(Some(raw_line)) = reader.next_line().await {
            // Split by \r to handle carriage-return-separated progress ticks
            let sub_lines: Vec<&str> = raw_line
                .split('\r')
                .map(|s| s.trim())
                .filter(|s| !s.is_empty())
                .collect();

            let mut jobs = state.pack_jobs.lock().await;
            if let Some(job) = jobs.get_mut(job_id) {
                for sub in &sub_lines {
                    let line = sub.to_string();

                    // Skip duplicate progress lines — only keep the latest
                    let is_progress = line.contains("Progress:");
                    if is_progress {
                        // Remove previous progress line if any
                        if let Some(pos) = job.lines.iter().rposition(|l| {
                            l.text.contains("Progress:")
                                && l.text.split("Progress:").next()
                                    == line.split("Progress:").next()
                        }) {
                            job.lines.remove(pos);
                        }
                    }

                    let (kind, progress) = classify_line(&line);
                    job.lines.push(PackLogLine {
                        text: line.clone(),
                        kind,
                    });
                    if let Some(p) = progress {
                        job.progress = p;
                    }
                    job.step = summarize_line(&line);
                }
            }
        }
    }

    // Wait for exit
    let exit = child.wait().await;
    let success = exit.is_ok_and(|s| s.success());

    let mut jobs = state.pack_jobs.lock().await;
    if let Some(job) = jobs.get_mut(job_id) {
        if success {
            // Find .gtpack in dist/
            let dist = out_dir.join("dist");
            let pack_path = std::fs::read_dir(&dist).ok().and_then(|mut rd| {
                rd.find_map(|e| {
                    let p = e.ok()?.path();
                    if p.extension()? == "gtpack" {
                        Some(p)
                    } else {
                        None
                    }
                })
            });

            if let Some(pp) = pack_path {
                let pack_filename = pp
                    .file_name()
                    .map(|f| f.to_string_lossy().to_string())
                    .unwrap_or_else(|| format!("{pack_name}.gtpack"));

                // Post-process: inject HTTP nodes into .ygtc if any
                if !opts.http_entries.is_empty() {
                    let flow_path = out_dir.join("flows").join("main.ygtc");
                    if let Ok(ygtc_content) = std::fs::read_to_string(&flow_path) {
                        let injected = crate::orchestrate::http_inject::inject_http_nodes(
                            &ygtc_content,
                            &opts.http_entries,
                        );
                        let _ = std::fs::write(&flow_path, injected);

                        let pack_yaml = out_dir.join("pack.yaml");
                        let _ = crate::orchestrate::http_inject::ensure_component_http_source(
                            &pack_yaml,
                        );
                    }

                    job.lines.push(PackLogLine {
                        text: format!(
                            "Injected {} HTTP API node(s) into flow",
                            opts.http_entries.len()
                        ),
                        kind: LogKind::Done,
                    });
                }

                // Optionally build .gtbundle
                if opts.build_bundle {
                    job.lines.push(PackLogLine {
                        text: "Building .gtbundle...".to_string(),
                        kind: LogKind::Progress,
                    });
                    job.step = "Building .gtbundle...".to_string();
                    job.progress = 90;
                    // Drop lock before blocking call
                    drop(jobs);

                    match crate::orchestrate::deployer::build_bundle(
                        &pp,
                        pack_name,
                        opts.providers.as_deref(),
                    ) {
                        Ok(br) => {
                            let fname = br
                                .bundle_path
                                .file_name()
                                .map(|f| f.to_string_lossy().to_string())
                                .unwrap_or_else(|| format!("{pack_name}.gtbundle"));
                            let dl = download_url(&br.bundle_path);
                            let mut jobs = state.pack_jobs.lock().await;
                            if let Some(job) = jobs.get_mut(job_id) {
                                job.pack_path = Some(br.bundle_path.display().to_string());
                                job.workspace_path = Some(br.workspace_path.display().to_string());
                                job.download_url = Some(dl);
                                job.filename = Some(fname);
                                job.status = PackJobStatus::Done;
                                job.progress = 100;
                                job.step = "Complete!".to_string();
                                job.lines.push(PackLogLine {
                                    text: format!("Bundle ready: {}", br.bundle_path.display()),
                                    kind: LogKind::Done,
                                });
                            }
                        }
                        Err(e) => {
                            let mut jobs = state.pack_jobs.lock().await;
                            if let Some(job) = jobs.get_mut(job_id) {
                                // Pack succeeded but bundle failed — provide pack download
                                job.pack_path = Some(pp.display().to_string());
                                job.workspace_path = Some(out_dir.display().to_string());
                                job.download_url = Some(download_url(&pp));
                                job.filename = Some(pack_filename.clone());
                                job.status = PackJobStatus::Done;
                                job.progress = 100;
                                job.step = "Pack done (bundle failed)".to_string();
                                job.lines.push(PackLogLine {
                                    text: format!("Bundle build failed: {e}"),
                                    kind: LogKind::Warning,
                                });
                            }
                        }
                    }
                    return;
                }

                // No bundle — just return pack
                job.pack_path = Some(pp.display().to_string());
                job.workspace_path = Some(out_dir.display().to_string());
                job.download_url = Some(download_url(&pp));
                job.filename = Some(pack_filename);
                job.status = PackJobStatus::Done;
                job.progress = 100;
                job.step = "Complete!".to_string();
            } else {
                job.status = PackJobStatus::Failed;
                job.error = Some("No .gtpack file found in dist/".to_string());
            }
        } else {
            job.status = PackJobStatus::Failed;
            job.error = Some("greentic-cards2pack failed".to_string());
        }
    }
}

/// Classify a log line for UI rendering.
fn classify_line(line: &str) -> (LogKind, Option<u8>) {
    if line.contains("Progress:") {
        // Parse "Progress: 4/7" → estimate percentage
        let pct = line.split("Progress:").nth(1).and_then(|s| {
            let parts: Vec<&str> = s.trim().split('/').collect();
            if parts.len() == 2 {
                let cur: f32 = parts[0].trim().parse().ok()?;
                let total: f32 = parts[1].trim().parse().ok()?;
                Some((20.0 + (cur / total) * 50.0) as u8) // Map to 20-70%
            } else {
                None
            }
        });
        (LogKind::Progress, pct)
    } else if line.contains("error") || line.contains("Error") || line.starts_with("ERR") {
        (LogKind::Error, None)
    } else if line.contains("warning") || line.contains("Warning") {
        (LogKind::Warning, None)
    } else if line.contains("wrote") || line.contains("Pack:") || line.contains("OK ") {
        (LogKind::Done, Some(85))
    } else if line.contains("[flow]") {
        (LogKind::Progress, Some(30))
    } else if line.contains("pack.yaml") {
        (LogKind::Progress, Some(50))
    } else if line.contains("Running:") {
        (LogKind::Progress, Some(75))
    } else {
        (LogKind::Info, None)
    }
}

/// Summarize a log line into a short step label.
fn summarize_line(line: &str) -> String {
    if line.contains("created pack at") {
        "Creating workspace...".to_string()
    } else if line.contains("[flow]") {
        line.trim().to_string()
    } else if line.contains("pack.yaml updated") {
        "Updating pack manifest...".to_string()
    } else if line.starts_with("OK ") || line.contains("valid") {
        "Validating flows...".to_string()
    } else if line.contains("wrote") && line.contains(".gtpack") {
        "Writing .gtpack archive...".to_string()
    } else if line.contains("Running:") {
        "Running greentic-pack build...".to_string()
    } else if line.contains("Pack:") && !line.contains("pack.yaml") {
        "Pack summary...".to_string()
    } else {
        line.chars().take(60).collect()
    }
}

fn download_url(path: &std::path::Path) -> String {
    format!(
        "/api/pack/download?path={}",
        urlencoding::encode(&path.display().to_string())
    )
}

fn uuid_short() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let t = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis();
    format!("{t:x}")
}