feagi-api 0.0.8

FEAGI REST API layer with HTTP and ZMQ transport adapters
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// Copyright 2025 Neuraville Inc.
// Licensed under the Apache License, Version 2.0

//! Region API Endpoints - Exact port from Python `/v1/region/*`

// Removed - using crate::common::State instead
use crate::common::ApiState;
use crate::common::{ApiError, ApiResult, Json, Path, State};
use feagi_services::types::CreateBrainRegionParams;
use feagi_structures::genomic::brain_regions::RegionID;
use std::collections::HashMap;

/// GET /v1/region/regions_members
///
/// Returns all brain regions with their member cortical areas
///
/// Example response:
/// ```json
/// {
///   "root": {
///     "title": "Root Brain Region",
///     "description": "",
///     "parent_region_id": null,
///     "coordinate_2d": [0, 0],
///     "coordinate_3d": [0, 0, 0],
///     "areas": ["area1", "area2"],
///     "regions": [],
///     "inputs": [],
///     "outputs": [],
///     "designated_inputs": [],
///     "designated_outputs": []
///   }
/// }
/// ```
#[utoipa::path(
    get,
    path = "/v1/region/regions_members",
    tag = "region",
    responses(
        (status = 200, description = "Brain regions with member areas", body = HashMap<String, serde_json::Value>),
        (status = 500, description = "Internal server error")
    )
)]
pub async fn get_regions_members(
    State(state): State<ApiState>,
) -> ApiResult<Json<HashMap<String, serde_json::Value>>> {
    use tracing::trace;
    let connectome_service = state.connectome_service.as_ref();
    match connectome_service.list_brain_regions().await {
        Ok(regions) => {
            trace!(target: "feagi-api", "Found {} brain regions to return", regions.len());
            let mut result = HashMap::new();
            for region in regions {
                trace!(
                    target: "feagi-api",
                    "Region: {} ({}) with {} areas",
                    region.region_id,
                    region.name,
                    region.cortical_areas.len()
                );

                // Extract inputs/outputs from region properties if they exist
                let inputs = region
                    .properties
                    .get("inputs")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect::<Vec<String>>()
                    })
                    .unwrap_or_default();

                let outputs = region
                    .properties
                    .get("outputs")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect::<Vec<String>>()
                    })
                    .unwrap_or_default();

                // Declared region IO roles (persisted in genome `properties`; drives BV IO preset).
                let designated_inputs = region
                    .properties
                    .get("designated_inputs")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect::<Vec<String>>()
                    })
                    .unwrap_or_default();

                let designated_outputs = region
                    .properties
                    .get("designated_outputs")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect::<Vec<String>>()
                    })
                    .unwrap_or_default();

                trace!(
                    target: "feagi-api",
                    "Inputs: {} areas, Outputs: {} areas, designated_in: {}, designated_out: {}",
                    inputs.len(),
                    outputs.len(),
                    designated_inputs.len(),
                    designated_outputs.len()
                );

                // Extract coordinate_3d from properties (set by smart positioning in neuroembryogenesis)
                let coordinate_3d = region
                    .properties
                    .get("coordinate_3d")
                    .and_then(|v| v.as_array())
                    .and_then(|arr| {
                        if arr.len() >= 3 {
                            Some(serde_json::json!([arr[0], arr[1], arr[2]]))
                        } else {
                            None
                        }
                    })
                    .unwrap_or_else(|| serde_json::json!([0, 0, 0]));

                // Extract coordinate_2d from properties
                let coordinate_2d = region
                    .properties
                    .get("coordinate_2d")
                    .and_then(|v| v.as_array())
                    .and_then(|arr| {
                        if arr.len() >= 2 {
                            Some(serde_json::json!([arr[0], arr[1]]))
                        } else {
                            None
                        }
                    })
                    .unwrap_or_else(|| serde_json::json!([0, 0]));

                result.insert(
                    region.region_id.clone(),
                    serde_json::json!({
                        "title": region.name,
                        "description": "",  // TODO: Add description field to BrainRegionInfo
                        "parent_region_id": region.parent_id,
                        "coordinate_2d": coordinate_2d,
                        "coordinate_3d": coordinate_3d,
                        "areas": region.cortical_areas,
                        "regions": region.child_regions,
                        "inputs": inputs,
                        "outputs": outputs,
                        "designated_inputs": designated_inputs,
                        "designated_outputs": designated_outputs,
                    }),
                );
            }
            trace!(target: "feagi-api", "Returning {} regions in response", result.len());
            Ok(Json(result))
        }
        Err(e) => Err(ApiError::internal(format!("Failed to get regions: {}", e))),
    }
}

/// POST /v1/region/region
#[utoipa::path(post, path = "/v1/region/region", tag = "region")]
pub async fn post_region(
    State(state): State<ApiState>,
    Json(mut req): Json<HashMap<String, serde_json::Value>>,
) -> ApiResult<Json<HashMap<String, serde_json::Value>>> {
    let connectome_service = state.connectome_service.as_ref();

    let title = req
        .get("title")
        .or_else(|| req.get("name"))
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| ApiError::invalid_input("title required"))?
        .to_string();
    req.remove("title");
    req.remove("name");

    let region_id = match req.get("region_id").and_then(|v| v.as_str()) {
        Some(value) if !value.trim().is_empty() => RegionID::from_string(value)
            .map_err(|e| ApiError::invalid_input(format!("Invalid region_id: {}", e)))?
            .to_string(),
        _ => RegionID::new().to_string(),
    };
    req.remove("region_id");

    let parent_region_id = req
        .get("parent_region_id")
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string);
    req.remove("parent_region_id");

    let region_type = req
        .get("region_type")
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string)
        .unwrap_or_else(|| "Undefined".to_string());
    req.remove("region_type");

    let coordinate_2d_value = req
        .get("coordinate_2d")
        .or_else(|| req.get("coordinates_2d"))
        .and_then(|v| v.as_array().cloned())
        .ok_or_else(|| ApiError::invalid_input("coordinates_2d required"))?;
    if coordinate_2d_value.len() != 2 {
        return Err(ApiError::invalid_input(
            "coordinates_2d must contain exactly 2 values",
        ));
    }
    req.remove("coordinate_2d");
    req.remove("coordinates_2d");

    let coordinate_3d_value = req
        .get("coordinate_3d")
        .or_else(|| req.get("coordinates_3d"))
        .and_then(|v| v.as_array().cloned())
        .ok_or_else(|| ApiError::invalid_input("coordinates_3d required"))?;
    if coordinate_3d_value.len() != 3 {
        return Err(ApiError::invalid_input(
            "coordinates_3d must contain exactly 3 values",
        ));
    }
    req.remove("coordinate_3d");
    req.remove("coordinates_3d");

    let mut properties: HashMap<String, serde_json::Value> = HashMap::new();
    properties.insert(
        "coordinate_2d".to_string(),
        serde_json::Value::Array(coordinate_2d_value),
    );
    properties.insert(
        "coordinate_3d".to_string(),
        serde_json::Value::Array(coordinate_3d_value),
    );
    if let Some(parent_region_id) = &parent_region_id {
        properties.insert(
            "parent_region_id".to_string(),
            serde_json::json!(parent_region_id),
        );
    }
    if let Some(areas) = req.remove("areas") {
        properties.insert("areas".to_string(), areas);
    }
    if let Some(regions) = req.remove("regions") {
        properties.insert("regions".to_string(), regions);
    }
    for (key, value) in req {
        properties.insert(key, value);
    }

    let params = CreateBrainRegionParams {
        region_id: region_id.clone(),
        name: title.clone(),
        region_type,
        parent_id: parent_region_id.clone(),
        properties: Some(properties),
    };

    let info = connectome_service
        .create_brain_region(params)
        .await
        .map_err(ApiError::from)?;

    let coordinate_2d = info
        .properties
        .get("coordinate_2d")
        .cloned()
        .ok_or_else(|| ApiError::internal("Missing coordinate_2d on created region"))?;
    let coordinate_3d = info
        .properties
        .get("coordinate_3d")
        .cloned()
        .ok_or_else(|| ApiError::internal("Missing coordinate_3d on created region"))?;

    let mut response = HashMap::from([
        ("region_id".to_string(), serde_json::json!(info.region_id)),
        ("title".to_string(), serde_json::json!(info.name)),
        (
            "parent_region_id".to_string(),
            serde_json::json!(info.parent_id),
        ),
        ("coordinate_2d".to_string(), coordinate_2d),
        ("coordinate_3d".to_string(), coordinate_3d),
        ("areas".to_string(), serde_json::json!(info.cortical_areas)),
        ("regions".to_string(), serde_json::json!(info.child_regions)),
    ]);

    if let Some(inputs) = info.properties.get("inputs") {
        response.insert("inputs".to_string(), inputs.clone());
    }
    if let Some(outputs) = info.properties.get("outputs") {
        response.insert("outputs".to_string(), outputs.clone());
    }

    Ok(Json(response))
}

/// PUT /v1/region/region
#[utoipa::path(put, path = "/v1/region/region", tag = "region")]
pub async fn put_region(
    State(state): State<ApiState>,
    Json(mut request): Json<HashMap<String, serde_json::Value>>,
) -> ApiResult<Json<HashMap<String, String>>> {
    let connectome_service = state.connectome_service.as_ref();

    // Extract region_id
    let region_id = request
        .get("region_id")
        .and_then(|v| v.as_str())
        .ok_or_else(|| ApiError::invalid_input("region_id required"))?
        .to_string();

    // Remove region_id from properties (it's not a property to update)
    request.remove("region_id");

    connectome_service
        .update_brain_region(&region_id, request)
        .await
        .map_err(ApiError::from)?;

    Ok(Json(HashMap::from([
        ("message".to_string(), "Brain region updated".to_string()),
        ("region_id".to_string(), region_id),
    ])))
}

/// DELETE /v1/region/region
#[utoipa::path(delete, path = "/v1/region/region", tag = "region")]
pub async fn delete_region(
    State(state): State<ApiState>,
    Json(req): Json<HashMap<String, String>>,
) -> ApiResult<Json<HashMap<String, String>>> {
    let connectome_service = state.connectome_service.as_ref();
    let region_id = req
        .get("region_id")
        .or_else(|| req.get("id"))
        .map(String::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| ApiError::invalid_input("region_id required"))?
        .to_string();

    connectome_service
        .delete_brain_region(&region_id)
        .await
        .map_err(ApiError::from)?;

    Ok(Json(HashMap::from([
        ("message".to_string(), "Brain region deleted".to_string()),
        ("region_id".to_string(), region_id),
    ])))
}

/// POST /v1/region/clone
#[utoipa::path(post, path = "/v1/region/clone", tag = "region")]
pub async fn post_clone(
    State(_state): State<ApiState>,
    Json(_req): Json<HashMap<String, serde_json::Value>>,
) -> ApiResult<Json<HashMap<String, String>>> {
    Err(ApiError::internal("Not yet implemented"))
}

/// PUT /v1/region/relocate_members
#[utoipa::path(put, path = "/v1/region/relocate_members", tag = "region")]
pub async fn put_relocate_members(
    State(state): State<ApiState>,
    Json(request): Json<HashMap<String, serde_json::Value>>,
) -> ApiResult<Json<HashMap<String, String>>> {
    let connectome_service = state.connectome_service.as_ref();

    if request.is_empty() {
        return Err(ApiError::invalid_input("Request cannot be empty"));
    }

    let mut updated_regions: Vec<String> = Vec::new();

    for (region_id, payload) in request {
        let payload_obj = payload.as_object().ok_or_else(|| {
            ApiError::invalid_input(format!("Region '{}' entry must be an object", region_id))
        })?;

        if payload_obj.contains_key("parent_region_id") {
            return Err(ApiError::invalid_input(
                "parent_region_id relocation is not implemented via relocate_members",
            ));
        }

        let mut properties: HashMap<String, serde_json::Value> = HashMap::new();
        if let Some(value) = payload_obj
            .get("coordinate_2d")
            .or_else(|| payload_obj.get("coordinates_2d"))
        {
            properties.insert("coordinate_2d".to_string(), value.clone());
        }
        if let Some(value) = payload_obj
            .get("coordinate_3d")
            .or_else(|| payload_obj.get("coordinates_3d"))
        {
            properties.insert("coordinate_3d".to_string(), value.clone());
        }

        if properties.is_empty() {
            return Err(ApiError::invalid_input(format!(
                "Region '{}' has no supported properties to update",
                region_id
            )));
        }

        connectome_service
            .update_brain_region(&region_id, properties)
            .await
            .map_err(ApiError::from)?;

        updated_regions.push(region_id);
    }

    Ok(Json(HashMap::from([
        (
            "message".to_string(),
            format!("Updated {} brain regions", updated_regions.len()),
        ),
        ("region_ids".to_string(), updated_regions.join(", ")),
    ])))
}

/// DELETE /v1/region/region_and_members
#[utoipa::path(delete, path = "/v1/region/region_and_members", tag = "region")]
pub async fn delete_region_and_members(
    State(_state): State<ApiState>,
    Json(_req): Json<HashMap<String, String>>,
) -> ApiResult<Json<HashMap<String, String>>> {
    Err(ApiError::internal("Not yet implemented"))
}

/// GET /v1/region/regions
/// Get list of all brain region IDs
#[utoipa::path(
    get,
    path = "/v1/region/regions",
    tag = "region",
    responses(
        (status = 200, description = "List of region IDs", body = Vec<String>)
    )
)]
pub async fn get_regions(State(state): State<ApiState>) -> ApiResult<Json<Vec<String>>> {
    let connectome_service = state.connectome_service.as_ref();

    let regions = connectome_service
        .list_brain_regions()
        .await
        .map_err(|e| ApiError::internal(format!("Failed to list regions: {}", e)))?;

    let region_ids: Vec<String> = regions.iter().map(|r| r.region_id.clone()).collect();
    Ok(Json(region_ids))
}

/// GET /v1/region/region_titles
/// Get mapping of region IDs to titles
#[utoipa::path(
    get,
    path = "/v1/region/region_titles",
    tag = "region",
    responses(
        (status = 200, description = "Region ID to title mapping", body = HashMap<String, String>)
    )
)]
pub async fn get_region_titles(
    State(state): State<ApiState>,
) -> ApiResult<Json<HashMap<String, String>>> {
    let connectome_service = state.connectome_service.as_ref();

    let regions = connectome_service
        .list_brain_regions()
        .await
        .map_err(|e| ApiError::internal(format!("Failed to list regions: {}", e)))?;

    let mut titles = HashMap::new();
    for region in regions {
        titles.insert(region.region_id.clone(), region.name.clone());
    }

    Ok(Json(titles))
}

/// GET /v1/region/region/{region_id}
/// Get detailed properties for a specific brain region
#[utoipa::path(
    get,
    path = "/v1/region/region/{region_id}",
    tag = "region",
    params(
        ("region_id" = String, Path, description = "Brain region ID")
    ),
    responses(
        (status = 200, description = "Region properties", body = HashMap<String, serde_json::Value>),
        (status = 404, description = "Region not found")
    )
)]
pub async fn get_region_detail(
    State(state): State<ApiState>,
    Path(region_id): Path<String>,
) -> ApiResult<Json<HashMap<String, serde_json::Value>>> {
    let connectome_service = state.connectome_service.as_ref();

    let region = connectome_service
        .get_brain_region(&region_id)
        .await
        .map_err(|e| ApiError::not_found("region", &e.to_string()))?;

    // Extract coordinate_3d from properties (set by smart positioning in neuroembryogenesis)
    let coordinate_3d = region
        .properties
        .get("coordinate_3d")
        .and_then(|v| v.as_array())
        .and_then(|arr| {
            if arr.len() >= 3 {
                Some(serde_json::json!([arr[0], arr[1], arr[2]]))
            } else {
                None
            }
        })
        .unwrap_or_else(|| serde_json::json!([0, 0, 0]));

    // Extract coordinate_2d from properties
    let coordinate_2d = region
        .properties
        .get("coordinate_2d")
        .and_then(|v| v.as_array())
        .and_then(|arr| {
            if arr.len() >= 2 {
                Some(serde_json::json!([arr[0], arr[1]]))
            } else {
                None
            }
        })
        .unwrap_or_else(|| serde_json::json!([0, 0]));

    let description = region
        .properties
        .get("description")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();

    let mut response = HashMap::new();
    response.insert("region_id".to_string(), serde_json::json!(region.region_id));
    response.insert("title".to_string(), serde_json::json!(region.name));
    response.insert("description".to_string(), serde_json::json!(description));
    response.insert("coordinate_2d".to_string(), coordinate_2d);
    response.insert("coordinate_3d".to_string(), coordinate_3d);
    response.insert(
        "areas".to_string(),
        serde_json::json!(region.cortical_areas),
    );
    response.insert(
        "regions".to_string(),
        serde_json::json!(region.child_regions),
    );
    response.insert(
        "parent_region_id".to_string(),
        serde_json::json!(region.parent_id),
    );

    Ok(Json(response))
}

/// PUT /v1/region/change_region_parent
/// Change the parent of a brain region
#[utoipa::path(
    put,
    path = "/v1/region/change_region_parent",
    tag = "region",
    responses(
        (status = 200, description = "Parent changed", body = HashMap<String, String>)
    )
)]
pub async fn put_change_region_parent(
    State(_state): State<ApiState>,
    Json(_request): Json<HashMap<String, String>>,
) -> ApiResult<Json<HashMap<String, String>>> {
    Ok(Json(HashMap::from([(
        "message".to_string(),
        "Region parent change not yet implemented".to_string(),
    )])))
}

/// PUT /v1/region/change_cortical_area_region
/// Change the region association of a cortical area
#[utoipa::path(
    put,
    path = "/v1/region/change_cortical_area_region",
    tag = "region",
    responses(
        (status = 200, description = "Association changed", body = HashMap<String, String>)
    )
)]
pub async fn put_change_cortical_area_region(
    State(_state): State<ApiState>,
    Json(_request): Json<HashMap<String, String>>,
) -> ApiResult<Json<HashMap<String, String>>> {
    Ok(Json(HashMap::from([(
        "message".to_string(),
        "Cortical area region association change not yet implemented".to_string(),
    )])))
}