diff --git a/tools/server/server.cpp b/tools/server/server.cpp
--- a/llama.cpp/tools/server/server.cpp
+++ b/llama.cpp/tools/server/server.cpp
@@ -15,6 +15,7 @@
 #include <atomic>
 #include <clocale>
 #include <exception>
+#include <functional>
 #include <signal.h>
 #include <thread> // for std::thread::hardware_concurrency
 
@@ -22,6 +23,13 @@
 #include <windows.h>
 #endif
 
+#ifdef COSMOCC
+#include <cerrno>
+#include <cstring>
+#include <cosmo.h>
+#include "llamafile.h"
+#endif
+
 static std::function<void(int)> shutdown_handler;
 static std::atomic_flag is_terminating = ATOMIC_FLAG_INIT;
 
@@ -40,7 +48,19 @@ static inline void signal_handler(int signal) {
 int llama_server(int argc, char ** argv);
 
 // to be used via CLI (argc / argv are used by router mode only)
-int llama_server(common_params & params, int argc, char ** argv);
+// on_ready / on_shutdown_available are llamafile combined-mode (TUI) callbacks.
+int llama_server(common_params & params, int argc, char ** argv,
+                 std::function<void(const std::string &)> on_ready = nullptr,
+                 std::function<void(std::function<void()>)> on_shutdown_available = nullptr);
+
+// Core server logic - can be called from llamafile main.cpp or standalone main()
+// Optional callbacks for combined mode:
+//   on_ready: called when server is fully loaded and accepting requests
+//   on_shutdown_available: provides a function to trigger server shutdown
+int server_main(int argc, char ** argv,
+                std::function<void(const std::string &)> on_ready,
+                std::function<void(std::function<void()>)> on_shutdown_available);
+
 void llama_server_terminate();
 void llama_server_terminate() {
     if (shutdown_handler) {
@@ -86,11 +106,23 @@ static server_http_context::handler_t ex_wrapper(server_http_context::handler_t
 }
 
 int llama_server(int argc, char ** argv) {
+    // thin wrapper for the `llama` multiplexer command; combined-mode callbacks
+    // are only used by llamafile's own TUI, which calls server_main() directly.
+    return server_main(argc, argv, nullptr, nullptr);
+}
+
+int server_main(int argc, char ** argv,
+                std::function<void(const std::string &)> on_ready,
+                std::function<void(std::function<void()>)> on_shutdown_available) {
     std::setlocale(LC_NUMERIC, "C");
 
     // own arguments required by this example
     common_params params;
 
+#ifdef COSMOCC
+    llamafile_has_metal();  // triggers Metal backend registration on macOS ARM64
+#endif
+
     common_init();
 
     // start the stream session manager GC right after common init, before any HTTP route can
@@ -104,10 +136,12 @@ int llama_server(int argc, char ** argv) {
     llama_backend_init();
     llama_numa_init(params.numa);
 
-    return llama_server(params, argc, argv);
+    return llama_server(params, argc, argv, on_ready, on_shutdown_available);
 }
 
-int llama_server(common_params & params, int argc, char ** argv) {
+int llama_server(common_params & params, int argc, char ** argv,
+                 std::function<void(const std::string &)> on_ready,
+                 std::function<void(std::function<void()>)> on_shutdown_available) {
     bool is_run_by_cli = (argv == nullptr);
 
     common_models_handler models_handler;
@@ -415,6 +449,92 @@ int llama_server(common_params & params, int argc, char ** argv) {
             llama_backend_free();
         };
 
+#ifdef COSMOCC
+        // Sandbox (pledge()/unveil(), llamafile issue #930). The whole
+        // derivation lives in llamafile/sandbox.c so it stays unit-testable
+        // and off the vendored diff. Placement is constrained on every side:
+        //   - after common_params_parse(): -hf downloads need connect()
+        //   - after ctx_http.init(): the TLS certificate/key are read there
+        //   - before ctx_http.start(): filters only cover threads created
+        //     after installation, so the HTTP listener/pool must not exist
+        //   - before load_model(): untrusted GGUF data is parsed sandboxed
+        //
+        // Combined mode hosts an in-process HTTP client (the TUI) that needs
+        // connect(), which the accept-only sandbox forbids, so it's skipped.
+        const bool combined_mode = on_ready || on_shutdown_available;
+        if (combined_mode) {
+            SRV_WRN("%s", "sandbox: disabled in combined mode; use --server for a sandboxed server\n");
+        } else {
+            // pledge() (no outbound network / writes / exec) is applied by
+            // default. unveil() path confinement is opt-in (--confine-reads),
+            // because a server opens files by path at request time (multimodal
+            // media, etc.) that can't be known when the ruleset locks.
+            //
+            // cosmo installs the SECCOMP/Landlock filters on the calling thread
+            // only (no TSYNC), so quiesce every pre-existing background thread
+            // across the call: the llama.cpp log worker (pause() joins it,
+            // resume() respawns it under the filter) and the stream-session GC
+            // started at the top of server_main() (stop joins it, start
+            // respawns it; no sessions exist yet, so stopping is a no-op
+            // beyond the join).
+            //
+            // When --confine-reads is on, unveil() confines reads to these
+            // directories, so collect every on-disk path the loader opens
+            // after the lock. Add to this list when llama.cpp gains a new file
+            // parameter (else it'd be denied under confinement). Paths read
+            // before the sandbox (ssl_file_key/cert in ctx_http.init(), -hf
+            // downloads in parse) need no entry.
+            std::vector<const char *> read_paths, rw_paths;
+            read_paths.push_back(params.model.path.c_str());
+            read_paths.push_back(params.mmproj.path.c_str());
+            read_paths.push_back(params.media_path.c_str());  // request-time media
+            read_paths.push_back(params.speculative.draft.mparams.path.c_str());
+            read_paths.push_back(params.speculative.ngram_cache.lookup_cache_static.c_str());
+            read_paths.push_back(params.public_path.c_str());
+            for (const auto & la : params.lora_adapters)
+                read_paths.push_back(la.path.c_str());
+            for (const auto & cv : params.control_vectors)
+                read_paths.push_back(cv.fname.c_str());
+            rw_paths.push_back(params.slot_save_path.c_str());
+            rw_paths.push_back(params.path_prompt_cache.c_str());
+            rw_paths.push_back(params.speculative.ngram_cache.lookup_cache_dynamic.c_str());
+
+            // Features that dial out at runtime need connect(), which the
+            // accept-only default forbids; relax to full sockets for them
+            // (still no writes/exec). --rpc has no params field -- its handler
+            // registers backends directly -- so detect it on argv/env.
+            const bool needs_outbound =
+                params.ui_mcp_proxy ||
+                !params.server_tools.empty() ||
+                llamafile_has(argv, "--rpc") ||
+                (std::getenv("LLAMA_ARG_RPC") != nullptr);
+
+            llamafile_sandbox_spec spec = {
+                read_paths.data(), (int) read_paths.size(),
+                rw_paths.data(), (int) rw_paths.size(),
+                FLAG_confine_reads, needs_outbound,
+            };
+            char promises[64];
+            common_log_pause(common_log_main());
+            server_stream_session_manager_stop();
+            int sandbox = llamafile_sandbox_server(&spec, promises, sizeof(promises));
+            int sandbox_errno = errno;  // capture before the respawns spawn threads
+            server_stream_session_manager_start();
+            common_log_resume(common_log_main());
+            if (sandbox == LLAMAFILE_SANDBOX_FAILED) {
+                SRV_ERR("sandbox: pledge failed: %s; retry with --unsecure to disable sandboxing\n",
+                        strerror(sandbox_errno));
+                clean_up();
+                return 1;
+            } else if (llamafile_sandbox_is_active(sandbox)) {
+                SRV_INF("sandbox: pledge(\"%s\") %s\n", promises,
+                        llamafile_sandbox_describe(sandbox));
+            } else {
+                SRV_WRN("sandbox: %s\n", llamafile_sandbox_describe(sandbox));
+            }
+        }
+#endif
+
         // start the HTTP server before loading the model to be able to serve /health requests
         if (!ctx_http.start()) {
             clean_up();
@@ -447,6 +567,13 @@ int llama_server(common_params & params, int argc, char ** argv) {
             // this will unblock start_loop()
             ctx_server.terminate();
         };
+
+        // Provide shutdown function to caller (for combined mode)
+        if (on_shutdown_available) {
+            on_shutdown_available([&ctx_server]() {
+                ctx_server.terminate();
+            });
+        }
     }
 
     // register signal handler if not running by CLI
@@ -481,6 +608,11 @@ int llama_server(common_params & params, int argc, char ** argv) {
         // when the HTTP server stops, clean up and exit
         clean_up();
     } else {
+        // Notify caller that server is ready (for combined mode TUI startup)
+        if (on_ready) {
+            on_ready(ctx_http.listening_address);
+        }
+
         // optionally, notify router server that this instance is ready
         std::thread monitor_thread;
         if (child.is_child()) {
@@ -505,5 +637,56 @@ int llama_server(common_params & params, int argc, char ** argv) {
         }
     }
 
+#ifdef LLAMAFILE_TUI
+    // In combined mode (callbacks provided), return normally so the caller
+    // can handle cleanup and TUI thread joining
+    if (on_ready || on_shutdown_available) {
+        return 0;
+    }
+    // By now the program can safely exit:
+    // Metal backend has async logging that llama_synchronize() doesn't wait for.
+    // Without this delay, _exit() might truncate llama_memory_breakdown_print's output
+    sleep(1);
+    // Use _exit() to avoid Metal cleanup crash (dangling refs with TUI + Metal + server)
+    _exit(0);
+#else
     return 0;
+#endif
 }
+
+// Standalone entry point for llama-server executable
+// Not compiled when building as part of llamafile TUI (which has its own main)
+// Having this allows us to test cosmocc-compiled llama.cpp in isolation.
+#ifndef LLAMAFILE_TUI
+int main(int argc, char ** argv) {
+#ifdef COSMOCC
+    argc = cosmo_args("/zip/.args", &argv);
+
+    // Check if verbose mode is requested (must be set before GPU init)
+    bool verbose = llamafile_has(argv, "--verbose");
+    FLAG_verbose = verbose ? 1 : 0;
+
+    // --unsecure is llamafile's flag, not llama.cpp's: consume it here so
+    // common_params_parse() never sees it (llamafile's own main strips it
+    // via parse_llamafile_args instead)
+    if (llamafile_consume_flag(&argc, argv, "--unsecure"))
+        FLAG_unsecure = true;
+    if (llamafile_consume_flag(&argc, argv, "--confine-reads"))
+        FLAG_confine_reads = true;
+
+    // Initialize GPU support early (must happen BEFORE llama_backend_init())
+    // This triggers dynamic loading of GPU backends (CUDA, ROCm, Metal)
+    // The llamafile_has_* functions use lazy initialization via cosmo_once()
+    llamafile_has_gpu();
+    if (!verbose) {
+        // disable ggml verbose logging
+        if (llamafile_has_metal()) {
+            llamafile_metal_log_set(llamafile_log_callback_null, NULL);
+        } else if (llamafile_has_cuda() || llamafile_has_amd_gpu()) {
+            llamafile_cuda_log_set(llamafile_log_callback_null, NULL);
+        }
+    }
+#endif
+    return server_main(argc, argv, nullptr, nullptr);
+}
+#endif
