codex-multi-workspace 0.2.0

Run Codex CLI in Docker across saved single-folder or multi-folder workspaces.
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
use std::fs;
use std::path::{Path, PathBuf};

use serde::Deserialize;
use thiserror::Error;

use crate::runtime::{RuntimeEnvironmentVariable, RuntimeLanguageVersion, RuntimeSpecError};

/// Workspace manifest describing folders and sandbox options.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkspaceManifest {
    name: String,
    folders: Vec<PathBuf>,
    sandbox: SandboxConfig,
    runtime: RuntimeConfig,
}

impl WorkspaceManifest {
    /// Create a workspace manifest.
    ///
    /// # Arguments
    ///
    /// * `name` - Stable workspace name used for session routing.
    /// * `folders` - One or more project folders included in the workspace.
    /// * `sandbox` - Runtime options applied when launching the sandbox.
    ///
    /// # Returns
    ///
    /// A validated workspace manifest.
    ///
    /// # Errors
    ///
    /// Returns [`ManifestError::EmptyName`] when `name` is blank.
    /// Returns [`ManifestError::NoFolders`] when no folders are provided.
    pub fn new(
        name: String,
        folders: Vec<PathBuf>,
        sandbox: SandboxConfig,
    ) -> Result<Self, ManifestError> {
        Self::with_runtime(name, folders, sandbox, RuntimeConfig::default())
    }

    /// Create a workspace manifest with runtime settings.
    ///
    /// # Arguments
    ///
    /// * `name` - Stable workspace name used for session routing.
    /// * `folders` - One or more project folders included in the workspace.
    /// * `sandbox` - Runtime sandbox options applied when launching the sandbox.
    /// * `runtime` - Container runtime image settings for this workspace.
    ///
    /// # Returns
    ///
    /// A validated workspace manifest.
    ///
    /// # Errors
    ///
    /// Returns [`ManifestError::EmptyName`] when `name` is blank.
    /// Returns [`ManifestError::NoFolders`] when no folders are provided.
    /// Returns [`ManifestError::EmptyRuntimeImage`] when `runtime.image` is blank.
    pub fn with_runtime(
        name: String,
        folders: Vec<PathBuf>,
        sandbox: SandboxConfig,
        runtime: RuntimeConfig,
    ) -> Result<Self, ManifestError> {
        if name.trim().is_empty() {
            return Err(ManifestError::EmptyName);
        }

        if folders.is_empty() {
            return Err(ManifestError::NoFolders);
        }

        if runtime.image().is_some_and(|image| image.trim().is_empty()) {
            return Err(ManifestError::EmptyRuntimeImage);
        }

        Ok(Self {
            name,
            folders,
            sandbox,
            runtime,
        })
    }

    /// Return the workspace name.
    ///
    /// # Returns
    ///
    /// The workspace name as a borrowed string slice.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Return workspace folders.
    ///
    /// # Returns
    ///
    /// A slice of folder paths included in this workspace.
    #[must_use]
    pub fn folders(&self) -> &[PathBuf] {
        &self.folders
    }

    /// Return sandbox runtime options.
    ///
    /// # Returns
    ///
    /// The sandbox configuration for this workspace.
    #[must_use]
    pub fn sandbox(&self) -> &SandboxConfig {
        &self.sandbox
    }

    /// Return container runtime options.
    ///
    /// # Returns
    ///
    /// The runtime configuration for this workspace.
    #[must_use]
    pub fn runtime(&self) -> &RuntimeConfig {
        &self.runtime
    }
}

/// Sandbox options loaded from a workspace manifest.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SandboxConfig {
    network: bool,
}

impl Default for SandboxConfig {
    fn default() -> Self {
        Self { network: true }
    }
}

impl SandboxConfig {
    /// Create a sandbox configuration.
    ///
    /// # Arguments
    ///
    /// * `network` - Whether the sandbox should allow network access.
    ///
    /// # Returns
    ///
    /// A sandbox configuration value.
    #[must_use]
    pub const fn new(network: bool) -> Self {
        Self { network }
    }

    /// Return whether sandbox network access is enabled.
    ///
    /// # Returns
    ///
    /// `true` when network access is enabled.
    #[must_use]
    pub const fn network(&self) -> bool {
        self.network
    }
}

/// Container runtime options loaded from a workspace manifest.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuntimeConfig {
    image: Option<String>,
    language_versions: Vec<RuntimeLanguageVersion>,
}

impl RuntimeConfig {
    /// Create a runtime configuration.
    ///
    /// # Arguments
    ///
    /// * `image` - Optional Docker image used for this workspace.
    ///
    /// # Returns
    ///
    /// A runtime configuration value.
    #[must_use]
    pub fn new(image: Option<String>) -> Self {
        Self {
            image,
            language_versions: Vec::new(),
        }
    }

    /// Create a runtime configuration with language versions.
    ///
    /// # Arguments
    ///
    /// * `image` - Optional Docker image used for this workspace.
    /// * `language_versions` - Codex Universal language runtimes requested by the workspace.
    ///
    /// # Returns
    ///
    /// A runtime configuration value.
    #[must_use]
    pub fn with_language_versions(
        image: Option<String>,
        language_versions: Vec<RuntimeLanguageVersion>,
    ) -> Self {
        Self {
            image,
            language_versions,
        }
    }

    /// Return the workspace-specific Docker image.
    ///
    /// # Returns
    ///
    /// `Some(image)` when the manifest selects a runtime image, otherwise `None`.
    #[must_use]
    pub fn image(&self) -> Option<&str> {
        self.image.as_deref()
    }

    /// Return selected language runtime versions.
    ///
    /// # Returns
    ///
    /// Language runtimes requested by this workspace.
    #[must_use]
    pub fn language_versions(&self) -> &[RuntimeLanguageVersion] {
        &self.language_versions
    }

    /// Return Docker environment variables for Codex Universal.
    ///
    /// # Returns
    ///
    /// `CODEX_ENV_*` variables generated from configured language runtimes.
    #[must_use]
    pub fn environment_variables(&self) -> Vec<RuntimeEnvironmentVariable> {
        self.language_versions
            .iter()
            .map(RuntimeLanguageVersion::environment_variable)
            .collect()
    }
}

/// Errors returned while loading or validating workspace manifests.
#[derive(Debug, Error)]
pub enum ManifestError {
    /// The manifest file could not be read.
    #[error("failed to read workspace manifest '{path}': {source}")]
    Read {
        /// Manifest path that failed to read.
        path: PathBuf,
        /// Underlying I/O error.
        source: std::io::Error,
    },

    /// The manifest YAML could not be parsed.
    #[error("invalid workspace manifest YAML: {0}")]
    Yaml(#[from] serde_yaml::Error),

    /// The workspace name was empty or only whitespace.
    #[error("workspace manifest name cannot be empty")]
    EmptyName,

    /// The workspace did not include any folders.
    #[error("workspace manifest must include at least one folder")]
    NoFolders,

    /// The workspace runtime image was empty or only whitespace.
    #[error("workspace manifest runtime image cannot be empty")]
    EmptyRuntimeImage,

    /// The workspace runtime language selection was invalid.
    #[error("invalid workspace runtime: {0}")]
    RuntimeSpec(#[from] RuntimeSpecError),

    /// A workspace folder path does not exist.
    #[error("workspace folder '{path}' does not exist")]
    FolderMissing {
        /// Missing workspace folder path.
        path: PathBuf,
    },

    /// A workspace folder path exists but is not a directory.
    #[error("workspace folder '{path}' is not a directory")]
    FolderNotDirectory {
        /// Non-directory workspace folder path.
        path: PathBuf,
    },
}

#[derive(Debug, Deserialize)]
struct RawWorkspaceManifest {
    name: String,
    folders: Vec<PathBuf>,
    #[serde(default)]
    sandbox: RawSandboxConfig,
    #[serde(default)]
    runtime: Option<RawRuntimeConfig>,
}

#[derive(Debug, Deserialize)]
struct RawSandboxConfig {
    #[serde(default = "default_sandbox_network")]
    network: bool,
}

impl Default for RawSandboxConfig {
    fn default() -> Self {
        Self {
            network: default_sandbox_network(),
        }
    }
}

const fn default_sandbox_network() -> bool {
    true
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RawRuntimeConfig {
    Spec(String),
    Specs(Vec<String>),
    Map(RawRuntimeMap),
}

#[derive(Debug, Default, Deserialize)]
struct RawRuntimeMap {
    image: Option<String>,
    #[serde(default)]
    languages: Vec<String>,
}

impl TryFrom<RawWorkspaceManifest> for WorkspaceManifest {
    type Error = ManifestError;

    fn try_from(raw: RawWorkspaceManifest) -> Result<Self, Self::Error> {
        let runtime = raw.runtime.unwrap_or_default().try_into()?;
        Self::with_runtime(
            raw.name,
            raw.folders,
            SandboxConfig::new(raw.sandbox.network),
            runtime,
        )
    }
}

impl Default for RawRuntimeConfig {
    fn default() -> Self {
        Self::Map(RawRuntimeMap::default())
    }
}

impl TryFrom<RawRuntimeConfig> for RuntimeConfig {
    type Error = ManifestError;

    fn try_from(raw: RawRuntimeConfig) -> Result<Self, Self::Error> {
        match raw {
            RawRuntimeConfig::Spec(spec) => runtime_from_parts(None, vec![spec]),
            RawRuntimeConfig::Specs(specs) => runtime_from_parts(None, specs),
            RawRuntimeConfig::Map(map) => runtime_from_parts(map.image, map.languages),
        }
    }
}

fn runtime_from_parts(
    image: Option<String>,
    specs: Vec<String>,
) -> Result<RuntimeConfig, ManifestError> {
    let image = image.map(|runtime_image| runtime_image.trim().to_owned());
    let language_versions = crate::runtime::parse_runtime_specs(&specs)?;

    Ok(RuntimeConfig::with_language_versions(
        image,
        language_versions,
    ))
}

/// Load a workspace manifest from a YAML file.
///
/// # Arguments
///
/// * `manifest_path` - Path to the YAML workspace manifest.
///
/// # Returns
///
/// A validated workspace manifest.
///
/// # Errors
///
/// Returns [`ManifestError::Read`] when the file cannot be read.
/// Returns [`ManifestError::Yaml`] when YAML parsing fails.
/// Returns validation errors when required fields are missing or invalid.
pub fn load_workspace_manifest(manifest_path: &Path) -> Result<WorkspaceManifest, ManifestError> {
    let manifest_yaml =
        fs::read_to_string(manifest_path).map_err(|source| ManifestError::Read {
            path: manifest_path.to_path_buf(),
            source,
        })?;
    parse_workspace_manifest(&manifest_yaml)
}

/// Parse a workspace manifest from YAML.
///
/// # Arguments
///
/// * `manifest_yaml` - YAML text containing workspace manifest fields.
///
/// # Returns
///
/// A validated workspace manifest.
///
/// # Errors
///
/// Returns [`ManifestError::Yaml`] when YAML parsing fails.
/// Returns validation errors when required fields are missing or invalid.
pub fn parse_workspace_manifest(manifest_yaml: &str) -> Result<WorkspaceManifest, ManifestError> {
    let raw_manifest = serde_yaml::from_str::<RawWorkspaceManifest>(manifest_yaml)?;
    raw_manifest.try_into()
}

/// Validate that every workspace folder exists and is a directory.
///
/// # Arguments
///
/// * `manifest` - Workspace manifest whose folders should be checked.
///
/// # Returns
///
/// `Ok(())` when all workspace folders exist and are directories.
///
/// # Errors
///
/// Returns [`ManifestError::FolderMissing`] when a folder path does not exist.
/// Returns [`ManifestError::FolderNotDirectory`] when a folder path is not a directory.
pub fn validate_workspace_folders(manifest: &WorkspaceManifest) -> Result<(), ManifestError> {
    for folder in manifest.folders() {
        if !folder.exists() {
            return Err(ManifestError::FolderMissing {
                path: folder.clone(),
            });
        }

        if !folder.is_dir() {
            return Err(ManifestError::FolderNotDirectory {
                path: folder.clone(),
            });
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::{SystemTime, UNIX_EPOCH};

    use super::*;

    static TEMP_DIR_COUNTER: AtomicUsize = AtomicUsize::new(0);

    #[derive(Debug)]
    struct TestTempDir {
        path: PathBuf,
    }

    impl TestTempDir {
        fn create() -> Self {
            let counter = TEMP_DIR_COUNTER.fetch_add(1, Ordering::Relaxed);
            let timestamp = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .expect("system clock should be after Unix epoch")
                .as_nanos();
            let path = std::env::temp_dir().join(format!(
                "codex-ws-test-{}-{timestamp}-{counter}",
                std::process::id()
            ));
            fs::create_dir(&path).expect("temporary test directory should be created");
            Self { path }
        }

        fn path(&self) -> &Path {
            &self.path
        }
    }

    impl Drop for TestTempDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.path);
        }
    }

    #[test]
    fn parse_workspace_manifest_supports_multiple_folders_and_network() {
        let manifest = parse_workspace_manifest(
            r#"
name: workspace-name
folders:
  - /projects/backend
  - /projects/frontend
sandbox:
  network: true
"#,
        )
        .expect("manifest should parse");

        assert_eq!(manifest.name(), "workspace-name");
        assert_eq!(
            manifest.folders(),
            &[
                PathBuf::from("/projects/backend"),
                PathBuf::from("/projects/frontend")
            ]
        );
        assert!(manifest.sandbox().network());
        assert_eq!(manifest.runtime().image(), None);
    }

    #[test]
    fn parse_workspace_manifest_supports_single_folder() {
        let manifest = parse_workspace_manifest(
            r#"
name: single-project
folders:
  - /projects/backend
"#,
        )
        .expect("manifest should parse");

        assert_eq!(manifest.name(), "single-project");
        assert_eq!(manifest.folders(), &[PathBuf::from("/projects/backend")]);
        assert!(manifest.sandbox().network());
        assert_eq!(manifest.runtime().image(), None);
    }

    #[test]
    fn parse_workspace_manifest_supports_runtime_image() {
        let manifest = parse_workspace_manifest(
            r#"
name: rust-project
folders:
  - /projects/rust-project
runtime:
  image: rust-codex-ws:latest
"#,
        )
        .expect("manifest should parse");

        assert_eq!(manifest.runtime().image(), Some("rust-codex-ws:latest"));
    }

    #[test]
    fn parse_workspace_manifest_supports_scalar_runtime_spec() {
        let manifest = parse_workspace_manifest(
            r#"
name: go-project
folders:
  - /projects/go-project
runtime: golang:1.25.1
"#,
        )
        .expect("manifest should parse");

        assert_eq!(
            manifest.runtime().environment_variables()[0].docker_assignment(),
            "CODEX_ENV_GO_VERSION=1.25.1"
        );
    }

    #[test]
    fn parse_workspace_manifest_supports_runtime_spec_list() {
        let manifest = parse_workspace_manifest(
            r#"
name: web-project
folders:
  - /projects/web-project
runtime:
  - node:22
  - python:3.13
"#,
        )
        .expect("manifest should parse");

        let variables = manifest.runtime().environment_variables();
        assert_eq!(
            variables
                .iter()
                .map(crate::runtime::RuntimeEnvironmentVariable::docker_assignment)
                .collect::<Vec<_>>(),
            vec![
                "CODEX_ENV_NODE_VERSION=22".to_owned(),
                "CODEX_ENV_PYTHON_VERSION=3.13".to_owned()
            ]
        );
    }

    #[test]
    fn parse_workspace_manifest_supports_runtime_map_languages() {
        let manifest = parse_workspace_manifest(
            r#"
name: mixed-project
folders:
  - /projects/mixed-project
runtime:
  languages:
    - rust:1.95.0
    - java:21
"#,
        )
        .expect("manifest should parse");

        let variables = manifest.runtime().environment_variables();
        assert_eq!(
            variables
                .iter()
                .map(crate::runtime::RuntimeEnvironmentVariable::docker_assignment)
                .collect::<Vec<_>>(),
            vec![
                "CODEX_ENV_RUST_VERSION=1.95.0".to_owned(),
                "CODEX_ENV_JAVA_VERSION=21".to_owned()
            ]
        );
    }

    #[test]
    fn parse_workspace_manifest_rejects_empty_name() {
        let error = parse_workspace_manifest(
            r#"
name: " "
folders:
  - /projects/backend
"#,
        )
        .expect_err("blank name should fail");

        assert!(matches!(error, ManifestError::EmptyName));
    }

    #[test]
    fn parse_workspace_manifest_rejects_empty_folders() {
        let error = parse_workspace_manifest(
            r#"
name: empty-workspace
folders: []
"#,
        )
        .expect_err("empty folders should fail");

        assert!(matches!(error, ManifestError::NoFolders));
    }

    #[test]
    fn parse_workspace_manifest_rejects_empty_runtime_image() {
        let error = parse_workspace_manifest(
            r#"
name: workspace
folders:
  - /projects/backend
runtime:
  image: " "
"#,
        )
        .expect_err("blank runtime image should fail");

        assert!(matches!(error, ManifestError::EmptyRuntimeImage));
    }

    #[test]
    fn parse_workspace_manifest_rejects_unsupported_runtime_versions() {
        let error = parse_workspace_manifest(
            r#"
name: workspace
folders:
  - /projects/backend
runtime: go:1.99.0
"#,
        )
        .expect_err("unsupported runtime version should fail");

        assert!(matches!(
            error,
            ManifestError::RuntimeSpec(crate::runtime::RuntimeSpecError::UnsupportedVersion {
                language: crate::runtime::RuntimeLanguage::Go,
                version
            }) if version == "1.99.0"
        ));
    }

    #[test]
    fn validate_workspace_folders_accepts_existing_directories() {
        let temp_dir = TestTempDir::create();
        let folder = temp_dir.path().join("project");
        fs::create_dir(&folder).expect("workspace folder should be created");
        let manifest = WorkspaceManifest::new(
            "workspace".to_owned(),
            vec![folder],
            SandboxConfig::default(),
        )
        .expect("manifest should be valid");

        validate_workspace_folders(&manifest).expect("folder validation should pass");
    }

    #[test]
    fn validate_workspace_folders_rejects_missing_paths() {
        let temp_dir = TestTempDir::create();
        let missing_folder = temp_dir.path().join("missing");
        let manifest = WorkspaceManifest::new(
            "workspace".to_owned(),
            vec![missing_folder.clone()],
            SandboxConfig::default(),
        )
        .expect("manifest should be valid");

        let error = validate_workspace_folders(&manifest).expect_err("missing folder should fail");

        assert!(matches!(
            error,
            ManifestError::FolderMissing { path } if path == missing_folder
        ));
    }

    #[test]
    fn validate_workspace_folders_rejects_files() {
        let temp_dir = TestTempDir::create();
        let file_path = temp_dir.path().join("file.txt");
        fs::write(&file_path, "not a directory").expect("file should be written");
        let manifest = WorkspaceManifest::new(
            "workspace".to_owned(),
            vec![file_path.clone()],
            SandboxConfig::default(),
        )
        .expect("manifest should be valid");

        let error = validate_workspace_folders(&manifest).expect_err("file path should fail");

        assert!(matches!(
            error,
            ManifestError::FolderNotDirectory { path } if path == file_path
        ));
    }
}