winx-code-agent 0.2.343

Remote-first Rust MCP runtime with Streamable HTTP, durable PTYs, and guarded agent tools
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
//! # Winx - Remote-first MCP runtime
//!
//! Winx exposes durable shell, file, and code-navigation tools over hardened
//! Streamable HTTP, with stdio retained for local MCP clients.

use std::io::Write;
use std::path::PathBuf;
#[cfg(unix)]
use std::time::Duration;

use clap::Parser;
#[cfg(unix)]
use winx_code_agent::daemon::{default_socket_path, DaemonClient};
#[cfg(unix)]
use winx_code_agent::runtime::{configured_daemon_binary, restart_control_daemon_at};
use winx_code_agent::{start_winx_server, Result, WinxError};

/// Winx - Remote-first MCP runtime
#[derive(Parser)]
#[command(name = "winx-code-agent")]
#[command(author = "Gabriel Maia")]
#[command(version = env!("WINX_BUILD_IDENTITY"))]
#[command(
    about = "Remote-first MCP runtime with Streamable HTTP, durable PTYs, and guarded shell/file tools",
    long_about = None
)]
struct Cli {
    /// Enable verbose logging
    #[arg(short, long)]
    verbose: bool,

    /// Enable debug logging
    #[arg(long)]
    debug: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(clap::Subcommand)]
enum Commands {
    /// Start MCP server (default: stdio transport for local clients)
    Serve {
        /// Serve over Streamable HTTP instead of stdio, for remote MCP clients
        /// (e.g. `ChatGPT` developer-mode connectors). Requires --token.
        #[arg(long)]
        http: bool,

        /// Address for the HTTP transport. Keep it on loopback and put an
        /// HTTPS tunnel in front — do not expose 0.0.0.0 on untrusted networks.
        #[arg(long, default_value = "127.0.0.1:8000")]
        bind: String,

        /// Shared secret required on every HTTP request. Prefer --token-file so
        /// the secret is not visible in process arguments. Falls back to
        /// `WINX_HTTP_TOKEN` when no other credential source is provided.
        #[arg(long, conflicts_with_all = ["token_file", "principal_config"])]
        token: Option<String>,

        /// Read the single-principal bearer token from a chmod-600 file.
        #[arg(long, value_name = "PATH", conflicts_with_all = ["token", "principal_config"])]
        token_file: Option<PathBuf>,

        /// TOML file containing multiple [[principals]] entries, each backed by
        /// `token_file` or `token_env`. Sessions and Tasks are isolated per principal.
        #[arg(long, value_name = "PATH", conflicts_with_all = ["token", "token_file"])]
        principal_config: Option<PathBuf>,

        /// Curated MCP catalog for a single-token principal. `full` preserves
        /// every tool; `coding`, `read-only`, and `terminal` reduce schemas and routing.
        #[arg(
            long,
            value_enum,
            default_value_t = winx_code_agent::tool_policy::ToolProfile::Full,
            conflicts_with = "principal_config"
        )]
        tool_profile: winx_code_agent::tool_policy::ToolProfile,

        /// Exact tool name to permit for a single-token principal. Repeat to
        /// build a custom catalog; when present, this replaces --tool-profile.
        #[arg(long = "allow-tool", value_name = "NAME", conflicts_with = "principal_config")]
        allowed_tools: Vec<String>,

        /// Permit a token shorter than 32 bytes. Intended only for local tests.
        #[arg(long)]
        allow_weak_token: bool,

        /// Permit binding HTTP to a non-loopback address. Off by default because
        /// this endpoint provides shell and filesystem access.
        #[arg(long)]
        allow_non_loopback: bool,

        /// Session key used by remote first-call initialization. `workspace`
        /// reuses one durable shell per principal/project; `conversation` also
        /// separates client conversations when a stable identity is available;
        /// `thread` trusts the caller's ID and requires explicit lifecycle care.
        #[arg(
            long,
            value_enum,
            default_value_t = winx_code_agent::config::HttpSessionAffinity::Workspace
        )]
        session_affinity: winx_code_agent::config::HttpSessionAffinity,

        /// Maximum HTTP requests executing concurrently.
        #[arg(
            long,
            default_value_t = winx_code_agent::http_server::DEFAULT_MAX_CONCURRENCY
        )]
        max_concurrency: usize,

        /// Fixed-window request limit per source IP.
        #[arg(
            long,
            default_value_t = winx_code_agent::http_server::DEFAULT_REQUESTS_PER_MINUTE
        )]
        requests_per_minute: u32,

        /// Extra Host authority to accept (your tunnel hostname, e.g.
        /// abc.trycloudflare.com). Repeatable. Loopback is always allowed.
        #[arg(long = "allowed-host")]
        allowed_host: Vec<String>,

        /// Also accept the token via a `?token=<token>` query parameter, for
        /// clients that only take a URL (e.g. `ChatGPT` MCP connectors). OFF by
        /// default: the header is preferred because a query token leaks into
        /// tunnel/proxy access logs and browser history. Use only on
        /// ephemeral/trusted tunnels.
        #[arg(long)]
        allow_query_token: bool,
    },

    /// List shell sessions owned by winxd
    #[cfg(unix)]
    List {
        #[arg(long)]
        socket: Option<PathBuf>,
    },

    /// Read a session's output using an independent consumer cursor
    #[cfg(unix)]
    Attach {
        thread_id: String,
        #[arg(long, default_value = "cli")]
        consumer: String,
        #[arg(long)]
        follow: bool,
        #[arg(long)]
        socket: Option<PathBuf>,
    },

    /// Stop and remove one or every daemon-owned shell session
    #[cfg(unix)]
    Kill {
        #[arg(required_unless_present = "all")]
        thread_id: Option<String>,
        #[arg(long, conflicts_with = "thread_id")]
        all: bool,
        #[arg(long)]
        socket: Option<PathBuf>,
    },

    /// Remove idle or unreachable daemon-owned shell sessions
    #[cfg(unix)]
    Prune {
        /// Override the configured idle TTL for this run. Zero prunes every idle session.
        #[arg(long)]
        idle_seconds: Option<u64>,
        #[arg(long)]
        socket: Option<PathBuf>,
    },

    /// Restart winxd without terminating per-session guardians or PTYs
    #[cfg(unix)]
    RestartDaemon {
        #[arg(long)]
        socket: Option<PathBuf>,
    },

    /// Print a redacted runtime/configuration diagnostic report
    Doctor,

    /// Aggregate privacy-safe tool/HTTP usage telemetry from JSONL logs
    Report {
        /// Base usage log path. Rotated siblings are discovered automatically.
        #[arg(long, value_name = "PATH")]
        log: Option<PathBuf>,
        /// Maximum number of matching events to aggregate.
        #[arg(long, default_value_t = 10_000)]
        last: usize,
        /// Ignore events older than this many minutes (zero disables filtering).
        #[arg(long, default_value_t = 0)]
        since_minutes: u64,
        /// Exact build display identity or package version to include.
        #[arg(long)]
        build: Option<String>,
    },
}

fn main() -> Result<()> {
    let cli = Cli::parse();
    let offline_report = matches!(&cli.command, Some(Commands::Report { .. }));

    // Apply Landlock before ANY worker thread exists. This includes the optional
    // non-blocking usage-log writer as well as Tokio and PTY children; otherwise
    // that writer would remain outside the Landlock domain for the process lifetime.
    let sandbox_report = winx_code_agent::sandbox::apply_if_requested();
    let _logging_guard = if offline_report {
        winx_code_agent::logging::initialize_without_usage(cli.verbose, cli.debug)?
    } else {
        winx_code_agent::logging::initialize(cli.verbose, cli.debug)?
    };
    sandbox_report.emit();

    tokio::runtime::Runtime::new()
        .map_err(|e| {
            WinxError::ShellInitializationError(format!("failed to start tokio runtime: {e}"))
        })?
        .block_on(async_main(cli))
}

async fn async_main(cli: Cli) -> Result<()> {
    match cli.command {
        Some(Commands::Serve {
            http: true,
            bind,
            token,
            token_file,
            principal_config,
            tool_profile,
            allowed_tools,
            allow_weak_token,
            allow_non_loopback,
            session_affinity,
            max_concurrency,
            requests_per_minute,
            allowed_host,
            allow_query_token,
        }) => {
            run_http_server(
                bind,
                token,
                token_file,
                principal_config,
                tool_profile,
                allowed_tools,
                allow_weak_token,
                allow_non_loopback,
                session_affinity,
                max_concurrency,
                requests_per_minute,
                allowed_host,
                allow_query_token,
            )
            .await
        }
        #[cfg(unix)]
        Some(Commands::List { socket }) => run_list(socket).await,
        #[cfg(unix)]
        Some(Commands::Attach { thread_id, consumer, follow, socket }) => {
            run_attach(socket, thread_id, consumer, follow).await
        }
        #[cfg(unix)]
        Some(Commands::Kill { thread_id, all, socket }) => run_kill(socket, thread_id, all).await,
        #[cfg(unix)]
        Some(Commands::Prune { idle_seconds, socket }) => run_prune(socket, idle_seconds).await,
        #[cfg(unix)]
        Some(Commands::RestartDaemon { socket }) => run_restart_daemon(socket).await,
        Some(Commands::Doctor) => run_doctor().await,
        Some(Commands::Report { log, last, since_minutes, build }) => {
            run_report(log, last, since_minutes, build).await
        }
        // Default: stdio transport for local MCP clients.
        None | Some(Commands::Serve { .. }) => run_server().await,
    }
}

#[cfg(unix)]
fn daemon_client(socket: Option<PathBuf>) -> DaemonClient {
    DaemonClient::new(socket.unwrap_or_else(default_socket_path))
}

#[cfg(unix)]
async fn run_list(socket: Option<PathBuf>) -> Result<()> {
    let sessions = daemon_client(socket).list_sessions().await?;
    serde_json::to_writer_pretty(std::io::stdout().lock(), &sessions)
        .map_err(|error| WinxError::SerializationError(error.to_string()))?;
    writeln!(std::io::stdout().lock())?;
    Ok(())
}

#[cfg(unix)]
async fn run_attach(
    socket: Option<PathBuf>,
    thread_id: String,
    consumer: String,
    follow: bool,
) -> Result<()> {
    let client = daemon_client(socket);
    loop {
        let read = client.read_output(&thread_id, &consumer).await?;
        if read.gap {
            writeln!(std::io::stderr().lock(), "(...daemon scrollback truncated...)")?;
        }
        if !read.output.is_empty() {
            let mut stdout = std::io::stdout().lock();
            stdout.write_all(read.output.as_bytes())?;
            stdout.flush()?;
        }
        if !follow {
            return Ok(());
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}

#[cfg(unix)]
async fn run_kill(socket: Option<PathBuf>, thread_id: Option<String>, all: bool) -> Result<()> {
    let client = daemon_client(socket);
    if all {
        let sessions = client.list_sessions().await?;
        let mut killed = 0usize;
        for session in sessions {
            if client.kill_session(&session.thread_id).await? {
                killed += 1;
            }
        }
        writeln!(std::io::stdout().lock(), "killed {killed} session(s)")?;
        return Ok(());
    }

    let thread_id = thread_id
        .ok_or_else(|| WinxError::InvalidInput("provide a thread_id or pass --all".to_string()))?;
    let killed = client.kill_session(&thread_id).await?;
    writeln!(std::io::stdout().lock(), "{}", if killed { "killed" } else { "not found" })?;
    Ok(())
}

#[cfg(unix)]
async fn run_prune(socket: Option<PathBuf>, idle_seconds: Option<u64>) -> Result<()> {
    let result = daemon_client(socket).prune_sessions(idle_seconds).await?;
    serde_json::to_writer_pretty(std::io::stdout().lock(), &result)
        .map_err(|error| WinxError::SerializationError(error.to_string()))?;
    writeln!(std::io::stdout().lock())?;
    Ok(())
}

#[cfg(unix)]
async fn run_restart_daemon(socket: Option<PathBuf>) -> Result<()> {
    let socket = socket.unwrap_or_else(default_socket_path);
    let binary = configured_daemon_binary()?;
    let hello = restart_control_daemon_at(&socket, &binary).await?;
    writeln!(
        std::io::stdout().lock(),
        "restarted winxd pid={} epoch={}",
        hello.daemon_pid,
        hello.daemon_epoch
    )?;
    Ok(())
}

async fn run_doctor() -> Result<()> {
    let report = winx_code_agent::diagnostics::doctor_report().await;

    serde_json::to_writer_pretty(std::io::stdout().lock(), &report)
        .map_err(|error| WinxError::SerializationError(error.to_string()))?;
    writeln!(std::io::stdout().lock())?;
    Ok(())
}

async fn run_report(
    log: Option<PathBuf>,
    last: usize,
    since_minutes: u64,
    build: Option<String>,
) -> Result<()> {
    let report = tokio::task::spawn_blocking(move || {
        winx_code_agent::report::usage_report(log.as_deref(), last, since_minutes, build.as_deref())
    })
    .await
    .map_err(|error| {
        WinxError::CommandExecutionError(format!("report worker failed: {error}"))
    })??;
    serde_json::to_writer_pretty(std::io::stdout().lock(), &report)
        .map_err(|error| WinxError::SerializationError(error.to_string()))?;
    writeln!(std::io::stdout().lock())?;
    Ok(())
}

/// Executes the remote MCP server over Streamable HTTP.
#[allow(clippy::too_many_arguments)]
async fn run_http_server(
    bind: String,
    token: Option<String>,
    token_file: Option<PathBuf>,
    principal_config: Option<PathBuf>,
    tool_profile: winx_code_agent::tool_policy::ToolProfile,
    allowed_tools: Vec<String>,
    allow_weak_token: bool,
    allow_non_loopback: bool,
    session_affinity: winx_code_agent::config::HttpSessionAffinity,
    max_concurrency: usize,
    requests_per_minute: u32,
    allowed_hosts: Vec<String>,
    allow_query_token: bool,
) -> Result<()> {
    if token.is_some() {
        tracing::warn!("--token exposes the HTTP secret in process arguments; prefer --token-file");
    }
    let explicit_tools = (!allowed_tools.is_empty()).then_some(allowed_tools.as_slice());
    let tool_policy =
        winx_code_agent::tool_policy::ToolPolicy::resolve(tool_profile, explicit_tools)?;
    let principals = winx_code_agent::config::load_http_principals_with_policy(
        principal_config.as_deref(),
        token,
        token_file.as_deref(),
        allow_weak_token,
        tool_policy,
    )?;
    let options = winx_code_agent::http_server::HttpServerOptions {
        bind: bind.clone(),
        principals,
        extra_hosts: allowed_hosts,
        allow_query_token,
        allow_non_loopback,
        session_affinity,
        max_concurrency,
        requests_per_minute,
    };
    tracing::info!(
        build = %winx_code_agent::build_info::display_version(),
        "Starting winx remote MCP (HTTP) on {bind}"
    );

    winx_code_agent::http_server::start_http_server_with_options(options).await.map_err(|error| {
        WinxError::ShellInitializationError(format!("HTTP server failed: {error}"))
    })
}

/// Executes the MCP server
async fn run_server() -> Result<()> {
    tracing::info!(
        build = %winx_code_agent::build_info::display_version(),
        "Starting winx MCP server"
    );

    match start_winx_server().await {
        Ok(()) => {
            tracing::info!("Server shutting down normally");
            Ok(())
        }
        Err(e) => {
            tracing::error!("Server error: {}", e);
            Err(WinxError::ShellInitializationError(format!("Failed to start server: {e}")))
        }
    }
}