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
//! Wizard routes:
//!   GET  /api/wizard/credentials/{cloud}  — check cloud credentials
//!   POST /api/wizard/build                — start build/deploy job
//!   GET  /api/wizard/build/{id}           — poll job progress
//!   GET  /api/wizard/download             — download built file

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

// ── Default providers always injected into every wizard build ────────────────
const WEBCHAT_PROVIDER: &str =
    "oci://ghcr.io/greenticai/packs/messaging/messaging-webchat-gui:latest";
const STATE_MEMORY_PROVIDER: &str = "oci://ghcr.io/greenticai/packs/state/state-memory:latest";

// ── Request bodies ───────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct CardEntry {
    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 WizardBuildBody {
    pub mode: String,
    pub name: String,
    pub cards: Vec<CardEntry>,
    #[serde(default)]
    pub channels: Vec<String>,
    #[serde(default)]
    pub cloud: Option<String>,
    #[serde(default)]
    pub translate: bool,
    #[serde(default)]
    pub languages: Vec<String>,
}

// ── GET /api/wizard/credentials/{cloud} ─────────────────────────────────────

pub async fn get_credentials(Path(cloud): Path<String>) -> impl IntoResponse {
    match cloud.as_str() {
        "aws" | "gcp" | "azure" => {}
        _ => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({"error": "unsupported cloud; use aws, gcp, or azure"})),
            )
                .into_response();
        }
    }

    let reqs = match deployer::target_requirements(&cloud) {
        Ok(v) => v,
        Err(e) => {
            return (
                StatusCode::OK,
                Json(json!({
                    "ready": false,
                    "provider": cloud,
                    "label": cloud_label(&cloud),
                    "requirements": [],
                    "error": format!("greentic-deployer unavailable: {e}"),
                })),
            )
                .into_response();
        }
    };

    // Parse credential_requirements from deployer output.
    // Each requirement has satisfaction_env_groups — if ANY group is fully
    // satisfied (all env vars set), that credential method is ready.
    // We check all groups and report the first group's prompt_fields as
    // the vars to configure.
    let cred_reqs = reqs
        .get("credential_requirements")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();

    // Check if any satisfaction group across all credential requirements is met
    let any_satisfied = cred_reqs.iter().any(|cr| {
        cr.get("satisfaction_env_groups")
            .and_then(|g| g.as_array())
            .is_some_and(|groups| {
                groups.iter().any(|group| {
                    group.as_array().is_some_and(|vars| {
                        vars.iter()
                            .all(|v| v.as_str().is_some_and(|k| std::env::var(k).is_ok()))
                    })
                })
            })
    });

    // Build flat list of env vars from first credential requirement's prompt_fields
    let requirements: Vec<Value> = cred_reqs
        .first()
        .and_then(|cr| cr.get("prompt_fields"))
        .and_then(|pf| pf.as_array())
        .cloned()
        .unwrap_or_default()
        .iter()
        .filter(|f| {
            let kind = f.get("kind").and_then(|v| v.as_str()).unwrap_or("");
            kind == "required" || kind == "secret"
        })
        .map(|f| {
            let key = f.get("env_name").and_then(|v| v.as_str()).unwrap_or("");
            let label = f.get("prompt").and_then(|v| v.as_str()).unwrap_or(key);
            let found = !key.is_empty() && std::env::var(key).is_ok();
            json!({"key": key, "label": label, "found": found})
        })
        .collect();

    let ready = any_satisfied;

    let provider = reqs
        .get("target")
        .and_then(|v| v.as_str())
        .unwrap_or(&cloud);
    let label = reqs
        .get("target_label")
        .and_then(|v| v.as_str())
        .unwrap_or(cloud_label(&cloud));

    (
        StatusCode::OK,
        Json(json!({
            "ready": ready,
            "provider": provider,
            "label": label,
            "requirements": requirements,
        })),
    )
        .into_response()
}

// ── POST /api/wizard/build ───────────────────────────────────────────────────

pub async fn post_build(
    State(state): State<Arc<AppState>>,
    Json(body): Json<WizardBuildBody>,
) -> impl IntoResponse {
    if body.cards.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": "no cards provided"})),
        )
            .into_response();
    }

    let mode = match body.mode.as_str() {
        "deploy" => WizardMode::Deploy,
        "develop" => WizardMode::Develop,
        _ => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({"error": "mode must be 'deploy' or 'develop'"})),
            )
                .into_response();
        }
    };

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

    // Build provider list: always include defaults + user channels
    let mut providers = vec![
        WEBCHAT_PROVIDER.to_string(),
        STATE_MEMORY_PROVIDER.to_string(),
    ];
    for ch in &body.channels {
        if !providers.contains(ch) {
            providers.push(ch.clone());
        }
    }

    // Convert card entries to (id, Value) pairs
    let card_pairs: Vec<(String, Value)> = body
        .cards
        .into_iter()
        .map(|ce| {
            let value = if let Some(card) = ce.card {
                card
            } else if matches!(ce.entry_type.as_deref(), Some("http")) {
                json!({"type": "http", "config": ce.config.unwrap_or_else(|| json!({}))})
            } else {
                json!({})
            };
            (ce.id, value)
        })
        .collect();

    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();
        }
    };

    {
        let mut jobs = state.wizard_jobs.lock().await;
        jobs.insert(
            job_id.clone(),
            WizardJob {
                mode: mode.clone(),
                lines: vec![PackLogLine {
                    text: format!("Starting wizard build: {}", body.name),
                    kind: LogKind::Info,
                }],
                progress: 5,
                step: "Preparing workspace...".to_string(),
                status: WizardJobStatus::Building,
                download_url: None,
                filename: None,
                deploy_url: None,
                error: None,
            },
        );
    }

    // Build subprocess args for greentic-cards2pack
    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.translate && !body.languages.is_empty() {
        args.extend([
            "--auto-translate".to_string(),
            "--langs".to_string(),
            body.languages.join(","),
        ]);
    } else {
        args.push("--no-auto-i18n".to_string());
    }

    let state_clone = state.clone();
    let jid = job_id.clone();
    let pack_name = body.name.clone();
    let out_dir = prep.out_dir.clone();
    let cloud = body.cloud.clone();
    let http_entries = prep.http_entries.clone();

    tokio::spawn(async move {
        crate::ui::routes::wizard_pipeline::run_wizard_pipeline(
            &state_clone,
            &jid,
            &args,
            &out_dir,
            &pack_name,
            &providers,
            &mode,
            cloud.as_deref(),
            &http_entries,
        )
        .await;
        prep.persist();
    });

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

// ── GET /api/wizard/build/{id} ───────────────────────────────────────────────

pub async fn get_build_status(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    let jobs = state.wizard_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,
                    "download_url": job.download_url,
                    "deploy_url":   job.deploy_url,
                    "filename":     job.filename,
                    "error":        job.error,
                })),
            )
                .into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(json!({"error": "wizard job not found"})),
        )
            .into_response(),
    }
}

// ── GET /api/wizard/download ─────────────────────────────────────────────────

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

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" || e == "zip");
    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(|| "bundle.zip".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(),
    }
}

// ── Utilities ────────────────────────────────────────────────────────────────

fn cloud_label(cloud: &str) -> &str {
    match cloud {
        "aws" => "Amazon Web Services",
        "gcp" => "Google Cloud",
        "azure" => "Microsoft Azure",
        _ => cloud,
    }
}

pub 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}")
}

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

/// Search a directory for the first file matching an extension.
pub fn find_file_in_dir(dir: &std::path::Path, ext: &str) -> Option<PathBuf> {
    std::fs::read_dir(dir).ok()?.find_map(|e| {
        let p = e.ok()?.path();
        if p.extension().is_some_and(|x| x == ext) {
            Some(p)
        } else {
            None
        }
    })
}

/// Recursively zip a directory into a zip file at `dest_path`.
pub fn zip_directory(src_dir: &std::path::Path, dest_path: &std::path::Path) -> anyhow::Result<()> {
    use std::fs::File;
    use std::io::Write;
    use zip::ZipWriter;
    use zip::write::SimpleFileOptions;

    let file = File::create(dest_path)?;
    let mut zip = ZipWriter::new(file);
    let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);

    for entry in walkdir::WalkDir::new(src_dir)
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let path = entry.path();
        let relative = path.strip_prefix(src_dir)?;
        let name = relative.to_string_lossy();

        if path.is_file() {
            zip.start_file(name, options)?;
            let data = std::fs::read(path)?;
            zip.write_all(&data)?;
        } else if path.is_dir() && !name.is_empty() {
            zip.add_directory(name, options)?;
        }
    }

    zip.finish()?;
    Ok(())
}