life-cli 0.3.1

Production agent deployment pipeline for Life Agent OS
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
//! Railway deployment backend — provisions Life agent stacks via Railway GraphQL API.
//!
//! Port of the TypeScript client at broomva.tech/apps/chat/lib/railway.ts
//! to native Rust for the `life deploy` CLI.

use std::collections::HashMap;

use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};
use tracing::{debug, info, warn};

use super::backend::{DeployBackend, DeployedService, DeploymentResult};
use crate::template::AgentTemplate;

const RAILWAY_API_URL: &str = "https://backboard.railway.app/graphql/v2";

pub struct RailwayBackend {
    token: String,
    client: reqwest::Client,
}

impl RailwayBackend {
    pub fn new(token: String) -> Self {
        Self {
            token,
            client: reqwest::Client::new(),
        }
    }

    /// Execute a GraphQL query/mutation against the Railway API.
    async fn graphql<T: for<'de> Deserialize<'de>>(
        &self,
        query: &str,
        variables: Value,
    ) -> Result<T> {
        let body = json!({
            "query": query,
            "variables": variables,
        });

        let resp = self
            .client
            .post(RAILWAY_API_URL)
            .header("Content-Type", "application/json")
            .header("Authorization", format!("Bearer {}", self.token))
            .json(&body)
            .send()
            .await
            .context("failed to reach Railway API")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let text = resp.text().await.unwrap_or_default();
            anyhow::bail!("Railway API returned HTTP {status}: {text}");
        }

        let json: Value = resp
            .json()
            .await
            .context("failed to parse Railway response")?;

        if let Some(errors) = json.get("errors") {
            if let Some(arr) = errors.as_array() {
                if !arr.is_empty() {
                    let messages: Vec<&str> = arr
                        .iter()
                        .filter_map(|e| e.get("message").and_then(Value::as_str))
                        .collect();
                    anyhow::bail!("Railway GraphQL error: {}", messages.join("; "));
                }
            }
        }

        let data = json
            .get("data")
            .context("Railway response missing 'data' field")?
            .clone();

        serde_json::from_value(data).context("failed to deserialize Railway response data")
    }
}

#[async_trait]
impl DeployBackend for RailwayBackend {
    async fn deploy(
        &self,
        project_name: &str,
        template: &AgentTemplate,
        extra_env: &HashMap<String, String>,
    ) -> Result<DeploymentResult> {
        // ── 1. Create Railway project ────────────────────────────────────────
        info!(project = project_name, "creating Railway project");

        #[derive(Deserialize)]
        struct ProjectCreate {
            #[serde(rename = "projectCreate")]
            project_create: IdNode,
        }
        #[derive(Deserialize)]
        struct IdNode {
            id: String,
        }

        let project: ProjectCreate = self
            .graphql(
                r#"mutation ($input: ProjectCreateInput!) {
                    projectCreate(input: $input) { id }
                }"#,
                json!({ "input": { "name": project_name } }),
            )
            .await
            .context("failed to create Railway project")?;

        let project_id = project.project_create.id;
        info!(project_id = %project_id, "project created");

        // ── 2. Get default environment ───────────────────────────────────────
        #[derive(Deserialize)]
        struct ProjectEnvs {
            project: ProjectEnvsInner,
        }
        #[derive(Deserialize)]
        struct ProjectEnvsInner {
            environments: Edges<EnvNode>,
        }
        #[derive(Deserialize)]
        struct Edges<T> {
            edges: Vec<Edge<T>>,
        }
        #[derive(Deserialize)]
        struct Edge<T> {
            node: T,
        }
        #[derive(Deserialize)]
        struct EnvNode {
            id: String,
            name: String,
        }

        let envs: ProjectEnvs = self
            .graphql(
                r#"query ($projectId: String!) {
                    project(id: $projectId) {
                        environments { edges { node { id name } } }
                    }
                }"#,
                json!({ "projectId": &project_id }),
            )
            .await
            .context("failed to fetch Railway environments")?;

        let env_id = envs
            .project
            .environments
            .edges
            .iter()
            .find(|e| e.node.name == "production")
            .or_else(|| envs.project.environments.edges.first())
            .map(|e| e.node.id.clone())
            .context("no environments found in Railway project")?;

        debug!(environment_id = %env_id, "using environment");

        // ── 3. Create services ───────────────────────────────────────────────
        let mut deployed_services = HashMap::new();

        for (svc_name, svc_def) in &template.services {
            info!(service = svc_name, image = %svc_def.image, "creating service");

            // 3a. Create service
            #[derive(Deserialize)]
            struct ServiceCreate {
                #[serde(rename = "serviceCreate")]
                service_create: IdNode,
            }

            let svc: ServiceCreate = self
                .graphql(
                    r#"mutation ($input: ServiceCreateInput!) {
                        serviceCreate(input: $input) { id }
                    }"#,
                    json!({
                        "input": {
                            "name": svc_name,
                            "projectId": &project_id,
                        }
                    }),
                )
                .await
                .with_context(|| format!("failed to create service '{svc_name}'"))?;

            let service_id = svc.service_create.id;

            // 3b. Set environment variables
            let mut vars: HashMap<String, String> = HashMap::new();
            vars.insert("PORT".to_string(), svc_def.port.to_string());

            // Shared env from template
            for (k, v) in &template.shared_env {
                vars.insert(k.clone(), v.clone());
            }

            // Service-specific env
            for (k, v) in &svc_def.env {
                vars.insert(k.clone(), v.clone());
            }

            // Extra env from CLI --env flags
            for (k, v) in extra_env {
                vars.insert(k.clone(), v.clone());
            }

            if let Err(e) = self
                .graphql::<Value>(
                    r#"mutation ($input: VariableCollectionUpsertInput!) {
                        variableCollectionUpsert(input: $input)
                    }"#,
                    json!({
                        "input": {
                            "projectId": &project_id,
                            "environmentId": &env_id,
                            "serviceId": &service_id,
                            "variables": vars,
                        }
                    }),
                )
                .await
            {
                warn!(service = svc_name, error = %e, "failed to set env vars (non-fatal)");
            }

            // 3c. Deploy from Docker image
            if let Err(e) = self
                .graphql::<Value>(
                    r#"mutation ($input: ServiceInstanceDeployInput!) {
                        serviceInstanceDeploy(input: $input) { id }
                    }"#,
                    json!({
                        "input": {
                            "serviceId": &service_id,
                            "environmentId": &env_id,
                            "source": { "image": &svc_def.image },
                        }
                    }),
                )
                .await
            {
                warn!(service = svc_name, error = %e, "failed to trigger deploy (non-fatal)");
            }

            // 3d. Create public domain if needed
            let mut url: Option<String> = None;
            if svc_def.public {
                match self
                    .graphql::<Value>(
                        r#"mutation ($input: ServiceInstanceDomainCreateInput!) {
                            serviceInstanceDomainCreate(input: $input) { domain }
                        }"#,
                        json!({
                            "input": {
                                "serviceId": &service_id,
                                "environmentId": &env_id,
                            }
                        }),
                    )
                    .await
                {
                    Ok(domain_data) => {
                        if let Some(domain) = domain_data
                            .get("serviceInstanceDomainCreate")
                            .and_then(|d| d.get("domain"))
                            .and_then(Value::as_str)
                        {
                            url = Some(format!("https://{domain}"));
                        }
                    }
                    Err(e) => {
                        warn!(service = svc_name, error = %e, "failed to create domain");
                        url = Some(format!("https://{svc_name}-{project_name}.up.railway.app"));
                    }
                }
            }

            deployed_services.insert(
                svc_name.clone(),
                DeployedService {
                    service_id,
                    url,
                    status: "DEPLOYING".to_string(),
                },
            );
        }

        Ok(DeploymentResult {
            project_id,
            environment_id: env_id,
            services: deployed_services,
        })
    }

    async fn status(&self, project_id: &str) -> Result<HashMap<String, DeployedService>> {
        #[derive(Deserialize)]
        struct ProjectStatus {
            project: ProjectServices,
        }
        #[derive(Deserialize)]
        struct ProjectServices {
            services: Edges<ServiceNode>,
        }
        #[derive(Deserialize)]
        struct Edges<T> {
            edges: Vec<Edge<T>>,
        }
        #[derive(Deserialize)]
        struct Edge<T> {
            node: T,
        }
        #[derive(Deserialize)]
        struct ServiceNode {
            id: String,
            name: String,
            #[serde(rename = "serviceInstances")]
            service_instances: Edges<InstanceNode>,
        }
        #[derive(Deserialize)]
        struct InstanceNode {
            domains: Option<DomainsNode>,
            #[serde(rename = "latestDeployment")]
            latest_deployment: Option<DeploymentNode>,
        }
        #[derive(Deserialize)]
        struct DomainsNode {
            #[serde(rename = "serviceDomains")]
            service_domains: Vec<DomainEntry>,
        }
        #[derive(Deserialize)]
        struct DomainEntry {
            domain: String,
        }
        #[derive(Deserialize)]
        struct DeploymentNode {
            status: String,
        }

        let data: ProjectStatus = self
            .graphql(
                r#"query ($projectId: String!) {
                    project(id: $projectId) {
                        services {
                            edges {
                                node {
                                    id
                                    name
                                    serviceInstances {
                                        edges {
                                            node {
                                                domains {
                                                    serviceDomains { domain }
                                                }
                                                latestDeployment { status }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }"#,
                json!({ "projectId": project_id }),
            )
            .await
            .context("failed to query Railway project status")?;

        let mut services = HashMap::new();

        for edge in data.project.services.edges {
            let svc = edge.node;
            let instance = svc.service_instances.edges.first();

            let status = instance
                .and_then(|i| i.node.latest_deployment.as_ref())
                .map(|d| d.status.clone())
                .unwrap_or_else(|| "UNKNOWN".to_string());

            let url = instance
                .and_then(|i| i.node.domains.as_ref())
                .and_then(|d| d.service_domains.first())
                .map(|d| format!("https://{}", d.domain));

            services.insert(
                svc.name.clone(),
                DeployedService {
                    service_id: svc.id,
                    url,
                    status,
                },
            );
        }

        Ok(services)
    }

    async fn destroy(&self, project_id: &str) -> Result<()> {
        info!(project_id = project_id, "destroying Railway project");

        self.graphql::<Value>(
            r#"mutation ($id: String!) {
                projectDelete(id: $id)
            }"#,
            json!({ "id": project_id }),
        )
        .await
        .context("failed to delete Railway project")?;

        info!("project destroyed");
        Ok(())
    }

    async fn restart(&self, project_id: &str) -> Result<()> {
        // Fetch all services and their latest deployment IDs
        #[derive(Deserialize)]
        struct ProjectDeploys {
            project: ProjectSvcs,
        }
        #[derive(Deserialize)]
        struct ProjectSvcs {
            services: Edges<SvcDeploy>,
        }
        #[derive(Deserialize)]
        struct Edges<T> {
            edges: Vec<Edge<T>>,
        }
        #[derive(Deserialize)]
        struct Edge<T> {
            node: T,
        }
        #[derive(Deserialize)]
        struct SvcDeploy {
            #[serde(rename = "serviceInstances")]
            service_instances: Edges<InstanceDeploy>,
        }
        #[derive(Deserialize)]
        struct InstanceDeploy {
            #[serde(rename = "latestDeployment")]
            latest_deployment: Option<DeployId>,
        }
        #[derive(Deserialize)]
        struct DeployId {
            id: String,
        }

        let data: ProjectDeploys = self
            .graphql(
                r#"query ($projectId: String!) {
                    project(id: $projectId) {
                        services {
                            edges {
                                node {
                                    serviceInstances {
                                        edges {
                                            node {
                                                latestDeployment { id }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }"#,
                json!({ "projectId": project_id }),
            )
            .await?;

        for edge in data.project.services.edges {
            if let Some(instance) = edge.node.service_instances.edges.first() {
                if let Some(deploy) = &instance.node.latest_deployment {
                    let _ = self
                        .graphql::<Value>(
                            r#"mutation ($id: String!) {
                                deploymentRestart(id: $id) { id }
                            }"#,
                            json!({ "id": &deploy.id }),
                        )
                        .await;
                }
            }
        }

        Ok(())
    }

    async fn scale(&self, _project_id: &str, _service_name: &str, _replicas: u32) -> Result<()> {
        // Railway handles scaling via their replica configuration.
        // This would need the serviceInstanceUpdate mutation with numReplicas.
        anyhow::bail!(
            "Railway scaling via API requires Enterprise plan. Use Railway dashboard to configure replicas."
        )
    }
}