winx-code-agent 0.2.358

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
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
//! Typed configuration and secret-loading helpers.

use std::path::{Path, PathBuf};

use serde::Deserialize;
use sha2::{Digest, Sha256};

use crate::errors::{Result, WinxError};
use crate::tool_policy::{ToolPolicy, ToolProfile};

/// Minimum accepted HTTP bearer-token length in bytes.
pub const MIN_HTTP_TOKEN_BYTES: usize = 32;

/// Server-process configuration that agent commands must never inherit. A Winx
/// shell otherwise passes the server's environment to every command, so a
/// nested `cargo test` or `winx-code-agent` run by an agent would append
/// synthetic events to the operator's usage log, and any command could read the
/// HTTP bearer token. An explicit assignment in the command itself still works.
pub const SERVER_ONLY_ENV: [&str; 4] =
    ["WINX_USAGE_LOG", "WINX_USAGE_LOG_ROTATION", "WINX_USAGE_LOG_KEEP_DAYS", "WINX_HTTP_TOKEN"];

/// How remote `Initialize(first_call)` requests select a durable shell session.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, clap::ValueEnum)]
pub enum HttpSessionAffinity {
    /// Reuse one session per authenticated principal and canonical workspace.
    /// This is the safe default for stateless clients whose generated thread IDs
    /// are not stable across reconnects or conversations.
    #[default]
    Workspace,
    /// Reuse one session per principal, conversation identity, and canonical
    /// workspace. `Mcp-Session-Id` is preferred; modern stateless clients fall
    /// back to their supplied first-call `thread_id`, then to workspace affinity.
    /// This separates parallel conversations without giving up workspace context.
    Conversation,
    /// Trust the external `thread_id` as the session key. This preserves parallel
    /// shells in one workspace, but callers must supply a stable ID and clean up
    /// abandoned sessions themselves.
    Thread,
}

/// Parse common human-friendly boolean spellings.
pub fn parse_bool(value: &str) -> Option<bool> {
    match value.trim().to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Some(true),
        "0" | "false" | "no" | "off" | "" => Some(false),
        _ => None,
    }
}

/// Read a boolean environment variable with one consistent spelling policy.
pub fn env_flag(name: &str) -> bool {
    std::env::var(name).ok().as_deref().and_then(parse_bool).unwrap_or(false)
}

/// Read and trim a non-empty environment variable.
pub fn env_text(name: &str) -> Option<String> {
    std::env::var(name).ok().map(|value| value.trim().to_string()).filter(|value| !value.is_empty())
}

/// Default visible-content budget for one `ReadFiles` call. 48 KiB of numbered
/// source is roughly 12-16k tokens: under Claude Code's ~25k-token tool-result
/// cap and claude.ai's ~150k-character cap with room for the structured
/// receipts, and below the sizes at which `ChatGPT` was observed to drop
/// content silently. It leaves the median call (~36 KB) untouched.
pub const DEFAULT_READ_CALL_BUDGET_BYTES: usize = 48 * 1024;
/// Default cap for one whole-file or open-ended read. Files above ~32 KiB
/// (~800 lines) are where an outline plus targeted ranges beats a raw dump, and
/// the remaining 16 KiB of the call budget still serves other batch items.
pub const DEFAULT_READ_FILE_BUDGET_BYTES: usize = 32 * 1024;
/// Default window in which an unchanged repeat is compacted: off. Under
/// workspace affinity a new chat inherits the thread of an earlier one, so it
/// could be told a file is "unchanged" that it never saw. Opt in with
/// `WINX_READ_UNCHANGED_TTL_SECS` (e.g. 900) for per-conversation threads.
pub const DEFAULT_READ_UNCHANGED_TTL_SECS: u64 = 0;
/// Smallest accepted non-zero byte budget; tiny budgets only produce slivers.
pub const MIN_READ_BUDGET_BYTES: usize = 1024;

/// Response-size policy for `ReadFiles`. `None` disables a byte budget.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ReadResponseBudget {
    /// Visible file bytes per call, shared by every item in a batch.
    pub call_bytes: Option<usize>,
    /// Cap for one whole-file or open-ended item. Explicit `start-end` ranges
    /// are deliberate and are bounded only by the call budget.
    pub file_bytes: Option<usize>,
    /// How long an unchanged, still-guarded repeat is compacted. Zero disables.
    pub unchanged_ttl: std::time::Duration,
}

impl Default for ReadResponseBudget {
    fn default() -> Self {
        Self::parse(None, None, None)
    }
}

impl ReadResponseBudget {
    /// Read `WINX_READ_CALL_BUDGET_BYTES`, `WINX_READ_FILE_BUDGET_BYTES` and
    /// `WINX_READ_UNCHANGED_TTL_SECS`.
    pub fn from_env() -> Self {
        Self::parse(
            env_text("WINX_READ_CALL_BUDGET_BYTES").as_deref(),
            env_text("WINX_READ_FILE_BUDGET_BYTES").as_deref(),
            env_text("WINX_READ_UNCHANGED_TTL_SECS").as_deref(),
        )
    }

    /// `0` disables a value; unparsable input keeps the default, and non-zero
    /// byte budgets are raised to [`MIN_READ_BUDGET_BYTES`]. The per-file cap
    /// never exceeds the call budget.
    pub fn parse(call: Option<&str>, file: Option<&str>, ttl: Option<&str>) -> Self {
        fn bytes(value: Option<&str>, default: usize) -> Option<usize> {
            match value.map(str::trim).map(str::parse::<usize>) {
                Some(Ok(0)) => None,
                Some(Ok(bytes)) => Some(bytes.max(MIN_READ_BUDGET_BYTES)),
                Some(Err(_)) | None => Some(default),
            }
        }
        let call_bytes = bytes(call, DEFAULT_READ_CALL_BUDGET_BYTES);
        let file_bytes = bytes(file, DEFAULT_READ_FILE_BUDGET_BYTES)
            .map(|file| call_bytes.map_or(file, |call| file.min(call)));
        let ttl_secs = ttl
            .and_then(|value| value.trim().parse::<u64>().ok())
            .unwrap_or(DEFAULT_READ_UNCHANGED_TTL_SECS);
        Self { call_bytes, file_bytes, unchanged_ttl: std::time::Duration::from_secs(ttl_secs) }
    }
}

/// Authenticated HTTP principal. Only a SHA-256 token digest is retained.
#[derive(Clone)]
pub struct HttpPrincipal {
    name: String,
    id: String,
    token_digest: [u8; 32],
    tool_policy: ToolPolicy,
    weak_token: bool,
}

impl std::fmt::Debug for HttpPrincipal {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("HttpPrincipal")
            .field("name", &self.name)
            .field("id", &self.id)
            .field("tool_policy", &self.tool_policy)
            .field("token", &"[REDACTED]")
            .finish_non_exhaustive()
    }
}

impl HttpPrincipal {
    pub fn new(name: impl Into<String>, token: &str, allow_weak_token: bool) -> Result<Self> {
        Self::new_with_tool_policy(name, token, allow_weak_token, ToolPolicy::default())
    }

    pub fn new_with_tool_policy(
        name: impl Into<String>,
        token: &str,
        allow_weak_token: bool,
        tool_policy: ToolPolicy,
    ) -> Result<Self> {
        let name = name.into().trim().to_string();
        if name.is_empty() {
            return Err(WinxError::ConfigurationError(
                "HTTP principal name cannot be empty".to_string(),
            ));
        }
        if !name
            .chars()
            .all(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '-'))
        {
            return Err(WinxError::ConfigurationError(format!(
                "HTTP principal name {name:?} may contain only ASCII letters, digits, '_' and '-'"
            )));
        }
        validate_http_token(token, allow_weak_token)?;
        let token_digest: [u8; 32] = Sha256::digest(token.as_bytes()).into();
        let id_digest = Sha256::digest(name.as_bytes());
        let id = id_digest[..8].iter().fold(String::with_capacity(16), |mut output, byte| {
            use std::fmt::Write as _;
            let _ = write!(output, "{byte:02x}");
            output
        });
        let weak_token = token.len() < MIN_HTTP_TOKEN_BYTES;
        Ok(Self { name, id, token_digest, tool_policy, weak_token })
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    /// Whether this principal was admitted below the minimum token length
    /// (`--allow-weak-token`). Such a token is guessable, so it keeps the
    /// failed-auth lockout of its source IP.
    pub fn has_weak_token(&self) -> bool {
        self.weak_token
    }

    pub fn session_prefix(&self) -> String {
        format!("p_{}__", self.id)
    }

    pub fn task_prefix(&self) -> String {
        format!("task_{}__", self.id)
    }

    pub fn matches_token(&self, presented: &str) -> bool {
        let digest: [u8; 32] = Sha256::digest(presented.as_bytes()).into();
        constant_time_digest_eq(&self.token_digest, &digest)
    }

    pub fn tool_policy(&self) -> ToolPolicy {
        self.tool_policy
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct PrincipalFile {
    principals: Vec<PrincipalEntry>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct PrincipalEntry {
    name: String,
    token_file: Option<PathBuf>,
    token_env: Option<String>,
    #[serde(default)]
    tool_profile: ToolProfile,
    allowed_tools: Option<Vec<String>>,
}

/// Resolve either a legacy single principal or a multi-principal TOML file.
pub fn load_http_principals(
    principal_config: Option<&Path>,
    command_token: Option<String>,
    command_token_file: Option<&Path>,
    allow_weak_token: bool,
) -> Result<Vec<HttpPrincipal>> {
    load_http_principals_with_policy(
        principal_config,
        command_token,
        command_token_file,
        allow_weak_token,
        ToolPolicy::default(),
    )
}

/// Resolve HTTP principals and apply `single_principal_policy` to legacy
/// `--token`/`--token-file`/environment authentication.
pub fn load_http_principals_with_policy(
    principal_config: Option<&Path>,
    command_token: Option<String>,
    command_token_file: Option<&Path>,
    allow_weak_token: bool,
    single_principal_policy: ToolPolicy,
) -> Result<Vec<HttpPrincipal>> {
    if principal_config.is_some() && (command_token.is_some() || command_token_file.is_some()) {
        return Err(WinxError::ConfigurationError(
            "--principal-config cannot be combined with --token/--token-file".to_string(),
        ));
    }

    let principals = if let Some(path) = principal_config {
        let content = std::fs::read_to_string(path).map_err(|error| {
            WinxError::ConfigurationError(format!(
                "cannot read HTTP principal config {}: {error}",
                path.display()
            ))
        })?;
        let config: PrincipalFile = toml::from_str(&content).map_err(|error| {
            WinxError::ConfigurationError(format!(
                "invalid HTTP principal config {}: {error}",
                path.display()
            ))
        })?;
        if config.principals.is_empty() {
            return Err(WinxError::ConfigurationError(
                "HTTP principal config must contain at least one [[principals]] entry".to_string(),
            ));
        }
        config
            .principals
            .into_iter()
            .map(|entry| {
                let tool_policy =
                    ToolPolicy::resolve(entry.tool_profile, entry.allowed_tools.as_deref())?;
                let token = match (entry.token_file.as_deref(), entry.token_env.as_deref()) {
                    (Some(path), None) => load_secret_file(path)?,
                    (None, Some(name)) => std::env::var(name).map_err(|error| {
                        WinxError::ConfigurationError(format!(
                            "HTTP principal {} token_env {name:?} is unavailable: {error}",
                            entry.name
                        ))
                    })?,
                    (Some(_), Some(_)) => {
                        return Err(WinxError::ConfigurationError(format!(
                            "HTTP principal {} must set exactly one of token_file or token_env",
                            entry.name
                        )))
                    }
                    (None, None) => {
                        return Err(WinxError::ConfigurationError(format!(
                            "HTTP principal {} must set token_file or token_env",
                            entry.name
                        )))
                    }
                };
                HttpPrincipal::new_with_tool_policy(
                    entry.name,
                    token.trim(),
                    allow_weak_token,
                    tool_policy,
                )
            })
            .collect::<Result<Vec<_>>>()?
    } else {
        let token = match (command_token, command_token_file) {
            (Some(_), Some(_)) => {
                return Err(WinxError::ConfigurationError(
                    "provide only one of --token or --token-file".to_string(),
                ))
            }
            (Some(token), None) => token,
            (None, Some(path)) => load_secret_file(path)?,
            (None, None) => env_text("WINX_HTTP_TOKEN").unwrap_or_default(),
        };
        vec![HttpPrincipal::new_with_tool_policy(
            "default",
            token.trim(),
            allow_weak_token,
            single_principal_policy,
        )?]
    };

    reject_duplicate_principals(&principals)?;
    Ok(principals)
}

pub fn load_secret_file(path: &Path) -> Result<String> {
    let metadata = std::fs::symlink_metadata(path).map_err(|error| {
        WinxError::ConfigurationError(format!(
            "cannot inspect secret file {}: {error}",
            path.display()
        ))
    })?;
    if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
        return Err(WinxError::ConfigurationError(format!(
            "secret path {} must be a regular, non-symlink file",
            path.display()
        )));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        let mode = metadata.permissions().mode();
        if mode & 0o077 != 0 {
            return Err(WinxError::ConfigurationError(format!(
                "secret file {} is readable or writable by group/others; use chmod 600",
                path.display()
            )));
        }
    }
    let value = std::fs::read_to_string(path).map_err(|error| {
        WinxError::ConfigurationError(format!(
            "cannot read secret file {}: {error}",
            path.display()
        ))
    })?;
    let value = value.trim().to_string();
    if value.is_empty() {
        return Err(WinxError::ConfigurationError(format!(
            "secret file {} is empty",
            path.display()
        )));
    }
    Ok(value)
}

fn validate_http_token(token: &str, allow_weak_token: bool) -> Result<()> {
    if token.is_empty() {
        return Err(WinxError::ConfigurationError(
            "refusing to start HTTP transport without a token (RCE exposure)".to_string(),
        ));
    }
    if !allow_weak_token && token.len() < MIN_HTTP_TOKEN_BYTES {
        return Err(WinxError::ConfigurationError(format!(
            "HTTP token is too short ({} bytes); use at least {MIN_HTTP_TOKEN_BYTES} bytes or pass --allow-weak-token for local development",
            token.len()
        )));
    }
    Ok(())
}

fn reject_duplicate_principals(principals: &[HttpPrincipal]) -> Result<()> {
    for (index, principal) in principals.iter().enumerate() {
        for other in principals.iter().skip(index + 1) {
            if principal.name == other.name || principal.id == other.id {
                return Err(WinxError::ConfigurationError(format!(
                    "duplicate HTTP principal name {:?}",
                    principal.name
                )));
            }
            if constant_time_digest_eq(&principal.token_digest, &other.token_digest) {
                return Err(WinxError::ConfigurationError(format!(
                    "HTTP principals {:?} and {:?} use the same token",
                    principal.name, other.name
                )));
            }
        }
    }
    Ok(())
}

fn constant_time_digest_eq(left: &[u8; 32], right: &[u8; 32]) -> bool {
    left.iter().zip(right).fold(0_u8, |difference, (left, right)| difference | (left ^ right)) == 0
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]

    #[cfg(unix)]
    use super::{load_http_principals, load_secret_file};
    use super::{parse_bool, HttpPrincipal};

    #[test]
    fn boolean_parser_is_consistent() {
        assert_eq!(parse_bool(" TRUE "), Some(true));
        assert_eq!(parse_bool("yes"), Some(true));
        assert_eq!(parse_bool("off"), Some(false));
        assert_eq!(parse_bool("false"), Some(false));
        assert_eq!(parse_bool("maybe"), None);
    }

    #[test]
    fn principal_keeps_only_a_digest_and_matches_constant_time() {
        let token = "0123456789abcdef0123456789abcdef";
        let principal = HttpPrincipal::new("chatgpt", token, false).expect("valid principal");
        assert!(principal.matches_token(token));
        assert!(!principal.matches_token("0123456789abcdef0123456789abcdeg"));
        assert!(!format!("{principal:?}").contains(token));
    }

    #[test]
    fn read_budget_parsing_has_safe_defaults_bounds_and_opt_outs() {
        use super::{ReadResponseBudget, DEFAULT_READ_CALL_BUDGET_BYTES};
        use std::time::Duration;

        let defaults = ReadResponseBudget::default();
        assert_eq!(defaults.call_bytes, Some(DEFAULT_READ_CALL_BUDGET_BYTES));
        assert_eq!(defaults.file_bytes, Some(32 * 1024));
        assert_eq!(defaults.unchanged_ttl, Duration::ZERO);

        let invalid = ReadResponseBudget::parse(Some("lots"), Some("-1"), Some("soon"));
        assert_eq!(invalid, defaults);

        let disabled = ReadResponseBudget::parse(Some("0"), Some("0"), Some("0"));
        assert_eq!(disabled.call_bytes, None);
        assert_eq!(disabled.file_bytes, None);
        assert!(disabled.unchanged_ttl.is_zero());

        // A per-file cap can never exceed the shared call budget, and tiny
        // budgets are raised to a useful minimum.
        let clamped = ReadResponseBudget::parse(Some("10"), Some("999999"), None);
        assert_eq!(clamped.call_bytes, Some(1024));
        assert_eq!(clamped.file_bytes, Some(1024));
        let file_only = ReadResponseBudget::parse(Some("0"), Some("4096"), None);
        assert_eq!((file_only.call_bytes, file_only.file_bytes), (None, Some(4096)));
    }

    #[cfg(unix)]
    #[test]
    fn secret_file_requires_user_only_permissions() {
        use std::os::unix::fs::PermissionsExt as _;

        let directory = tempfile::TempDir::new().expect("temp directory");
        let secret = directory.path().join("token");
        std::fs::write(&secret, "0123456789abcdef0123456789abcdef\n").expect("write token");
        std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o644))
            .expect("set broad permissions");
        assert!(load_secret_file(&secret).is_err());

        std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o600))
            .expect("set private permissions");
        assert_eq!(
            load_secret_file(&secret).expect("private token"),
            "0123456789abcdef0123456789abcdef"
        );
    }

    #[cfg(unix)]
    #[test]
    fn principal_toml_loads_independent_file_backed_identities() {
        use std::os::unix::fs::PermissionsExt as _;

        let directory = tempfile::TempDir::new().expect("temp directory");
        let left = directory.path().join("left-token");
        let right = directory.path().join("right-token");
        for (path, value) in [
            (&left, "left-0123456789abcdef0123456789abcdef"),
            (&right, "right-0123456789abcdef0123456789abcdef"),
        ] {
            std::fs::write(path, value).expect("write token");
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
                .expect("private token permissions");
        }
        let config = directory.path().join("principals.toml");
        std::fs::write(
            &config,
            format!(
                "[[principals]]\nname = \"left\"\ntoken_file = {left:?}\ntool_profile = \"terminal\"\n\n[[principals]]\nname = \"right\"\ntoken_file = {right:?}\nallowed_tools = [\"Initialize\", \"ReadFiles\"]\n"
            ),
        )
        .expect("write principal config");

        let principals =
            load_http_principals(Some(&config), None, None, false).expect("load principals");
        assert_eq!(principals.len(), 2);
        assert!(principals[0].matches_token("left-0123456789abcdef0123456789abcdef"));
        assert!(principals[1].matches_token("right-0123456789abcdef0123456789abcdef"));
        assert_ne!(principals[0].session_prefix(), principals[1].session_prefix());
        assert_eq!(
            principals[0].tool_policy().names().collect::<Vec<_>>(),
            vec!["Initialize", "BashCommand", "Execution", "Agent"]
        );
        assert_eq!(
            principals[1].tool_policy().names().collect::<Vec<_>>(),
            vec!["Initialize", "ReadFiles"]
        );
    }
}