oxios 1.9.0

Oxios Agent OS — Agent Operating System powered by oxi-sdk
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
use std::sync::Arc;

use axum::Json;
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use serde::{Deserialize, Serialize};

use oxios_kernel::ArgumentDef;
use oxios_kernel::access_manager::AuditEntry;
use oxios_kernel::metrics::registry;

use crate::api::routes::PageParams;
use crate::api::server::AppState;

// ---------------------------------------------------------------------------
// Prometheus Metrics
// ---------------------------------------------------------------------------

/// GET /api/metrics — Prometheus-compatible metrics endpoint.
pub(crate) async fn handle_metrics() -> Result<String, StatusCode> {
    Ok(registry().export())
}

// ---------------------------------------------------------------------------
// Scheduler (AIOS-inspired task scheduling)
// ---------------------------------------------------------------------------

/// Scheduler statistics response.
#[derive(Debug, Serialize)]
pub(crate) struct SchedulerStatsResponse {
    queued: usize,
    running: usize,
    max_concurrent: usize,
    rate_limit_per_minute: u32,
    rate_remaining: u32,
}

/// GET /api/scheduler/stats — Get scheduler statistics.
pub(crate) async fn handle_scheduler_stats(
    state: State<Arc<AppState>>,
) -> Json<SchedulerStatsResponse> {
    let stats = state.kernel.infra.scheduler_stats();
    Json(SchedulerStatsResponse {
        queued: stats.queued,
        running: stats.running,
        max_concurrent: stats.max_concurrent,
        rate_limit_per_minute: stats.rate_limit_per_minute,
        rate_remaining: stats.rate_remaining,
    })
}

/// Task summary for listing.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct TaskSummary {
    id: String,
    description: String,
    priority: String,
    status: String,
    created_at: String,
    error: Option<String>,
}

/// GET /api/scheduler/tasks — List queued and running tasks.
pub(crate) async fn handle_scheduler_tasks(
    state: State<Arc<AppState>>,
    _params: Query<PageParams>,
) -> Json<serde_json::Value> {
    let queued: Vec<TaskSummary> = state
        .kernel
        .infra
        .queued_tasks()
        .into_iter()
        .map(|t| TaskSummary {
            id: t.id.to_string(),
            description: t.description,
            priority: format!("{:?}", t.priority).to_lowercase(),
            status: format!("{:?}", t.status).to_lowercase(),
            created_at: t.created_at.to_rfc3339(),
            error: t.error,
        })
        .collect();

    let running: Vec<TaskSummary> = state
        .kernel
        .infra
        .running_tasks()
        .into_iter()
        .map(|t| TaskSummary {
            id: t.id.to_string(),
            description: t.description,
            priority: format!("{:?}", t.priority).to_lowercase(),
            status: format!("{:?}", t.status).to_lowercase(),
            created_at: t.created_at.to_rfc3339(),
            error: t.error,
        })
        .collect();

    Json(serde_json::json!({
        "queued": queued,
        "running": running,
    }))
}

// ---------------------------------------------------------------------------
// Audit & Permissions
// ---------------------------------------------------------------------------

/// Audit log entry response.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct AuditEntryResponse {
    timestamp: String,
    agent_name: String,
    action: String,
    resource: String,
    allowed: bool,
    reason: Option<String>,
}

impl From<&AuditEntry> for AuditEntryResponse {
    fn from(entry: &AuditEntry) -> Self {
        Self {
            timestamp: entry.timestamp.to_rfc3339(),
            agent_name: entry.agent_name.clone(),
            action: entry.action.clone(),
            resource: entry.resource.clone(),
            allowed: entry.allowed,
            reason: entry.reason.clone(),
        }
    }
}

/// Audit log with pagination.
#[derive(Debug, Deserialize)]
pub struct AuditLogParams {
    #[serde(default = "default_page")]
    pub page: usize,
    #[serde(default = "default_limit")]
    pub limit: usize,
}

fn default_page() -> usize {
    1
}
fn default_limit() -> usize {
    50
}

/// GET /api/audit — Get security audit log (paginated).
pub(crate) async fn handle_audit_log(
    state: State<Arc<AppState>>,
    Query(params): Query<AuditLogParams>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let entries = state.kernel.security.get_audit_log();
    let total = entries.len();
    let limit = params.limit.min(500);
    let offset = (params.page.saturating_sub(1)) * limit;
    let page_entries: Vec<_> = entries
        .iter()
        .rev()
        .skip(offset)
        .take(limit)
        .map(AuditEntryResponse::from)
        .collect();
    Ok(Json(serde_json::json!({
        "items": page_entries,
        "total": total,
        "page": params.page,
        "limit": limit,
    })))
}

/// Permission update request from JSON API.
/// We avoid derive(Deserialize) to prevent conflicts with kernel's PermissionUpdate.
pub(crate) struct PermissionsUpdate {
    allowed_tools: Option<Vec<String>>,
    allowed_paths: Option<Vec<String>>,
    denied_paths: Option<Vec<String>>,
    network_access: Option<bool>,
    max_execution_time_secs: Option<u64>,
    max_memory_mb: Option<u64>,
    can_fork: Option<bool>,
}

impl PermissionsUpdate {
    /// Parse from JSON value.
    pub fn from_json(value: serde_json::Value) -> Self {
        Self {
            allowed_tools: value
                .get("allowed_tools")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(String::from))
                        .collect()
                }),
            allowed_paths: value
                .get("allowed_paths")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(String::from))
                        .collect()
                }),
            denied_paths: value
                .get("denied_paths")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(String::from))
                        .collect()
                }),
            network_access: value.get("network_access").and_then(|v| v.as_bool()),
            max_execution_time_secs: value
                .get("max_execution_time_secs")
                .and_then(|v| v.as_u64()),
            max_memory_mb: value.get("max_memory_mb").and_then(|v| v.as_u64()),
            can_fork: value.get("can_fork").and_then(|v| v.as_bool()),
        }
    }

    /// Convert to kernel PermissionUpdate.
    pub fn into_kernel(self) -> oxios_kernel::access_manager::PermissionUpdate {
        oxios_kernel::access_manager::PermissionUpdate {
            allowed_tools: self
                .allowed_tools
                .map(|t| t.into_iter().collect::<std::collections::HashSet<String>>()),
            allowed_paths: self.allowed_paths,
            denied_paths: self.denied_paths,
            network_access: self.network_access,
            max_execution_time_secs: self.max_execution_time_secs,
            max_memory_mb: self.max_memory_mb,
            can_fork: self.can_fork,
        }
    }
}

/// GET /api/permissions/:agent — Get permissions for an agent.
pub(crate) async fn handle_permissions_get(
    state: State<Arc<AppState>>,
    Path(agent): Path<String>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    match state.kernel.security.get_permissions(&agent) {
        Some(perms) => Ok(Json(serde_json::json!({
            "agent_name": perms.agent_name,
            "allowed_tools": perms.allowed_tools.iter().cloned().collect::<Vec<_>>(),
            "allowed_paths": perms.allowed_paths,
            "denied_paths": perms.denied_paths,
            "network_access": perms.network_access,
            "max_execution_time_secs": perms.max_execution_time_secs,
            "max_memory_mb": perms.max_memory_mb,
            "can_fork": perms.can_fork,
        }))),
        None => Err(StatusCode::NOT_FOUND),
    }
}

/// PUT /api/permissions/:agent — Set permissions for an agent.
pub(crate) async fn handle_permissions_put(
    state: State<Arc<AppState>>,
    Path(agent): Path<String>,
    Json(body): Json<serde_json::Value>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let update = PermissionsUpdate::from_json(body).into_kernel();
    state
        .kernel
        .security
        .update_permissions(&agent, update)
        .map_err(|e: anyhow::Error| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    tracing::info!(agent = %agent, "Permissions updated");
    Ok(Json(serde_json::json!({
        "status": "updated",
        "agent": agent,
    })))
}

// ---------------------------------------------------------------------------
// MCP (Model Context Protocol)
// ---------------------------------------------------------------------------

/// MCP server configuration response.
#[derive(Debug, Serialize)]
pub(crate) struct McpServerResponse {
    name: String,
    command: String,
    args: Vec<String>,
    enabled: bool,
    initialized: bool,
}

/// GET /api/mcp/servers — List registered MCP servers.
pub(crate) async fn handle_mcp_servers_list(
    state: State<Arc<AppState>>,
) -> Json<Vec<McpServerResponse>> {
    let servers = state.kernel.mcp.list_servers();
    let mut results = Vec::new();
    for name in servers {
        let (command, args, enabled) = state
            .kernel
            .mcp
            .get_server(&name)
            .map(|s| (s.command.clone(), s.args.clone(), s.enabled))
            .unwrap_or_else(|| ("unknown".to_string(), Vec::new(), false));
        let initialized = state.kernel.mcp.client_status(&name).await.unwrap_or(false);
        results.push(McpServerResponse {
            name: name.to_string(),
            command,
            args,
            enabled,
            initialized,
        });
    }
    Json(results)
}

/// MCP server registration request.
#[derive(Debug, Deserialize)]
pub(crate) struct McpServerRegisterRequest {
    name: String,
    command: String,
    #[serde(default)]
    args: Vec<String>,
}

/// Shell interpreters that must never be spawned as an MCP server.
/// Spawning any of these lets a caller run arbitrary commands via
/// `args = ["-c", "<cmd>"]`, which defeats the purpose of the MCP
/// command surface (RCE by design of the report's F4 scenario).
const BLOCKED_MCP_SHELLS: &[&str] = &[
    "sh",
    "bash",
    "dash",
    "zsh",
    "ksh",
    "csh",
    "tcsh",
    "fish",
    "ash",
    "busybox",
    "cmd",
    "cmd.exe",
    "powershell",
    "powershell.exe",
    "pwsh",
    "pwsh.exe",
];

/// Validate an MCP server command before spawning it.
///
/// Rejects shell interpreters (which would allow `args = ["-c", ...]`
/// arbitrary code execution) and commands containing shell metacharacters
/// or path-traversal sequences. Returns the (possibly canonicalized)
/// command basename for allowlist checks.
fn validate_mcp_command(command: &str) -> Result<(), String> {
    if command.is_empty() {
        return Err("command must not be empty".into());
    }
    // Reject control / NUL bytes outright.
    if command.chars().any(|c| c.is_control() || c == '\u{0}') {
        return Err("command contains control characters".into());
    }
    // Reject shell metacharacters and whitespace — MCP commands are a
    // single token (e.g. `npx`, `python`, `node`). Any of these would
    // indicate an attempt to chain or inject.
    const FORBIDDEN: &[char] = &[
        ' ', '\t', ';', '|', '&', '>', '<', '`', '$', '(', ')', '{', '}', '\n', '\r', '*', '?',
        '\\', '"', '\'',
    ];
    if command.contains(FORBIDDEN) {
        return Err(format!(
            "command contains forbidden characters (shell metacharacters or whitespace): {command:?}"
        ));
    }
    // Reject path traversal in case the command is a path.
    if command.contains("..") {
        return Err("command must not contain path traversal (..)".into());
    }
    // Basename of the command for the shell blocklist check.
    let basename = command.rsplit('/').next().unwrap_or(command);
    let basename_lower = basename.to_ascii_lowercase();
    if BLOCKED_MCP_SHELLS.iter().any(|s| *s == basename_lower) {
        return Err(format!(
            "refusing to spawn shell interpreter '{basename}' as an MCP server \
             (would allow arbitrary command execution)"
        ));
    }
    Ok(())
}

/// POST /api/mcp/servers — Register a new MCP server and start it.
pub(crate) async fn handle_mcp_server_register(
    state: State<Arc<AppState>>,
    Json(body): Json<McpServerRegisterRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let name = body.name.clone();
    let command = body.command.clone();

    // F4: validate the command before we spawn anything. Refuses shell
    // interpreters and commands with shell metacharacters / traversal.
    if let Err(reason) = validate_mcp_command(&command) {
        tracing::warn!(
            server = %name,
            command = %command,
            reason = %reason,
            "Rejected MCP server registration (unsafe command)"
        );
        return Err((
            StatusCode::BAD_REQUEST,
            format!("Invalid command: {reason}"),
        ));
    }

    // Audit log: record what is being spawned and from where, before spawn.
    tracing::info!(
        server = %name,
        command = %command,
        args = ?body.args,
        auth_enabled = state.config.read().security.auth_enabled,
        "MCP server registration accepted (spawning)"
    );

    let mut server = oxios_kernel::McpServer::new(&name, &command);
    server.args = body.args;
    server.enabled = true;
    state.kernel.mcp.register_server(server);
    if let Err(e) = state.kernel.mcp.init_server(&name).await {
        tracing::error!(server = %name, error = %e, "Failed to start MCP server; rolling back registration");
        // Rollback the registration so a failed spawn does not leave a
        // phantom entry in the server list.
        if let Err(rb) = state.kernel.mcp.remove_server(&name).await {
            tracing::warn!(server = %name, error = %rb, "Failed to roll back MCP server registration");
        }
        return Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string()));
    }
    tracing::info!(server = %name, command = %command, "MCP server registered and started");
    Ok(Json(serde_json::json!({
        "status": "registered",
        "name": name,
        "command": command,
    })))
}

/// MCP tool summary exposed to agents.
#[derive(Debug, Serialize)]
pub(crate) struct McpToolResponse {
    name: String,
    description: String,
    server: String,
    arguments: Vec<ArgumentDef>,
}

/// GET /api/mcp/tools — List all available MCP tools.
pub(crate) async fn handle_mcp_tools_list(
    state: State<Arc<AppState>>,
) -> Json<Vec<McpToolResponse>> {
    let tools = match state.kernel.mcp.list_tools().await {
        Ok(t) => t,
        Err(e) => {
            tracing::warn!(error = %e, "Failed to list MCP tools");
            Vec::new()
        }
    };

    // Reconstruct server attribution from cached tools.
    let mut results = Vec::new();
    for name in state.kernel.mcp.list_servers() {
        if let Some(cached) = state.kernel.mcp.cached_tools(&name).await {
            for tool in cached {
                results.push(McpToolResponse {
                    name: tool.name,
                    description: tool.description,
                    server: name.to_string(),
                    arguments: tool.arguments,
                });
            }
        }
    }
    // Fallback: if no cached tools, list from list_tools() with unknown server.
    if results.is_empty() {
        for tool in &tools {
            results.push(McpToolResponse {
                name: tool.name.clone(),
                description: tool.description.clone(),
                server: "<unknown>".to_string(),
                arguments: tool.arguments.clone(),
            });
        }
    }
    Json(results)
}

/// Request body for calling an MCP tool.
#[derive(Debug, Deserialize)]
pub(crate) struct McpToolCallRequest {
    server: String,
    tool: String,
    #[serde(default)]
    arguments: serde_json::Value,
}

/// POST /api/mcp/tools — Call an MCP tool.
pub(crate) async fn handle_mcp_tool_call(
    state: State<Arc<AppState>>,
    Json(body): Json<McpToolCallRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let result = state.kernel.mcp.call_tool(&body.server, &body.tool, body.arguments)
        .await
        .map_err(|e| {
            tracing::error!(server = %body.server, tool = %body.tool, error = %e, "MCP tool call failed");
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
        })?;

    // Serialize the content blocks.
    let content: Vec<serde_json::Value> = result
        .content
        .iter()
        .map(|block| serde_json::to_value(block).unwrap_or_default())
        .collect();

    Ok(Json(serde_json::json!({
        "content": content,
        "is_error": result.is_error,
    })))
}

/// DELETE /api/mcp/servers/{name} — Disconnect and remove an MCP server.
pub(crate) async fn handle_mcp_server_delete(
    state: State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    state.kernel.mcp.remove_server(&name).await.map_err(|e| {
        tracing::error!(server = %name, error = %e, "Failed to remove MCP server");
        (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
    })?;
    tracing::info!(server = %name, "MCP server removed");
    Ok(Json(
        serde_json::json!({ "status": "removed", "name": name }),
    ))
}

/// POST /api/mcp/servers/{name}/toggle — Toggle MCP server enabled/disabled.
pub(crate) async fn handle_mcp_server_toggle(
    state: State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let enabled = state.kernel.mcp.toggle_server(&name).await.map_err(|e| {
        tracing::error!(server = %name, error = %e, "Failed to toggle MCP server");
        (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
    })?;
    tracing::info!(server = %name, enabled = enabled, "MCP server toggled");
    Ok(Json(
        serde_json::json!({ "status": "toggled", "name": name, "enabled": enabled }),
    ))
}

/// POST /api/mcp/servers/{name}/refresh — Refresh tools for an MCP server.
pub(crate) async fn handle_mcp_server_refresh(
    state: State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    state.kernel.mcp.init_server(&name).await.map_err(|e| {
        tracing::error!(server = %name, error = %e, "Failed to refresh MCP server");
        (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
    })?;
    tracing::info!(server = %name, "MCP server tools refreshed");
    Ok(Json(
        serde_json::json!({ "status": "refreshed", "name": name }),
    ))
}

// ---------------------------------------------------------------------------
// Security / Permissions overview
// ---------------------------------------------------------------------------

/// GET /api/security/permissions — List roles and policies.
pub(crate) async fn handle_security_permissions(
    _state: State<Arc<AppState>>,
) -> Json<serde_json::Value> {
    use oxios_kernel::access_manager::Role;
    let roles: Vec<String> = [
        format!("{:?}", Role::User).to_lowercase(),
        format!("{:?}", Role::Superuser).to_lowercase(),
        format!("{:?}", Role::Admin).to_lowercase(),
    ]
    .into_iter()
    .map(|r| r.to_lowercase())
    .collect();

    // Build policy summaries from each role's default policy
    let mut policies = Vec::new();
    for role in [Role::User, Role::Superuser, Role::Admin] {
        let policy = role.default_policy();
        // Serialize the policy to get its allowed actions
        let val = serde_json::to_value(&policy).unwrap_or_default();
        policies.push(serde_json::json!({
            "name": format!("{}-default", format!("{role:?}").to_lowercase()),
            "effect": "allow",
            "resources": val.get("allowed_actions").and_then(|v| v.as_array())
                .map(|arr| arr.iter().filter_map(|v| v.as_str().map(String::from)).collect::<Vec<_>>())
                .unwrap_or_default(),
        }));
    }

    Json(serde_json::json!({
        "roles": roles,
        "policies": policies,
    }))
}