tnk 0.1.5

Zero-trust sandbox for local inference and secure AI coding agent runtimes.
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
// Copyright 2026 tappunk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "IS BASIS",
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

pub mod container;
pub mod container_utils;
pub mod lima;
pub mod shared;
pub mod types;

use shared::load_profile_manifest;

use async_trait::async_trait;
use serde::Serialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::config;

#[derive(serde::Deserialize, Debug, Clone, Default)]
pub struct SandboxManifest {
    pub image: Option<String>,
    pub resources: Option<ResourceLimits>,
    pub mounts: Option<HashMap<String, String>>,
    pub security: Option<SecurityCaps>,
}

#[derive(serde::Deserialize, Debug, Clone, Default)]
pub struct ResourceLimits {
    pub cpus: Option<u32>,
    pub memory: Option<String>,
}

#[derive(serde::Deserialize, Debug, Clone, Default)]
pub struct SecurityCaps {
    pub network: Option<String>,
    pub workspace_mode: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Runtime {
    Container,
    #[default]
    Lima,
}

impl Runtime {
    pub fn as_str(&self) -> &'static str {
        match self {
            Runtime::Container => "container",
            Runtime::Lima => "lima",
        }
    }

    pub fn try_from_str(s: &str) -> Option<Self> {
        match s {
            "container" => Some(Runtime::Container),
            "lima" => Some(Runtime::Lima),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct SandboxEntry {
    pub id: String,
    pub status: String,
    pub mount: String,
}

pub fn resolve_runtime(
    runtime_flag: Option<String>,
    default_sandbox_runtime: Option<String>,
) -> Result<Runtime, color_eyre::Report> {
    if let Some(flag) = runtime_flag {
        return Runtime::try_from_str(&flag)
            .ok_or_else(|| color_eyre::eyre::eyre!("unsupported sandbox runtime: {}", flag));
    }
    Ok(default_sandbox_runtime
        .as_deref()
        .and_then(Runtime::try_from_str)
        .unwrap_or_default())
}

#[derive(Debug, Clone, Default)]
pub struct ProfileSettings {
    pub cpus: Option<u32>,
    pub memory: Option<String>,
    pub network_none: bool,
    pub workspace_guest_path: String,
    pub image: String,
    pub uses_golden_image: bool,
}

#[async_trait]
#[allow(clippy::too_many_arguments)]
pub trait SandboxBackend: Sized {
    const BINARY: &'static str;

    async fn resolve_id() -> Result<(String, PathBuf, PathBuf), color_eyre::Report>;

    async fn start(
        profile_name: String,
        audit_log: Option<String>,
        settings: &ProfileSettings,
        runtime_envs: &[(String, String)],
    ) -> Result<(), color_eyre::Report>;

    async fn shell(
        profile: Option<String>,
        command: Option<String>,
        no_tty: bool,
        explicit_envs: Vec<String>,
        audit_log: Option<String>,
        settings: &ProfileSettings,
        runtime_envs: &[(String, String)],
    ) -> Result<(), color_eyre::Report>;

    async fn stop(names: Vec<String>, all: bool) -> Result<(), color_eyre::Report>;

    async fn delete(id: &str, force: bool) -> Result<(), color_eyre::Report>;

    async fn ls() -> Result<Vec<SandboxEntry>, color_eyre::Report>;

    async fn exists(id: &str) -> Result<bool, color_eyre::Report>;

    async fn is_running(id: &str) -> Result<bool, color_eyre::Report>;

    async fn cleanup_untracked(verbose: bool) -> Result<(), color_eyre::Report>;

    async fn provision(
        id: &str,
        profile_name: &str,
        engine_runtime: &str,
        model_name: &str,
        ctx_window: u32,
        mount_point: &Path,
        port: u16,
        settings: &ProfileSettings,
    ) -> Result<(), color_eyre::Report>;

    async fn build_golden_image(profile_name: String) -> Result<(), color_eyre::Report>;

    async fn resolve_gateway(id: &str) -> Result<String, color_eyre::Report>;

    async fn runtime_env(
        id: &str,
        port: u16,
        engine_runtime: &str,
        model_name: &str,
    ) -> Result<Vec<(String, String)>, color_eyre::Report>;

    async fn resolve_active_model_and_ctx(
        port: u16,
        engine_runtime: &str,
    ) -> Result<(String, u32), color_eyre::Report>;
}

pub trait BackendRuntimeContract {
    fn host_gateway_url(port: u16) -> String;
    fn inference_url(host: &str, port: u16) -> String;
    fn mcp_bridge_url(host: &str) -> String;
    fn searxng_url(host: &str) -> String;
}

impl BackendRuntimeContract for Runtime {
    fn host_gateway_url(port: u16) -> String {
        format!("http://127.0.0.1:{}", port)
    }

    fn inference_url(host: &str, port: u16) -> String {
        format!("http://{}:{}/v1", host, port)
    }

    fn mcp_bridge_url(host: &str) -> String {
        format!("http://{}:18765", host)
    }

    fn searxng_url(host: &str) -> String {
        format!("http://{}:18766", host)
    }
}

pub use container::ContainerBackend;
pub use lima::LimaBackend;

pub use container::build_golden_image_impl as build_golden_image;
pub use container::{cleanup_untracked_vms, resolve_workspace_context, sandbox_exists};

pub async fn sandbox_exists_with_runtime(
    id: &str,
    runtime_flag: Option<String>,
) -> Result<bool, color_eyre::Report> {
    let cfg = config::load().await?;
    let runtime = resolve_runtime(runtime_flag, cfg.default_sandbox_runtime.clone())?;

    match runtime {
        Runtime::Container => ContainerBackend::exists(id).await,
        Runtime::Lima => LimaBackend::exists(id).await,
    }
}

pub async fn stop(
    names: Vec<String>,
    all: bool,
    runtime_flag: Option<String>,
) -> Result<(), color_eyre::Report> {
    let cfg = config::load().await?;
    let runtime = resolve_runtime(runtime_flag, cfg.default_sandbox_runtime.clone())?;

    match runtime {
        Runtime::Container => ContainerBackend::stop(names, all).await?,
        Runtime::Lima => LimaBackend::stop(names, all).await?,
    }
    Ok(())
}

pub async fn delete_sandbox(
    id: &str,
    force: bool,
    runtime_flag: Option<String>,
) -> Result<(), color_eyre::Report> {
    let cfg = config::load().await?;
    let runtime = resolve_runtime(runtime_flag, cfg.default_sandbox_runtime.clone())?;

    match runtime {
        Runtime::Container => ContainerBackend::delete(id, force).await?,
        Runtime::Lima => LimaBackend::delete(id, force).await?,
    }
    Ok(())
}

pub async fn start(
    profile_name: String,
    audit_log: Option<String>,
    runtime_flag: Option<String>,
) -> Result<(), color_eyre::Report> {
    let cfg = config::load().await?;
    let runtime = resolve_runtime(runtime_flag, cfg.default_sandbox_runtime.clone())?;
    let (id, project_root, _workdir) = resolve_workspace_context()?;

    let settings = resolve_profile_settings(&profile_name, &project_root).await?;
    let home = std::env::var("HOME")?;
    let server_port = cfg.server_port.unwrap_or(8080);
    let engine_name = cfg.default_engine_runtime.as_deref().unwrap_or("llama");
    let (active_model, _ctx_window) =
        crate::sandbox::shared::resolve_active_model_and_ctx_impl(&home, server_port, engine_name)
            .await;
    let runtime_envs = match runtime {
        Runtime::Container => {
            ContainerBackend::runtime_env(&id, server_port, engine_name, &active_model).await?
        }
        Runtime::Lima => {
            LimaBackend::runtime_env(&id, server_port, engine_name, &active_model).await?
        }
    };

    match runtime {
        Runtime::Container => {
            ContainerBackend::start(profile_name, audit_log, &settings, &runtime_envs).await?
        }
        Runtime::Lima => {
            LimaBackend::start(profile_name, audit_log, &settings, &runtime_envs).await?
        }
    }

    Ok(())
}

pub async fn shell(
    profile: Option<String>,
    command: Option<String>,
    no_tty: bool,
    explicit_envs: Vec<String>,
    audit_log: Option<String>,
    runtime_flag: Option<String>,
) -> Result<(), color_eyre::Report> {
    let cfg = config::load().await?;
    let runtime = resolve_runtime(runtime_flag, cfg.default_sandbox_runtime.clone())?;
    let (id, project_root, _workdir) = resolve_workspace_context()?;

    let settings = resolve_profile_settings("base", &project_root).await?;
    let home = std::env::var("HOME")?;
    let server_port = cfg.server_port.unwrap_or(8080);
    let engine_name = cfg.default_engine_runtime.as_deref().unwrap_or("llama");
    let (active_model, _ctx_window) =
        crate::sandbox::shared::resolve_active_model_and_ctx_impl(&home, server_port, engine_name)
            .await;
    let runtime_envs = match runtime {
        Runtime::Container => {
            ContainerBackend::runtime_env(&id, server_port, engine_name, &active_model).await?
        }
        Runtime::Lima => {
            LimaBackend::runtime_env(&id, server_port, engine_name, &active_model).await?
        }
    };

    match runtime {
        Runtime::Container => {
            ContainerBackend::shell(
                profile,
                command,
                no_tty,
                explicit_envs,
                audit_log,
                &settings,
                &runtime_envs,
            )
            .await?
        }
        Runtime::Lima => {
            LimaBackend::shell(
                profile,
                command,
                no_tty,
                explicit_envs,
                audit_log,
                &settings,
                &runtime_envs,
            )
            .await?
        }
    }

    Ok(())
}

pub async fn ls(
    out_fmt: crate::OutputFormat,
    quiet: bool,
    runtime_flag: Option<String>,
) -> Result<(), color_eyre::Report> {
    let cfg = config::load().await?;
    let runtime = resolve_runtime(runtime_flag, cfg.default_sandbox_runtime.clone())?;

    let entries = match runtime {
        Runtime::Container => ContainerBackend::ls().await?,
        Runtime::Lima => LimaBackend::ls().await?,
    };

    if entries.is_empty() {
        if out_fmt == crate::OutputFormat::Json {
            println!("[]");
        }
        return Ok(());
    }

    if quiet {
        for entry in &entries {
            println!("{}", entry.id);
        }
        return Ok(());
    }

    if out_fmt == crate::OutputFormat::Json {
        let payload: Vec<serde_json::Value> = entries
            .iter()
            .map(|e| serde_json::json!({"name": e.id, "status": e.status, "mount": e.mount}))
            .collect();
        println!("{}", serde_json::to_string(&payload)?);
        return Ok(());
    }

    if out_fmt == crate::OutputFormat::Ndjson {
        for entry in &entries {
            let payload =
                serde_json::json!({"name": entry.id, "status": entry.status, "mount": entry.mount});
            println!("{}", serde_json::to_string(&payload)?);
        }
        return Ok(());
    }

    for entry in &entries {
        println!("{:<30} {}  mount: {}", entry.id, entry.status, entry.mount);
    }

    Ok(())
}

async fn resolve_profile_settings(
    profile_name: &str,
    _project_root: &Path,
) -> Result<ProfileSettings, color_eyre::Report> {
    let manifest: Option<SandboxManifest> = load_profile_manifest(profile_name).await?;

    let mut settings = ProfileSettings {
        workspace_guest_path: "/workspace".to_string(),
        ..Default::default()
    };

    if let Some(ref m) = manifest {
        if let Some(ref resources) = m.resources {
            settings.cpus = resources.cpus;
            settings.memory = resources.memory.clone();
        }
        if let Some(ref security) = m.security
            && let Some(ref network) = security.network
        {
            let mode = network.trim();
            if mode.eq_ignore_ascii_case("none") || mode.eq_ignore_ascii_case("restricted") {
                settings.network_none = true;
            }
        }
        if let Some(ref mounts) = m.mounts
            && let Some(guest) = mounts.get("workspace")
            && guest.trim().starts_with('/')
        {
            settings.workspace_guest_path = guest.trim().to_string();
        }
    }

    Ok(settings)
}