Compare commits

...
Author SHA1 Message Date
Pascal 41bd0f8303 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.
2026-11-30 19:13:16 +01:00
Pascal 697fa7e887 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.
2026-11-30 18:44:11 +01:00
Pascal d6448000c5 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.
2026-11-30 18:13:35 +01:00
Pascal 8374915b12 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.
2026-11-30 18:13:35 +01:00
7 changed files with 992 additions and 91 deletions
+16
View File
@@ -264,6 +264,22 @@ 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` starts the command in the background, the call returns after about 1 s with the first output and a `task_id`
- `params.detach_on_timeout: true` moves the command to the background when it reaches its timeout, instead of killing it
- 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)
+10 -41
View File
@@ -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;
+48 -1
View File
@@ -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>;
File diff suppressed because it is too large Load Diff
+12
View File
@@ -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();
};
+8
View File
@@ -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()) {
@@ -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,9 @@ 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"
BACKGROUND_CONV_ID = "conv-background"
@pytest.fixture(autouse=True)
@@ -262,6 +267,89 @@ 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 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": "echo hello", "background": True})
assert "hello" in res["plain_text_response"]
assert "exit code: 0" in res["plain_text_response"]
task_id = res["task_id"]
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()
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"]
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 "running" 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_on_timeout():
global server
server.start()
res = call_tool_in_conversation("exec_shell_command", {"command": COMMAND_RUNNING_UNTIL_STOPPED, "timeout": 1, "detach_on_timeout": True})
assert "moved to the background" in res["plain_text_response"]
stopped = server.make_request("DELETE", f"/tools/tasks?conv_id={BACKGROUND_CONV_ID}&id={res['task_id']}")
assert stopped.body["status"] == "stopped"
def test_tools_builtin_cwd_header(tmp_path):
global server
server.start()