Console Playground

CLI

Fast command-line client for code execution and interactive sessions. 42+ languages, 30+ shells/REPLs.

Official OpenAPI Swagger Docs ↗

Quick Start — D

# Download + setup
curl -O https://git.unturf.com/engineering/unturf/un-inception/-/raw/main/clients/d/sync/src/un.d
export UNSANDBOX_PUBLIC_KEY="unsb-pk-xxxx-xxxx-xxxx-xxxx"
export UNSANDBOX_SECRET_KEY="unsb-sk-xxxxx-xxxxx-xxxxx-xxxxx"
# Run code
./un script.d

Downloads

Install Guide →
Static Binary
Linux x86_64 (5.3MB)
un
D SDK
un.d (74.2 KB)
Download

Features

  • 42+ languages - Python, JS, Go, Rust, C++, Java...
  • Sessions - 30+ shells/REPLs, tmux persistence
  • Files - Upload files, collect artifacts
  • Services - Persistent containers with domains
  • Snapshots - Point-in-time backups
  • Images - Publish, share, transfer

Integration Quickstart ⚡

Add unsandbox superpowers to your existing D app:

1
Download
curl -O https://git.unturf.com/engineering/unturf/un-inception/-/raw/main/clients/d/sync/src/un.d
2
Set API Keys
# Option A: Environment variables
export UNSANDBOX_PUBLIC_KEY="unsb-pk-xxxx-xxxx-xxxx-xxxx"
export UNSANDBOX_SECRET_KEY="unsb-sk-xxxxx-xxxxx-xxxxx-xxxxx"

# Option B: Config file (persistent)
mkdir -p ~/.unsandbox
echo "unsb-pk-xxxx-xxxx-xxxx-xxxx,unsb-sk-xxxxx-xxxxx-xxxxx-xxxxx" > ~/.unsandbox/accounts.csv
3
Hello World
// In your D app:
import un;

void main() {
    auto result = executeCode("d", `writeln("Hello from D running on unsandbox!");`);
    writeln(result["stdout"]);  // Hello from D running on unsandbox!
}
Demo cooldown: s
stdout:

                      
JSON Response:

                      
4
Compile & Run
dmd -of=myapp main.d un.d && ./myapp
Source Code 📄 (1761 lines)
MD5: c37c02781994894db5d710a3fa7d3211 SHA256: 9af17c0ab4afd00b3729f64cdfa24296888d01bf8eb0169b7cd9816422d5bbb6
// PUBLIC DOMAIN - NO LICENSE, NO WARRANTY
//
// This is free public domain software for the public good of a permacomputer hosted
// at permacomputer.com - an always-on computer by the people, for the people. One
// which is durable, easy to repair, and distributed like tap water for machine
// learning intelligence.
//
// The permacomputer is community-owned infrastructure optimized around four values:
//
//   TRUTH    - First principles, math & science, open source code freely distributed
//   FREEDOM  - Voluntary partnerships, freedom from tyranny & corporate control
//   HARMONY  - Minimal waste, self-renewing systems with diverse thriving connections
//   LOVE     - Be yourself without hurting others, cooperation through natural law
//
// This software contributes to that vision by enabling code execution across 42+
// programming languages through a unified interface, accessible to all. Code is
// seeds to sprout on any abandoned technology.
//
// Learn more: https://www.permacomputer.com
//
// Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
// software, either in source code form or as a compiled binary, for any purpose,
// commercial or non-commercial, and by any means.
//
// NO WARRANTY. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
//
// That said, our permacomputer's digital membrane stratum continuously runs unit,
// integration, and functional tests on all of it's own software - with our
// permacomputer monitoring itself, repairing itself, with minimal human in the
// loop guidance. Our agents do their best.
//
// Copyright 2025 TimeHexOn & foxhop & russell@unturf
// https://www.timehexon.com
// https://www.foxhop.net
// https://www.unturf.com/software


// UN CLI - D Implementation (using curl subprocess for simplicity)
// Compile: dmd un.d -of=un_d
// Or with LDC: ldc2 un.d -of=un_d
// Usage:
//   un_d script.py
//   un_d -e KEY=VALUE script.py
//   un_d session --list
//   un_d service --name web --ports 8080

import std.stdio;
import std.file;
import std.path;
import std.process;
import std.string;
import std.conv;
import std.array;
import std.algorithm;

immutable string API_BASE = "https://api.unsandbox.com";
immutable string PORTAL_BASE = "https://unsandbox.com";
immutable string BLUE = "\033[34m";
immutable string RED = "\033[31m";
immutable string GREEN = "\033[32m";
immutable string YELLOW = "\033[33m";
immutable string RESET = "\033[0m";
immutable size_t MAX_ENV_CONTENT_SIZE = 65536;
immutable int LANGUAGES_CACHE_TTL = 3600; // 1 hour in seconds

string detectLanguage(string filename) {
    string[string] langMap = [
        ".py": "python", ".js": "javascript", ".ts": "typescript",
        ".go": "go", ".rs": "rust", ".c": "c", ".cpp": "cpp",
        ".d": "d", ".zig": "zig", ".nim": "nim", ".v": "v",
        ".rb": "ruby", ".php": "php", ".sh": "bash"
    ];

    string ext = extension(filename);
    return langMap.get(ext, "");
}

string escapeJson(string s) {
    string result;
    foreach (c; s) {
        switch (c) {
            case '"': result ~= "\\\""; break;
            case '\\': result ~= "\\\\"; break;
            case '\n': result ~= "\\n"; break;
            case '\r': result ~= "\\r"; break;
            case '\t': result ~= "\\t"; break;
            default: result ~= c; break;
        }
    }
    return result;
}

string readAndBase64(string filepath) {
    import std.base64 : Base64;
    try {
        auto content = readText(filepath);
        return Base64.encode(cast(ubyte[])content);
    } catch (Exception e) {
        stderr.writefln("%sError: Cannot read file: %s%s", RED, filepath, RESET);
        return "";
    }
}

string buildInputFilesJson(string[] files) {
    if (files.length == 0) return "";
    string[] fileJsons;
    foreach (f; files) {
        string b64 = readAndBase64(f);
        if (b64.empty) continue;
        string basename = baseName(f);
        fileJsons ~= format(`{"filename":"%s","content":"%s"}`, escapeJson(basename), b64);
    }
    if (fileJsons.length == 0) return "";
    import std.array : join;
    return format(`,"input_files":[%s]`, fileJsons.join(","));
}

string computeHmac(string secretKey, string message) {
    import std.process : pipeShell, Redirect, wait;
    import std.stdio : File;

    auto cmd = format("echo -n '%s' | openssl dgst -sha256 -hmac '%s' -hex 2>/dev/null | sed 's/.*= //'", message, secretKey);
    auto pipes = pipeShell(cmd, Redirect.stdout);
    string result = pipes.stdout.readln().strip();
    wait(pipes.pid);
    return result;
}

string getTimestamp() {
    import std.datetime.systime : Clock;
    return format("%d", Clock.currTime.toUnixTime());
}

string getLanguagesCachePath() {
    string home = environment.get("HOME", "");
    if (home.empty) return "";
    return buildPath(home, ".unsandbox", "languages.json");
}

string loadLanguagesCache() {
    import std.datetime.systime : Clock;
    string cachePath = getLanguagesCachePath();
    if (cachePath.empty || !exists(cachePath)) return "";

    try {
        string content = readText(cachePath);
        // Parse timestamp from JSON
        import std.algorithm : findSplitAfter;
        auto tsSearch = content.findSplitAfter(`"timestamp":`);
        if (tsSearch[0].length == 0) return "";

        // Find the end of the number
        string remaining = tsSearch[1];
        size_t numEnd = 0;
        while (numEnd < remaining.length && (remaining[numEnd] >= '0' && remaining[numEnd] <= '9')) {
            numEnd++;
        }
        if (numEnd == 0) return "";

        long cachedTime = to!long(remaining[0..numEnd]);
        long currentTime = Clock.currTime.toUnixTime();

        // Check if cache is still valid (within TTL)
        if (currentTime - cachedTime < LANGUAGES_CACHE_TTL) {
            return content;
        }
    } catch (Exception e) {
        // Cache read failed, return empty to fetch fresh
    }
    return "";
}

void saveLanguagesCache(string response) {
    import std.datetime.systime : Clock;
    string cachePath = getLanguagesCachePath();
    if (cachePath.empty) return;

    try {
        // Ensure directory exists
        string cacheDir = dirName(cachePath);
        if (!exists(cacheDir)) {
            mkdirRecurse(cacheDir);
        }

        // Extract languages array from response
        import std.algorithm : findSplitAfter;

        // Find the languages array
        auto langSearch = response.findSplitAfter(`"languages":`);
        if (langSearch[0].length == 0) return;

        // Find the array brackets
        auto bracketStart = langSearch[1].findSplitAfter("[");
        if (bracketStart[0].length == 0) return;

        // Find matching closing bracket
        string rest = "[" ~ bracketStart[1];
        int depth = 1;
        size_t endPos = 1;
        while (endPos < rest.length && depth > 0) {
            if (rest[endPos] == '[') depth++;
            else if (rest[endPos] == ']') depth--;
            endPos++;
        }
        string languagesArray = rest[0..endPos];

        // Build cache JSON with timestamp
        long timestamp = Clock.currTime.toUnixTime();
        string cacheJson = format(`{"languages":%s,"timestamp":%d}`, languagesArray, timestamp);
        std.file.write(cachePath, cacheJson);
    } catch (Exception e) {
        // Cache write failed, ignore
    }
}

string buildAuthHeaders(string method, string path, string body, string publicKey, string secretKey) {
    if (secretKey.empty) {
        // Legacy mode: use public_key as bearer token
        return format("-H 'Authorization: Bearer %s'", publicKey);
    }

    // HMAC mode
    string timestamp = getTimestamp();
    string message = format("%s:%s:%s:%s", timestamp, method, path, body);
    string signature = computeHmac(secretKey, message);

    return format("-H 'Authorization: Bearer %s' -H 'X-Timestamp: %s' -H 'X-Signature: %s'",
                  publicKey, timestamp, signature);
}

string execCurl(string cmd) {
    auto result = executeShell(cmd);
    string output = result.output;

    // Check for timestamp authentication errors
    import std.algorithm : canFind;
    if (output.canFind("timestamp") &&
        (output.canFind("401") || output.canFind("expired") || output.canFind("invalid"))) {
        stderr.writefln("%sError: Request timestamp expired (must be within 5 minutes of server time)%s", RED, RESET);
        stderr.writefln("%sYour computer's clock may have drifted.%s", YELLOW, RESET);
        stderr.writeln("Check your system time and sync with NTP if needed:");
        stderr.writeln("  Linux:   sudo ntpdate -s time.nist.gov");
        stderr.writeln("  macOS:   sudo sntp -sS time.apple.com");
        stderr.writeln("  Windows: w32tm /resync");
        exit(1);
    }

    return output;
}

// Execute curl and get HTTP status code along with response body
struct CurlResult {
    string body;
    int status;
}

CurlResult execCurlWithStatus(string cmd) {
    // Modify cmd to include status code output
    string fullCmd = cmd ~ " -w '\\n%{http_code}'";
    auto result = executeShell(fullCmd);
    string output = result.output.strip();

    // Find the last line (status code)
    import std.algorithm : findSplitAfter;
    auto lastNewline = output.findSplitAfter("\n");

    // Walk backwards to find status code at end
    string statusStr = "";
    string bodyStr = output;
    if (output.length >= 3) {
        // Try to parse last 3 chars as status
        size_t i = output.length;
        while (i > 0 && output[i-1] >= '0' && output[i-1] <= '9') i--;
        if (i < output.length) {
            statusStr = output[i..$];
            bodyStr = output[0..i].strip();
        }
    }

    int status = 0;
    try {
        status = to!int(statusStr);
    } catch (Exception e) {
        status = 0;
    }

    return CurlResult(bodyStr, status);
}

// Handle 428 sudo OTP challenge - prompts user for OTP and retries request
bool handleSudoChallenge(string method, string path, string bodyContent, string publicKey, string secretKey, string response) {
    // Extract challenge_id from response
    string challengeId = extractJsonField(response, "challenge_id");

    stderr.writefln("%sConfirmation required. Check your email for a one-time code.%s", YELLOW, RESET);
    stderr.write("Enter OTP: ");
    stderr.flush();

    import std.stdio : stdin;
    string otp;
    try {
        otp = stdin.readln();
        if (otp is null) {
            stderr.writefln("%sError: Failed to read OTP%s", RED, RESET);
            return false;
        }
        otp = otp.strip();
    } catch (Exception e) {
        stderr.writefln("%sError: Failed to read OTP%s", RED, RESET);
        return false;
    }

    if (otp.empty) {
        stderr.writefln("%sError: Operation cancelled%s", RED, RESET);
        return false;
    }

    // Retry the request with sudo headers
    string authHeaders = buildAuthHeaders(method, path, bodyContent, publicKey, secretKey);
    authHeaders ~= format(" -H 'X-Sudo-OTP: %s'", otp);
    if (!challengeId.empty) {
        authHeaders ~= format(" -H 'X-Sudo-Challenge: %s'", challengeId);
    }

    string cmd;
    if (method == "DELETE") {
        cmd = format(`curl -s -X DELETE '%s%s' %s`, API_BASE, path, authHeaders);
    } else if (method == "POST") {
        cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, bodyContent);
    } else {
        cmd = format(`curl -s -X %s '%s%s' %s`, method, API_BASE, path, authHeaders);
    }

    auto retryResult = execCurlWithStatus(cmd);

    if (retryResult.status >= 200 && retryResult.status < 300) {
        writefln("%sOperation completed successfully%s", GREEN, RESET);
        return true;
    }

    // Extract error message if available
    string errorMsg = extractJsonField(retryResult.body, "error");
    if (!errorMsg.empty) {
        stderr.writefln("%sError: %s%s", RED, errorMsg, RESET);
    } else {
        stderr.writefln("%sError: HTTP %d%s", RED, retryResult.status, RESET);
        if (!retryResult.body.empty) stderr.writeln(retryResult.body);
    }
    return false;
}

// Execute a destructive operation that may require sudo OTP confirmation
bool execDestructiveCurl(string method, string path, string bodyContent, string publicKey, string secretKey, string successMsg) {
    string authHeaders = buildAuthHeaders(method, path, bodyContent, publicKey, secretKey);

    string cmd;
    if (method == "DELETE") {
        cmd = format(`curl -s -X DELETE '%s%s' %s`, API_BASE, path, authHeaders);
    } else if (method == "POST" && !bodyContent.empty) {
        cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, bodyContent);
    } else if (method == "POST") {
        cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    } else {
        cmd = format(`curl -s -X %s '%s%s' %s`, method, API_BASE, path, authHeaders);
    }

    auto result = execCurlWithStatus(cmd);

    // Handle 428 sudo challenge
    if (result.status == 428) {
        return handleSudoChallenge(method, path, bodyContent, publicKey, secretKey, result.body);
    }

    if (result.status >= 200 && result.status < 300) {
        if (!successMsg.empty) {
            writefln("%s%s%s", GREEN, successMsg, RESET);
        }
        return true;
    }

    if (result.status == 404) {
        stderr.writefln("%sError: Not found%s", RED, RESET);
    } else {
        stderr.writefln("%sError: HTTP %d%s", RED, result.status, RESET);
        if (!result.body.empty) stderr.writeln(result.body);
    }
    return false;
}

bool execCurlPut(string endpoint, string body, string publicKey, string secretKey) {
    import std.file : write, remove;
    import std.random : uniform;
    string tmpFile = format("/tmp/un_d_%d.txt", uniform(0, 999999));
    write(tmpFile, body);
    string authHeaders = buildAuthHeaders("PUT", endpoint, body, publicKey, secretKey);
    string cmd = format(`curl -s -o /dev/null -w '%%{http_code}' -X PUT '%s%s' -H 'Content-Type: text/plain' %s -d @%s`, API_BASE, endpoint, authHeaders, tmpFile);
    auto result = executeShell(cmd);
    remove(tmpFile);
    try {
        int status = to!int(result.output.strip());
        return status >= 200 && status < 300;
    } catch (Exception e) {
        return false;
    }
}

string readEnvFile(string path) {
    if (!exists(path)) {
        stderr.writefln("%sError: Env file not found: %s%s", RED, path, RESET);
        exit(1);
    }
    return readText(path);
}

string buildEnvContent(string[] envs, string envFile) {
    string[] lines = envs.dup;
    if (!envFile.empty) {
        string content = readEnvFile(envFile);
        foreach (line; content.split("\n")) {
            string trimmed = line.strip();
            if (!trimmed.empty && !trimmed.startsWith("#")) {
                lines ~= trimmed;
            }
        }
    }
    import std.array : join;
    return lines.join("\n");
}

string extractJsonField(string response, string field) {
    import std.algorithm : findSplitAfter;
    auto search = response.findSplitAfter(format(`"%s":"`, field));
    if (search[0].length > 0 && search[1].length > 0) {
        auto endSearch = search[1].findSplitAfter(`"`);
        if (endSearch[0].length > 1) {
            return endSearch[0][0..$-1];
        }
    }
    return "";
}

// ============================================================================
// Library Functions for D SDK (matching C reference un.h)
// ============================================================================

immutable string SDK_VERSION = "4.2.0";

// Execute code synchronously
string execute(string language, string code, string publicKey, string secretKey) {
    string body_ = format(`{"language":"%s","code":"%s"}`, escapeJson(language), escapeJson(code));
    string authHeaders = buildAuthHeaders("POST", "/execute", body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s/execute' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, authHeaders, body_);
    return execCurl(cmd);
}

// Execute code asynchronously (returns job_id)
string executeAsync(string language, string code, string publicKey, string secretKey) {
    string body_ = format(`{"language":"%s","code":"%s","async":true}`, escapeJson(language), escapeJson(code));
    string authHeaders = buildAuthHeaders("POST", "/execute", body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s/execute' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, authHeaders, body_);
    return execCurl(cmd);
}

// Get job status
string getJob(string jobId, string publicKey, string secretKey) {
    string path = format("/jobs/%s", jobId);
    string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

// Wait for job completion
string waitForJob(string jobId, string publicKey, string secretKey) {
    import core.thread : Thread;
    import core.time : msecs;
    int[7] pollDelays = [300, 450, 700, 900, 650, 1600, 2000];
    int delayIdx = 0;

    while (true) {
        string result = getJob(jobId, publicKey, secretKey);
        import std.algorithm : canFind;
        if (result.canFind(`"status":"completed"`) || result.canFind(`"status":"failed"`) ||
            result.canFind(`"status":"timeout"`) || result.canFind(`"status":"cancelled"`)) {
            return result;
        }
        Thread.sleep(msecs(pollDelays[delayIdx % 7]));
        if (delayIdx < 6) delayIdx++;
    }
}

// Cancel a job
string cancelJob(string jobId, string publicKey, string secretKey) {
    string path = format("/jobs/%s/cancel", jobId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

// List all jobs
string listJobs(string publicKey, string secretKey) {
    string authHeaders = buildAuthHeaders("GET", "/jobs", "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s/jobs' %s`, API_BASE, authHeaders);
    return execCurl(cmd);
}

// Get supported languages
string getLanguages(string publicKey, string secretKey) {
    string authHeaders = buildAuthHeaders("GET", "/languages", "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s/languages' %s`, API_BASE, authHeaders);
    return execCurl(cmd);
}

// Session functions
string sessionList(string publicKey, string secretKey) {
    string authHeaders = buildAuthHeaders("GET", "/sessions", "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s/sessions' %s`, API_BASE, authHeaders);
    return execCurl(cmd);
}

string sessionGet(string sessionId, string publicKey, string secretKey) {
    string path = format("/sessions/%s", sessionId);
    string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string sessionCreate(string shell, string network, string publicKey, string secretKey) {
    string body_ = format(`{"shell":"%s"`, shell.empty ? "bash" : shell);
    if (!network.empty) body_ ~= format(`,"network":"%s"`, network);
    body_ ~= "}";
    string authHeaders = buildAuthHeaders("POST", "/sessions", body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s/sessions' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, authHeaders, body_);
    return execCurl(cmd);
}

string sessionDestroy(string sessionId, string publicKey, string secretKey) {
    string path = format("/sessions/%s", sessionId);
    string authHeaders = buildAuthHeaders("DELETE", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X DELETE '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string sessionFreeze(string sessionId, string publicKey, string secretKey) {
    string path = format("/sessions/%s/freeze", sessionId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string sessionUnfreeze(string sessionId, string publicKey, string secretKey) {
    string path = format("/sessions/%s/unfreeze", sessionId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string sessionBoost(string sessionId, int vcpu, string publicKey, string secretKey) {
    string path = format("/sessions/%s/boost", sessionId);
    string body_ = vcpu > 0 ? format(`{"vcpu":%d}`, vcpu) : "{}";
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

string sessionUnboost(string sessionId, string publicKey, string secretKey) {
    string path = format("/sessions/%s/unboost", sessionId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string sessionExecute(string sessionId, string command, string publicKey, string secretKey) {
    string path = format("/sessions/%s/shell", sessionId);
    string body_ = format(`{"command":"%s"}`, escapeJson(command));
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

// Service functions
string serviceListFn(string publicKey, string secretKey) {
    string authHeaders = buildAuthHeaders("GET", "/services", "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s/services' %s`, API_BASE, authHeaders);
    return execCurl(cmd);
}

string serviceGet(string serviceId, string publicKey, string secretKey) {
    string path = format("/services/%s", serviceId);
    string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string serviceCreate(string name, string ports, string bootstrap, string network, string publicKey, string secretKey) {
    string body_ = format(`{"name":"%s"`, escapeJson(name));
    if (!ports.empty) body_ ~= format(`,"ports":"%s"`, ports);
    if (!bootstrap.empty) body_ ~= format(`,"bootstrap":"%s"`, escapeJson(bootstrap));
    if (!network.empty) body_ ~= format(`,"network":"%s"`, network);
    body_ ~= "}";
    string authHeaders = buildAuthHeaders("POST", "/services", body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s/services' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, authHeaders, body_);
    return execCurl(cmd);
}

string serviceDestroy(string serviceId, string publicKey, string secretKey) {
    string path = format("/services/%s", serviceId);
    string authHeaders = buildAuthHeaders("DELETE", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X DELETE '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string serviceFreeze(string serviceId, string publicKey, string secretKey) {
    string path = format("/services/%s/freeze", serviceId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string serviceUnfreeze(string serviceId, string publicKey, string secretKey) {
    string path = format("/services/%s/unfreeze", serviceId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string serviceLock(string serviceId, string publicKey, string secretKey) {
    string path = format("/services/%s/lock", serviceId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string serviceUnlock(string serviceId, string publicKey, string secretKey) {
    string path = format("/services/%s/unlock", serviceId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string serviceRedeploy(string serviceId, string bootstrap, string publicKey, string secretKey) {
    string path = format("/services/%s/redeploy", serviceId);
    string body_ = bootstrap.empty ? "{}" : format(`{"bootstrap":"%s"}`, escapeJson(bootstrap));
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

string serviceLogs(string serviceId, bool all, string publicKey, string secretKey) {
    string path = format("/services/%s/logs%s", serviceId, all ? "?all=true" : "");
    string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string serviceExecute(string serviceId, string command, int timeoutMs, string publicKey, string secretKey) {
    string path = format("/services/%s/execute", serviceId);
    string body_ = format(`{"command":"%s"`, escapeJson(command));
    if (timeoutMs > 0) body_ ~= format(`,"timeout":%d`, timeoutMs);
    body_ ~= "}";
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

string serviceResize(string serviceId, int vcpu, string publicKey, string secretKey) {
    string path = format("/services/%s/resize", serviceId);
    string body_ = format(`{"vcpu":%d}`, vcpu);
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

// Snapshot functions
string snapshotList(string publicKey, string secretKey) {
    string authHeaders = buildAuthHeaders("GET", "/snapshots", "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s/snapshots' %s`, API_BASE, authHeaders);
    return execCurl(cmd);
}

string snapshotGet(string snapshotId, string publicKey, string secretKey) {
    string path = format("/snapshots/%s", snapshotId);
    string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string snapshotSession(string sessionId, string name, bool hot, string publicKey, string secretKey) {
    string path = format("/sessions/%s/snapshot", sessionId);
    string body_ = "{";
    if (!name.empty) body_ ~= format(`"name":"%s",`, escapeJson(name));
    body_ ~= format(`"hot":%s}`, hot ? "true" : "false");
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

string snapshotService(string serviceId, string name, bool hot, string publicKey, string secretKey) {
    string path = format("/services/%s/snapshot", serviceId);
    string body_ = "{";
    if (!name.empty) body_ ~= format(`"name":"%s",`, escapeJson(name));
    body_ ~= format(`"hot":%s}`, hot ? "true" : "false");
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

string snapshotRestore(string snapshotId, string publicKey, string secretKey) {
    string path = format("/snapshots/%s/restore", snapshotId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string snapshotDelete(string snapshotId, string publicKey, string secretKey) {
    string path = format("/snapshots/%s", snapshotId);
    string authHeaders = buildAuthHeaders("DELETE", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X DELETE '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string snapshotLock(string snapshotId, string publicKey, string secretKey) {
    string path = format("/snapshots/%s/lock", snapshotId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string snapshotUnlock(string snapshotId, string publicKey, string secretKey) {
    string path = format("/snapshots/%s/unlock", snapshotId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string snapshotClone(string snapshotId, string cloneType, string name, string ports, string shell, string publicKey, string secretKey) {
    string path = format("/snapshots/%s/clone", snapshotId);
    string body_ = format(`{"type":"%s"`, cloneType);
    if (!name.empty) body_ ~= format(`,"name":"%s"`, escapeJson(name));
    if (!ports.empty) body_ ~= format(`,"ports":"%s"`, ports);
    if (!shell.empty) body_ ~= format(`,"shell":"%s"`, shell);
    body_ ~= "}";
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

// Image functions
string imageList(string filter, string publicKey, string secretKey) {
    string path = filter.empty ? "/images" : format("/images?filter=%s", filter);
    string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string imageGetFn(string imageId, string publicKey, string secretKey) {
    string path = format("/images/%s", imageId);
    string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string imagePublish(string sourceType, string sourceId, string name, string description, string publicKey, string secretKey) {
    string body_ = format(`{"source_type":"%s","source_id":"%s"`, sourceType, sourceId);
    if (!name.empty) body_ ~= format(`,"name":"%s"`, escapeJson(name));
    if (!description.empty) body_ ~= format(`,"description":"%s"`, escapeJson(description));
    body_ ~= "}";
    string authHeaders = buildAuthHeaders("POST", "/images", body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s/images' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, authHeaders, body_);
    return execCurl(cmd);
}

string imageDelete(string imageId, string publicKey, string secretKey) {
    string path = format("/images/%s", imageId);
    string authHeaders = buildAuthHeaders("DELETE", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X DELETE '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string imageLock(string imageId, string publicKey, string secretKey) {
    string path = format("/images/%s/lock", imageId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string imageUnlock(string imageId, string publicKey, string secretKey) {
    string path = format("/images/%s/unlock", imageId);
    string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string imageSetVisibility(string imageId, string visibility, string publicKey, string secretKey) {
    string path = format("/images/%s/visibility", imageId);
    string body_ = format(`{"visibility":"%s"}`, visibility);
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

string imageGrantAccess(string imageId, string trustedKey, string publicKey, string secretKey) {
    string path = format("/images/%s/grant", imageId);
    string body_ = format(`{"trusted_api_key":"%s"}`, trustedKey);
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

string imageRevokeAccess(string imageId, string trustedKey, string publicKey, string secretKey) {
    string path = format("/images/%s/revoke", imageId);
    string body_ = format(`{"trusted_api_key":"%s"}`, trustedKey);
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

string imageListTrusted(string imageId, string publicKey, string secretKey) {
    string path = format("/images/%s/trusted", imageId);
    string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

string imageTransfer(string imageId, string toApiKey, string publicKey, string secretKey) {
    string path = format("/images/%s/transfer", imageId);
    string body_ = format(`{"to_api_key":"%s"}`, toApiKey);
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

string imageSpawn(string imageId, string name, string ports, string bootstrap, string network, string publicKey, string secretKey) {
    string path = format("/images/%s/spawn", imageId);
    string body_ = "{";
    string[] fields;
    if (!name.empty) fields ~= format(`"name":"%s"`, escapeJson(name));
    if (!ports.empty) fields ~= format(`"ports":"%s"`, ports);
    if (!bootstrap.empty) fields ~= format(`"bootstrap":"%s"`, escapeJson(bootstrap));
    if (!network.empty) fields ~= format(`"network":"%s"`, network);
    import std.array : join;
    body_ ~= fields.join(",") ~ "}";
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

string imageCloneFn(string imageId, string name, string description, string publicKey, string secretKey) {
    string path = format("/images/%s/clone", imageId);
    string body_ = "{";
    string[] fields;
    if (!name.empty) fields ~= format(`"name":"%s"`, escapeJson(name));
    if (!description.empty) fields ~= format(`"description":"%s"`, escapeJson(description));
    import std.array : join;
    body_ ~= fields.join(",") ~ "}";
    string authHeaders = buildAuthHeaders("POST", path, body_, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, path, authHeaders, body_);
    return execCurl(cmd);
}

// PaaS Logs functions
string logsFetch(string source, int lines, string since, string grep, string publicKey, string secretKey) {
    string path = "/paas/logs?";
    if (!source.empty) path ~= format("source=%s&", source);
    if (lines > 0) path ~= format("lines=%d&", lines);
    if (!since.empty) path ~= format("since=%s&", since);
    if (!grep.empty) path ~= format("grep=%s&", grep);
    if (path[$-1] == '&' || path[$-1] == '?') path = path[0..$-1];
    string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s%s' %s`, API_BASE, path, authHeaders);
    return execCurl(cmd);
}

// Key validation
string validateKeysFn(string publicKey, string secretKey) {
    string authHeaders = buildAuthHeaders("POST", "/keys/validate", "", publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s/keys/validate' %s`, API_BASE, authHeaders);
    return execCurl(cmd);
}

// Utility functions
string hmacSign(string secretKey, string message) {
    return computeHmac(secretKey, message);
}

bool healthCheck() {
    string cmd = format(`curl -s -o /dev/null -w '%%{http_code}' '%s/health' 2>/dev/null`, API_BASE);
    auto result = executeShell(cmd);
    try {
        return to!int(result.output.strip()) == 200;
    } catch (Exception e) {
        return false;
    }
}

string sdkVersion() {
    return SDK_VERSION;
}

__gshared string lastErrorMsg;

void setLastError(string msg) {
    lastErrorMsg = msg;
}

string lastError() {
    return lastErrorMsg;
}

void cmdServiceEnv(string action, string target, string[] svcEnvs, string svcEnvFile, string publicKey, string secretKey) {
    if (action == "status") {
        if (target.empty) {
            stderr.writefln("%sError: service env status requires service ID%s", RED, RESET);
            exit(1);
        }
        string path = format("/services/%s/env", target);
        string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
        string cmd = format(`curl -s -X GET '%s/services/%s/env' %s`, API_BASE, target, authHeaders);
        string response = execCurl(cmd);

        import std.algorithm : canFind;
        if (response.canFind(`"has_vault":true`)) {
            writefln("%sVault: configured%s", GREEN, RESET);
            string envCount = extractJsonField(response, "env_count");
            if (!envCount.empty) writefln("Variables: %s", envCount);
            string updatedAt = extractJsonField(response, "updated_at");
            if (!updatedAt.empty) writefln("Updated: %s", updatedAt);
        } else {
            writefln("%sVault: not configured%s", YELLOW, RESET);
        }
        return;
    }

    if (action == "set") {
        if (target.empty) {
            stderr.writefln("%sError: service env set requires service ID%s", RED, RESET);
            exit(1);
        }
        if (svcEnvs.length == 0 && svcEnvFile.empty) {
            stderr.writefln("%sError: service env set requires -e or --env-file%s", RED, RESET);
            exit(1);
        }
        string envContent = buildEnvContent(svcEnvs, svcEnvFile);
        if (envContent.length > MAX_ENV_CONTENT_SIZE) {
            stderr.writefln("%sError: Env content exceeds maximum size of 64KB%s", RED, RESET);
            exit(1);
        }
        if (execCurlPut(format("/services/%s/env", target), envContent, publicKey, secretKey)) {
            writefln("%sVault updated for service %s%s", GREEN, target, RESET);
        } else {
            stderr.writefln("%sError: Failed to update vault%s", RED, RESET);
            exit(1);
        }
        return;
    }

    if (action == "export") {
        if (target.empty) {
            stderr.writefln("%sError: service env export requires service ID%s", RED, RESET);
            exit(1);
        }
        string path = format("/services/%s/env/export", target);
        string authHeaders = buildAuthHeaders("POST", path, "{}", publicKey, secretKey);
        string cmd = format(`curl -s -X POST '%s/services/%s/env/export' -H 'Content-Type: application/json' %s -d '{}'`, API_BASE, target, authHeaders);
        string response = execCurl(cmd);
        string content = extractJsonField(response, "content");
        if (!content.empty) {
            content = content.replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t").replace("\\\"", "\"").replace("\\\\", "\\");
            write(content);
        }
        return;
    }

    if (action == "delete") {
        if (target.empty) {
            stderr.writefln("%sError: service env delete requires service ID%s", RED, RESET);
            exit(1);
        }
        string path = format("/services/%s/env", target);
        string authHeaders = buildAuthHeaders("DELETE", path, "", publicKey, secretKey);
        string cmd = format(`curl -s -o /dev/null -w '%%{http_code}' -X DELETE '%s/services/%s/env' %s`, API_BASE, target, authHeaders);
        auto result = executeShell(cmd);
        try {
            int status = to!int(result.output.strip());
            if (status >= 200 && status < 300) {
                writefln("%sVault deleted for service %s%s", GREEN, target, RESET);
            } else {
                stderr.writefln("%sError: Failed to delete vault%s", RED, RESET);
                exit(1);
            }
        } catch (Exception e) {
            stderr.writefln("%sError: Failed to delete vault%s", RED, RESET);
            exit(1);
        }
        return;
    }

    stderr.writefln("%sError: Unknown env action: %s%s", RED, action, RESET);
    stderr.writeln("Usage: un.d service env <status|set|export|delete> <service_id>");
    exit(1);
}

void cmdExecute(string sourceFile, string[] envs, bool artifacts, string network, int vcpu, string publicKey, string secretKey) {
    string lang = detectLanguage(sourceFile);
    if (lang.empty) {
        stderr.writefln("%sError: Cannot detect language%s", RED, RESET);
        exit(1);
    }

    string code = readText(sourceFile);
    string json = format(`{"language":"%s","code":"%s"`, lang, escapeJson(code));

    if (envs.length > 0) {
        json ~= `,"env":{`;
        foreach (i, e; envs) {
            auto parts = e.split("=");
            if (parts.length == 2) {
                if (i > 0) json ~= ",";
                json ~= format(`"%s":"%s"`, parts[0], escapeJson(parts[1]));
            }
        }
        json ~= "}";
    }

    if (artifacts) json ~= `,"return_artifacts":true`;
    if (!network.empty) json ~= format(`,"network":"%s"`, network);
    if (vcpu > 0) json ~= format(`,"vcpu":%d`, vcpu);
    json ~= "}";

    string authHeaders = buildAuthHeaders("POST", "/execute", json, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s/execute' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, authHeaders, json);
    string result = execCurl(cmd);

    writeln(result);
}

void cmdSession(bool list, string kill, string shell, string network, int vcpu, bool tmux, bool screen, string[] inputFiles, string publicKey, string secretKey) {
    if (list) {
        string authHeaders = buildAuthHeaders("GET", "/sessions", "", publicKey, secretKey);
        string cmd = format(`curl -s -X GET '%s/sessions' %s`, API_BASE, authHeaders);
        writeln(execCurl(cmd));
        return;
    }

    if (!kill.empty) {
        string path = format("/sessions/%s", kill);
        string authHeaders = buildAuthHeaders("DELETE", path, "", publicKey, secretKey);
        string cmd = format(`curl -s -X DELETE '%s/sessions/%s' %s`, API_BASE, kill, authHeaders);
        execCurl(cmd);
        writefln("%sSession terminated: %s%s", GREEN, kill, RESET);
        return;
    }

    string json = format(`{"shell":"%s"`, shell.empty ? "bash" : shell);
    if (!network.empty) json ~= format(`,"network":"%s"`, network);
    if (vcpu > 0) json ~= format(`,"vcpu":%d`, vcpu);
    if (tmux) json ~= `,"persistence":"tmux"`;
    if (screen) json ~= `,"persistence":"screen"`;
    json ~= buildInputFilesJson(inputFiles);
    json ~= "}";

    writefln("%sCreating session...%s", YELLOW, RESET);
    string authHeaders = buildAuthHeaders("POST", "/sessions", json, publicKey, secretKey);
    string cmd = format(`curl -s -X POST '%s/sessions' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, authHeaders, json);
    writeln(execCurl(cmd));
}

void cmdService(string name, string ports, string bootstrap, string bootstrapFile, string type, bool list, string info, string logs, string tail, string sleep, string wake, string destroy, string resize, int resizeVcpu, string execute, string command, string dumpBootstrap, string dumpFile, string unfreezeOnDemand, bool unfreezeOnDemandEnabled, bool createUnfreezeOnDemand, string network, int vcpu, string[] inputFiles, string[] svcEnvs, string svcEnvFile, string envAction, string envTarget, string publicKey, string secretKey) {
    // Handle env subcommand
    if (!envAction.empty) {
        cmdServiceEnv(envAction, envTarget, svcEnvs, svcEnvFile, publicKey, secretKey);
        return;
    }

    if (list) {
        string authHeaders = buildAuthHeaders("GET", "/services", "", publicKey, secretKey);
        string cmd = format(`curl -s -X GET '%s/services' %s`, API_BASE, authHeaders);
        writeln(execCurl(cmd));
        return;
    }

    if (!info.empty) {
        string path = format("/services/%s", info);
        string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
        string cmd = format(`curl -s -X GET '%s/services/%s' %s`, API_BASE, info, authHeaders);
        writeln(execCurl(cmd));
        return;
    }

    if (!logs.empty) {
        string path = format("/services/%s/logs", logs);
        string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
        string cmd = format(`curl -s -X GET '%s/services/%s/logs' %s`, API_BASE, logs, authHeaders);
        write(execCurl(cmd));
        return;
    }

    if (!tail.empty) {
        string path = format("/services/%s/logs", tail);
        string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
        string cmd = format(`curl -s -X GET '%s/services/%s/logs?lines=9000' %s`, API_BASE, tail, authHeaders);
        write(execCurl(cmd));
        return;
    }

    if (!sleep.empty) {
        string path = format("/services/%s/freeze", sleep);
        string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
        string cmd = format(`curl -s -X POST '%s/services/%s/freeze' %s`, API_BASE, sleep, authHeaders);
        execCurl(cmd);
        writefln("%sService frozen: %s%s", GREEN, sleep, RESET);
        return;
    }

    if (!wake.empty) {
        string path = format("/services/%s/unfreeze", wake);
        string authHeaders = buildAuthHeaders("POST", path, "", publicKey, secretKey);
        string cmd = format(`curl -s -X POST '%s/services/%s/unfreeze' %s`, API_BASE, wake, authHeaders);
        execCurl(cmd);
        writefln("%sService unfreezing: %s%s", GREEN, wake, RESET);
        return;
    }

    if (!unfreezeOnDemand.empty) {
        string json = format(`{"unfreeze_on_demand":%s}`, unfreezeOnDemandEnabled ? "true" : "false");
        string path = format("/services/%s", unfreezeOnDemand);
        string authHeaders = buildAuthHeaders("PATCH", path, json, publicKey, secretKey);
        string cmd = format(`curl -s -X PATCH '%s/services/%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, unfreezeOnDemand, authHeaders, json);
        execCurl(cmd);
        string status = unfreezeOnDemandEnabled ? "enabled" : "disabled";
        writefln("%sUnfreeze-on-demand %s for service: %s%s", GREEN, status, unfreezeOnDemand, RESET);
        return;
    }

    if (!destroy.empty) {
        string path = format("/services/%s", destroy);
        execDestructiveCurl("DELETE", path, "", publicKey, secretKey, format("Service destroyed: %s", destroy));
        return;
    }

    if (!resize.empty) {
        if (resizeVcpu < 1 || resizeVcpu > 8) {
            stderr.writefln("%sError: --vcpu must be between 1 and 8%s", RED, RESET);
            exit(1);
        }
        string json = format(`{"vcpu":%d}`, resizeVcpu);
        string path = format("/services/%s", resize);
        string authHeaders = buildAuthHeaders("PATCH", path, json, publicKey, secretKey);
        string cmd = format(`curl -s -X PATCH '%s/services/%s' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, resize, authHeaders, json);
        execCurl(cmd);
        int ram = resizeVcpu * 2;
        writefln("%sService resized to %d vCPU, %d GB RAM%s", GREEN, resizeVcpu, ram, RESET);
        return;
    }

    if (!execute.empty) {
        string json = format(`{"command":"%s"}`, escapeJson(command));
        string path = format("/services/%s/execute", execute);
        string authHeaders = buildAuthHeaders("POST", path, json, publicKey, secretKey);
        string cmd = format(`curl -s -X POST '%s/services/%s/execute' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, execute, authHeaders, json);
        string result = execCurl(cmd);

        // Simple JSON parsing for stdout/stderr
        import std.algorithm : findSplitAfter;
        auto stdoutSearch = result.findSplitAfter(`"stdout":"`);
        if (stdoutSearch[0].length > 0 && stdoutSearch[1].length > 0) {
            auto stdoutEnd = stdoutSearch[1].findSplitAfter(`"`);
            if (stdoutEnd[0].length > 1) {
                string output = stdoutEnd[0][0..$-1];
                output = output.replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t").replace("\\\"", "\"").replace("\\\\", "\\");
                write(output);
            }
        }

        auto stderrSearch = result.findSplitAfter(`"stderr":"`);
        if (stderrSearch[0].length > 0 && stderrSearch[1].length > 0) {
            auto stderrEnd = stderrSearch[1].findSplitAfter(`"`);
            if (stderrEnd[0].length > 1) {
                string errout = stderrEnd[0][0..$-1];
                errout = errout.replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t").replace("\\\"", "\"").replace("\\\\", "\\");
                stderr.write(errout);
            }
        }
        return;
    }

    if (!dumpBootstrap.empty) {
        stderr.writefln("Fetching bootstrap script from %s...", dumpBootstrap);
        string json = `{"command":"cat /tmp/bootstrap.sh"}`;
        string path = format("/services/%s/execute", dumpBootstrap);
        string authHeaders = buildAuthHeaders("POST", path, json, publicKey, secretKey);
        string cmd = format(`curl -s -X POST '%s/services/%s/execute' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, dumpBootstrap, authHeaders, json);
        string result = execCurl(cmd);

        import std.algorithm : findSplitAfter;
        auto stdoutSearch = result.findSplitAfter(`"stdout":"`);
        if (stdoutSearch[0].length > 0 && stdoutSearch[1].length > 0) {
            auto stdoutEnd = stdoutSearch[1].findSplitAfter(`"`);
            if (stdoutEnd[0].length > 1) {
                string bootstrapScript = stdoutEnd[0][0..$-1];
                bootstrapScript = bootstrapScript.replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t").replace("\\\"", "\"").replace("\\\\", "\\");

                if (!dumpFile.empty) {
                    try {
                        std.file.write(dumpFile, bootstrapScript);
                        version(Posix) {
                            import core.sys.posix.sys.stat;
                            chmod(dumpFile.toStringz(), octal!755);
                        }
                        writefln("Bootstrap saved to %s", dumpFile);
                    } catch (Exception e) {
                        stderr.writefln("%sError: Could not write to %s: %s%s", RED, dumpFile, e.msg, RESET);
                        exit(1);
                    }
                } else {
                    write(bootstrapScript);
                }
            } else {
                stderr.writefln("%sError: Failed to fetch bootstrap (service not running or no bootstrap file)%s", RED, RESET);
                exit(1);
            }
        } else {
            stderr.writefln("%sError: Failed to fetch bootstrap (service not running or no bootstrap file)%s", RED, RESET);
            exit(1);
        }
        return;
    }

    if (!name.empty) {
        string json = format(`{"name":"%s"`, name);
        if (!ports.empty) json ~= format(`,"ports":[%s]`, ports);
        if (!type.empty) json ~= format(`,"service_type":"%s"`, type);
        if (!bootstrap.empty) {
            json ~= format(`,"bootstrap":"%s"`, escapeJson(bootstrap));
        }
        if (!bootstrapFile.empty) {
            if (exists(bootstrapFile)) {
                string bootCode = readText(bootstrapFile);
                json ~= format(`,"bootstrap_content":"%s"`, escapeJson(bootCode));
            } else {
                stderr.writefln("%sError: Bootstrap file not found: %s%s", RED, bootstrapFile, RESET);
                exit(1);
            }
        }
        if (!network.empty) json ~= format(`,"network":"%s"`, network);
        if (vcpu > 0) json ~= format(`,"vcpu":%d`, vcpu);
        if (createUnfreezeOnDemand) json ~= `,"unfreeze_on_demand":true`;
        json ~= buildInputFilesJson(inputFiles);
        json ~= "}";

        writefln("%sCreating service...%s", YELLOW, RESET);
        string authHeaders = buildAuthHeaders("POST", "/services", json, publicKey, secretKey);
        string cmd = format(`curl -s -X POST '%s/services' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, authHeaders, json);
        string response = execCurl(cmd);
        writeln(response);

        // Auto-set vault if -e or --env-file provided
        if (svcEnvs.length > 0 || !svcEnvFile.empty) {
            string serviceId = extractJsonField(response, "service_id");
            if (serviceId.empty) serviceId = extractJsonField(response, "id");
            if (!serviceId.empty) {
                string envContent = buildEnvContent(svcEnvs, svcEnvFile);
                if (execCurlPut(format("/services/%s/env", serviceId), envContent, publicKey, secretKey)) {
                    writefln("%sVault configured for service %s%s", GREEN, serviceId, RESET);
                } else {
                    stderr.writefln("%sWarning: Failed to set vault%s", YELLOW, RESET);
                }
            }
        }
        return;
    }

    stderr.writefln("%sError: Specify --name to create a service%s", RED, RESET);
    exit(1);
}

void cmdImage(bool list, string info, string del, string lock, string unlock,
              string publish, string sourceType, string visibilityId, string visibility,
              string spawn, string clone, string name, string ports, string publicKey, string secretKey) {
    if (list) {
        string authHeaders = buildAuthHeaders("GET", "/images", "", publicKey, secretKey);
        string cmd = format(`curl -s -X GET '%s/images' %s`, API_BASE, authHeaders);
        writeln(execCurl(cmd));
        return;
    }

    if (!info.empty) {
        string path = format("/images/%s", info);
        string authHeaders = buildAuthHeaders("GET", path, "", publicKey, secretKey);
        string cmd = format(`curl -s -X GET '%s/images/%s' %s`, API_BASE, info, authHeaders);
        writeln(execCurl(cmd));
        return;
    }

    if (!del.empty) {
        string path = format("/images/%s", del);
        execDestructiveCurl("DELETE", path, "", publicKey, secretKey, format("Image deleted: %s", del));
        return;
    }

    if (!lock.empty) {
        string path = format("/images/%s/lock", lock);
        string json = "{}";
        string authHeaders = buildAuthHeaders("POST", path, json, publicKey, secretKey);
        string cmd = format(`curl -s -X POST '%s/images/%s/lock' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, lock, authHeaders, json);
        execCurl(cmd);
        writefln("%sImage locked: %s%s", GREEN, lock, RESET);
        return;
    }

    if (!unlock.empty) {
        string path = format("/images/%s/unlock", unlock);
        execDestructiveCurl("POST", path, "{}", publicKey, secretKey, format("Image unlocked: %s", unlock));
        return;
    }

    if (!publish.empty) {
        if (sourceType.empty) {
            stderr.writefln("%sError: --publish requires --source-type (service or snapshot)%s", RED, RESET);
            exit(1);
        }
        string json = format(`{"source_type":"%s","source_id":"%s"`, sourceType, publish);
        if (!name.empty) {
            json ~= format(`,"name":"%s"`, escapeJson(name));
        }
        json ~= "}";
        string path = "/images/publish";
        string authHeaders = buildAuthHeaders("POST", path, json, publicKey, secretKey);
        string cmd = format(`curl -s -X POST '%s/images/publish' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, authHeaders, json);
        writefln("%sImage published%s", GREEN, RESET);
        writeln(execCurl(cmd));
        return;
    }

    if (!visibilityId.empty) {
        if (visibility.empty) {
            stderr.writefln("%sError: --visibility requires visibility mode (private, unlisted, public)%s", RED, RESET);
            exit(1);
        }
        string json = format(`{"visibility":"%s"}`, visibility);
        string path = format("/images/%s/visibility", visibilityId);
        string authHeaders = buildAuthHeaders("POST", path, json, publicKey, secretKey);
        string cmd = format(`curl -s -X POST '%s/images/%s/visibility' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, visibilityId, authHeaders, json);
        execCurl(cmd);
        writefln("%sImage visibility set to: %s%s", GREEN, visibility, RESET);
        return;
    }

    if (!spawn.empty) {
        string json = "{";
        bool hasField = false;
        if (!name.empty) {
            json ~= format(`"name":"%s"`, escapeJson(name));
            hasField = true;
        }
        if (!ports.empty) {
            if (hasField) json ~= ",";
            json ~= format(`"ports":[%s]`, ports);
        }
        json ~= "}";
        string path = format("/images/%s/spawn", spawn);
        string authHeaders = buildAuthHeaders("POST", path, json, publicKey, secretKey);
        string cmd = format(`curl -s -X POST '%s/images/%s/spawn' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, spawn, authHeaders, json);
        writefln("%sService spawned from image%s", GREEN, RESET);
        writeln(execCurl(cmd));
        return;
    }

    if (!clone.empty) {
        string json = "{";
        if (!name.empty) {
            json ~= format(`"name":"%s"`, escapeJson(name));
        }
        json ~= "}";
        string path = format("/images/%s/clone", clone);
        string authHeaders = buildAuthHeaders("POST", path, json, publicKey, secretKey);
        string cmd = format(`curl -s -X POST '%s/images/%s/clone' -H 'Content-Type: application/json' %s -d '%s'`, API_BASE, clone, authHeaders, json);
        writefln("%sImage cloned%s", GREEN, RESET);
        writeln(execCurl(cmd));
        return;
    }

    // Default: list images
    string authHeaders = buildAuthHeaders("GET", "/images", "", publicKey, secretKey);
    string cmd = format(`curl -s -X GET '%s/images' %s`, API_BASE, authHeaders);
    writeln(execCurl(cmd));
}

void cmdLanguages(bool jsonOutput, string publicKey, string secretKey) {
    // Try to load from cache first
    string cachedResponse = loadLanguagesCache();
    string result;

    if (!cachedResponse.empty) {
        result = cachedResponse;
    } else {
        // Fetch from API
        string authHeaders = buildAuthHeaders("GET", "/languages", "", publicKey, secretKey);
        string cmd = format(`curl -s -X GET '%s/languages' %s`, API_BASE, authHeaders);
        result = execCurl(cmd);

        // Save to cache
        saveLanguagesCache(result);
    }

    if (jsonOutput) {
        // Extract language names and output as JSON array
        string[] names;
        import std.algorithm : findSplitAfter;
        string remaining = result;
        while (true) {
            auto search = remaining.findSplitAfter(`"name":"`);
            if (search[0].length == 0) break;
            auto endSearch = search[1].findSplitAfter(`"`);
            if (endSearch[0].length > 1) {
                names ~= endSearch[0][0..$-1];
            }
            remaining = endSearch[1];
        }
        import std.array : join;
        writefln("[%s]", names.map!(n => format(`"%s"`, n)).join(","));
    } else {
        // Output one language per line
        import std.algorithm : findSplitAfter;
        string remaining = result;
        while (true) {
            auto search = remaining.findSplitAfter(`"name":"`);
            if (search[0].length == 0) break;
            auto endSearch = search[1].findSplitAfter(`"`);
            if (endSearch[0].length > 1) {
                writeln(endSearch[0][0..$-1]);
            }
            remaining = endSearch[1];
        }
    }
}

void openBrowser(string url) {
    version(linux) {
        executeShell("xdg-open \"" ~ url ~ "\" 2>/dev/null &");
    } else version(OSX) {
        executeShell("open \"" ~ url ~ "\"");
    } else version(Windows) {
        executeShell("start \"\" \"" ~ url ~ "\"");
    } else {
        stderr.writefln("%sError: Unsupported platform for browser opening%s", RED, RESET);
    }
}

string formatDuration(long totalMinutes) {
    long days = totalMinutes / (24 * 60);
    long hours = (totalMinutes % (24 * 60)) / 60;
    long minutes = totalMinutes % 60;

    if (days > 0) {
        return format("%dd %dh %dm", days, hours, minutes);
    } else if (hours > 0) {
        return format("%dh %dm", hours, minutes);
    } else {
        return format("%dm", minutes);
    }
}

void validateKey(string publicKey, string secretKey, bool extend) {
    import std.json;
    import std.datetime;

    string authHeaders = buildAuthHeaders("POST", "/keys/validate", "", publicKey, secretKey);
    string cmd = format(`curl -s -w '\n%%{http_code}' -X POST '%s/keys/validate' -H 'Content-Type: application/json' %s`, PORTAL_BASE, authHeaders);
    string response = execCurl(cmd);

    auto lines = response.split("\n");
    string body = lines.length > 1 ? lines[0..$-1].join("\n") : response;
    string statusCode = lines.length > 1 ? lines[$-1] : "200";

    JSONValue result;
    try {
        result = parseJSON(body);
    } catch (Exception e) {
        stderr.writefln("%sError parsing response: %s%s", RED, e.msg, RESET);
        exit(1);
    }

    if (statusCode[0] == '4' || statusCode[0] == '5') {
        // Invalid key
        writefln("%sInvalid%s", RED, RESET);
        if ("error" in result) {
            writefln("Reason: %s", result["error"].str);
        } else if ("message" in result) {
            writefln("Reason: %s", result["message"].str);
        }
        exit(1);
    }

    bool valid = result["valid"].type == JSONType.true_;
    bool expired = result["expired"].type == JSONType.true_;
    string publicKey = "public_key" in result ? result["public_key"].str : "";
    string tier = "tier" in result ? result["tier"].str : "";
    string status = "status" in result ? result["status"].str : "";

    if (expired) {
        // Expired key
        writefln("%sExpired%s", RED, RESET);
        writefln("Public Key: %s", publicKey);
        writefln("Tier: %s", tier);
        if ("expires_at" in result) {
            writefln("Expired: %s", result["expires_at"].str);
        }
        writefln("%sTo renew: Visit https://unsandbox.com/keys/extend%s", YELLOW, RESET);

        if (extend) {
            string extendURL = PORTAL_BASE ~ "/keys/extend?pk=" ~ publicKey;
            writefln("\n%sOpening browser to extend key...%s", GREEN, RESET);
            openBrowser(extendURL);
        }
        exit(1);
    }

    if (valid) {
        // Valid key
        writefln("%sValid%s", GREEN, RESET);
        writefln("Public Key: %s", publicKey);
        writefln("Tier: %s", tier);
        writefln("Status: %s", status);

        if ("expires_at" in result) {
            string expiresAt = result["expires_at"].str;
            writefln("Expires: %s", expiresAt);

            // Calculate time remaining (simplified - just show the date)
            // Full datetime parsing would require additional complexity
        }

        if ("rate_limit" in result && result["rate_limit"].type != JSONType.null_) {
            writefln("Rate Limit: %.0f req/min", result["rate_limit"].floating);
        }
        if ("burst" in result && result["burst"].type != JSONType.null_) {
            writefln("Burst: %.0f req", result["burst"].floating);
        }
        if ("concurrency" in result && result["concurrency"].type != JSONType.null_) {
            writefln("Concurrency: %.0f", result["concurrency"].floating);
        }

        if (extend) {
            string extendURL = PORTAL_BASE ~ "/keys/extend?pk=" ~ publicKey;
            writefln("\n%sOpening browser to extend key...%s", GREEN, RESET);
            openBrowser(extendURL);
        }
    } else {
        // Invalid key
        writefln("%sInvalid%s", RED, RESET);
        if ("error" in result) {
            writefln("Reason: %s", result["error"].str);
        }
        exit(1);
    }
}

int main(string[] args) {
    string publicKey = environment.get("UNSANDBOX_PUBLIC_KEY", "");
    string secretKey = environment.get("UNSANDBOX_SECRET_KEY", "");

    // Fall back to UNSANDBOX_API_KEY for backwards compatibility
    if (publicKey.empty) {
        publicKey = environment.get("UNSANDBOX_API_KEY", "");
    }

    if (args.length < 2) {
        stderr.writefln("Usage: %s [options] <source_file>", args[0]);
        stderr.writefln("       %s languages [--json]", args[0]);
        stderr.writefln("       %s session [options]", args[0]);
        stderr.writefln("       %s service [options]", args[0]);
        stderr.writefln("       %s service env <action> <service_id> [options]", args[0]);
        stderr.writefln("       %s image [options]", args[0]);
        stderr.writefln("       %s key [options]", args[0]);
        stderr.writeln("");
        stderr.writeln("Service env commands:");
        stderr.writeln("  env status <id>     Show vault status");
        stderr.writeln("  env set <id>        Set vault (-e KEY=VALUE or --env-file FILE)");
        stderr.writeln("  env export <id>     Export vault contents");
        stderr.writeln("  env delete <id>     Delete vault");
        return 1;
    }

    if (args[1] == "session") {
        bool list = false;
        string kill, shell, network;
        int vcpu = 0;
        bool tmux = false, screen = false;
        string[] inputFiles;

        for (size_t i = 2; i < args.length; i++) {
            if (args[i] == "--list") list = true;
            else if (args[i] == "--kill" && i+1 < args.length) kill = args[++i];
            else if (args[i] == "--shell" && i+1 < args.length) shell = args[++i];
            else if (args[i] == "-n" && i+1 < args.length) network = args[++i];
            else if (args[i] == "-v" && i+1 < args.length) vcpu = to!int(args[++i]);
            else if (args[i] == "--tmux") tmux = true;
            else if (args[i] == "--screen") screen = true;
            else if (args[i] == "-f" && i+1 < args.length) inputFiles ~= args[++i];
            else if (args[i] == "-k" && i+1 < args.length) publicKey = args[++i];
        }

        cmdSession(list, kill, shell, network, vcpu, tmux, screen, inputFiles, publicKey, secretKey);
        return 0;
    }

    if (args[1] == "service") {
        string name, ports, bootstrap, bootstrapFile, type;
        bool list = false;
        string info, logs, tail, sleep, wake, destroy, resize, execute, command, dumpBootstrap, dumpFile, unfreezeOnDemand, network;
        bool unfreezeOnDemandEnabled = true;
        bool createUnfreezeOnDemand = false;
        int vcpu = 0;
        int resizeVcpu = 0;
        string[] inputFiles;
        string[] svcEnvs;
        string svcEnvFile;
        string envAction, envTarget;

        // Check for env subcommand
        if (args.length > 2 && args[2] == "env") {
            if (args.length > 3) envAction = args[3];
            if (args.length > 4 && !args[4].startsWith("-")) envTarget = args[4];
            for (size_t i = 5; i < args.length; i++) {
                if (args[i] == "-e" && i+1 < args.length) svcEnvs ~= args[++i];
                else if (args[i] == "--env-file" && i+1 < args.length) svcEnvFile = args[++i];
                else if (args[i] == "-k" && i+1 < args.length) publicKey = args[++i];
            }
            cmdService(name, ports, bootstrap, bootstrapFile, type, list, info, logs, tail, sleep, wake, destroy, resize, resizeVcpu, execute, command, dumpBootstrap, dumpFile, unfreezeOnDemand, unfreezeOnDemandEnabled, createUnfreezeOnDemand, network, vcpu, inputFiles, svcEnvs, svcEnvFile, envAction, envTarget, publicKey, secretKey);
            return 0;
        }

        for (size_t i = 2; i < args.length; i++) {
            if (args[i] == "--name" && i+1 < args.length) name = args[++i];
            else if (args[i] == "--ports" && i+1 < args.length) ports = args[++i];
            else if (args[i] == "--bootstrap" && i+1 < args.length) bootstrap = args[++i];
            else if (args[i] == "--bootstrap-file" && i+1 < args.length) bootstrapFile = args[++i];
            else if (args[i] == "--type" && i+1 < args.length) type = args[++i];
            else if (args[i] == "--list") list = true;
            else if (args[i] == "--info" && i+1 < args.length) info = args[++i];
            else if (args[i] == "--logs" && i+1 < args.length) logs = args[++i];
            else if (args[i] == "--tail" && i+1 < args.length) tail = args[++i];
            else if (args[i] == "--freeze" && i+1 < args.length) sleep = args[++i];
            else if (args[i] == "--unfreeze" && i+1 < args.length) wake = args[++i];
            else if (args[i] == "--destroy" && i+1 < args.length) destroy = args[++i];
            else if (args[i] == "--resize" && i+1 < args.length) resize = args[++i];
            else if (args[i] == "--vcpu" && i+1 < args.length) resizeVcpu = to!int(args[++i]);
            else if (args[i] == "--execute" && i+1 < args.length) execute = args[++i];
            else if (args[i] == "--command" && i+1 < args.length) command = args[++i];
            else if (args[i] == "--dump-bootstrap" && i+1 < args.length) dumpBootstrap = args[++i];
            else if (args[i] == "--dump-file" && i+1 < args.length) dumpFile = args[++i];
            else if (args[i] == "--unfreeze-on-demand" && i+1 < args.length) unfreezeOnDemand = args[++i];
            else if (args[i] == "--unfreeze-on-demand-enabled" && i+1 < args.length) unfreezeOnDemandEnabled = args[++i] == "true";
            else if (args[i] == "--with-unfreeze-on-demand") createUnfreezeOnDemand = true;
            else if (args[i] == "-n" && i+1 < args.length) network = args[++i];
            else if (args[i] == "-v" && i+1 < args.length) vcpu = to!int(args[++i]);
            else if (args[i] == "-f" && i+1 < args.length) inputFiles ~= args[++i];
            else if (args[i] == "-e" && i+1 < args.length) svcEnvs ~= args[++i];
            else if (args[i] == "--env-file" && i+1 < args.length) svcEnvFile = args[++i];
            else if (args[i] == "-k" && i+1 < args.length) publicKey = args[++i];
        }

        cmdService(name, ports, bootstrap, bootstrapFile, type, list, info, logs, tail, sleep, wake, destroy, resize, resizeVcpu, execute, command, dumpBootstrap, dumpFile, unfreezeOnDemand, unfreezeOnDemandEnabled, createUnfreezeOnDemand, network, vcpu, inputFiles, svcEnvs, svcEnvFile, envAction, envTarget, publicKey, secretKey);
        return 0;
    }

    if (args[1] == "key") {
        bool extend = false;

        for (size_t i = 2; i < args.length; i++) {
            if (args[i] == "--extend") extend = true;
            else if (args[i] == "-k" && i+1 < args.length) publicKey = args[++i];
        }

        if (publicKey.empty) {
            stderr.writefln("%sError: UNSANDBOX_PUBLIC_KEY or UNSANDBOX_API_KEY not set%s", RED, RESET);
            return 1;
        }

        validateKey(publicKey, secretKey, extend);
        return 0;
    }

    if (args[1] == "languages") {
        bool jsonOutput = false;

        for (size_t i = 2; i < args.length; i++) {
            if (args[i] == "--json") jsonOutput = true;
            else if (args[i] == "-k" && i+1 < args.length) publicKey = args[++i];
        }

        if (publicKey.empty) {
            stderr.writefln("%sError: UNSANDBOX_PUBLIC_KEY or UNSANDBOX_API_KEY not set%s", RED, RESET);
            return 1;
        }

        cmdLanguages(jsonOutput, publicKey, secretKey);
        return 0;
    }

    if (args[1] == "image") {
        bool list = false;
        string info, del, lock, unlock, publish, sourceType, visibilityId, visibility;
        string spawn, clone, name, ports;

        for (size_t i = 2; i < args.length; i++) {
            if (args[i] == "--list" || args[i] == "-l") list = true;
            else if (args[i] == "--info" && i+1 < args.length) info = args[++i];
            else if (args[i] == "--delete" && i+1 < args.length) del = args[++i];
            else if (args[i] == "--lock" && i+1 < args.length) lock = args[++i];
            else if (args[i] == "--unlock" && i+1 < args.length) unlock = args[++i];
            else if (args[i] == "--publish" && i+1 < args.length) publish = args[++i];
            else if (args[i] == "--source-type" && i+1 < args.length) sourceType = args[++i];
            else if (args[i] == "--visibility" && i+2 < args.length) {
                visibilityId = args[++i];
                visibility = args[++i];
            }
            else if (args[i] == "--spawn" && i+1 < args.length) spawn = args[++i];
            else if (args[i] == "--clone" && i+1 < args.length) clone = args[++i];
            else if (args[i] == "--name" && i+1 < args.length) name = args[++i];
            else if (args[i] == "--ports" && i+1 < args.length) ports = args[++i];
            else if (args[i] == "-k" && i+1 < args.length) publicKey = args[++i];
        }

        if (publicKey.empty) {
            stderr.writefln("%sError: UNSANDBOX_PUBLIC_KEY or UNSANDBOX_API_KEY not set%s", RED, RESET);
            return 1;
        }

        cmdImage(list, info, del, lock, unlock, publish, sourceType, visibilityId, visibility, spawn, clone, name, ports, publicKey, secretKey);
        return 0;
    }

    // Execute mode
    string[] envs;
    bool artifacts = false;
    string network, sourceFile;
    int vcpu = 0;

    for (size_t i = 1; i < args.length; i++) {
        if (args[i] == "-e" && i+1 < args.length) envs ~= args[++i];
        else if (args[i] == "-a") artifacts = true;
        else if (args[i] == "-n" && i+1 < args.length) network = args[++i];
        else if (args[i] == "-v" && i+1 < args.length) vcpu = to!int(args[++i]);
        else if (args[i] == "-k" && i+1 < args.length) publicKey = args[++i];
        else if (args[i].startsWith("-")) {
            stderr.writefln("%sUnknown option: %s%s", RED, args[i], RESET);
            return 1;
        }
        else sourceFile = args[i];
    }

    if (sourceFile.empty) {
        stderr.writefln("%sError: No source file specified%s", RED, RESET);
        return 1;
    }

    cmdExecute(sourceFile, envs, artifacts, network, vcpu, publicKey, secretKey);
    return 0;
}

Documentation clarifications

Dependencies

C Binary (un1) — requires libcurl and libwebsockets:

sudo apt install build-essential libcurl4-openssl-dev libwebsockets-dev
wget unsandbox.com/downloads/un.c && gcc -O2 -o un un.c -lcurl -lwebsockets

SDK Implementations — most use stdlib only (Ruby, JS, Go, etc). Some require minimal deps:

pip install requests  # Python

Execute Code

Run a Script

./un hello.py
./un app.js
./un main.rs

With Environment Variables

./un -e DEBUG=1 -e NAME=World script.py

With Input Files (teleport files into sandbox)

./un -f data.csv -f config.json process.py

Get Compiled Binary (teleport artifacts out)

./un -a -o ./bin main.c

Interactive Sessions

Start a Shell Session

# Default bash shell
./un session

# Choose your shell
./un session --shell zsh
./un session --shell fish

# Jump into a REPL
./un session --shell python3
./un session --shell node
./un session --shell julia

Session with Network Access

./un session -n semitrusted

Session Auditing (full terminal recording)

# Record everything (including vim, interactive programs)
./un session --audit -o ./logs

# Replay session later
zcat session.log*.gz | less -R

Collect Artifacts from Session

# Files in /tmp/artifacts/ are collected on exit
./un session -a -o ./outputs

Session Persistence (tmux/screen)

# Default: session terminates on disconnect (clean exit)
./un session

# With tmux: session persists, can reconnect later
./un session --tmux
# Press Ctrl+b then d to detach

# With screen: alternative multiplexer
./un session --screen
# Press Ctrl+a then d to detach

List Active Sessions

./un session --list

# Output:
# Active sessions: 2
#
# SESSION ID                               CONTAINER            SHELL      TTL      STATUS
# abc123...                                unsb-vm-12345        python3    45m30s   active
# def456...                                unsb-vm-67890        bash       1h2m     active

Reconnect to Existing Session

# Reconnect by container name (requires --tmux or --screen)
./un session --attach unsb-vm-12345

# Use exit to terminate session, or detach to keep it running

Terminate a Session

./un session --kill unsb-vm-12345

Available Shells & REPLs

Shells: bash, dash, sh, zsh, fish, ksh, tcsh, csh, elvish, xonsh, ash

REPLs:  python3, bpython, ipython    # Python
        node                          # JavaScript
        ruby, irb                     # Ruby
        lua                           # Lua
        php                           # PHP
        perl                          # Perl
        guile, scheme                 # Scheme
        ghci                          # Haskell
        erl, iex                      # Erlang/Elixir
        sbcl, clisp                   # Common Lisp
        r                             # R
        julia                         # Julia
        clojure                       # Clojure

API Key Management

Check Key Status

# Check if your API key is valid
./un key

# Output:
# Valid: key expires in 30 days

Extend Expired Key

# Open the portal to extend an expired key
./un key --extend

# This opens the unsandbox.com portal where you can
# add more credits to extend your key's expiration

Authentication

Credentials are loaded in priority order (highest first):

# 1. CLI flags (highest priority)
./un -p unsb-pk-xxxx -k unsb-sk-xxxxx script.py

# 2. Environment variables
export UNSANDBOX_PUBLIC_KEY=unsb-pk-xxxx-xxxx-xxxx-xxxx
export UNSANDBOX_SECRET_KEY=unsb-sk-xxxxx-xxxxx-xxxxx-xxxxx
./un script.py

# 3. Config file (lowest priority)
# ~/.unsandbox/accounts.csv format: public_key,secret_key
mkdir -p ~/.unsandbox
echo "unsb-pk-xxxx-xxxx-xxxx-xxxx,unsb-sk-xxxxx-xxxxx-xxxxx-xxxxx" > ~/.unsandbox/accounts.csv
./un script.py

Requests are signed with HMAC-SHA256. The bearer token contains only the public key; the secret key computes the signature (never transmitted).

Resource Scaling

Set vCPU Count

# Default: 1 vCPU, 2GB RAM
./un script.py

# Scale up: 4 vCPUs, 8GB RAM
./un -v 4 script.py

# Maximum: 8 vCPUs, 16GB RAM
./un --vcpu 8 heavy_compute.py

Live Session Boosting

# Boost a running session to 2 vCPU, 4GB RAM
./un session --boost sandbox-abc

# Boost to specific vCPU count (4 vCPU, 8GB RAM)
./un session --boost sandbox-abc --boost-vcpu 4

# Return to base resources (1 vCPU, 2GB RAM)
./un session --unboost sandbox-abc

Session Freeze/Unfreeze

Freeze and Unfreeze Sessions

# Freeze a session (stop billing, preserve state)
./un session --freeze sandbox-abc

# Unfreeze a frozen session
./un session --unfreeze sandbox-abc

# Note: Requires --tmux or --screen for persistence

Persistent Services

Create a Service

# Web server with ports
./un service --name web --ports 80,443 --bootstrap "python -m http.server 80"

# With custom domains
./un service --name blog --ports 8000 --domains blog.example.com

# Game server with SRV records
./un service --name mc --type minecraft --bootstrap ./setup.sh

# Deploy app tarball with bootstrap script
./un service --name app --ports 8000 -f app.tar.gz --bootstrap-file ./setup.sh
# setup.sh: cd /tmp && tar xzf app.tar.gz && ./app/start.sh

Manage Services

# List all services
./un service --list

# Get service details
./un service --info abc123

# View bootstrap logs
./un service --logs abc123
./un service --tail abc123  # last 9000 lines

# Execute command in running service
./un service --execute abc123 'journalctl -u myapp -n 50'

# Dump bootstrap script (for migrations)
./un service --dump-bootstrap abc123
./un service --dump-bootstrap abc123 backup.sh

# Freeze/unfreeze service
./un service --freeze abc123
./un service --unfreeze abc123

# Service settings (auto-wake, freeze page display)
./un service --auto-unfreeze abc123      # enable auto-wake on HTTP
./un service --no-auto-unfreeze abc123   # disable auto-wake
./un service --show-freeze-page abc123   # show HTML payment page (default)
./un service --no-show-freeze-page abc123  # return JSON error instead

# Redeploy with new bootstrap
./un service --redeploy abc123 --bootstrap ./new-setup.sh

# Destroy service
./un service --destroy abc123

Snapshots

List Snapshots

./un snapshot --list

# Output:
# Snapshots: 3
#
# SNAPSHOT ID                              NAME             SOURCE     SIZE     CREATED
# unsb-snapshot-a1b2-c3d4-e5f6-g7h8        before-upgrade   session    512 MB   2h ago
# unsb-snapshot-i9j0-k1l2-m3n4-o5p6        stable-v1.0      service    1.2 GB   1d ago

Create Session Snapshot

# Snapshot with name
./un session --snapshot unsb-vm-12345 --name "before upgrade"

# Quick snapshot (auto-generated name)
./un session --snapshot unsb-vm-12345

Create Service Snapshot

# Standard snapshot (pauses container briefly)
./un service --snapshot unsb-service-abc123 --name "stable v1.0"

# Hot snapshot (no pause, may be inconsistent)
./un service --snapshot unsb-service-abc123 --hot

Restore from Snapshot

# Restore session from snapshot
./un session --restore unsb-snapshot-a1b2-c3d4-e5f6-g7h8

# Restore service from snapshot
./un service --restore unsb-snapshot-i9j0-k1l2-m3n4-o5p6

Delete Snapshot

./un snapshot --delete unsb-snapshot-a1b2-c3d4-e5f6-g7h8

Images

Images are independent, transferable container images that survive container deletion. Unlike snapshots (which live with their container), images can be shared with other users, transferred between API keys, or made public in the marketplace.

List Images

# List all images (owned + shared + public)
./un image --list

# List only your images
./un image --list owned

# List images shared with you
./un image --list shared

# List public marketplace images
./un image --list public

# Get image details
./un image --info unsb-image-xxxx-xxxx-xxxx-xxxx

Publish Images

# Publish from a stopped or frozen service
./un image --publish-service unsb-service-abc123 \
   --name "My App v1.0" --description "Production snapshot"

# Publish from a snapshot
./un image --publish-snapshot unsb-snapshot-xxxx-xxxx-xxxx-xxxx \
   --name "Stable Release"

# Note: Cannot publish from running containers - stop or freeze first

Create Services from Images

# Spawn a new service from an image
./un image --spawn unsb-image-xxxx-xxxx-xxxx-xxxx \
   --name new-service --ports 80,443

# Clone an image (creates a copy you own)
./un image --clone unsb-image-xxxx-xxxx-xxxx-xxxx

Image Protection

# Lock image to prevent accidental deletion
./un image --lock unsb-image-xxxx-xxxx-xxxx-xxxx

# Unlock image to allow deletion
./un image --unlock unsb-image-xxxx-xxxx-xxxx-xxxx

# Delete image (must be unlocked)
./un image --delete unsb-image-xxxx-xxxx-xxxx-xxxx

Visibility & Sharing

# Set visibility level
./un image --visibility unsb-image-xxxx-xxxx-xxxx-xxxx private   # owner only (default)
./un image --visibility unsb-image-xxxx-xxxx-xxxx-xxxx unlisted  # can be shared
./un image --visibility unsb-image-xxxx-xxxx-xxxx-xxxx public    # marketplace

# Share with specific user
./un image --grant unsb-image-xxxx-xxxx-xxxx-xxxx \
   --key unsb-pk-friend-friend-friend-friend

# Revoke access
./un image --revoke unsb-image-xxxx-xxxx-xxxx-xxxx \
   --key unsb-pk-friend-friend-friend-friend

# List who has access
./un image --trusted unsb-image-xxxx-xxxx-xxxx-xxxx

Transfer Ownership

# Transfer image to another API key
./un image --transfer unsb-image-xxxx-xxxx-xxxx-xxxx \
   --to unsb-pk-newowner-newowner-newowner-newowner

Usage Reference

Usage: ./un [options] <source_file>
       ./un session [options]
       ./un service [options]
       ./un snapshot [options]
       ./un image [options]
       ./un key

Commands:
  (default)        Execute source file in sandbox
  session          Open interactive shell/REPL session
  service          Manage persistent services
  snapshot         Manage container snapshots
  image            Manage container images (publish, share, transfer)
  key              Check API key validity and expiration

Options:
  -e KEY=VALUE     Set environment variable (can use multiple times)
  -f FILE          Add input file (can use multiple times)
  -a               Return and save artifacts from /tmp/artifacts/
  -o DIR           Output directory for artifacts (default: current dir)
  -p KEY           Public key (or set UNSANDBOX_PUBLIC_KEY env var)
  -k KEY           Secret key (or set UNSANDBOX_SECRET_KEY env var)
  -n MODE          Network mode: zerotrust (default) or semitrusted
  -v N, --vcpu N   vCPU count 1-8, each vCPU gets 2GB RAM (default: 1)
  -y               Skip confirmation for large uploads (>1GB)
  -h               Show this help

Authentication (priority order):
  1. -p and -k flags (public and secret key)
  2. UNSANDBOX_PUBLIC_KEY + UNSANDBOX_SECRET_KEY env vars
  3. ~/.unsandbox/accounts.csv (format: public_key,secret_key per line)

Session options:
  -s, --shell SHELL  Shell/REPL to use (default: bash)
  -l, --list         List active sessions
  --attach ID        Reconnect to existing session (ID or container name)
  --kill ID          Terminate a session (ID or container name)
  --freeze ID        Freeze a session (requires --tmux/--screen)
  --unfreeze ID      Unfreeze a frozen session
  --boost ID         Boost session resources (2 vCPU, 4GB RAM)
  --boost-vcpu N     Specify vCPU count for boost (1-8)
  --unboost ID       Return to base resources
  --audit            Record full session for auditing
  --tmux             Enable session persistence with tmux (allows reconnect)
  --screen           Enable session persistence with screen (allows reconnect)

Service options:
  --name NAME        Service name (creates new service)
  --ports PORTS      Comma-separated ports (e.g., 80,443)
  --domains DOMAINS  Custom domains (e.g., example.com,www.example.com)
  --type TYPE        Service type: minecraft, mumble, teamspeak, source, tcp, udp
  --bootstrap CMD    Bootstrap command/file/URL to run on startup
  -f FILE            Upload file to /tmp/ (can use multiple times)
  -l, --list         List all services
  --info ID          Get service details
  --tail ID          Get last 9000 lines of bootstrap logs
  --logs ID          Get all bootstrap logs
  --freeze ID        Freeze a service
  --unfreeze ID      Unfreeze a service
  --auto-unfreeze ID       Enable auto-wake on HTTP request
  --no-auto-unfreeze ID    Disable auto-wake on HTTP request
  --show-freeze-page ID    Show HTML payment page when frozen (default)
  --no-show-freeze-page ID Return JSON error when frozen
  --destroy ID       Destroy a service
  --redeploy ID      Re-run bootstrap script (requires --bootstrap)
  --execute ID CMD   Run a command in a running service
  --dump-bootstrap ID [FILE]  Dump bootstrap script (for migrations)
  --snapshot ID    Create snapshot of session or service
  --snapshot-name  User-friendly name for snapshot
  --hot            Create snapshot without pausing (may be inconsistent)
  --restore ID     Restore session/service from snapshot ID

Snapshot options:
  -l, --list       List all snapshots
  --info ID        Get snapshot details
  --delete ID      Delete a snapshot permanently

Image options:
  -l, --list [owned|shared|public]  List images (all, owned, shared, or public)
  --info ID        Get image details
  --publish-service ID   Publish image from stopped/frozen service
  --publish-snapshot ID  Publish image from snapshot
  --name NAME      Name for published image
  --description DESC  Description for published image
  --delete ID      Delete image (must be unlocked)
  --clone ID       Clone image (creates copy you own)
  --spawn ID       Create service from image (requires --name)
  --lock ID        Lock image to prevent deletion
  --unlock ID      Unlock image to allow deletion
  --visibility ID LEVEL  Set visibility (private|unlisted|public)
  --grant ID --key KEY   Grant access to another API key
  --revoke ID --key KEY  Revoke access from API key
  --transfer ID --to KEY Transfer ownership to API key
  --trusted ID     List API keys with access

Key options:
  (no options)       Check API key validity
  --extend           Open portal to extend an expired key

Examples:
  ./un script.py                       # execute Python script
  ./un -e DEBUG=1 script.py            # with environment variable
  ./un -f data.csv process.py          # with input file
  ./un -a -o ./bin main.c              # save compiled artifacts
  ./un -v 4 heavy.py                   # with 4 vCPUs, 8GB RAM
  ./un session                         # interactive bash session
  ./un session --tmux                  # bash with reconnect support
  ./un session --list                  # list active sessions
  ./un session --attach unsb-vm-12345  # reconnect to session
  ./un session --kill unsb-vm-12345    # terminate a session
  ./un session --freeze unsb-vm-12345  # freeze session
  ./un session --unfreeze unsb-vm-12345  # unfreeze session
  ./un session --boost unsb-vm-12345   # boost resources
  ./un session --unboost unsb-vm-12345 # return to base
  ./un session --shell python3         # Python REPL
  ./un session --shell node            # Node.js REPL
  ./un session -n semitrusted          # session with network access
  ./un session --audit -o ./logs       # record session for auditing
  ./un service --name web --ports 80   # create web service
  ./un service --list                  # list all services
  ./un service --logs abc123           # view bootstrap logs
  ./un key                             # check API key
  ./un key --extend                    # extend expired key
  ./un snapshot --list                 # list all snapshots
  ./un session --snapshot unsb-vm-123  # snapshot a session
  ./un service --snapshot abc123       # snapshot a service
  ./un session --restore unsb-snapshot-xxxx  # restore from snapshot
  ./un image --list                  # list all images
  ./un image --list owned            # list your images
  ./un image --publish-service abc   # publish image from service
  ./un image --spawn img123 --name x # create service from image
  ./un image --grant img --key pk    # share image with user

CLI Inception

The UN CLI has been implemented in 42 programming languages, demonstrating that the unsandbox API can be accessed from virtually any environment.

View All 42 Implementations →

License

PUBLIC DOMAIN - NO LICENSE, NO WARRANTY

This is free public domain software for the public good of a permacomputer hosted
at permacomputer.com - an always-on computer by the people, for the people. One
that is durable, easy to repair, and distributed like tap water for machine
learning intelligence.

The permacomputer is community-owned infrastructure optimized around four values:

  TRUTH    - First principles, math & science, open source code freely distributed
  FREEDOM  - Voluntary partnerships, freedom from tyranny & corporate control
  HARMONY  - Minimal waste, self-renewing systems with diverse thriving connections
  LOVE     - Be yourself without hurting others, cooperation through natural law

This software contributes to that vision by enabling code execution across all 42
programming languages through a unified interface, accessible to everyone. Code is
seeds to sprout on any abandoned technology.

Learn more: https://www.permacomputer.com

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.

NO WARRANTY. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.

That said, our permacomputer's digital membrane stratum continuously runs unit,
integration, and functional tests on all its own software - with our permacomputer
monitoring itself, repairing itself, with minimal human guidance in the loop.
Our agents do their best.

Copyright 2025 TimeHexOn & foxhop & russell@unturf
https://www.timehexon.com
https://www.foxhop.net
https://www.unturf.com/software

Export Vault

Enter a password to encrypt your exported vault. You'll need this password to import the vault on another device.

Import Vault

Select an exported vault file and enter the export password to decrypt it.