halo-agent 0.1.0

Halo Agent and Workflow execution kernel
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
//! One persistent, application-selected container for file and command tools.
//! Construction performs no Docker I/O. The first asynchronous operation starts
//! the environment; it is never silently replaced by a fresh, empty container.

use std::sync::Arc;
use std::{collections::BTreeMap, path::PathBuf};

use serde_json::{Value, json};
use tokio::sync::{Mutex, RwLock};

use super::tools;
use crate::{
    Cancellation, Error,
    components::{mcp::Server, skill::Skill},
    core::{
        agent::dispatch::{Dispatch, ToolInputs},
        operation::{cancellable, check},
        sandbox::docker as sandbox,
    },
    workspace::{Definition, Mode},
};

mod files;

/// Image and resource limits reuse the existing Docker Sandbox configuration.
/// No host directory is mounted unless `host_workdir` is explicitly provided.
/// The prepared Linux image must provide /bin/sh, sleep, cat, mkdir, mv, rm and
/// find (including -print0, -mindepth and -maxdepth). Nothing is installed.
#[derive(Clone)]
pub struct Config {
    pub sandbox: sandbox::Config,
    pub workdir: String,
    pub host_workdir: Option<PathBuf>,
    pub env: BTreeMap<String, String>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            sandbox: Default::default(),
            workdir: "/workspace".into(),
            host_workdir: None,
            env: Default::default(),
        }
    }
}

#[derive(Clone)]
pub struct Docker {
    backend: std::sync::Arc<Backend>,
    definition: Definition,
    dispatch: Dispatch,
    pub(super) discover_skills: bool,
    pub(super) access: Arc<RwLock<()>>,
    pub(super) skill_cache: tools::SkillCache,
}

impl Docker {
    /// Validate/store settings only. No CLI invocation, image pull, installation
    /// or host execution fallback. File operations lazily initialize once.
    pub fn new(config: Config) -> Result<Self, Error> {
        config.sandbox.validate()?;
        let relative = config
            .workdir
            .strip_prefix('/')
            .ok_or_else(|| Error::new("INVALID_ARGUMENTS", "Docker workdir must be absolute"))?;
        super::validate_path(relative)?;
        if config.workdir.contains([',', ':'])
            || config.workdir.chars().any(char::is_control)
            || config
                .host_workdir
                .as_ref()
                .is_some_and(|path| path.to_str().is_none_or(|text| text.contains([',', '\0'])))
            || config.env.iter().any(|(key, value)| {
                key.is_empty()
                    || !key.bytes().enumerate().all(|(i, byte)| {
                        byte == b'_'
                            || byte.is_ascii_alphabetic()
                            || (i > 0 && byte.is_ascii_digit())
                    })
                    || value.contains('\0')
            })
        {
            return Err(Error::new(
                "INVALID_ARGUMENTS",
                "invalid Docker workspace configuration",
            ));
        }
        Ok(Self {
            definition: Definition {
                mode: Mode::Local,
                // Container path, not a fictional host directory. No secrets
                // or host mount configuration enter the public definition.
                path: Some(config.workdir.clone()),
                metadata: serde_json::Map::from_iter([("environment".into(), json!("docker"))]),
            },
            backend: std::sync::Arc::new(Backend {
                config,
                state: Mutex::new(State::New),
            }),
            dispatch: Dispatch::new(),
            discover_skills: false,
            access: Arc::new(RwLock::new(())),
            skill_cache: Arc::new(RwLock::new(None)),
        })
    }

    /// Discover `skills/<name>/SKILL.md` inside this container for each run.
    /// Opt-in because discovery starts the container before model dispatch or
    /// Tool permission checks; the default preserves no-I/O construction.
    pub fn with_skill_discovery(mut self) -> Self {
        self.discover_skills = true;
        self
    }

    /// Register application Tools on this Workspace.
    #[allow(private_bounds)]
    pub fn tools<I>(mut self, tools: I) -> Self
    where
        I: ToolInputs,
    {
        self.dispatch = self.dispatch.tools(tools);
        self
    }

    /// Register already connected and discovered MCP servers on this Workspace.
    #[allow(private_bounds)]
    pub fn mcps<S>(mut self, servers: impl IntoIterator<Item = S>) -> Self
    where
        S: Server + 'static,
    {
        self.dispatch = self.dispatch.mcps(servers);
        self
    }

    /// Register in-process Skills on this Workspace.
    #[allow(private_bounds)]
    pub fn skills<S>(mut self, skills: impl IntoIterator<Item = S>) -> Result<Self, Error>
    where
        S: Skill + 'static,
    {
        self.dispatch = self.dispatch.skills(skills)?;
        Ok(self)
    }

    pub async fn list(
        &self,
        path: &str,
        recursive: bool,
        cancellation: &Cancellation,
    ) -> Result<Vec<String>, Error> {
        self.backend.list(path, recursive, cancellation).await
    }

    pub async fn read(&self, path: &str, cancellation: &Cancellation) -> Result<Vec<u8>, Error> {
        self.backend.read(path, cancellation).await
    }

    pub async fn write(
        &self,
        path: &str,
        data: Vec<u8>,
        cancellation: &Cancellation,
    ) -> Result<(), Error> {
        self.backend.write(path, data, cancellation).await
    }

    pub async fn delete(&self, path: &str, cancellation: &Cancellation) -> Result<(), Error> {
        self.backend.delete(path, cancellation).await
    }

    /// Deterministic release for direct users. Closing is terminal and does not
    /// remove host-mounted files. Tool-owned environments are released when
    /// their final owner is dropped; keep Tokio alive for best-effort cleanup.
    pub async fn close(&self) -> Result<(), Error> {
        tokio::runtime::Handle::try_current()
            .map_err(|_| Error::new("UNAVAILABLE", "Docker workspace requires a Tokio runtime"))?;
        let mut state = self.backend.state.lock().await;
        if let State::Ready(mut container) = std::mem::replace(&mut *state, State::Closed) {
            container.guard.cleanup().await?;
        }
        Ok(())
    }

    pub(super) async fn command(
        &self,
        input: Value,
        cancellation: &Cancellation,
    ) -> Result<Value, Error> {
        #[derive(serde::Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Input {
            args: Vec<String>,
        }
        let input: Input = serde_json::from_value(input)
            .map_err(|_| Error::new("INVALID_ARGUMENTS", "command input requires args"))?;
        if input.args.is_empty()
            || input.args[0].trim().is_empty()
            || input.args.iter().any(|arg| arg.contains('\0'))
            || input.args.iter().map(String::len).sum::<usize>() > 1024 * 1024
        {
            return Err(Error::new(
                "INVALID_ARGUMENTS",
                "invalid sandbox command arguments",
            ));
        }
        let output = self
            .backend
            .execute(&input.args, None, cancellation)
            .await?;
        let stdout = String::from_utf8(output.stdout)
            .map_err(|_| Error::new("INVALID_RESPONSE", "sandbox stdout is not UTF-8"))?;
        let stderr = String::from_utf8(output.stderr)
            .map_err(|_| Error::new("INVALID_RESPONSE", "sandbox stderr is not UTF-8"))?;
        let data = json!({"stdout":stdout,"stderr":stderr,"exit_code":output.code});
        if output.code != 0 {
            return Err(Error::new("EXECUTION_FAILED", "sandbox command failed")
                .with_details(data.to_string()));
        }
        Ok(data)
    }
}

impl From<Docker> for Dispatch {
    fn from(mut workspace: Docker) -> Self {
        let dispatch = std::mem::take(&mut workspace.dispatch);
        tools::attach(tools::Files::Docker(workspace), dispatch)
    }
}

impl Docker {
    /// Internal Tool catalog used to implement the Workspace contract.
    pub(super) fn tool_catalog(&self) -> Vec<crate::tool::ToolDefinition> {
        Dispatch::from(self.clone()).tool_catalog()
    }

    pub(super) fn mcp_catalog(&self) -> Vec<crate::mcp::Definition> {
        Dispatch::from(self.clone()).mcp_catalog()
    }

    pub(super) fn skill_catalog(&self) -> Vec<crate::skill::Definition> {
        self.dispatch.skill_catalog()
    }

    /// Execute one configured or built-in Workspace Tool.
    pub async fn execute(
        &self,
        call: crate::tool::Call,
        cancellation: &Cancellation,
    ) -> Result<(crate::Message, crate::tool::Evaluation), Error> {
        Dispatch::from(self.clone())
            .execute(call, cancellation)
            .await
    }
}

impl crate::workspace::Workspace for Docker {
    fn definition(&self) -> &Definition {
        &self.definition
    }

    fn tool(&self) -> Vec<crate::tool::ToolDefinition> {
        self.tool_catalog()
    }

    fn mcp(&self) -> Vec<crate::mcp::Definition> {
        self.mcp_catalog()
    }

    fn skill(&self) -> Vec<crate::skill::Definition> {
        self.skill_catalog()
    }

    fn execute<'a>(
        &'a self,
        call: crate::tool::Call,
        cancellation: &'a Cancellation,
    ) -> crate::workspace::ToolFuture<'a> {
        Box::pin(self.execute(call, cancellation))
    }
}

// This is private backend lifecycle state, not Runtime or a second Workspace
// component protocol. Serializing exec also makes cancellation cleanup safe.
struct Backend {
    config: Config,
    state: Mutex<State>,
}
enum State {
    New,
    Ready(Container),
    Closed,
}
struct Container {
    id: String,
    guard: sandbox::Guard,
}

impl Backend {
    async fn execute(
        &self,
        args: &[String],
        input: Option<&[u8]>,
        cancellation: &Cancellation,
    ) -> Result<sandbox::Bytes, Error> {
        check(cancellation)?;
        tokio::runtime::Handle::try_current()
            .map_err(|_| Error::new("UNAVAILABLE", "Docker workspace requires a Tokio runtime"))?;
        let mut state = cancellable(async { Ok(self.state.lock().await) }, cancellation).await?;
        // Ownership moves into this operation. If its Future is dropped, the
        // guard cleans up, and the shared state stays Closed, never New.
        let (mut container, initialize) = match std::mem::replace(&mut *state, State::Closed) {
            State::New => (
                Container {
                    id: String::new(),
                    guard: sandbox::Guard::new("docker".into(), "heart-workspace"),
                },
                true,
            ),
            State::Ready(container) => (container, false),
            State::Closed => return Err(Error::new("UNAVAILABLE", "Docker workspace is closed")),
        };
        let result = cancellable(
            async {
                tokio::time::timeout(self.config.sandbox.timeout, async {
                    if initialize {
                        self.initialize(&mut container).await?;
                    }
                    let mut command = vec!["exec".into()];
                    if input.is_some() {
                        command.push("--interactive".into());
                    }
                    command.extend([
                        "--workdir".into(),
                        self.config.workdir.clone(),
                        "--".into(),
                        container.id.clone(),
                    ]);
                    command.extend_from_slice(args);
                    let output = sandbox::cli_bytes(
                        std::path::Path::new("docker"),
                        &command,
                        input,
                        self.config.sandbox.max_output,
                    )
                    .await?;
                    // Distinguish a failed command from a lost/stopped environment.
                    self.running(&container.id).await?;
                    Ok(output)
                })
                .await
                .map_err(|_| Error::new("TIMEOUT", "workspace operation timed out"))?
            },
            cancellation,
        )
        .await;
        match result {
            Ok(output) => {
                *state = State::Ready(container);
                Ok(output)
            }
            Err(error) => {
                // Killing the CLI alone does not kill docker exec. Close the
                // owned container so an unknown writer cannot keep running
                // behind later file operations. Never retry on a fresh image.
                if let Err(cleanup) = container.guard.cleanup().await {
                    eprintln!("workspace cleanup failed: {}", cleanup.code);
                }
                Err(error)
            }
        }
    }

    async fn initialize(&self, container: &mut Container) -> Result<(), Error> {
        let mut args = vec![
            "create".into(),
            "--name".into(),
            container.guard.name().into(),
            "--label".into(),
            format!("{}={}", sandbox::LABEL, container.guard.token()),
        ];
        args.extend(self.config.sandbox.create_args());
        if self.config.workdir != "/tmp" {
            args.extend([
                "--tmpfs".into(),
                "/tmp:rw,nosuid,nodev,size=64m,mode=1777".into(),
            ]);
        }
        if let Some(host) = &self.config.host_workdir {
            let host = tokio::fs::canonicalize(host)
                .await
                .map_err(super::io_error)?;
            if !tokio::fs::metadata(&host)
                .await
                .map_err(super::io_error)?
                .is_dir()
            {
                return Err(Error::new(
                    "INVALID_ARGUMENTS",
                    "host_workdir must be an existing directory",
                ));
            }
            let host = host
                .to_str()
                .filter(|path| !path.contains([',', '\0']))
                .ok_or_else(|| Error::new("INVALID_ARGUMENTS", "unsupported host_workdir path"))?;
            args.extend([
                "--mount".into(),
                format!("type=bind,source={host},target={}", self.config.workdir),
            ]);
        } else {
            args.extend([
                "--tmpfs".into(),
                format!(
                    "{}:rw,nosuid,nodev,size={},mode=1777",
                    self.config.workdir, self.config.sandbox.memory
                ),
            ]);
        }
        for (name, value) in &self.config.env {
            args.extend(["--env".into(), format!("{name}={value}")]);
        }
        args.extend(["--workdir".into(), self.config.workdir.clone(), "--entrypoint".into(), "/bin/sh".into(),
            self.config.sandbox.image.clone(), "-c".into(),
            "for cmd in sleep cat mkdir mv rm find; do command -v \"$cmd\" >/dev/null || exit 127; done; trap 'exit 0' TERM INT; while :; do sleep 3600 & wait \"$!\"; done".into()]);
        let created = sandbox::cli_bytes(std::path::Path::new("docker"), &args, None, 4096).await?;
        // Do not copy Docker stderr: it can echo explicit environment secrets.
        if created.code != 0 {
            return Err(Error::new(
                "UNAVAILABLE",
                "Docker could not create workspace",
            ));
        }
        let id = std::str::from_utf8(&created.stdout)
            .unwrap_or_default()
            .trim();
        if !sandbox::container_id(id) {
            return Err(Error::new(
                "INVALID_RESPONSE",
                "invalid Docker container ID",
            ));
        }
        container.id = id.into();
        let started = sandbox::cli_bytes(
            std::path::Path::new("docker"),
            &["start".into(), id.into()],
            None,
            4096,
        )
        .await?;
        if started.code != 0 {
            return Err(Error::new(
                "UNAVAILABLE",
                "Docker could not start workspace",
            ));
        }
        self.running(id).await
    }

    async fn running(&self, id: &str) -> Result<(), Error> {
        let inspected = sandbox::cli_bytes(
            std::path::Path::new("docker"),
            &[
                "inspect".into(),
                "--format".into(),
                "{{json .State}}".into(),
                id.into(),
            ],
            None,
            4096,
        )
        .await?;
        if inspected.code != 0 {
            return Err(Error::new(
                "UNAVAILABLE",
                "Docker workspace could not be inspected",
            ));
        }
        let state: Value = serde_json::from_slice(&inspected.stdout)
            .map_err(|_| Error::new("INVALID_RESPONSE", "invalid Docker workspace state"))?;
        if state.get("OOMKilled").and_then(Value::as_bool) == Some(true) {
            return Err(Error::new(
                "RESOURCE_EXHAUSTED",
                "workspace memory limit exceeded",
            ));
        }
        if state.get("Running").and_then(Value::as_bool) != Some(true) {
            return Err(Error::new("UNAVAILABLE", "Docker workspace is not running"));
        }
        Ok(())
    }
}