Commit 777839789 for llama.cpp

commit 77783978926c321b9c77243dc0bf134cdb7c5f02
Author: Pascal <admin@serveurperso.com>
Date:   Mon Nov 30 16:09:01 2026 +0100

    server: run tool commands as a job ended with everything it started (#33367)

    run_subprocess read the output until EOF and the timeout only killed
    the shell, so a process the command left running kept the pipe open
    and the call with it.

    The command now runs as a job: a process group of its own on POSIX
    (posix_spawn), a Job Object on Windows (created suspended, then
    assigned). The output is polled against a deadline, and the whole job
    is killed once the command exits, times out, or the caller stops it.

    tools_io::run takes a should_stop, checked even while the command
    writes nothing, so dropping a /tools request stops its command.

    On Windows, cmd gets /d /s /c and the command as written, since it
    does not parse its command line with the C runtime rules.

diff --git a/tools/server/server-tools.cpp b/tools/server/server-tools.cpp
index 7f4650157..97bf2136d 100644
--- a/tools/server/server-tools.cpp
+++ b/tools/server/server-tools.cpp
@@ -30,6 +30,11 @@
 #   include <io.h>
 #else
 #   include <cerrno>
+#   include <csignal>
+#   include <fcntl.h>
+#   include <poll.h>
+#   include <spawn.h>
+#   include <sys/wait.h>
 #   include <unistd.h>
 #endif

@@ -176,15 +181,49 @@ public:
     virtual list_result list_entries(const std::string & base, int max_depth, list_kind kind) const = 0;
     // on_chunk, if set, is called with each chunk of output as it is read (before truncation cuts in);
     // returning false terminates the process early (e.g. the client disconnected)
+    // should_stop, if set, is checked while the process runs, even when it writes nothing; true terminates it
     virtual exec_result run(
             const std::vector<std::string> & args,
             size_t max_output,
             int timeout_secs,
-            const std::function<bool(const std::string &)> & on_chunk = nullptr) const = 0;
+            const std::function<bool(const std::string &)> & on_chunk = nullptr,
+            const std::function<bool()> & should_stop = nullptr) const = 0;
+};
+
+// time the output gets to close once the job is killed, and between two checks of exit, deadline and stop
+static constexpr int SERVER_TOOL_SUBPROCESS_DRAIN_MS = 2000;
+static constexpr int SERVER_TOOL_SUBPROCESS_POLL_MS  = 100;
+
+// output of a job, capped at max_output, handed to on_chunk as it arrives until on_chunk returns false
+struct subprocess_output {
+    size_t max_output;
+    const std::function<bool(const std::string &)> & on_chunk;
+    std::string text;
+    bool truncated = false;
+    bool stopped   = false;
+
+    subprocess_output(size_t max_output, const std::function<bool(const std::string &)> & on_chunk)
+        : max_output(max_output), on_chunk(on_chunk) {}
+
+    void add(const char * buf, size_t len) {
+        if (truncated) {
+            return;
+        }
+        if (text.size() + len > max_output) {
+            len = max_output - text.size();
+            truncated = true;
+        }
+        text.append(buf, len);
+        if (on_chunk && !stopped && len > 0) {
+            stopped = !on_chunk(console_output_to_utf8(std::string(buf, len)));
+        }
+    }
 };

 // shared subprocess execution helper, used by both the local and the isolate-backed tools_io implementations.
 // combine_stderr=false when the raw stdout bytes must not be tainted by stderr, e.g. reading file contents.
+// the command runs as a job, a process group on POSIX and a Job Object on Windows, killed with everything it started
+// once the command exits, times out, or the caller stops it, so a call leaves nothing running
 static tools_io::exec_result run_subprocess(
         const std::vector<std::string> & args,
         size_t max_output,
@@ -192,110 +231,445 @@ static tools_io::exec_result run_subprocess(
         const std::function<bool(const std::string &)> & on_chunk,
         bool combine_stderr,
         const std::string & cwd = "",
-        const std::string * stdin_data = nullptr) {
+        const std::string * stdin_data = nullptr,
+        const std::function<bool()> & should_stop = nullptr);
+
+#if !defined(LLAMA_SUBPROCESS)
+
+static tools_io::exec_result run_subprocess(
+        const std::vector<std::string> &, size_t, int, const std::function<bool(const std::string &)> &,
+        bool, const std::string &, const std::string *, const std::function<bool()> &) {
     tools_io::exec_result res;
+    res.output = "failed to spawn process";
+    return res;
+}

-    common_subproc proc;
+#elif defined(_WIN32)

-    int options = subprocess_option_no_window
-                | subprocess_option_inherit_environment
-                | subprocess_option_search_user_path;
-    if (combine_stderr) {
-        options |= subprocess_option_combined_stdout_stderr;
+struct subprocess_handle {
+    HANDLE h = nullptr;
+
+    subprocess_handle() = default;
+    explicit subprocess_handle(HANDLE h) : h(h == INVALID_HANDLE_VALUE ? nullptr : h) {}
+    subprocess_handle(const subprocess_handle &) = delete;
+    subprocess_handle & operator=(const subprocess_handle &) = delete;
+    ~subprocess_handle() { reset(); }
+
+    void reset() {
+        if (h) {
+            CloseHandle(h);
+            h = nullptr;
+        }
+    }
+};
+
+static std::wstring subprocess_wide(const std::string & s) {
+    const int len = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int) s.size(), nullptr, 0);
+    std::wstring w(len, L'\0');
+    MultiByteToWideChar(CP_UTF8, 0, s.data(), (int) s.size(), w.data(), len);
+    return w;
+}
+
+// the command line the MSVC runtime of the child parses back into args
+// cmd.exe parses its own command line without the C runtime rules, so its args go as written
+static std::wstring subprocess_command_line(const std::vector<std::string> & args) {
+    const bool verbatim = !args.empty() && _stricmp(args[0].c_str(), "cmd") == 0;
+    std::string line;
+    for (const auto & arg : args) {
+        if (!line.empty()) {
+            line += ' ';
+        }
+        if (verbatim) {
+            line += arg;
+            continue;
+        }
+        const bool quote = arg.empty() || arg.find_first_of(" \t\v") != std::string::npos;
+        if (quote) {
+            line += '"';
+        }
+        size_t backslashes = 0;
+        for (const char c : arg) {
+            if (c == '\\') {
+                backslashes++;
+                continue;
+            }
+            line.append(c == '"' ? backslashes * 2 + 1 : backslashes, '\\');
+            line += c;
+            backslashes = 0;
+        }
+        line.append(quote ? backslashes * 2 : backslashes, '\\');
+        if (quote) {
+            line += '"';
+        }
+    }
+    return subprocess_wide(line);
+}
+
+// reads the output of the job until every writer closed its end
+struct subprocess_reader {
+    HANDLE pipe;
+    std::mutex mutex;
+    std::string pending;
+
+    std::string take() {
+        std::string chunk;
+        std::lock_guard<std::mutex> lock(mutex);
+        chunk.swap(pending);
+        return chunk;
     }

-    if (!proc.create(args, options, {}, cwd.empty() ? nullptr : cwd.c_str())) {
-        res.output = "failed to spawn process";
+    static DWORD WINAPI run(void * p) {
+        auto * r = (subprocess_reader *) p;
+        char buf[4096];
+        DWORD got = 0;
+        while (ReadFile(r->pipe, buf, sizeof(buf), &got, nullptr) && got > 0) {
+            std::lock_guard<std::mutex> lock(r->mutex);
+            r->pending.append(buf, got);
+        }
+        return 0;
+    }
+};
+
+// writes the stdin data of the job, then closes it
+struct subprocess_writer {
+    HANDLE pipe;
+    const std::string * data;
+
+    static DWORD WINAPI run(void * p) {
+        auto * w = (subprocess_writer *) p;
+        size_t done = 0;
+        DWORD put = 0;
+        while (done < w->data->size() &&
+               WriteFile(w->pipe, w->data->data() + done, (DWORD) std::min<size_t>(w->data->size() - done, 65536), &put, nullptr)) {
+            done += put;
+        }
+        CloseHandle(w->pipe);
+        return 0;
+    }
+};
+
+static tools_io::exec_result run_subprocess(
+        const std::vector<std::string> & args,
+        size_t max_output,
+        int timeout_secs,
+        const std::function<bool(const std::string &)> & on_chunk,
+        bool combine_stderr,
+        const std::string & cwd,
+        const std::string * stdin_data,
+        const std::function<bool()> & should_stop) {
+    tools_io::exec_result res;
+    res.output = "failed to spawn process";
+
+    // only the child ends are inheritable, and only by this child (handle list below)
+    SECURITY_ATTRIBUTES sa = { sizeof(sa), nullptr, TRUE };
+    HANDLE in_r = nullptr, in_w = nullptr, out_r = nullptr, out_w = nullptr;
+    if (!CreatePipe(&in_r, &in_w, &sa, 0)) {
+        return res;
+    }
+    subprocess_handle in_child(in_r), in_parent(in_w);
+    if (!CreatePipe(&out_r, &out_w, &sa, 0)) {
+        return res;
+    }
+    subprocess_handle out_parent(out_r), out_child(out_w);
+    subprocess_handle err_child(combine_stderr ? nullptr :
+        CreateFileW(L"NUL", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, nullptr));
+    SetHandleInformation(in_parent.h,  HANDLE_FLAG_INHERIT, 0);
+    SetHandleInformation(out_parent.h, HANDLE_FLAG_INHERIT, 0);
+    HANDLE err = combine_stderr ? out_child.h : err_child.h;
+    if (!err) {
         return res;
     }

-    std::atomic<bool> done{false};
-    std::atomic<bool> timed_out{false};
+    subprocess_handle job(CreateJobObjectW(nullptr, nullptr));
+    if (!job.h) {
+        return res;
+    }
+    JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits = {};
+    limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
+    SetInformationJobObject(job.h, JobObjectExtendedLimitInformation, &limits, sizeof(limits));
+
+    HANDLE inherited[3] = { in_child.h, out_child.h, err };
+    const DWORD n_inherited = combine_stderr ? 2 : 3;
+    SIZE_T attrs_size = 0;
+    InitializeProcThreadAttributeList(nullptr, 1, 0, &attrs_size);
+    std::vector<char> attrs_buf(attrs_size);
+    auto attrs = (LPPROC_THREAD_ATTRIBUTE_LIST) attrs_buf.data();
+    if (!InitializeProcThreadAttributeList(attrs, 1, 0, &attrs_size)) {
+        return res;
+    }
+    UpdateProcThreadAttribute(attrs, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherited, n_inherited * sizeof(HANDLE), nullptr, nullptr);
+
+    STARTUPINFOEXW si = {};
+    si.StartupInfo.cb         = sizeof(si);
+    si.StartupInfo.dwFlags    = STARTF_USESTDHANDLES;
+    si.StartupInfo.hStdInput  = in_child.h;
+    si.StartupInfo.hStdOutput = out_child.h;
+    si.StartupInfo.hStdError  = err;
+    si.lpAttributeList        = attrs;
+
+    // suspended until it belongs to the job, so nothing it starts escapes the job
+    std::wstring command = subprocess_command_line(args);
+    const std::wstring directory = subprocess_wide(cwd);
+    PROCESS_INFORMATION pi = {};
+    const BOOL spawned = CreateProcessW(nullptr, command.data(), nullptr, nullptr, TRUE,
+                                        CREATE_SUSPENDED | CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, nullptr,
+                                        cwd.empty() ? nullptr : directory.c_str(), &si.StartupInfo, &pi);
+    DeleteProcThreadAttributeList(attrs);
+    in_child.reset();
+    out_child.reset();
+    err_child.reset();
+    if (!spawned) {
+        return res;
+    }
+    subprocess_handle process(pi.hProcess), thread(pi.hThread);
+    if (!AssignProcessToJobObject(job.h, process.h)) {
+        TerminateProcess(process.h, 1);
+        return res;
+    }
+    ResumeThread(thread.h);

-    std::thread timeout_thread([&]() {
-        auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout_secs);
-        while (!done.load()) {
-            if (std::chrono::steady_clock::now() >= deadline) {
-                timed_out.store(true);
-                proc.terminate();
-                return;
-            }
-            std::this_thread::sleep_for(std::chrono::milliseconds(100));
+    subprocess_reader reader;
+    reader.pipe = out_parent.h;
+    subprocess_handle reading(CreateThread(nullptr, 0, subprocess_reader::run, &reader, 0, nullptr));
+
+    subprocess_writer writer = { in_parent.h, stdin_data };
+    subprocess_handle writing;
+    if (stdin_data != nullptr && !stdin_data->empty()) {
+        // the writer closes the pipe once done
+        in_parent.h = nullptr;
+        writing.h = CreateThread(nullptr, 0, subprocess_writer::run, &writer, 0, nullptr);
+        if (!writing.h) {
+            CloseHandle(writer.pipe);
         }
-    });
+    } else {
+        in_parent.reset();
+    }

-    // write stdin before reading stdout, the child drains stdin as it goes
-    // always close stdin, a transport client waits forever if its stdin pipe stays open
-    if (FILE * in = proc.stdin_file()) {
-        if (stdin_data != nullptr && !stdin_data->empty()) {
-#if defined(_WIN32)
-            // pipe fds default to CRT text mode: binary keeps the bytes untranslated
-            _setmode(_fileno(in), _O_BINARY);
-#endif
-            // a short write is not an error by itself, the exit code below decides
-            fwrite(stdin_data->data(), 1, stdin_data->size(), in);
+    subprocess_output out(max_output, on_chunk);
+    const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout_secs);
+    while (WaitForSingleObject(process.h, SERVER_TOOL_SUBPROCESS_POLL_MS) == WAIT_TIMEOUT) {
+        const std::string chunk = reader.take();
+        out.add(chunk.data(), chunk.size());
+        if (std::chrono::steady_clock::now() >= deadline) {
+            res.timed_out = true;
+            break;
+        }
+        if (out.stopped || (should_stop && should_stop())) {
+            break;
         }
-        fflush(in);
     }
-    proc.close_stdin();

-    FILE * f = proc.stdout_file();
-    std::string output;
-    bool truncated = false;
-    if (f) {
-#if defined(_WIN32)
-        // pipe fds default to CRT text mode: binary keeps the bytes untranslated
-        _setmode(_fileno(f), _O_BINARY);
+    TerminateJobObject(job.h, 1);
+    WaitForSingleObject(process.h, INFINITE);
+    if (WaitForSingleObject(reading.h, SERVER_TOOL_SUBPROCESS_DRAIN_MS) == WAIT_TIMEOUT) {
+        CancelSynchronousIo(reading.h);
+        WaitForSingleObject(reading.h, INFINITE);
+    }
+    const std::string rest = reader.take();
+    out.add(rest.data(), rest.size());
+    if (writing.h) {
+        CancelSynchronousIo(writing.h);
+        WaitForSingleObject(writing.h, INFINITE);
+    }
+
+    DWORD code = 1;
+    GetExitCodeProcess(process.h, &code);
+    res.exit_code = (int) code;
+    res.output    = console_output_to_utf8(out.text);
+    if (out.truncated) {
+        res.output += "\n[output truncated]";
+    }
+    return res;
+}
+
+#else
+
+extern char ** environ;
+
+// a pipe no concurrent spawn inherits
+static bool subprocess_pipe(int fd[2]) {
+#if defined(__APPLE__)
+    if (pipe(fd) != 0) {
+        return false;
+    }
+    fcntl(fd[0], F_SETFD, FD_CLOEXEC);
+    fcntl(fd[1], F_SETFD, FD_CLOEXEC);
+    return true;
+#else
+    return pipe2(fd, O_CLOEXEC) == 0;
+#endif
+}
+
+// the spelling of the chdir file action follows the detection of the vendored subprocess.h
+static int subprocess_addchdir(posix_spawn_file_actions_t * actions, const char * cwd) {
+#if SUBPROCESS_ADDCHDIR_IS_POSIX
+    return posix_spawn_file_actions_addchdir(actions, cwd);
+#elif SUBPROCESS_HAVE_CWD && !SUBPROCESS_SPAWN_VIA_FORK
+#if defined(__APPLE__) && defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#endif
+    return posix_spawn_file_actions_addchdir_np(actions, cwd);
+#if defined(__APPLE__) && defined(__clang__)
+#pragma clang diagnostic pop
 #endif
-        // read raw bytes, not lines: the output can hold NUL and must arrive as soon as it is ready
-        // keep draining past the size cap, else the child blocks on a full pipe
-        char buf[4096];
-        for (;;) {
-#if defined(_WIN32)
-            const int n = _read(_fileno(f), buf, (unsigned) sizeof(buf));
 #else
-            ssize_t n = read(fileno(f), buf, sizeof(buf));
-            while (n < 0 && errno == EINTR) {
-                n = read(fileno(f), buf, sizeof(buf));
-            }
+    (void) actions;
+    (void) cwd;
+    return ENOSYS;
 #endif
-            if (n <= 0) {
-                break;
+}
+
+static tools_io::exec_result run_subprocess(
+        const std::vector<std::string> & args,
+        size_t max_output,
+        int timeout_secs,
+        const std::function<bool(const std::string &)> & on_chunk,
+        bool combine_stderr,
+        const std::string & cwd,
+        const std::string * stdin_data,
+        const std::function<bool()> & should_stop) {
+    tools_io::exec_result res;
+    res.output = "failed to spawn process";
+
+    int in[2], out_pipe[2];
+    if (!subprocess_pipe(in)) {
+        return res;
+    }
+    if (!subprocess_pipe(out_pipe)) {
+        close(in[0]);
+        close(in[1]);
+        return res;
+    }
+
+    posix_spawn_file_actions_t actions;
+    posix_spawn_file_actions_init(&actions);
+    posix_spawn_file_actions_adddup2(&actions, in[0], 0);
+    posix_spawn_file_actions_adddup2(&actions, out_pipe[1], 1);
+    if (combine_stderr) {
+        posix_spawn_file_actions_adddup2(&actions, out_pipe[1], 2);
+    } else {
+        posix_spawn_file_actions_addopen(&actions, 2, "/dev/null", O_WRONLY, 0);
+    }
+    int err = cwd.empty() ? 0 : subprocess_addchdir(&actions, cwd.c_str());
+
+    // a group of its own, with the signals the server ignores back to their default, so a pipeline dies of SIGPIPE as usual
+    posix_spawnattr_t attr;
+    posix_spawnattr_init(&attr);
+    sigset_t none, defaults;
+    sigemptyset(&none);
+    sigemptyset(&defaults);
+    sigaddset(&defaults, SIGPIPE);
+    posix_spawnattr_setsigmask(&attr, &none);
+    posix_spawnattr_setsigdefault(&attr, &defaults);
+    posix_spawnattr_setpgroup(&attr, 0);
+    posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF);
+
+    std::vector<char *> argv;
+    for (const auto & a : args) {
+        argv.push_back(const_cast<char *>(a.c_str()));
+    }
+    argv.push_back(nullptr);
+
+    pid_t pid = 0;
+    if (err == 0) {
+        err = posix_spawnp(&pid, argv[0], &actions, &attr, argv.data(), environ);
+    }
+    posix_spawn_file_actions_destroy(&actions);
+    posix_spawnattr_destroy(&attr);
+    close(in[0]);
+    close(out_pipe[1]);
+    if (err != 0) {
+        close(in[1]);
+        close(out_pipe[0]);
+        return res;
+    }
+
+    int in_fd  = in[1];
+    int out_fd = out_pipe[0];
+    size_t written = 0;
+    if (stdin_data == nullptr || stdin_data->empty()) {
+        close(in_fd);
+        in_fd = -1;
+    } else {
+        fcntl(in_fd, F_SETFL, fcntl(in_fd, F_GETFL) | O_NONBLOCK);
+    }
+
+    subprocess_output out(max_output, on_chunk);
+    using clock = std::chrono::steady_clock;
+    const auto deadline = clock::now() + std::chrono::seconds(timeout_secs);
+    auto drain_end = clock::time_point::max();
+    bool exited = false;
+    bool killed = false;
+    int status = 0;
+
+    for (;;) {
+        pollfd fds[2] = {
+            { out_fd, POLLIN,  0 },
+            { in_fd,  POLLOUT, 0 },
+        };
+        if (poll(fds, 2, SERVER_TOOL_SUBPROCESS_POLL_MS) < 0 && errno != EINTR) {
+            break;
+        }
+        if (out_fd >= 0 && (fds[0].revents & (POLLIN | POLLHUP | POLLERR))) {
+            char buf[4096];
+            const ssize_t got = read(out_fd, buf, sizeof(buf));
+            if (got > 0) {
+                out.add(buf, (size_t) got);
+            } else if (got == 0 || errno != EINTR) {
+                close(out_fd);
+                out_fd = -1;
             }
-            if (truncated) {
-                continue;
+        }
+        if (in_fd >= 0 && (fds[1].revents & (POLLOUT | POLLHUP | POLLERR))) {
+            const ssize_t put = write(in_fd, stdin_data->data() + written, stdin_data->size() - written);
+            if (put > 0) {
+                written += (size_t) put;
             }
-            const size_t len = (size_t) n;
-            if (output.size() + len <= max_output) {
-                output.append(buf, len);
-                if (on_chunk && !on_chunk(console_output_to_utf8(std::string(buf, len)))) {
-                    proc.terminate();
-                    break;
-                }
-            } else {
-                size_t remaining = max_output - output.size();
-                output.append(buf, remaining);
-                if (on_chunk && remaining > 0) on_chunk(console_output_to_utf8(std::string(buf, remaining)));
-                truncated = true;
+            if ((put < 0 && errno != EAGAIN && errno != EINTR) || written == stdin_data->size()) {
+                close(in_fd);
+                in_fd = -1;
             }
         }
+        if (!exited && waitpid(pid, &status, WNOHANG) == pid) {
+            exited = true;
+        }
+        const auto now = clock::now();
+        if (!killed && !exited && now >= deadline) {
+            res.timed_out = true;
+        }
+        // the command exits or is ended: what it left running dies with it
+        if (!killed && (exited || res.timed_out || out.stopped || (should_stop && should_stop()))) {
+            killed = true;
+            kill(-pid, SIGKILL);
+            drain_end = now + std::chrono::milliseconds(SERVER_TOOL_SUBPROCESS_DRAIN_MS);
+        }
+        if ((exited && out_fd < 0) || now >= drain_end) {
+            break;
+        }
     }

-    done.store(true);
-    if (timeout_thread.joinable()) {
-        timeout_thread.join();
+    if (in_fd >= 0) {
+        close(in_fd);
+    }
+    if (out_fd >= 0) {
+        close(out_fd);
+    }
+    if (!exited) {
+        kill(-pid, SIGKILL);
+        waitpid(pid, &status, 0);
     }

-    res.exit_code = proc.join();
-
-    res.output    = console_output_to_utf8(output);
-    res.timed_out = timed_out.load();
-    if (truncated) {
+    res.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
+    res.output    = console_output_to_utf8(out.text);
+    if (out.truncated) {
         res.output += "\n[output truncated]";
     }
     return res;
 }

+#endif
+
 class tools_io_basic : public tools_io {
 public:
     // cwd, if non-empty, is used to resolve relative paths and as the working directory for run()
@@ -406,8 +780,9 @@ public:
             const std::vector<std::string> & args,
             size_t max_output,
             int timeout_secs,
-            const std::function<bool(const std::string &)> & on_chunk = nullptr) const override {
-        return run_subprocess(args, max_output, timeout_secs, on_chunk, /*combine_stderr=*/true, cwd);
+            const std::function<bool(const std::string &)> & on_chunk = nullptr,
+            const std::function<bool()> & should_stop = nullptr) const override {
+        return run_subprocess(args, max_output, timeout_secs, on_chunk, /*combine_stderr=*/true, cwd, nullptr, should_stop);
     }

 private:
@@ -617,14 +992,15 @@ public:
             const std::vector<std::string> & args,
             size_t max_output,
             int timeout_secs,
-            const std::function<bool(const std::string &)> & on_chunk = nullptr) const override {
+            const std::function<bool(const std::string &)> & on_chunk = nullptr,
+            const std::function<bool()> & should_stop = nullptr) const override {
         std::vector<std::string> inner = {"timeout", std::to_string(timeout_secs) + "s"};
         inner.insert(inner.end(), args.begin(), args.end());
         // small buffer over timeout_secs so the in-isolate `timeout` has a chance to exit cleanly
         // before the host-side supervisory timeout forcibly kills the client
         return run_subprocess(
             build_argv(with_cwd(inner), /*needs_stdin=*/true),
-            max_output, timeout_secs + 5, on_chunk, true);
+            max_output, timeout_secs + 5, on_chunk, true, "", nullptr, should_stop);
     }

 protected:
@@ -1286,7 +1662,7 @@ struct server_tool_exec_shell_command : server_tool {
         };
     }

-    json invoke(json params, server_tool::stream * st, const std::function<bool()> &) const override {
+    json invoke(json params, server_tool::stream * st, const std::function<bool()> & should_stop) const override {
         std::string command   = params.at("command").get<std::string>();
         int    timeout        = json_value(params, "timeout",         10);
         size_t max_output     = (size_t) json_value(params, "max_output_size", (int) SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE);
@@ -1295,10 +1671,11 @@ struct server_tool_exec_shell_command : server_tool {
         max_output = std::min(max_output, SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE);

         // an isolate is always POSIX regardless of host OS, so it always gets `sh -c`
+        // cmd gets the command as written: /d skips AutoRun, /s removes only the outer quotes
 #ifdef _WIN32
         std::vector<std::string> args = !json_value(params, "runtime", std::string()).empty()
             ? std::vector<std::string>{"sh", "-c", command}
-            : std::vector<std::string>{"cmd", "/c", command};
+            : std::vector<std::string>{"cmd", "/d", "/s", "/c", "\"" + command + "\""};
 #else
         std::vector<std::string> args = {"sh", "-c", command};
 #endif
@@ -1309,6 +1686,8 @@ struct server_tool_exec_shell_command : server_tool {
             auto res = io->run(args, max_output, timeout, [st](const std::string & chunk) {
                 st->push(chunk);
                 return !st->alive || st->alive();
+            }, [st]() {
+                return st->alive && !st->alive();
             });
             if (st->alive && !st->alive()) {
                 return json();
@@ -1321,7 +1700,7 @@ struct server_tool_exec_shell_command : server_tool {
             return json();
         }

-        auto res = io->run(args, max_output, timeout);
+        auto res = io->run(args, max_output, timeout, nullptr, should_stop);

         std::string text_output = res.output;
         text_output += string_format("\n[exit code: %d]", res.exit_code);
diff --git a/tools/server/tests/unit/test_tools_builtin.py b/tools/server/tests/unit/test_tools_builtin.py
index 486ba8481..6cb4f7ac9 100755
--- a/tools/server/tests/unit/test_tools_builtin.py
+++ b/tools/server/tests/unit/test_tools_builtin.py
@@ -2,6 +2,8 @@ import os
 import re
 import shutil
 import subprocess
+import sys
+import time

 import pytest
 from utils import *
@@ -17,6 +19,9 @@ GREP_MARKER = "llama_cpp_test_tools_builtin_marker_grep_search"
 # image the container runtime tests run their shell in
 CONTAINER_IMAGE = "busybox"

+COMMAND_LEAVING_A_PROCESS = "start /b ping -n 30 127.0.0.1 & echo started" if os.name == "nt" else "sleep 30 & echo started"
+COMMAND_OUTLIVING_THE_TIMEOUT = "ping -n 30 127.0.0.1 & echo done" if os.name == "nt" else "sleep 30; echo done"
+

 @pytest.fixture(autouse=True)
 def create_server():
@@ -226,6 +231,37 @@ def test_tools_builtin_exec_shell_command_stream():
     assert "[exit code: 0]" in chunks


+def test_tools_builtin_exec_shell_command_double_quotes():
+    global server
+    server.start()
+
+    res = call_tool("exec_shell_command", {"command": f"\"{sys.executable}\" -c \"print('quoted arg')\""})
+    assert "quoted arg" in res["plain_text_response"]
+    assert "[exit code: 0]" in res["plain_text_response"]
+
+
+def test_tools_builtin_exec_shell_command_returns_when_the_shell_exits():
+    global server
+    server.start()
+
+    start = time.monotonic()
+    res = call_tool("exec_shell_command", {"command": COMMAND_LEAVING_A_PROCESS, "timeout": 20})
+    assert time.monotonic() - start < 10
+    assert "started" in res["plain_text_response"]
+    assert "[exit code: 0]" in res["plain_text_response"]
+
+
+def test_tools_builtin_exec_shell_command_timeout_ends_the_command():
+    global server
+    server.start()
+
+    start = time.monotonic()
+    res = call_tool("exec_shell_command", {"command": COMMAND_OUTLIVING_THE_TIMEOUT, "timeout": 2})
+    assert time.monotonic() - start < 10
+    assert "[exit due to timed out]" in res["plain_text_response"]
+    assert "done" not in res["plain_text_response"]
+
+
 def test_tools_builtin_cwd_header(tmp_path):
     global server
     server.start()