Commit 2868ee950 for llama.cpp
commit 2868ee950fc4fd8c69f29fff31158618de685fd2
Author: Pascal <admin@serveurperso.com>
Date: Tue Dec 1 14:12:38 2026 +0100
server: background tasks for the built-in shell tool (#33391)
* server: add background tasks to the built-in tools
exec_shell_command can now run a command in the background
(background: true), for dev servers, builds or downloads. The call
returns right away with a task id, and the task keeps running until it
exits or is stopped.
Tasks belong to the conversation of the X-Conversation-Id header. The
model manages its own with the new background_task tool, the UI
follows them on /tools/tasks/events, and nothing is left running when
the server exits.
* server: let a running command move to the background
Every exec_shell_command now runs as a task its call waits for, and
sends its exec_id first. POST /tools/tasks with from_exec_id moves it
to the background: the call returns at once and the command keeps
running under the same id. With detach_on_timeout, a command that
reaches its timeout goes to the background instead of being killed.
* server: read whether a task is attached without the registry lock
An exec waiting for its task checked it from inside the output read,
under the output lock, while moving a task to the background takes the
registry lock first and then reads the output size. ThreadSanitizer
reported the lock order inversion.
* doc, nits: follow the naming and comment rules for tasks, document them
tools_task_status values are upper case and prefixed, like the other
server enums, and comments no longer split a sentence over two lines.
README-dev.md describes the background tasks of the /tools API.
* server: address review from ngxson
A background command now runs attached for background_after_seconds
(default 1) and then moves to the background; one that ends before
returns like any other command. This replaces both the fixed 1 s wait
of background: true and detach_on_timeout.
A background command has no timeout, and a command moved to the
background loses its own. The code already did this, now the tool
description, the README and the tests say so.
When the client leaves during that wait, a background command still
moves to the background instead of being stopped.
Task ids are random, so a client can not guess the tasks of another
conversation.
diff --git a/tools/server/README-dev.md b/tools/server/README-dev.md
index 55925bb99..92085e550 100644
--- a/tools/server/README-dev.md
+++ b/tools/server/README-dev.md
@@ -264,6 +264,23 @@ or, if `invoke()` threw:
There is no `[DONE]` sentinel (unlike `/chat/completions`), the stream ends after the `done`
+**Background tasks**
+
+`exec_shell_command` runs every command as a task. With an `X-Conversation-Id` header, set by the client and never by the model, a task can move to the background: owned by that conversation, it keeps running after its call returns. Without the header, commands run and block as before.
+
+- `params.background: true` runs the command with no timeout: if it still runs after `params.background_after_seconds` (default 1), it moves to the background and the call returns with the output so far and a `task_id`; a command that ends before returns like any other
+- a command moved to the background, by `background` or by `POST /tools/tasks`, loses its timeout
+- task ids are random, so a client can not guess the tasks of another conversation
+- with `stream: true`, the first event carries the id of the command: `{"chunk": "", "exec_id": 3}`
+
+Routes, all scoped to the conversation the request names:
+- `POST /tools/tasks` with `{"conv_id": "c", "from_exec_id": 3}`: move a running command to the background, its call returns at once and the task keeps the same id
+- `GET /tools/tasks/events?conv_ids=a,b`: SSE, a `snapshot` of the background tasks of these conversations, then `task_started`, `task_output` (`id` and `offset`, at most one every 500 ms per task) and `task_exited`
+- `GET /tools/tasks/output?conv_id=c&id=3&from=0`: the task, its `output` since `from`, `next` for the next read, and `skipped` when older output was dropped (256 KB kept per task)
+- `DELETE /tools/tasks?conv_id=c&id=3`: stop a task and everything it started
+
+The model gets the `background_task` tool (`list`, `output`, `stop`) for the tasks of its conversation. Everything still running is stopped when the server exits.
+
### Router mode: how child <--> router communicates
Upon spawning a new child process using `subprocess`, both child and router listen to the stdout/stderr (combined)
diff --git a/tools/server/server-stream.cpp b/tools/server/server-stream.cpp
index f6b9b8a9f..9671838a9 100644
--- a/tools/server/server-stream.cpp
+++ b/tools/server/server-stream.cpp
@@ -8,11 +8,6 @@
#include <utility>
#include <shared_mutex>
-enum class stream_read_status {
- OK,
- OFFSET_LOST,
-};
-
namespace {
constexpr int64_t STREAM_SESSION_TTL_SECONDS = 300;
constexpr size_t STREAM_SESSION_MAX_BYTES = 4 * 1024 * 1024;
@@ -72,42 +67,6 @@ void server_stream_session_manager_stop() {
g_stream_sessions.stop_gc();
}
-struct stream_session {
- std::string conversation_id;
- int64_t started_ts; // unix seconds at construction
-
- stream_session(std::string conversation_id_, size_t max_bytes_);
- stream_session(const stream_session &) = delete;
- stream_session & operator=(const stream_session &) = delete;
-
- bool append(const char * data, size_t len);
-
- void finalize();
-
- // drain from offset into sink, blocking for more bytes or finalize. OFFSET_LOST if offset
- // fell below the dropped prefix
- stream_read_status read_from(size_t offset,
- const std::function<bool(const char *, size_t)> & sink,
- const std::function<bool()> & should_stop);
-
- bool is_done() const;
- bool is_cancelled() const;
- size_t total_size() const; // bytes that ever entered the session
- size_t dropped_prefix() const; // bytes evicted from the front due to cap
- int64_t completed_at() const; // 0 while alive, unix seconds after finalize
-
- void cancel();
-
-private:
- mutable std::mutex mu;
- std::condition_variable cv;
- std::vector<char> buffer;
- size_t prefix_dropped;
- size_t cap_bytes;
- bool done;
- std::atomic<bool> cancelled; // polled lock-free by the should_stop closure, no mu
- int64_t completed_ts;
-};
stream_session::stream_session(std::string conversation_id_, size_t max_bytes_)
: conversation_id(std::move(conversation_id_))
, started_ts(now_seconds())
@@ -194,6 +153,16 @@ stream_read_status stream_session::read_from(size_t offset,
}
}
+stream_read_status stream_session::read_available(size_t offset, std::string & out) const {
+ std::lock_guard<std::mutex> lock(mu);
+ if (offset < prefix_dropped) {
+ return stream_read_status::OFFSET_LOST;
+ }
+ const size_t local_off = std::min(offset - prefix_dropped, buffer.size());
+ out.append(buffer.begin() + local_off, buffer.end());
+ return stream_read_status::OK;
+}
+
bool stream_session::is_done() const {
std::lock_guard<std::mutex> lock(mu);
return done;
diff --git a/tools/server/server-stream.h b/tools/server/server-stream.h
index 00beaabbd..e1b578e80 100644
--- a/tools/server/server-stream.h
+++ b/tools/server/server-stream.h
@@ -3,15 +3,62 @@
#include "server-http.h"
#include <atomic>
+#include <condition_variable>
#include <cstddef>
+#include <cstdint>
#include <functional>
#include <memory>
+#include <mutex>
#include <string>
+#include <vector>
// streaming buffer for one generation, survives HTTP disconnect. the producer appends SSE bytes,
// readers drain from any offset via read_from. keyed by conversation_id, one conv = one live session
-struct stream_session;
+enum class stream_read_status {
+ OK,
+ OFFSET_LOST,
+};
+
+struct stream_session {
+ std::string conversation_id;
+ int64_t started_ts; // unix seconds at construction
+
+ stream_session(std::string conversation_id_, size_t max_bytes_);
+ stream_session(const stream_session &) = delete;
+ stream_session & operator=(const stream_session &) = delete;
+
+ bool append(const char * data, size_t len);
+
+ void finalize();
+
+ // drain from offset into sink, blocking for more bytes or finalize. OFFSET_LOST if offset
+ // fell below the dropped prefix
+ stream_read_status read_from(size_t offset,
+ const std::function<bool(const char *, size_t)> & sink,
+ const std::function<bool()> & should_stop);
+
+ // append what is buffered from offset to out without waiting. OFFSET_LOST if offset fell below the dropped prefix
+ stream_read_status read_available(size_t offset, std::string & out) const;
+
+ bool is_done() const;
+ bool is_cancelled() const;
+ size_t total_size() const; // bytes that ever entered the session
+ size_t dropped_prefix() const; // bytes evicted from the front due to cap
+ int64_t completed_at() const; // 0 while alive, unix seconds after finalize
+
+ void cancel();
+
+private:
+ mutable std::mutex mu;
+ std::condition_variable cv;
+ std::vector<char> buffer;
+ size_t prefix_dropped;
+ size_t cap_bytes;
+ bool done;
+ std::atomic<bool> cancelled; // polled lock-free by the should_stop closure, no mu
+ int64_t completed_ts;
+};
using stream_session_ptr = std::shared_ptr<stream_session>;
diff --git a/tools/server/server-tools.cpp b/tools/server/server-tools.cpp
index 156ea9ffc..4596274cd 100644
--- a/tools/server/server-tools.cpp
+++ b/tools/server/server-tools.cpp
@@ -1,4 +1,5 @@
#include "server-tools.h"
+#include "server-stream.h"
#include "subproc.h"
#include "base64.hpp"
@@ -20,6 +21,8 @@
#include <functional>
#include <memory>
#include <mutex>
+#include <random>
+#include <climits>
#if defined(_WIN32)
# ifndef NOMINMAX
@@ -222,28 +225,30 @@ struct subprocess_output {
}
};
-// 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(
+struct subprocess_job_result {
+ bool spawned = false;
+ bool timed_out = false;
+ int exit_code = -1;
+};
+
+// runs args as a job (process group on POSIX, Job Object on Windows), killed with everything it started once it exits, times out, or sink or should_stop asks to stop
+// sink takes the output as it arrives, false stops the job; a timeout_secs of 0 or less means no deadline
+// combine_stderr=false when the raw stdout bytes must not be tainted by stderr, e.g. reading file contents
+static subprocess_job_result run_job(
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 = nullptr,
- const std::function<bool()> & should_stop = nullptr);
+ const std::string & cwd,
+ const std::string * stdin_data,
+ int timeout_secs,
+ const std::function<bool(const char *, size_t)> & sink,
+ const std::function<bool()> & should_stop);
#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;
+static subprocess_job_result run_job(
+ const std::vector<std::string> &, bool, const std::string &, const std::string *, int,
+ const std::function<bool(const char *, size_t)> &, const std::function<bool()> &) {
+ return {};
}
#elif defined(_WIN32)
@@ -350,17 +355,15 @@ struct subprocess_writer {
}
};
-static tools_io::exec_result run_subprocess(
+static subprocess_job_result run_job(
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,
+ int timeout_secs,
+ const std::function<bool(const char *, size_t)> & sink,
const std::function<bool()> & should_stop) {
- tools_io::exec_result res;
- res.output = "failed to spawn process";
+ subprocess_job_result res;
// only the child ends are inheritable, and only by this child (handle list below)
SECURITY_ATTRIBUTES sa = { sizeof(sa), nullptr, TRUE };
@@ -447,16 +450,19 @@ static tools_io::exec_result run_subprocess(
in_parent.reset();
}
- subprocess_output out(max_output, on_chunk);
+ res.spawned = true;
+ bool stopped = false;
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) {
+ if (!chunk.empty() && !sink(chunk.data(), chunk.size())) {
+ stopped = true;
+ }
+ if (timeout_secs > 0 && std::chrono::steady_clock::now() >= deadline) {
res.timed_out = true;
break;
}
- if (out.stopped || (should_stop && should_stop())) {
+ if (stopped || (should_stop && should_stop())) {
break;
}
}
@@ -468,7 +474,9 @@ static tools_io::exec_result run_subprocess(
WaitForSingleObject(reading.h, INFINITE);
}
const std::string rest = reader.take();
- out.add(rest.data(), rest.size());
+ if (!rest.empty()) {
+ sink(rest.data(), rest.size());
+ }
if (writing.h) {
CancelSynchronousIo(writing.h);
WaitForSingleObject(writing.h, INFINITE);
@@ -477,10 +485,6 @@ static tools_io::exec_result run_subprocess(
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;
}
@@ -522,17 +526,15 @@ static int subprocess_addchdir(posix_spawn_file_actions_t * actions, const char
#endif
}
-static tools_io::exec_result run_subprocess(
+static subprocess_job_result run_job(
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,
+ int timeout_secs,
+ const std::function<bool(const char *, size_t)> & sink,
const std::function<bool()> & should_stop) {
- tools_io::exec_result res;
- res.output = "failed to spawn process";
+ subprocess_job_result res;
int in[2], out_pipe[2];
if (!subprocess_pipe(in)) {
@@ -597,7 +599,8 @@ static tools_io::exec_result run_subprocess(
fcntl(in_fd, F_SETFL, fcntl(in_fd, F_GETFL) | O_NONBLOCK);
}
- subprocess_output out(max_output, on_chunk);
+ res.spawned = true;
+ bool stopped = false;
using clock = std::chrono::steady_clock;
const auto deadline = clock::now() + std::chrono::seconds(timeout_secs);
auto drain_end = clock::time_point::max();
@@ -617,7 +620,9 @@ static tools_io::exec_result run_subprocess(
char buf[4096];
const ssize_t got = read(out_fd, buf, sizeof(buf));
if (got > 0) {
- out.add(buf, (size_t) got);
+ if (!sink(buf, (size_t) got)) {
+ stopped = true;
+ }
} else if (got == 0 || errno != EINTR) {
close(out_fd);
out_fd = -1;
@@ -637,11 +642,11 @@ static tools_io::exec_result run_subprocess(
exited = true;
}
const auto now = clock::now();
- if (!killed && !exited && now >= deadline) {
+ if (!killed && !exited && timeout_secs > 0 && 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()))) {
+ if (!killed && (exited || res.timed_out || stopped || (should_stop && should_stop()))) {
killed = true;
kill(-pid, SIGKILL);
drain_end = now + std::chrono::milliseconds(SERVER_TOOL_SUBPROCESS_DRAIN_MS);
@@ -663,6 +668,35 @@ static tools_io::exec_result run_subprocess(
}
res.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
+ return res;
+}
+
+#endif
+
+// shared subprocess execution helper, used by both the local and the isolate-backed tools_io implementations
+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 = nullptr,
+ const std::function<bool()> & should_stop = nullptr) {
+ subprocess_output out(max_output, on_chunk);
+ const subprocess_job_result job = run_job(args, combine_stderr, cwd, stdin_data, timeout_secs,
+ [&out](const char * buf, size_t len) {
+ out.add(buf, len);
+ return !out.stopped;
+ }, should_stop);
+
+ tools_io::exec_result res;
+ if (!job.spawned) {
+ res.output = "failed to spawn process";
+ return res;
+ }
+ res.exit_code = job.exit_code;
+ res.timed_out = job.timed_out;
res.output = console_output_to_utf8(out.text);
if (out.truncated) {
res.output += "\n[output truncated]";
@@ -670,8 +704,6 @@ static tools_io::exec_result run_subprocess(
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()
@@ -1627,6 +1659,415 @@ struct server_tool_grep_search : server_tool {
}
};
+//
+// tasks: every exec_shell_command runs as a task, attached to the call that waits for it
+// a detached task outlives its call, owned by a conversation: started with background = true, it moves there after background_after_seconds,
+// or a client moves it there while it runs; a detached task has no timeout
+// everything still running is stopped when the server exits
+//
+
+static constexpr size_t SERVER_TOOL_TASK_OUTPUT_MAX_BYTES = 256 * 1024;
+static constexpr size_t SERVER_TOOL_TASK_READ_MAX_BYTES = 16 * 1024; // tail a read gives the model
+static constexpr size_t SERVER_TOOL_TASKS_MAX_PER_CONV = 8; // detached tasks running in one conversation
+static constexpr size_t SERVER_TOOL_TASKS_MAX = 32; // detached tasks kept, running and finished
+static constexpr int SERVER_TOOL_TASK_OUTPUT_EVENT_MS = 500; // at most one output event per task in this time
+static constexpr int SERVER_TOOL_TASK_BACKGROUND_AFTER = 1; // seconds a background command runs attached by default, so early errors show
+
+enum tools_task_status {
+ TOOLS_TASK_STATUS_RUNNING,
+ TOOLS_TASK_STATUS_EXITED,
+ TOOLS_TASK_STATUS_STOPPED,
+};
+
+static std::string tools_task_status_to_string(tools_task_status status) {
+ switch (status) {
+ case TOOLS_TASK_STATUS_RUNNING: return "running";
+ case TOOLS_TASK_STATUS_EXITED: return "exited";
+ case TOOLS_TASK_STATUS_STOPPED: return "stopped";
+ default: return "unknown";
+ }
+}
+
+static int64_t tools_task_now_ms() {
+ return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+
+struct tools_task {
+ int id = 0;
+ std::string conv_id; // empty when the client sent none: the task can not be detached
+ std::string command;
+ std::string description;
+ std::string cwd;
+ std::string notify;
+ int64_t started_at = 0; // unix seconds
+ bool detach_at_deadline = false; // a background command: its deadline moves it to the background instead of killing it
+
+ stream_session output{"", SERVER_TOOL_TASK_OUTPUT_MAX_BYTES};
+ std::atomic<bool> stop{false};
+ std::atomic<int64_t> deadline_ms{0}; // steady clock, 0 for none
+ std::atomic<bool> attached{true}; // written under tools_tasks::mutex, read without it
+ std::thread pump;
+ std::mutex pump_mutex; // guards pump, one joiner at a time
+
+ // under tools_tasks::mutex
+ bool timed_out = false;
+ tools_task_status status = TOOLS_TASK_STATUS_RUNNING;
+ int exit_code = -1;
+ size_t model_offset = 0; // output the model has already read
+
+ json to_json() const {
+ json j = {
+ {"id", id},
+ {"conv_id", conv_id},
+ {"command", command},
+ {"description", description},
+ {"cwd", cwd},
+ {"notify", notify},
+ {"started_at", started_at},
+ {"status", tools_task_status_to_string(status)},
+ {"offset", output.total_size()},
+ };
+ if (status != TOOLS_TASK_STATUS_RUNNING) {
+ j["exit_code"] = exit_code;
+ }
+ if (timed_out) {
+ j["timed_out"] = true;
+ }
+ return j;
+ }
+};
+
+using tools_task_ptr = std::shared_ptr<tools_task>;
+
+// the output of a task from offset, at most max_bytes of its tail, and where the next read starts
+struct tools_task_read {
+ std::string text;
+ size_t next = 0;
+ size_t skipped = 0; // bytes between offset and what text starts with, dropped or cut to max_bytes
+};
+
+static tools_task_read tools_task_read_output(const tools_task & task, size_t offset, size_t max_bytes) {
+ tools_task_read r;
+ if (task.output.read_available(offset, r.text) == stream_read_status::OFFSET_LOST) {
+ r.skipped = task.output.dropped_prefix() - offset;
+ offset = task.output.dropped_prefix();
+ task.output.read_available(offset, r.text);
+ }
+ r.next = offset + r.text.size();
+ if (r.text.size() > max_bytes) {
+ r.skipped += r.text.size() - max_bytes;
+ r.text.erase(0, r.text.size() - max_bytes);
+ }
+ return r;
+}
+
+struct tools_tasks {
+ tools_tasks() = default;
+ tools_tasks(const tools_tasks &) = delete;
+ tools_tasks & operator=(const tools_tasks &) = delete;
+
+ ~tools_tasks() {
+ std::vector<tools_task_ptr> all;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ all = tasks;
+ }
+ for (auto & t : all) {
+ t->stop = true;
+ }
+ for (auto & t : all) {
+ join(*t);
+ }
+ }
+
+ // starts args as a task attached to the calling exec
+ // a command is killed after deadline_secs (0 for none), a background command moves to the background after deadline_secs instead
+ // throws when a background command does not fit the limits
+ tools_task_ptr start(const std::vector<std::string> & args, const std::string & conv_id, const json & params, bool background, int deadline_secs) {
+ auto task = std::make_shared<tools_task>();
+ task->conv_id = conv_id;
+ task->command = json_value(params, "command", std::string());
+ task->description = json_value(params, "description", std::string());
+ task->cwd = json_value(params, "cwd", std::string());
+ task->notify = json_value(params, "notify", std::string("exit"));
+ task->started_at = (int64_t) std::chrono::duration_cast<std::chrono::seconds>(
+ std::chrono::system_clock::now().time_since_epoch()).count();
+ task->detach_at_deadline = background;
+ if (background || deadline_secs > 0) {
+ task->deadline_ms = tools_task_now_ms() + (int64_t) deadline_secs * 1000;
+ }
+
+ tools_task_ptr evicted;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ if (background) {
+ // fail now rather than when it moves to the background
+ evicted = make_room(conv_id);
+ }
+ task->id = new_id();
+ tasks.push_back(task);
+ }
+ if (evicted) {
+ join(*evicted);
+ }
+ {
+ std::lock_guard<std::mutex> lock(task->pump_mutex);
+ task->pump = std::thread([this, task, args]() {
+ run_task(task, args);
+ });
+ }
+ return task;
+ }
+
+ // moves a running attached task to the background: its exec stops waiting and the task outlives it
+ // false with the reason when it can not
+ bool detach(tools_task & task, std::string & reason) {
+ tools_task_ptr evicted;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ if (!task.attached) {
+ return true;
+ }
+ if (task.conv_id.empty()) {
+ reason = "a background task belongs to a conversation: the client must send the X-Conversation-Id header";
+ return false;
+ }
+ if (task.status != TOOLS_TASK_STATUS_RUNNING) {
+ reason = "the command already finished";
+ return false;
+ }
+ try {
+ evicted = make_room(task.conv_id);
+ } catch (const std::exception & e) {
+ reason = e.what();
+ return false;
+ }
+ task.attached = false;
+ task.deadline_ms = 0; // a detached task has no timeout
+ }
+ if (evicted) {
+ join(*evicted);
+ }
+ notify_event("task_started", task);
+ return true;
+ }
+
+ // a task of the conversation, attached ones only when asked for, to detach them
+ tools_task_ptr get(int id, const std::string & conv_id, bool include_attached = false) {
+ std::lock_guard<std::mutex> lock(mutex);
+ for (const auto & t : tasks) {
+ if (t->id == id && t->conv_id == conv_id && (include_attached || !t->attached)) {
+ return t;
+ }
+ }
+ return nullptr;
+ }
+
+ json list(const std::unordered_set<std::string> & conv_ids) {
+ std::lock_guard<std::mutex> lock(mutex);
+ json result = json::array();
+ for (const auto & t : tasks) {
+ if (!t->attached && conv_ids.count(t->conv_id)) {
+ result.push_back(t->to_json());
+ }
+ }
+ return result;
+ }
+
+ json to_json(const tools_task & task) {
+ std::lock_guard<std::mutex> lock(mutex);
+ return task.to_json();
+ }
+
+ // lock free, so it can be checked while holding the lock of the task output
+ bool is_attached(const tools_task & task) const {
+ return task.attached;
+ }
+
+ // the output the model has not read yet, marked as read
+ tools_task_read read_for_model(tools_task & task) {
+ size_t from;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ from = task.model_offset;
+ }
+ tools_task_read r = tools_task_read_output(task, from, SERVER_TOOL_TASK_READ_MAX_BYTES);
+ std::lock_guard<std::mutex> lock(mutex);
+ task.model_offset = r.next;
+ return r;
+ }
+
+ void mark_read(tools_task & task, size_t offset) {
+ std::lock_guard<std::mutex> lock(mutex);
+ task.model_offset = offset;
+ }
+
+ // stops the task and waits for its job to end
+ void stop(tools_task & task) {
+ task.stop = true;
+ join(task);
+ }
+
+ // drops a finished attached task, once its exec has its result
+ void remove(tools_task & task) {
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ tasks.erase(std::remove_if(tasks.begin(), tasks.end(), [&task](const tools_task_ptr & t) {
+ return t.get() == &task;
+ }), tasks.end());
+ }
+ join(task);
+ }
+
+ // SSE events of the detached tasks, see setup_tasks_routes
+ server_response events;
+ std::atomic<int> next_client_id{0};
+
+private:
+ std::mutex mutex;
+ std::vector<tools_task_ptr> tasks;
+ std::mt19937 rng{std::random_device{}()};
+
+ // a random id, so a client can not guess the tasks of another conversation
+ int new_id() {
+ std::uniform_int_distribution<int> dist(1, INT_MAX);
+ for (;;) {
+ const int id = dist(rng);
+ if (std::none_of(tasks.begin(), tasks.end(), [id](const tools_task_ptr & t) { return t->id == id; })) {
+ return id;
+ }
+ }
+ }
+
+ void join(tools_task & task) {
+ std::lock_guard<std::mutex> lock(task.pump_mutex);
+ if (task.pump.joinable()) {
+ task.pump.join();
+ }
+ }
+
+ // room for one more detached task of conv_id, evicting the oldest finished one when needed; under mutex
+ tools_task_ptr make_room(const std::string & conv_id) {
+ size_t running_in_conv = 0;
+ size_t detached = 0;
+ for (const auto & t : tasks) {
+ if (t->attached) {
+ continue;
+ }
+ detached++;
+ if (t->conv_id == conv_id && t->status == TOOLS_TASK_STATUS_RUNNING) {
+ running_in_conv++;
+ }
+ }
+ if (running_in_conv >= SERVER_TOOL_TASKS_MAX_PER_CONV) {
+ throw std::runtime_error(string_format("this conversation already runs %zu background tasks, stop one first", SERVER_TOOL_TASKS_MAX_PER_CONV));
+ }
+ if (detached < SERVER_TOOL_TASKS_MAX) {
+ return nullptr;
+ }
+ auto it = std::find_if(tasks.begin(), tasks.end(), [](const tools_task_ptr & t) {
+ return !t->attached && t->status != TOOLS_TASK_STATUS_RUNNING;
+ });
+ if (it == tasks.end()) {
+ throw std::runtime_error(string_format("the server already runs %zu background tasks", SERVER_TOOL_TASKS_MAX));
+ }
+ tools_task_ptr evicted = *it;
+ tasks.erase(it);
+ return evicted;
+ }
+
+ void notify_event(const std::string & event, const tools_task & task, json data = json::object()) {
+ auto result = std::make_unique<server_task_result_router>();
+ data["event"] = event;
+ data["conv_id"] = task.conv_id;
+ if (event == "task_output") {
+ data["id"] = task.id;
+ } else {
+ data["task"] = to_json(task);
+ }
+ result->data = std::move(data);
+ events.broadcast(std::move(result));
+ }
+
+ void run_task(const tools_task_ptr & task_ptr, const std::vector<std::string> & args) {
+ tools_task & task = *task_ptr;
+ using clock = std::chrono::steady_clock;
+ auto last_event = clock::time_point();
+ bool dirty = false;
+ // one output event per detached task at most every SERVER_TOOL_TASK_OUTPUT_EVENT_MS, the reader fetches the rest by offset
+ auto flush = [&](bool force) {
+ const auto now = clock::now();
+ if (dirty && (force || now - last_event >= std::chrono::milliseconds(SERVER_TOOL_TASK_OUTPUT_EVENT_MS)) && !is_attached(task)) {
+ dirty = false;
+ last_event = now;
+ notify_event("task_output", task, {{"offset", task.output.total_size()}});
+ }
+ };
+
+ const subprocess_job_result job = run_job(args, true, task.cwd, nullptr, 0,
+ [&](const char * buf, size_t len) {
+ task.output.append(buf, len);
+ dirty = true;
+ flush(false);
+ return true;
+ }, [&]() {
+ flush(false);
+ const int64_t deadline = task.deadline_ms.load();
+ if (deadline > 0 && tools_task_now_ms() >= deadline) {
+ std::string reason;
+ if (!task.detach_at_deadline || !detach(task, reason)) {
+ std::lock_guard<std::mutex> lock(mutex);
+ task.timed_out = true;
+ return true;
+ }
+ }
+ return task.stop.load();
+ });
+ if (!job.spawned) {
+ const std::string msg = "failed to spawn process";
+ task.output.append(msg.data(), msg.size());
+ dirty = true;
+ }
+ flush(true);
+ bool attached;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ task.status = task.timed_out || !task.stop ? TOOLS_TASK_STATUS_EXITED : TOOLS_TASK_STATUS_STOPPED;
+ task.exit_code = job.exit_code;
+ attached = task.attached;
+ }
+ task.output.finalize();
+ if (!attached) {
+ notify_event("task_exited", task);
+ }
+ }
+};
+
+// a conversation keeps its tasks when the user switches model: "<conv>::<model>" is keyed on <conv>
+static std::string tools_task_conv_id(const std::string & conv_id) {
+ return conv_id.substr(0, conv_id.find("::"));
+}
+
+// the text a model reads for a task: its new output, then its state
+static std::string tools_task_report(const tools_task_read & r, const json & task) {
+ std::string text;
+ if (r.skipped > 0) {
+ text += string_format("[%zu bytes skipped]\n", r.skipped);
+ }
+ text += console_output_to_utf8(r.text);
+ if (!text.empty() && text.back() != '\n') {
+ text += '\n';
+ }
+ const int id = task.at("id").get<int>();
+ const std::string status = task.at("status").get<std::string>();
+ if (status == "running") {
+ text += string_format("[background task %d running]", id);
+ } else {
+ text += string_format("[background task %d %s, exit code: %d]", id, status.c_str(), task.at("exit_code").get<int>());
+ }
+ return text;
+}
+
//
// exec_shell_command: run an arbitrary shell command
//
@@ -1635,7 +2076,9 @@ static constexpr size_t SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE = 16 * 10
static constexpr int SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT = 60; // seconds
struct server_tool_exec_shell_command : server_tool {
- server_tool_exec_shell_command() {
+ tools_tasks * tasks;
+
+ explicit server_tool_exec_shell_command(tools_tasks * tasks) : tasks(tasks) {
name = "exec_shell_command";
display_name = "Execute shell command";
uses_cwd = true;
@@ -1655,8 +2098,11 @@ struct server_tool_exec_shell_command : server_tool {
// first, so a client can show it while the command still streams; the tool ignores it
{"description", {{"type", "string"}, {"description", "Short plain-language description of what this command does, starting with a verb, e.g. 'List files in the project root'. 3 to 10 words. Shown to the user."}}},
{"command", {{"type", "string"}, {"description", "Shell command to execute"}}},
- {"timeout", {{"type", "integer"}, {"description", string_format("Timeout in seconds (default 10, max %d)", SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT)}}},
+ {"timeout", {{"type", "integer"}, {"description", string_format("Timeout in seconds (default 10, max %d), none for a background command", SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT)}}},
{"max_output_size", {{"type", "integer"}, {"description", string_format("Maximum output size in bytes (default %zu)", SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE)}}},
+ {"background", {{"type", "boolean"}, {"description", "Run the command as a background task (default false), for long-running commands such as dev servers, watchers, builds or downloads. It has no timeout: if it still runs after background_after_seconds, the call returns with a task id and the first output; read the new output and stop the task with background_task. Do not add `&` or `nohup` yourself."}}},
+ {"notify", {{"type", "string"}, {"enum", json::array({"exit", "progress", "none"})}, {"description", "For a background task: when you want to get an update without asking, on exit (default), on new output too, or never"}}},
+ {"background_after_seconds", {{"type", "integer"}, {"description", string_format("For a background command: seconds to wait for its output before the call returns (default %d, max %d)", SERVER_TOOL_TASK_BACKGROUND_AFTER, SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT)}}},
}},
{"required", json::array({"description", "command"})},
}},
@@ -1682,6 +2128,36 @@ struct server_tool_exec_shell_command : server_tool {
std::vector<std::string> args = {"sh", "-c", command};
#endif
+ const std::string conv_id = json_value(params, "conversation_id", std::string());
+ const bool background = json_value(params, "background", false);
+
+ // a tools runtime runs the command in an isolate, where a task can not follow it
+ if (!json_value(params, "runtime", std::string()).empty()) {
+ if (background) {
+ return {{"error", "background tasks do not run in a tools runtime yet"}};
+ }
+ return run_in_runtime(args, params, max_output, timeout, st, should_stop);
+ }
+ if (background && conv_id.empty()) {
+ return {{"error", "a background task belongs to a conversation: the client must send the X-Conversation-Id header"}};
+ }
+
+ tools_task_ptr task;
+ try {
+ // a background command has no timeout, its deadline only moves it to the background
+ const int after = std::clamp(json_value(params, "background_after_seconds", SERVER_TOOL_TASK_BACKGROUND_AFTER), 0, SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT);
+ task = tasks->start(args, conv_id, params, background, background ? after : timeout);
+ } catch (const std::exception & e) {
+ return {{"error", e.what()}};
+ }
+ if (st) {
+ st->push_data({{"exec_id", task->id}});
+ }
+ return wait_attached(*task, max_output, st, should_stop);
+ }
+
+ json run_in_runtime(const std::vector<std::string> & args, const json & params, size_t max_output, int timeout,
+ server_tool::stream * st, const std::function<bool()> & should_stop) const {
auto io = make_tools_io(params);
if (st) {
@@ -1712,6 +2188,126 @@ struct server_tool_exec_shell_command : server_tool {
return {{"plain_text_response", text_output}};
}
+
+ // waits for the command of an attached task, streaming its output, until it ends, the client leaves, or it is moved to the background
+ json wait_attached(tools_task & task, size_t max_output, server_tool::stream * st, const std::function<bool()> & should_stop) const {
+ auto client_gone = [&]() {
+ return st ? (st->alive && !st->alive()) : (should_stop && should_stop());
+ };
+ std::function<bool(const std::string &)> on_chunk = nullptr;
+ if (st) {
+ on_chunk = [st](const std::string & chunk) {
+ st->push(chunk);
+ return !st->alive || st->alive();
+ };
+ }
+ subprocess_output out(max_output, on_chunk);
+ size_t consumed = 0;
+ task.output.read_from(0, [&](const char * buf, size_t len) {
+ out.add(buf, len);
+ consumed += len;
+ return true;
+ }, [&]() {
+ return !tasks->is_attached(task) || client_gone();
+ });
+
+ std::string text = console_output_to_utf8(out.text);
+ if (out.truncated) {
+ text += "\n[output truncated]";
+ }
+ if (!tasks->is_attached(task)) {
+ tasks->mark_read(task, consumed);
+ const std::string tail = string_format("\n[moved to the background as task %d: read its output and stop it with background_task]", task.id);
+ if (st) {
+ st->push(tail);
+ return json();
+ }
+ return {{"plain_text_response", text + tail}, {"task_id", task.id}};
+ }
+ if (!task.output.is_done()) {
+ // the client left: a background command still moves to the background, any other is stopped
+ std::string reason;
+ if (!task.detach_at_deadline || !tasks->detach(task, reason)) {
+ tasks->stop(task);
+ tasks->remove(task);
+ }
+ return json();
+ }
+
+ const json result = tasks->to_json(task);
+ tasks->remove(task);
+ std::string tail = string_format("\n[exit code: %d]", result.at("exit_code").get<int>());
+ if (result.contains("timed_out")) {
+ tail += " [exit due to timed out]";
+ }
+ if (st) {
+ st->push(tail);
+ return json();
+ }
+ return {{"plain_text_response", text + tail}};
+ }
+};
+
+//
+// background_task: list, read and stop the background tasks of the conversation
+//
+
+struct server_tool_background_task : server_tool {
+ tools_tasks * tasks;
+
+ explicit server_tool_background_task(tools_tasks * tasks) : tasks(tasks) {
+ name = "background_task";
+ display_name = "Background task";
+ }
+
+ json get_definition() const override {
+ return {
+ {"type", "function"},
+ {"function", {
+ {"name", name},
+ {"description", "List the background tasks started by exec_shell_command in this conversation, read the output a task printed since the last read, or stop a task."},
+ {"parameters", {
+ {"type", "object"},
+ {"properties", {
+ {"action", {{"type", "string"}, {"enum", json::array({"list", "output", "stop"})}}},
+ {"task_id", {{"type", "integer"}, {"description", "Task to read or stop, not needed to list"}}},
+ }},
+ {"required", json::array({"action"})},
+ }},
+ }},
+ };
+ }
+
+ json invoke(json params, server_tool::stream *, const std::function<bool()> &) const override {
+ const std::string conv_id = json_value(params, "conversation_id", std::string());
+ if (conv_id.empty()) {
+ return {{"error", "background tasks belong to a conversation: the client must send the X-Conversation-Id header"}};
+ }
+ const std::string action = params.at("action").get<std::string>();
+
+ if (action == "list") {
+ std::string text;
+ for (const auto & t : tasks->list({conv_id})) {
+ text += string_format("%d: %s", t.at("id").get<int>(), t.at("status").get<std::string>().c_str());
+ if (t.contains("exit_code")) {
+ text += string_format(" (exit code: %d)", t.at("exit_code").get<int>());
+ }
+ text += ", " + t.at("command").get<std::string>() + "\n";
+ }
+ return {{"plain_text_response", text.empty() ? "no background task" : text}};
+ }
+
+ tools_task_ptr task = tasks->get(json_value(params, "task_id", 0), conv_id);
+ if (!task) {
+ return {{"error", "no such background task in this conversation"}};
+ }
+ if (action == "stop") {
+ tasks->stop(*task);
+ } else if (action != "output") {
+ return {{"error", "unknown action: " + action}};
+ }
+ return {{"plain_text_response", tools_task_report(tasks->read_for_model(*task), tasks->to_json(*task))}};
+ }
};
//
@@ -2154,12 +2750,19 @@ struct server_tool_get_info : server_tool {
struct server_tool_stream_result : server_task_result {
std::string chunk;
+ json data; // fields sent beside the chunk, e.g. the exec_id of a command
bool done = false;
std::string error_msg;
json to_json() override {
if (!done) {
- return {{"chunk", chunk}};
+ json result = {{"chunk", chunk}};
+ if (data.is_object()) {
+ for (const auto & item : data.items()) {
+ result[item.key()] = item.value();
+ }
+ }
+ return result;
} else {
json result = {{"done", true}};
if (!error_msg.empty()) {
@@ -2178,6 +2781,13 @@ void server_tool::stream::push(const std::string & chunk) {
qr.send(std::move(r));
}
+void server_tool::stream::push_data(const json & data) {
+ auto r = std::make_unique<server_tool_stream_result>();
+ r->id = id;
+ r->data = data;
+ qr.send(std::move(r));
+}
+
struct server_tools_res : server_http_res {
std::thread worker;
server_response * qr = nullptr; // set only for streaming responses
@@ -2345,7 +2955,7 @@ static server_tool & find_tool(std::vector<std::unique_ptr<server_tool>> & tools
// public API
//
-static std::vector<std::unique_ptr<server_tool>> build_tools() {
+static std::vector<std::unique_ptr<server_tool>> build_tools(tools_tasks * tasks) {
// IMPORTANT: for contributors, please keep this array of tools as minimal as possible
// we only accept minimal i/o and shell command tools here
// for example, do not add: web search, get date time, etc.
@@ -2354,7 +2964,8 @@ static std::vector<std::unique_ptr<server_tool>> build_tools() {
tools.push_back(std::make_unique<server_tool_read_file>());
tools.push_back(std::make_unique<server_tool_file_glob_search>());
tools.push_back(std::make_unique<server_tool_grep_search>());
- tools.push_back(std::make_unique<server_tool_exec_shell_command>());
+ tools.push_back(std::make_unique<server_tool_exec_shell_command>(tasks));
+ tools.push_back(std::make_unique<server_tool_background_task>(tasks));
tools.push_back(std::make_unique<server_tool_write_file>());
tools.push_back(std::make_unique<server_tool_edit_file>());
tools.push_back(std::make_unique<server_tool_get_info>());
@@ -2404,7 +3015,8 @@ void server_tools::setup(const std::vector<std::string> & enabled_tools,
}
std::unordered_set<std::string> enabled_set(enabled_tools.begin(), enabled_tools.end());
- auto all_tools = build_tools();
+ tasks = std::make_unique<tools_tasks>();
+ auto all_tools = build_tools(tasks.get());
// collect all known tool names for validation
std::vector<std::string> known_names;
@@ -2505,6 +3117,13 @@ void server_tools::setup(const std::vector<std::string> & enabled_tools,
params["runtime"] = runtime_header;
}
+ // the conversation background tasks belong to, set by the client, never by the model
+ params.erase("conversation_id");
+ const std::string conv_id = server_stream_conv_id_from_headers(req.headers);
+ if (!conv_id.empty()) {
+ params["conversation_id"] = tools_task_conv_id(conv_id);
+ }
+
// x-resp-type header is only used by read_file for now
if (params.contains("resp_type")) {
params.erase("resp_type");
@@ -2571,4 +3190,147 @@ void server_tools::setup(const std::vector<std::string> & enabled_tools,
}
return res;
};
+
+ setup_tasks_routes();
+}
+
+static constexpr int SERVER_TOOL_TASKS_EVENTS_KEEPALIVE_SECS = 15;
+
+// one SSE client of the task events, waiting on its own id
+struct tools_tasks_client {
+ server_response & events;
+ const int id;
+
+ tools_tasks_client(server_response & events, int id) : events(events), id(id) {
+ events.add_waiting_task_id(id);
+ }
+ ~tools_tasks_client() {
+ events.remove_waiting_task_id(id);
+ }
+};
+
+void server_tools::setup_tasks_routes() {
+ auto res_error = [](int status, const std::string & msg) {
+ auto res = std::make_unique<server_http_res>();
+ res->status = status;
+ res->data = safe_json_to_str(format_error_response(msg, status == 404 ? ERROR_TYPE_NOT_FOUND : ERROR_TYPE_INVALID_REQUEST));
+ return res;
+ };
+ // the task a request names, only within the conversation it names too
+ auto find_task = [this](const server_http_req & req) -> tools_task_ptr {
+ if (!tasks) {
+ return nullptr;
+ }
+ int id = 0;
+ try {
+ id = std::stoi(req.get_param("id"));
+ } catch (...) {
+ return nullptr;
+ }
+ return tasks->get(id, tools_task_conv_id(req.get_param("conv_id")));
+ };
+
+ // GET /tools/tasks/events?conv_ids=a,b: a snapshot of the tasks of these conversations, then their events
+ // the server only answers for the conversations it is asked about, it never lists the others
+ handle_tasks_events = [this, res_error](const server_http_req & req) -> server_http_res_ptr {
+ std::unordered_set<std::string> conv_ids;
+ for (const auto & id : string_split<std::string>(req.get_param("conv_ids"), ',')) {
+ if (!id.empty()) {
+ conv_ids.insert(tools_task_conv_id(id));
+ }
+ }
+ if (!tasks || conv_ids.empty()) {
+ return res_error(400, "conv_ids is required");
+ }
+ auto client = std::make_shared<tools_tasks_client>(tasks->events, tasks->next_client_id.fetch_add(1));
+ std::string snapshot = "data: " + safe_json_to_str({{"event", "snapshot"}, {"tasks", tasks->list(conv_ids)}}) + "\n\n";
+
+ auto res = std::make_unique<server_http_res>();
+ res->status = 200;
+ res->content_type = "text/event-stream";
+ res->next = [client, conv_ids, snapshot = std::move(snapshot), &req](std::string & output) mutable -> bool {
+ if (!snapshot.empty()) {
+ output = std::move(snapshot);
+ snapshot.clear();
+ return true;
+ }
+ for (int idle = 0; ; idle++) {
+ server_task_result_ptr result = client->events.recv_with_timeout({client->id}, 1);
+ if (req.should_stop()) {
+ return false;
+ }
+ if (!result) {
+ if (idle >= SERVER_TOOL_TASKS_EVENTS_KEEPALIVE_SECS) {
+ output = ": keepalive\n\n";
+ return true;
+ }
+ continue;
+ }
+ json data = result->to_json();
+ if (conv_ids.count(json_value(data, "conv_id", std::string()))) {
+ output = "data: " + safe_json_to_str(data) + "\n\n";
+ return true;
+ }
+ }
+ };
+ return res;
+ };
+
+ // GET /tools/tasks/output?conv_id=c&id=n&from=offset: the output of a task since an offset
+ handle_tasks_output = [this, res_error, find_task](const server_http_req & req) -> server_http_res_ptr {
+ tools_task_ptr task = find_task(req);
+ if (!task) {
+ return res_error(404, "no such background task in this conversation");
+ }
+ size_t from = 0;
+ try {
+ from = std::stoull(req.get_param("from", "0"));
+ } catch (...) {
+ return res_error(400, "from must be an offset");
+ }
+ const tools_task_read r = tools_task_read_output(*task, from, SERVER_TOOL_TASK_OUTPUT_MAX_BYTES);
+ json data = tasks->to_json(*task);
+ data["output"] = console_output_to_utf8(r.text);
+ data["next"] = r.next;
+ data["skipped"] = r.skipped;
+ auto res = std::make_unique<server_http_res>();
+ res->data = safe_json_to_str(data);
+ return res;
+ };
+
+ // POST /tools/tasks {"conv_id": c, "from_exec_id": n}: move a running command to the background, its call returns at once
+ handle_tasks_create = [this, res_error](const server_http_req & req) -> server_http_res_ptr {
+ std::string conv_id;
+ int exec_id = 0;
+ try {
+ const json body = json::parse(req.body);
+ conv_id = tools_task_conv_id(body.at("conv_id").get<std::string>());
+ exec_id = body.at("from_exec_id").get<int>();
+ } catch (...) {
+ return res_error(400, "expected a JSON body with conv_id and from_exec_id");
+ }
+ tools_task_ptr task = tasks ? tasks->get(exec_id, conv_id, true) : nullptr;
+ if (!task) {
+ return res_error(404, "no such command in this conversation");
+ }
+ std::string reason;
+ if (!tasks->detach(*task, reason)) {
+ return res_error(400, reason);
+ }
+ auto res = std::make_unique<server_http_res>();
+ res->data = safe_json_to_str(tasks->to_json(*task));
+ return res;
+ };
+
+ // DELETE /tools/tasks?conv_id=c&id=n: stop a task, with everything it started
+ handle_tasks_stop = [this, res_error, find_task](const server_http_req & req) -> server_http_res_ptr {
+ tools_task_ptr task = find_task(req);
+ if (!task) {
+ return res_error(404, "no such background task in this conversation");
+ }
+ tasks->stop(*task);
+ auto res = std::make_unique<server_http_res>();
+ res->data = safe_json_to_str(tasks->to_json(*task));
+ return res;
+ };
}
diff --git a/tools/server/server-tools.h b/tools/server/server-tools.h
index 5a63ee973..03ef99cda 100644
--- a/tools/server/server-tools.h
+++ b/tools/server/server-tools.h
@@ -25,6 +25,7 @@ struct server_tool {
int id;
std::function<bool()> alive;
void push(const std::string & chunk);
+ void push_data(const json & data);
};
// should_stop: true once the caller stopped waiting, e.g. the client dropped the connection; a null should_stop means "never stop"
virtual json invoke(json params, stream * st = nullptr, const std::function<bool()> & should_stop = nullptr) const = 0;
@@ -33,6 +34,7 @@ struct server_tool {
};
struct server_tools_runtime; // impl detail, defined in server-tools.cpp
+struct tools_tasks; // impl detail, defined in server-tools.cpp
struct server_tools {
std::vector<std::unique_ptr<server_tool>> tools;
@@ -44,13 +46,23 @@ struct server_tools {
// set when --tools-runtime is configured; routes every tool call through an isolate
std::unique_ptr<server_tools_runtime> runtime;
+ // background tasks started by exec_shell_command, stopped with everything they started when this is destroyed
+ std::unique_ptr<tools_tasks> tasks;
+
void setup(const std::vector<std::string> & enabled_tools,
server_mcp & mcp_mgr,
const std::string & tools_runtime);
server_http_context::handler_t handle_get;
server_http_context::handler_t handle_post;
+ server_http_context::handler_t handle_tasks_events; // GET /tools/tasks/events?conv_ids=a,b
+ server_http_context::handler_t handle_tasks_create; // POST /tools/tasks {"conv_id": c, "from_exec_id": n}
+ server_http_context::handler_t handle_tasks_output; // GET /tools/tasks/output?conv_id=c&id=n&from=offset
+ server_http_context::handler_t handle_tasks_stop; // DELETE /tools/tasks?conv_id=c&id=n
server_tools();
~server_tools();
+
+private:
+ void setup_tasks_routes();
};
diff --git a/tools/server/server.cpp b/tools/server/server.cpp
index 8b9b73db7..de5bea8b4 100644
--- a/tools/server/server.cpp
+++ b/tools/server/server.cpp
@@ -308,6 +308,10 @@ static bool server_setup_features(
}
ctx_http.get ("/tools", ex_wrapper(tools.handle_get));
ctx_http.post("/tools", ex_wrapper(tools.handle_post));
+ ctx_http.get ("/tools/tasks/events", ex_wrapper(tools.handle_tasks_events));
+ ctx_http.get ("/tools/tasks/output", ex_wrapper(tools.handle_tasks_output));
+ ctx_http.post("/tools/tasks", ex_wrapper(tools.handle_tasks_create));
+ ctx_http.del ("/tools/tasks", ex_wrapper(tools.handle_tasks_stop));
if (!params.server_tools.empty()) {
warn_names.push_back("server tools (experimental)");
}
@@ -320,6 +324,10 @@ static bool server_setup_features(
} else {
ctx_http.get ("/tools", ex_wrapper(res_403));
ctx_http.post("/tools", ex_wrapper(res_403));
+ ctx_http.get ("/tools/tasks/events", ex_wrapper(res_403));
+ ctx_http.get ("/tools/tasks/output", ex_wrapper(res_403));
+ ctx_http.post("/tools/tasks", ex_wrapper(res_403));
+ ctx_http.del ("/tools/tasks", ex_wrapper(res_403));
}
if (!warn_names.empty()) {
diff --git a/tools/server/tests/unit/test_tools_builtin.py b/tools/server/tests/unit/test_tools_builtin.py
index 6cb4f7ac9..4e69ae46a 100755
--- a/tools/server/tests/unit/test_tools_builtin.py
+++ b/tools/server/tests/unit/test_tools_builtin.py
@@ -1,3 +1,4 @@
+import json
import os
import re
import shutil
@@ -6,6 +7,7 @@ import sys
import time
import pytest
+import requests
from utils import *
server: ServerProcess
@@ -21,6 +23,10 @@ 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"
+COMMAND_RUNNING_UNTIL_STOPPED = "ping -n 30 127.0.0.1 > nul" if os.name == "nt" else "sleep 30"
+COMMAND_ENDING_AFTER_3_SECONDS = "echo hello & ping -n 4 127.0.0.1 > nul & echo bye" if os.name == "nt" else "echo hello; sleep 3; echo bye"
+
+BACKGROUND_CONV_ID = "conv-background"
@pytest.fixture(autouse=True)
@@ -262,6 +268,132 @@ def test_tools_builtin_exec_shell_command_timeout_ends_the_command():
assert "done" not in res["plain_text_response"]
+def call_tool_in_conversation(name: str, params: dict) -> dict:
+ return call_tool(name, params, headers={"X-Conversation-Id": f"{BACKGROUND_CONV_ID}::some/model"})
+
+
+def wait_task_exited(events) -> list:
+ seen = []
+ for line in events.iter_lines():
+ if line.startswith(b"data: "):
+ seen.append(json.loads(line[6:])["event"])
+ if seen[-1] == "task_exited":
+ break
+ events.close()
+ return seen
+
+
+def test_tools_builtin_background_task_needs_a_conversation():
+ global server
+ server.start()
+
+ err = call_tool_expect_error("exec_shell_command", {"command": "echo hello", "background": True})
+ assert "X-Conversation-Id" in err
+
+
+def test_tools_builtin_background_task_output_and_events():
+ global server
+ server.start()
+
+ events = requests.get(server.make_url(f"/tools/tasks/events?conv_ids={BACKGROUND_CONV_ID}"), stream=True, timeout=30)
+ res = call_tool_in_conversation("exec_shell_command", {"command": COMMAND_ENDING_AFTER_3_SECONDS, "background": True})
+ assert "hello" in res["plain_text_response"]
+ assert "moved to the background" in res["plain_text_response"]
+ task_id = res["task_id"]
+
+ seen = wait_task_exited(events)
+ assert seen[0] == "snapshot"
+ assert "task_started" in seen
+
+ assert f"{task_id}: exited" in call_tool_in_conversation("background_task", {"action": "list"})["plain_text_response"]
+ other = server.make_request("POST", "/tools", data={"tool": "background_task", "params": {"action": "output", "task_id": task_id}},
+ headers={"X-Conversation-Id": "conv-other"})
+ assert "error" in other.body
+ output = server.make_request("GET", f"/tools/tasks/output?conv_id={BACKGROUND_CONV_ID}&id={task_id}&from=0")
+ assert "hello" in output.body["output"]
+ assert "bye" in output.body["output"]
+
+
+def test_tools_builtin_background_task_ending_early_returns_like_any_command():
+ global server
+ server.start()
+
+ res = call_tool_in_conversation("exec_shell_command", {"command": "echo quick", "background": True})
+ assert "quick" in res["plain_text_response"]
+ assert "exit code: 0" in res["plain_text_response"]
+ assert "task_id" not in res
+
+
+def test_tools_builtin_background_task_has_no_timeout():
+ global server
+ server.start()
+
+ events = requests.get(server.make_url(f"/tools/tasks/events?conv_ids={BACKGROUND_CONV_ID}"), stream=True, timeout=30)
+ res = call_tool_in_conversation("exec_shell_command", {
+ "command": COMMAND_ENDING_AFTER_3_SECONDS, "background": True, "background_after_seconds": 0, "timeout": 1,
+ })
+ task_id = res["task_id"]
+ wait_task_exited(events)
+
+ output = server.make_request("GET", f"/tools/tasks/output?conv_id={BACKGROUND_CONV_ID}&id={task_id}&from=0")
+ assert "bye" in output.body["output"]
+ assert output.body["exit_code"] == 0
+ assert "timed_out" not in output.body
+
+
+def test_tools_builtin_background_task_stop():
+ global server
+ server.start()
+
+ res = call_tool_in_conversation("exec_shell_command", {"command": COMMAND_RUNNING_UNTIL_STOPPED, "background": True})
+ assert "moved to the background" in res["plain_text_response"]
+
+ start = time.monotonic()
+ stopped = server.make_request("DELETE", f"/tools/tasks?conv_id={BACKGROUND_CONV_ID}&id={res['task_id']}")
+ assert time.monotonic() - start < 10
+ assert stopped.body["status"] == "stopped"
+
+
+def test_tools_builtin_exec_moved_to_the_background_while_running():
+ global server
+ server.start()
+
+ events = server.make_stream_request("POST", "/tools", data={
+ "tool": "exec_shell_command",
+ "params": {"command": COMMAND_RUNNING_UNTIL_STOPPED, "timeout": 20},
+ "stream": True,
+ }, headers={"X-Conversation-Id": BACKGROUND_CONV_ID})
+ exec_id = next(events)["exec_id"]
+
+ res = server.make_request("POST", "/tools/tasks", data={"conv_id": BACKGROUND_CONV_ID, "from_exec_id": exec_id})
+ assert res.status_code == 200, res.body
+ assert "moved to the background" in "".join(e.get("chunk", "") for e in events)
+
+ stopped = server.make_request("DELETE", f"/tools/tasks?conv_id={BACKGROUND_CONV_ID}&id={exec_id}")
+ assert stopped.body["status"] == "stopped"
+
+
+def test_tools_builtin_exec_moved_to_the_background_loses_its_timeout():
+ global server
+ server.start()
+
+ events = requests.get(server.make_url(f"/tools/tasks/events?conv_ids={BACKGROUND_CONV_ID}"), stream=True, timeout=30)
+ call = server.make_stream_request("POST", "/tools", data={
+ "tool": "exec_shell_command",
+ "params": {"command": COMMAND_ENDING_AFTER_3_SECONDS, "timeout": 2},
+ "stream": True,
+ }, headers={"X-Conversation-Id": BACKGROUND_CONV_ID})
+ exec_id = next(call)["exec_id"]
+
+ res = server.make_request("POST", "/tools/tasks", data={"conv_id": BACKGROUND_CONV_ID, "from_exec_id": exec_id})
+ assert res.status_code == 200, res.body
+ wait_task_exited(events)
+
+ output = server.make_request("GET", f"/tools/tasks/output?conv_id={BACKGROUND_CONV_ID}&id={exec_id}&from=0")
+ assert "bye" in output.body["output"]
+ assert "timed_out" not in output.body
+
+
def test_tools_builtin_cwd_header(tmp_path):
global server
server.start()