#include "server-tools.h" #include "server-stream.h" #include "subproc.h" #include "base64.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(_WIN32) # ifndef NOMINMAX # define NOMINMAX # endif # include # include # include #else # include # include # include # include # include # include # include #endif namespace fs = std::filesystem; // // internal helpers // #if defined(_WIN32) // code page of the system locale, read once at first use static UINT legacy_oem_code_page() { static const UINT cp = [] { DWORD value = 0; const int ret = GetLocaleInfoEx(LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_IDEFAULTCODEPAGE | LOCALE_RETURN_NUMBER, reinterpret_cast(&value), sizeof(value) / sizeof(WCHAR)); if (ret > 0 && value && value != CP_OEMCP) { return static_cast(value); } return GetOEMCP(); }(); return cp; } #endif // a child process writes in the legacy console code page, so accented output would reach // the JSON layer as invalid bytes. run() spawns without a console, so the console // code page never applies static std::string console_output_to_utf8(const std::string & text) { #if defined(_WIN32) // a chunk can end mid sequence, so the incomplete tail is dropped first if (text.empty() || is_valid_utf8(text.substr(0, validate_utf8(text)))) { // never decode twice a child that already emits UTF-8 return text; } const UINT cp = legacy_oem_code_page(); // fail rather than emit replacement characters when the code page is wrong const int wide_len = MultiByteToWideChar(cp, MB_ERR_INVALID_CHARS, text.data(), (int) text.size(), nullptr, 0); if (wide_len <= 0) { return text; } std::wstring wide(wide_len, L'\0'); MultiByteToWideChar(cp, MB_ERR_INVALID_CHARS, text.data(), (int) text.size(), wide.data(), wide_len); const int utf8_len = WideCharToMultiByte(CP_UTF8, 0, wide.data(), wide_len, nullptr, 0, nullptr, nullptr); if (utf8_len <= 0) { return text; } std::string utf8(utf8_len, '\0'); WideCharToMultiByte(CP_UTF8, 0, wide.data(), wide_len, utf8.data(), utf8_len, nullptr, nullptr); return utf8; #else return text; #endif } json server_tool::to_json() const { return { {"display_name", display_name}, {"tool", name}, {"type", type()}, {"permissions", json{ {"write", permission_write} }}, {"uses_cwd", uses_cwd}, {"definition", get_definition()}, }; } static constexpr size_t SERVER_TOOL_GIT_LS_FILES_MAX_OUTPUT = 8 * 1024 * 1024; // 8 MB // budget for one listing call, shared by the git and walker paths static constexpr int SERVER_TOOL_LIST_ENTRIES_TIMEOUT = 15; // seconds // entry kinds a directory listing may return enum class list_kind { files, // regular files only dirs, // directories only all, // both }; // home directory, read once at first use (getenv is not thread safe against setenv) static const std::string & home_dir() { static const std::string home = [] { #ifdef _WIN32 const std::string h = common_get_env("HOME"); return h.empty() ? common_get_env("USERPROFILE") : h; #else return common_get_env("HOME"); #endif }(); return home; } static std::string expand_home(const std::string & path) { if (path.empty() || path[0] != '~') return path; if (path.size() > 1 && path[1] != '/' && path[1] != '\\') return path; const std::string & home = home_dir(); if (home.empty()) return path; return home + path.substr(1); } // depth of a '/'-separated relative path: "a/b/c" is 3 static int entry_depth(const std::string & rel) { return 1 + (int) std::count(rel.begin(), rel.end(), '/'); } // directories that a listing reports but never descends into: they can be enormous // lowercase only, the local walker case-folds a name before the lookup static const char * const SERVER_TOOL_JUNK_DIR_NAMES[] = { ".git", ".svn", ".hg", "node_modules", "__pycache__", ".venv", "venv", "dist", "build", "target", ".cache", ".idea", ".vscode", }; class tools_io { public: struct exec_result { std::string output; int exit_code = -1; bool timed_out = false; }; virtual ~tools_io() = default; virtual bool is_directory(const std::string & path) const = 0; virtual bool is_regular_file(const std::string & path) const = 0; virtual bool file_size(const std::string & path, uintmax_t & out_size) const = 0; virtual bool read_file(const std::string & path, std::string & out) const = 0; virtual bool write_file(const std::string & path, const std::string & content) const = 0; // resolve `path` against the IO's working directory; absolute paths are returned unchanged virtual std::string resolve(const std::string & path) const = 0; struct list_entry { std::string rel; // '/'-separated, relative to `base` bool is_dir = false; }; struct list_result { std::vector entries; std::string err; // set when `base` is not a directory bool truncated = false; // set when the walk could not see everything }; // entries relative to `base`, which must already be resolved (absolute) // max_depth == 0 means unlimited, 1 means direct children of `base` only 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 & args, size_t max_output, int timeout_secs, const std::function & on_chunk = nullptr, const std::function & should_stop = nullptr) const = 0; }; #if defined(LLAMA_SUBPROCESS) // 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; #endif // 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 & on_chunk; std::string text; bool truncated = false; bool stopped = false; subprocess_output(size_t max_output, const std::function & 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))); } } }; 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 & args, bool combine_stderr, const std::string & cwd, const std::string * stdin_data, int timeout_secs, const std::function & sink, const std::function & should_stop); #if !defined(LLAMA_SUBPROCESS) static subprocess_job_result run_job( const std::vector &, bool, const std::string &, const std::string *, int, const std::function &, const std::function &) { return {}; } #elif defined(_WIN32) 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 & 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 lock(mutex); chunk.swap(pending); return chunk; } 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 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(w->data->size() - done, 65536), &put, nullptr)) { done += put; } CloseHandle(w->pipe); return 0; } }; static subprocess_job_result run_job( const std::vector & args, bool combine_stderr, const std::string & cwd, const std::string * stdin_data, int timeout_secs, const std::function & sink, const std::function & should_stop) { 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 }; 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; } 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 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); 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(); } 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(); 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 (stopped || (should_stop && should_stop())) { break; } } 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(); if (!rest.empty()) { sink(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; 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 #else (void) actions; (void) cwd; return ENOSYS; #endif } static subprocess_job_result run_job( const std::vector & args, bool combine_stderr, const std::string & cwd, const std::string * stdin_data, int timeout_secs, const std::function & sink, const std::function & should_stop) { subprocess_job_result res; 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 argv; for (const auto & a : args) { argv.push_back(const_cast(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); } 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(); 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) { if (!sink(buf, (size_t) got)) { stopped = true; } } else if (got == 0 || errno != EINTR) { close(out_fd); out_fd = -1; } } 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; } 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 && 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 || 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; } } 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 = 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 & args, size_t max_output, int timeout_secs, const std::function & on_chunk, bool combine_stderr, const std::string & cwd = "", const std::string * stdin_data = nullptr, const std::function & 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]"; } return res; } 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() explicit tools_io_basic(std::string cwd = "") : cwd(std::move(cwd)) {} // expands a leading `~`, then resolves `path` against `cwd` (or the server // working directory when `cwd` is unset); the result is always absolute std::string resolve(const std::string & path) const override { const std::string p = expand_home(path); fs::path full = p; if (!full.is_absolute()) { if (cwd.empty()) { std::error_code ec; const fs::path cur = fs::current_path(ec); if (ec) return p; full = cur / full; } else { full = fs::path(cwd) / full; } } // drop "." and ".." so they never reach git or the client full = full.lexically_normal(); // a trailing ".." normalizes to a path that ends with a separator if (!full.has_filename() && full != full.root_path()) { full = full.parent_path(); } return full.generic_string(); } bool is_directory(const std::string & path) const override { std::error_code ec; return fs::is_directory(resolve(path), ec) && !ec; } bool is_regular_file(const std::string & path) const override { std::error_code ec; return fs::is_regular_file(resolve(path), ec) && !ec; } bool file_size(const std::string & path, uintmax_t & out_size) const override { std::error_code ec; out_size = fs::file_size(resolve(path), ec); return !ec; } bool read_file(const std::string & path, std::string & out) const override { std::ifstream f(resolve(path), std::ios::binary); if (!f) return false; std::ostringstream ss; ss << f.rdbuf(); out = ss.str(); return true; } bool write_file(const std::string & path, const std::string & content) const override { std::error_code ec; fs::path fpath = resolve(path); if (fpath.has_parent_path()) { fs::create_directories(fpath.parent_path(), ec); if (ec) return false; } std::ofstream f(fpath, std::ios::binary); if (!f) return false; f << content; return (bool) f; } list_result list_entries(const std::string & base, int max_depth, list_kind kind) const override { list_result out; std::error_code ec; if (!fs::is_directory(base, ec) || ec) { out.err = "path does not exist or is not a directory"; return out; } const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(SERVER_TOOL_LIST_ENTRIES_TIMEOUT); // git ls-files cannot list directories; use the walker when they are requested if (kind == list_kind::files) { auto res = run( {"git", "-C", base, "ls-files", "--cached", "--others", "--exclude-standard"}, SERVER_TOOL_GIT_LS_FILES_MAX_OUTPUT, SERVER_TOOL_LIST_ENTRIES_TIMEOUT); if (res.exit_code == 0 && !res.timed_out) { std::istringstream iss(res.output); std::string line; while (std::getline(iss, line)) { if (!line.empty() && line.back() == '\r') line.pop_back(); if (line.empty()) continue; std::replace(line.begin(), line.end(), '\\', '/'); if (max_depth > 0 && entry_depth(line) > max_depth) continue; if (is_regular_file((fs::path(base) / line).generic_string())) { out.entries.push_back({line, false}); } } return out; } } out.entries = list_entries_fallback(base, max_depth, kind, deadline, out.truncated); return out; } exec_result run( const std::vector & args, size_t max_output, int timeout_secs, const std::function & on_chunk = nullptr, const std::function & should_stop = nullptr) const override { return run_subprocess(args, max_output, timeout_secs, on_chunk, /*combine_stderr=*/true, cwd, nullptr, should_stop); } private: std::string cwd; // a link can point back to an ancestor and loop forever, so it is never walked static bool is_link(const fs::directory_entry & entry) { std::error_code ec; if (entry.is_symlink(ec) || ec) { return true; } #if defined(_WIN32) // a junction looks like a plain directory to std::filesystem, so read the reparse tag WIN32_FIND_DATAW data; const HANDLE h = FindFirstFileW(entry.path().c_str(), &data); if (h == INVALID_HANDLE_VALUE) { return false; } FindClose(h); if ((data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0) { return false; } // other reparse points (cloud placeholder, dedup stub) are real directories return data.dwReserved0 == IO_REPARSE_TAG_SYMLINK || data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT; #else return false; #endif } // NTFS is case insensitive, so Build and build are the same directory static std::string get_effective_name(const std::string & fname) { #if defined(_WIN32) std::string lowered = fname; std::transform(lowered.begin(), lowered.end(), lowered.begin(), [](unsigned char c) { return (char) std::tolower(c); }); return lowered; #else return fname; #endif } static const std::unordered_set & junk_dir_names() { static const std::unordered_set names( std::begin(SERVER_TOOL_JUNK_DIR_NAMES), std::end(SERVER_TOOL_JUNK_DIR_NAMES)); return names; } std::vector list_entries_fallback(const std::string & base, int max_depth, list_kind kind, std::chrono::steady_clock::time_point deadline, bool & truncated) const { std::vector result; std::vector> stack; stack.emplace_back(base, fs::path(), 0); while (!stack.empty()) { if (std::chrono::steady_clock::now() >= deadline) { truncated = true; return result; } auto [dir, rel_dir, depth] = std::move(stack.back()); stack.pop_back(); std::error_code ec; // step the iterator by hand: the throwing increment escapes on a directory that goes away fs::directory_iterator it(dir, fs::directory_options::skip_permission_denied, ec); // permission errors are skipped above, so this is a subtree the caller never sees if (ec) { truncated = true; continue; } for (const fs::directory_iterator end; it != end; it.increment(ec)) { if (ec) { truncated = true; break; } if (std::chrono::steady_clock::now() >= deadline) { truncated = true; return result; } const fs::directory_entry & entry = *it; const fs::path fname = entry.path().filename(); std::error_code tec; const bool is_dir = entry.is_directory(tec); if (tec) continue; if (is_dir) { if (kind == list_kind::dirs || kind == list_kind::all) { result.push_back({(rel_dir / fname).generic_string(), true}); } // junk directories stay selectable but are never walked: they can be enormous if (junk_dir_names().count(get_effective_name(fname.generic_string())) > 0) continue; if (!is_link(entry) && (max_depth == 0 || depth + 1 < max_depth)) { stack.emplace_back(entry.path(), rel_dir / fname, depth + 1); } } else if (entry.is_regular_file(tec)) { if (kind == list_kind::files || kind == list_kind::all) { result.push_back({(rel_dir / fname).generic_string(), false}); } } } } return result; } }; // timeout for auxiliary isolate calls (stat/mkdir/ls helpers); exec_shell_command uses its own // caller-controlled timeout instead, enforced separately in run() static constexpr int SERVER_TOOL_ISOLATE_EXEC_TIMEOUT = 15; // seconds static constexpr size_t SERVER_TOOL_ISOLATE_READ_FILE_MAX_SIZE = 64 * 1024 * 1024; // 64 MB // runs every tools_io operation as a command inside an isolate: a container, a remote host, ... // the isolate is created, mounted, and torn down externally by the caller // it must provide a POSIX environment: sh, cat, wc, mkdir, dirname, find, timeout class tools_io_isolate : public tools_io { public: // cwd, if non-empty, is used to resolve relative paths and as the working directory for run() explicit tools_io_isolate(std::string cwd = "") : cwd(std::move(cwd)) {} // resolves `path` against `cwd` if `path` is relative and `cwd` is set; otherwise returns `path` unchanged. // isolate paths are always POSIX-style ('/'), regardless of host OS. std::string resolve(const std::string & path) const override { if (cwd.empty() || (!path.empty() && path[0] == '/')) { return path; } return cwd + "/" + path; } bool is_directory(const std::string & path) const override { return shell_test("-d", resolve(path)); } bool is_regular_file(const std::string & path) const override { return shell_test("-f", resolve(path)); } bool file_size(const std::string & path, uintmax_t & out_size) const override { auto res = exec({"sh", "-c", "wc -c < \"$1\"", "_", resolve(path)}, 64, true); if (res.exit_code != 0 || res.timed_out) return false; try { size_t pos; out_size = (uintmax_t) std::stoull(res.output, &pos); } catch (...) { return false; } return true; } bool read_file(const std::string & path, std::string & out) const override { // combine_stderr=false: stderr must not be spliced into raw file bytes auto res = exec({"cat", "--", resolve(path)}, SERVER_TOOL_ISOLATE_READ_FILE_MAX_SIZE, false); if (res.exit_code != 0 || res.timed_out) return false; out = res.output; return true; } bool write_file(const std::string & path, const std::string & content) const override { // the content travels on stdin: no argv for the far side to re-parse, no temp file on the host auto res = run_subprocess( build_argv({"sh", "-c", "mkdir -p \"$(dirname \"$1\")\" && cat > \"$1\"", "_", resolve(path)}, /*needs_stdin=*/true), 4096, SERVER_TOOL_ISOLATE_EXEC_TIMEOUT, nullptr, true, "", &content); return res.exit_code == 0 && !res.timed_out; } list_result list_entries(const std::string & base, int max_depth, list_kind kind) const override { list_result out; const std::string abs_base = resolve(base); if (!is_directory(base)) { out.err = "path does not exist or is not a directory"; return out; } // git ls-files cannot list directories; use the walker when they are requested if (kind == list_kind::files) { auto res = exec( {"sh", "-c", "cd \"$1\" && git ls-files --cached --others --exclude-standard", "_", abs_base}, SERVER_TOOL_GIT_LS_FILES_MAX_OUTPUT, true); if (res.exit_code == 0 && !res.timed_out) { for (const auto & rel : split_lines(res.output, /*strip_dot_slash=*/false)) { if (max_depth > 0 && entry_depth(rel) > max_depth) continue; out.entries.push_back({rel, false}); } return out; } } if (kind == list_kind::dirs || kind == list_kind::all) { for (auto & rel : find_entries(abs_base, max_depth, /*dirs=*/true, out.truncated)) { out.entries.push_back({std::move(rel), true}); } } if (kind == list_kind::files || kind == list_kind::all) { for (auto & rel : find_entries(abs_base, max_depth, /*dirs=*/false, out.truncated)) { out.entries.push_back({std::move(rel), false}); } } return out; } // wraps the command with an in-isolate `timeout`, since killing the host-side client // does not kill the process tree running inside the isolate exec_result run( const std::vector & args, size_t max_output, int timeout_secs, const std::function & on_chunk = nullptr, const std::function & should_stop = nullptr) const override { std::vector 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, "", nullptr, should_stop); } protected: // wrap `inner` (a complete POSIX argv) into the host-side argv that runs it in the isolate // a transport that re-parses its args in a remote shell (ssh) must join `inner` with shell_quote_join() virtual std::vector build_argv(const std::vector & inner, bool needs_stdin) const = 0; // quote `argv` into a single string that a POSIX shell re-parses into exactly `argv` static std::string shell_quote_join(const std::vector & argv) { std::string out; for (const auto & arg : argv) { if (!out.empty()) out += ' '; out += '\''; for (const char c : arg) { // a single quote cannot be escaped inside single quotes: close, escape, reopen if (c == '\'') out += "'\\''"; else out += c; } out += '\''; } return out; } private: std::string cwd; // set the working directory in the command itself, no `-w` equivalent exists on every transport // auxiliary calls do not need this, they use the absolute paths from resolve() std::vector with_cwd(const std::vector & inner) const { if (cwd.empty()) { return inner; } // 127 is what a shell reports for a command it could not run std::vector out = {"sh", "-c", "cd \"$1\" || exit 127; shift; exec \"$@\"", "_", cwd}; out.insert(out.end(), inner.begin(), inner.end()); return out; } exec_result exec(const std::vector & inner, size_t max_output, bool combine_stderr) const { return run_subprocess( build_argv(inner, /*needs_stdin=*/false), max_output, SERVER_TOOL_ISOLATE_EXEC_TIMEOUT, nullptr, combine_stderr); } bool shell_run(const std::vector & inner) const { auto res = exec(inner, 4096, true); return res.exit_code == 0 && !res.timed_out; } bool shell_test(const char * flag, const std::string & path) const { return shell_run({"sh", "-c", std::string("[ ") + flag + " \"$1\" ]", "_", path}); } static std::vector split_lines(const std::string & text, bool strip_dot_slash) { std::vector result; std::istringstream iss(text); std::string line; while (std::getline(iss, line)) { if (!line.empty() && line.back() == '\r') line.pop_back(); if (line.empty()) continue; if (strip_dot_slash && line.rfind("./", 0) == 0) line = line.substr(2); std::replace(line.begin(), line.end(), '\\', '/'); result.push_back(line); } return result; } // one `find` pass in the isolate. junk directories stay selectable but are never descended into, // and -mindepth/-maxdepth keep a busybox image working as well as a GNU one std::vector find_entries(const std::string & abs_base, int max_depth, bool dirs, bool & truncated) const { std::string prune_expr; for (const char * n : SERVER_TOOL_JUNK_DIR_NAMES) { if (!prune_expr.empty()) prune_expr += " -o "; prune_expr += std::string("-name ") + n; } std::string cmd = "cd \"$1\" && find . -mindepth 1"; if (max_depth > 0) { cmd += " -maxdepth " + std::to_string(max_depth); } cmd += " \\( " + prune_expr + " \\) -prune"; cmd += dirs ? " -print -o -type d -print" : " -o -type f -print"; auto res = exec({"sh", "-c", cmd, "_", abs_base}, SERVER_TOOL_GIT_LS_FILES_MAX_OUTPUT, true); truncated = truncated || res.timed_out; return split_lines(res.output, /*strip_dot_slash=*/true); } }; // an already-running container, driven through ` exec` // docker and podman take the same verbs and the same argument order, so one class drives both class tools_io_container : public tools_io_isolate { public: tools_io_container(std::string bin, std::string container_id, std::string cwd = "") : tools_io_isolate(std::move(cwd)), bin(std::move(bin)), container_id(std::move(container_id)) {} protected: std::vector build_argv(const std::vector & inner, bool needs_stdin) const override { std::vector argv = {bin, "exec"}; if (needs_stdin) { argv.push_back("-i"); } argv.push_back(container_id); argv.insert(argv.end(), inner.begin(), inner.end()); return argv; } private: std::string bin; std::string container_id; }; // a remote host reached over ssh // this is remoting, not isolation: the tools can do anything the target account can do class tools_io_ssh : public tools_io_isolate { public: tools_io_ssh(std::string target, std::string cwd = "") : tools_io_isolate(std::move(cwd)), target(std::move(target)) {} // the target can come from a client header, and ssh reads options from its argv // a target starting with '-' would become one, e.g. -oProxyCommand= runs on the host static bool is_valid_target(const std::string & target) { if (target.empty() || target[0] == '-') { return false; } return std::all_of(target.begin(), target.end(), [](unsigned char c) { return std::isalnum(c) || c == '.' || c == '-' || c == '_' || c == '@'; }); } protected: std::vector build_argv(const std::vector & inner, bool needs_stdin) const override { // the remote shell re-parses the command line, so `inner` travels as one quoted word std::vector argv = ssh_argv(); if (!needs_stdin) { argv.push_back("-n"); } argv.push_back(target); argv.push_back(shell_quote_join(inner)); return argv; } private: std::string target; // there is no console here, so a prompt would hang the tool call // key-based auth only, and the admin must trust the host key beforehand static std::vector ssh_argv() { return { "ssh", "-o", "BatchMode=yes", "-o", "PasswordAuthentication=no", "-o", "KbdInteractiveAuthentication=no", "-o", "StrictHostKeyChecking=yes", }; } }; // ":" spawns a container and owns it, "-container:" attaches to one struct container_runtime_spec { std::string bin; std::string arg; // image name when spawning, container id when attaching bool attach = false; static bool parse(const std::string & spec, container_runtime_spec & out) { // docker and podman take the same verbs, hence a single implementation static const char * engines[] = {"docker", "podman"}; for (const char * bin : engines) { const std::string attach_prefix = std::string(bin) + "-container:"; if (spec.rfind(attach_prefix, 0) == 0) { out = {bin, spec.substr(attach_prefix.size()), true}; return true; } const std::string spawn_prefix = std::string(bin) + ":"; if (spec.rfind(spawn_prefix, 0) == 0) { out = {bin, spec.substr(spawn_prefix.size()), false}; return true; } } return false; } // same risk as the ssh target: an id starting with '-' would become an engine option, // e.g. --privileged static bool is_valid_id(const std::string & id) { if (id.empty() || !std::isalnum((unsigned char) id[0])) { return false; } return std::all_of(id.begin(), id.end(), [](unsigned char c) { return std::isalnum(c) || c == '.' || c == '-' || c == '_'; }); } }; static std::unique_ptr make_tools_io(const json & params) { std::string cwd = json_value(params, "cwd", std::string()); std::string runtime = json_value(params, "runtime", std::string()); if (runtime.empty()) { // an empty runtime runs the tools on the host return std::make_unique(cwd); } container_runtime_spec container; if (container_runtime_spec::parse(runtime, container)) { // spawning belongs to the runtime that owns the container, a tool call only attaches if (!container.attach) { throw std::runtime_error("tool runtime must name a running container: " + runtime); } if (!container_runtime_spec::is_valid_id(container.arg)) { throw std::runtime_error("invalid container id: " + container.arg); } return std::make_unique(container.bin, container.arg, cwd); } const std::string ssh_prefix = "ssh:"; if (runtime.rfind(ssh_prefix, 0) == 0) { std::string target = runtime.substr(ssh_prefix.size()); if (!tools_io_ssh::is_valid_target(target)) { throw std::runtime_error("invalid ssh target: " + target); } return std::make_unique(target, cwd); } // do not fall back to the host, the caller asked for an isolate throw std::runtime_error("unknown tool runtime: " + runtime); } // no '/' in pattern -> match basename at any depth; else match full relative path static bool path_glob_match(const std::string & pattern, const std::string & rel_path) { if (pattern.find('/') == std::string::npos) { return glob_match(pattern, fs::path(rel_path).filename().generic_string()); } if (pattern == "**" || pattern.rfind("**/", 0) == 0 || pattern.rfind('/', 0) == 0) { return glob_match(pattern, rel_path); } return glob_match("**/" + pattern, rel_path); } // // read_file: read a file with optional line range and line-number prefix // static constexpr size_t SERVER_TOOL_READ_FILE_MAX_SIZE = 16 * 1024; // 16 KB static constexpr size_t SERVER_TOOL_READ_FILE_MAX_SIZE_BASE64 = 32 * 1024 * 1024; // 32 MB struct server_tool_read_file : server_tool { server_tool_read_file() { name = "read_file"; display_name = "Read file"; uses_cwd = true; permission_write = false; } json get_definition() const override { return { {"type", "function"}, {"function", { {"name", name}, {"description", "Read the contents of a file. Optionally specify a 1-based line range. " "If append_loc is true, each line is prefixed with its line number (e.g. \"1\u2192...\")."}, {"parameters", { {"type", "object"}, {"properties", { {"path", {{"type", "string"}, {"description", "Path to the file"}}}, {"start_line", {{"type", "integer"}, {"description", "First line to read, 1-based (default: 1)"}}}, {"end_line", {{"type", "integer"}, {"description", "Last line to read, 1-based inclusive (default: end of file)"}}}, {"append_loc", {{"type", "boolean"}, {"description", "Prefix each line with its line number"}}}, }}, {"required", json::array({"path"})}, }}, }}, }; } json invoke(json params, server_tool::stream *, const std::function &) const override { std::string path = params.at("path").get(); int start_line = json_value(params, "start_line", 1); int end_line = json_value(params, "end_line", -1); // -1 = no limit bool append_loc = json_value(params, "append_loc", false); // comes from the x-resp-type header, the model cannot ask for it bool as_base64 = json_value(params, "resp_type", std::string()) == "base64"; auto io = make_tools_io(params); uintmax_t file_size = 0; if (!io->file_size(path, file_size)) { return {{"error", "cannot stat file: " + path}}; } if (as_base64) { if (file_size > SERVER_TOOL_READ_FILE_MAX_SIZE_BASE64) { return {{"error", string_format( "file too large (%zu bytes, max %zu)", (size_t)file_size, SERVER_TOOL_READ_FILE_MAX_SIZE_BASE64)}}; } std::string content; if (!io->read_file(path, content)) { return {{"error", "failed to open file: " + path}}; } return { {"base64", base64::encode(content.data(), content.size())}, {"size_bytes", (size_t) content.size()}, }; } if (file_size > SERVER_TOOL_READ_FILE_MAX_SIZE && end_line == -1) { return {{"error", string_format( "file too large (%zu bytes, max %zu). Use start_line/end_line to read a portion.", (size_t)file_size, SERVER_TOOL_READ_FILE_MAX_SIZE)}}; } std::string content; if (!io->read_file(path, content)) { return {{"error", "failed to open file: " + path}}; } std::istringstream f(content); std::string result; std::string line; int lineno = 0; while (std::getline(f, line)) { lineno++; if (lineno < start_line) continue; if (end_line != -1 && lineno > end_line) break; std::string out_line; if (append_loc) { out_line = std::to_string(lineno) + "\u2192" + line + "\n"; } else { out_line = line + "\n"; } if (result.size() + out_line.size() > SERVER_TOOL_READ_FILE_MAX_SIZE) { result += "[output truncated]"; break; } result += out_line; } return {{"plain_text_response", result}}; } }; // // file_glob_search: find files matching a glob pattern under a base directory // static constexpr int SERVER_TOOL_FILE_SEARCH_MAX_RESULTS = 100; static constexpr const char * SERVER_TOOL_FILE_SEARCH_TYPE_FILE = "file"; static constexpr const char * SERVER_TOOL_FILE_SEARCH_TYPE_DIR = "dir"; static constexpr const char * SERVER_TOOL_FILE_SEARCH_TYPE_ALL = "all"; struct server_tool_file_glob_search : server_tool { server_tool_file_glob_search() { name = "file_glob_search"; display_name = "File search"; uses_cwd = true; permission_write = false; } json get_definition() const override { return { {"type", "function"}, {"function", { {"name", name}, {"description", "Recursively search for files matching a glob pattern under a directory. " "Automatically skips files ignored by .gitignore (when the directory is inside a git repo) " "and common junk directories (.git, node_modules, build, dist, etc.) otherwise. " "A pattern with no '/' (e.g. \"*.cpp\") matches the file's basename at any depth. " "A pattern containing '/' matches the full relative path; unless already anchored with " "\"**/\" or a leading '/', it is automatically prefixed with \"**/\". " "Use type=\"dir\" or \"all\" to also list directories; directory entries are suffixed with '/' in the output. " "Note: directory listings do not apply .gitignore filtering."}, {"parameters", { {"type", "object"}, {"properties", { {"path", {{"type", "string"}, {"description", "Base directory to search in"}}}, {"include", {{"type", "string"}, {"description", "Glob pattern for files to include (e.g. \"*.cpp\" or \"src/**/*.cpp\"). Default: **"}}}, {"exclude", {{"type", "string"}, {"description", "Glob pattern for files to exclude"}}}, {"type", {{"type", "string"}, {"description", "Entry type to return: \"file\" (default), \"dir\" or \"all\""}}}, {"max_depth", {{"type", "integer"}, {"description", "Maximum depth to descend into subdirectories (default: 0 = unlimited; 1 = direct children only)"}}}, {"limit", {{"type", "integer"}, {"description", string_format("Maximum number of results to return, capped at %d (default %d)", SERVER_TOOL_FILE_SEARCH_MAX_RESULTS, SERVER_TOOL_FILE_SEARCH_MAX_RESULTS)}}}, }}, {"required", json::array({"path"})}, }}, }}, }; } json invoke(json params, server_tool::stream *, const std::function &) const override { auto io = make_tools_io(params); const std::string path = params.at("path").get(); std::string base = io->resolve(path); std::string include = json_value(params, "include", std::string("**")); std::string exclude = json_value(params, "exclude", std::string("")); std::string type = json_value(params, "type", std::string("file")); int max_depth = std::max(0, json_value(params, "max_depth", 0)); const int limit_req = json_value(params, "limit", SERVER_TOOL_FILE_SEARCH_MAX_RESULTS); if (limit_req < 1) { return {{"error", "invalid limit: " + std::to_string(limit_req) + " (expected 1 or more)"}}; } const int limit = std::min(limit_req, SERVER_TOOL_FILE_SEARCH_MAX_RESULTS); list_kind kind; if (type == SERVER_TOOL_FILE_SEARCH_TYPE_FILE) { kind = list_kind::files; } else if (type == SERVER_TOOL_FILE_SEARCH_TYPE_DIR) { kind = list_kind::dirs; } else if (type == SERVER_TOOL_FILE_SEARCH_TYPE_ALL) { kind = list_kind::all; } else { return {{"error", "invalid type: " + type + " (expected \"file\", \"dir\" or \"all\")"}}; } const auto listing = io->list_entries(base, max_depth, kind); if (!listing.err.empty()) { return {{"error", listing.err + ": " + path}}; } std::vector matches; for (const auto & entry : listing.entries) { if (!path_glob_match(include, entry.rel)) continue; if (!exclude.empty() && path_glob_match(exclude, entry.rel)) continue; matches.push_back(entry); } size_t total = matches.size(); size_t shown = std::min(total, (size_t) limit); std::ostringstream output_text; json entries_json = json::array(); for (size_t i = 0; i < shown; i++) { output_text << matches[i].rel << (matches[i].is_dir ? "/" : "") << "\n"; entries_json.push_back({ {"path", matches[i].rel}, {"type", matches[i].is_dir ? "dir" : "file"}, }); } output_text << "\n---\nTotal matches: " << total << "\n"; if (total > shown) { output_text << string_format( "[%zu results limit reached (%zu total matches). Refine the glob pattern to narrow the search.]\n", shown, total); } if (listing.truncated) { output_text << "[results truncated: time budget or unreadable directory]\n"; } // `base` is always absolute (resolve falls back to the server cwd), so // API clients (e.g. the Llama Chat picker) can join the relative entries // into absolute paths. `plain_text_response` is what the model sees; // `entries` is the same data as structured JSON for the UI picker, // which reads `entries`/`base` instead of re-parsing the text. return {{"plain_text_response", output_text.str()}, {"entries", entries_json}, {"base", base}}; } }; // // grep_search: search for a regex pattern in files // static constexpr size_t SERVER_TOOL_GREP_SEARCH_MAX_RESULTS = 100; struct server_tool_grep_search : server_tool { server_tool_grep_search() { name = "grep_search"; display_name = "Grep search"; uses_cwd = true; permission_write = false; } json get_definition() const override { return { {"type", "function"}, {"function", { {"name", name}, {"description", "Search for a pattern in files under a path. Returns matching lines with file paths " "(and, unless searching a single file, paths relative to the given directory). " "Automatically skips files ignored by .gitignore (when the directory is inside a git repo) " "and common junk directories (.git, node_modules, build, dist, etc.) otherwise. " "include/exclude: a pattern with no '/' matches the basename at any depth; a pattern " "containing '/' matches the full relative path (auto-anchored with \"**/\" unless already anchored)."}, {"parameters", { {"type", "object"}, {"properties", { {"path", {{"type", "string"}, {"description", "File or directory to search in"}}}, {"pattern", {{"type", "string"}, {"description", "Pattern to search for (regular expression unless literal is true)"}}}, {"include", {{"type", "string"}, {"description", "Glob pattern to filter files (default: **)"}}}, {"exclude", {{"type", "string"}, {"description", "Glob pattern to exclude files"}}}, {"return_line_numbers", {{"type", "boolean"}, {"description", "If true, include line numbers in results"}}}, {"literal", {{"type", "boolean"}, {"description", "Treat pattern as a literal string instead of a regular expression (default: false)"}}}, {"ignore_case", {{"type", "boolean"}, {"description", "Case-insensitive search (default: false)"}}}, {"context_lines", {{"type", "integer"}, {"description", "Number of lines of context to show before and after each match (default: 0)"}}}, {"offset", {{"type", "integer"}, {"description", "Number of matching lines to skip (default: 0)"}}}, }}, {"required", json::array({"path", "pattern"})}, }}, }}, }; } json invoke(json params, server_tool::stream *, const std::function &) const override { std::string path = params.at("path").get(); std::string pat_str = params.at("pattern").get(); std::string include = json_value(params, "include", std::string("**")); std::string exclude = json_value(params, "exclude", std::string("")); bool show_lineno = json_value(params, "return_line_numbers", false); bool literal = json_value(params, "literal", false); bool ignore_case = json_value(params, "ignore_case", false); int ctx_lines = std::max(0, json_value(params, "context_lines", 0)); uint64_t offset = std::max(0, json_value(params, "offset", int64_t{0})); std::string pattern_src = pat_str; if (literal) { static const std::string specials = "\\^$.|?*+()[]{}"; std::string escaped; escaped.reserve(pat_str.size() * 2); for (char c : pat_str) { if (specials.find(c) != std::string::npos) escaped += '\\'; escaped += c; } pattern_src = escaped; } std::regex pattern; try { auto flags = std::regex::ECMAScript; if (ignore_case) flags |= std::regex::icase; pattern = std::regex(pattern_src, flags); } catch (const std::regex_error & e) { return {{"error", std::string("invalid regex: ") + e.what()}}; } auto io = make_tools_io(params); // collect (absolute_path, display_path) pairs to search std::vector> files; bool listing_truncated = false; const std::string abs_path = io->resolve(path); if (io->is_regular_file(abs_path)) { files.emplace_back(abs_path, path); } else if (io->is_directory(abs_path)) { const auto listing = io->list_entries(abs_path, 0, list_kind::files); if (!listing.err.empty()) { return {{"error", listing.err + ": " + path}}; } listing_truncated = listing.truncated; for (const auto & entry : listing.entries) { if (!path_glob_match(include, entry.rel)) continue; if (!exclude.empty() && path_glob_match(exclude, entry.rel)) continue; files.emplace_back((fs::path(abs_path) / entry.rel).generic_string(), entry.rel); } } else { return {{"error", "path does not exist: " + path}}; } std::sort(files.begin(), files.end(), [](const auto & a, const auto & b) { return a.second < b.second; }); std::ostringstream output_text; uint64_t skipped = 0; size_t total = 0; bool has_more = false; bool show_num = show_lineno || ctx_lines > 0; for (const auto & file_entry : files) { if (has_more) break; const std::string & fpath = file_entry.first; const std::string & display_path = file_entry.second; std::string content; if (!io->read_file(fpath, content)) continue; std::vector lines; { std::istringstream f(content); std::string line; while (std::getline(f, line)) lines.push_back(line); } for (size_t i = 0; i < lines.size(); i++) { if (!std::regex_search(lines[i], pattern)) continue; if (skipped < offset) { skipped++; continue; } if (total >= SERVER_TOOL_GREP_SEARCH_MAX_RESULTS) { has_more = true; break; } long ctx_start = ctx_lines > 0 ? std::max(0, (long) i - ctx_lines) : (long) i; long ctx_end = ctx_lines > 0 ? std::min((long) lines.size() - 1, (long) i + ctx_lines) : (long) i; for (long j = ctx_start; j <= ctx_end; j++) { bool is_match = (j == (long) i); output_text << display_path << (is_match ? ':' : '-'); if (show_num) { output_text << (j + 1) << (is_match ? ':' : '-'); } output_text << lines[j] << "\n"; } if (ctx_lines > 0) { output_text << "--\n"; } total++; } } output_text << "\n---\nTotal matches: " << total << "\n"; if (has_more) { output_text << "Continue with offset=" << offset + total << " and the same search arguments.\n"; } if (listing_truncated) { output_text << "[results truncated: time budget or unreadable directory]\n"; } return {{"plain_text_response", output_text.str()}}; } }; // // 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::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 stop{false}; std::atomic deadline_ms{0}; // steady clock, 0 for none std::atomic 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; // 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 all; { std::lock_guard 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 & args, const std::string & conv_id, const json & params, bool background, int deadline_secs) { auto task = std::make_shared(); 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::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 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 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 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 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 & conv_ids) { std::lock_guard 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 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 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 lock(mutex); task.model_offset = r.next; return r; } void mark_read(tools_task & task, size_t offset) { std::lock_guard 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 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 next_client_id{0}; private: std::mutex mutex; std::vector 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 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 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(); 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 & 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 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 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: "::" is keyed on 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(); const std::string status = task.at("status").get(); 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()); } return text; } // // exec_shell_command: run an arbitrary shell command // static constexpr size_t SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE = 16 * 1024; // 16 KB static constexpr int SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT = 60; // seconds struct server_tool_exec_shell_command : server_tool { 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; permission_write = true; support_stream = true; } json get_definition() const override { return { {"type", "function"}, {"function", { {"name", name}, {"description", "Execute a shell command and return its output (stdout and stderr combined)."}, {"parameters", { {"type", "object"}, {"properties", { // 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), 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"})}, }}, }}, }; } json invoke(json params, server_tool::stream * st, const std::function & should_stop) const override { std::string command = params.at("command").get(); 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); timeout = std::min(timeout, SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT); 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 args = !json_value(params, "runtime", std::string()).empty() ? std::vector{"sh", "-c", command} : std::vector{"cmd", "/d", "/s", "/c", "\"" + command + "\""}; #else std::vector 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 & args, const json & params, size_t max_output, int timeout, server_tool::stream * st, const std::function & should_stop) const { auto io = make_tools_io(params); if (st) { 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(); } std::string tail = string_format("\n[exit code: %d]", res.exit_code); if (res.timed_out) { tail += " [exit due to timed out]"; } st->push(tail); return json(); } 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); if (res.timed_out) { text_output += " [exit due to timed out]"; } 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 & should_stop) const { auto client_gone = [&]() { return st ? (st->alive && !st->alive()) : (should_stop && should_stop()); }; std::function 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()); 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 &) 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(); if (action == "list") { std::string text; for (const auto & t : tasks->list({conv_id})) { text += string_format("%d: %s", t.at("id").get(), t.at("status").get().c_str()); if (t.contains("exit_code")) { text += string_format(" (exit code: %d)", t.at("exit_code").get()); } text += ", " + t.at("command").get() + "\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))}}; } }; // // write_file: create or overwrite a file // struct server_tool_write_file : server_tool { server_tool_write_file() { name = "write_file"; display_name = "Write file"; uses_cwd = true; permission_write = true; } json get_definition() const override { return { {"type", "function"}, {"function", { {"name", name}, {"description", "Write content to a file, creating it (including parent directories) if it does not exist. May use with edit_file for more complex edits."}, {"parameters", { {"type", "object"}, {"properties", { {"path", {{"type", "string"}, {"description", "Path of the file to write"}}}, {"content", {{"type", "string"}, {"description", "Content to write"}}}, }}, {"required", json::array({"path", "content"})}, }}, }}, }; } json invoke(json params, server_tool::stream *, const std::function &) const override { std::string path = params.at("path").get(); std::string content = params.at("content").get(); auto io = make_tools_io(params); if (!io->write_file(path, content)) { return {{"error", "failed to write file: " + path}}; } return {{"result", "file written successfully"}, {"path", path}, {"bytes", content.size()}}; } }; // // edit_file: exact text replacement, one or more edits per call // struct server_tool_edit_file : server_tool { server_tool_edit_file() { name = "edit_file"; display_name = "Edit file"; uses_cwd = true; permission_write = true; } json get_definition() const override { return { {"type", "function"}, {"function", { {"name", name}, {"description", "Edit a file using exact text replacement. Each edits[].old_text must be unique in the file " "and is matched against the original content, not incrementally. Merge nearby changes into " "one edit instead of overlapping edits. Use write_file to replace the whole file."}, {"parameters", { {"type", "object"}, {"properties", { {"path", {{"type", "string"}, {"description", "Path to the file to edit"}}}, {"edits", { {"type", "array"}, {"description", "One or more exact text replacements to apply"}, {"items", { {"type", "object"}, {"properties", { {"old_text", {{"type", "string"}, {"description", "Exact text to find; must be unique in the file and must not overlap with other edits"}}}, {"new_text", {{"type", "string"}, {"description", "Text to replace old_text with"}}}, }}, {"required", json::array({"old_text", "new_text"})}, }}, }}, }}, {"required", json::array({"path", "edits"})}, }}, }}, }; } json invoke(json params, server_tool::stream *, const std::function &) const override { std::string path = params.at("path").get(); const json & edits_json = params.at("edits"); if (!edits_json.is_array() || edits_json.empty()) { return {{"error", "\"edits\" must be a non-empty array"}}; } struct edit_req { std::string old_text; std::string new_text; }; std::vector edits; edits.reserve(edits_json.size()); for (const auto & e : edits_json) { edit_req er; er.old_text = e.at("old_text").get(); er.new_text = e.at("new_text").get(); if (er.old_text.empty()) { return {{"error", string_format("edits[%zu].old_text must not be empty", edits.size())}}; } edits.push_back(std::move(er)); } auto io = make_tools_io(params); std::string original_content; if (!io->read_file(path, original_content)) { return {{"error", "failed to open file: " + path}}; } // does any old_text need fuzzy matching (no exact match found)? bool any_fuzzy = false; for (size_t i = 0; i < edits.size(); i++) { if (original_content.find(edits[i].old_text) != std::string::npos) continue; std::string fuzzy_content = normalize_for_fuzzy_match(original_content); std::string fuzzy_old = normalize_for_fuzzy_match(edits[i].old_text); if (fuzzy_content.find(fuzzy_old) == std::string::npos) { return {{"error", string_format( "could not find edits[%zu].old_text in %s, it must match the file's current content exactly", i, path.c_str())}}; } any_fuzzy = true; } std::string base_content = any_fuzzy ? normalize_for_fuzzy_match(original_content) : original_content; // uniqueness check always uses fuzzy-normalized text, so a whitespace-only duplicate still counts std::vector matched; matched.reserve(edits.size()); for (size_t i = 0; i < edits.size(); i++) { std::string needle = any_fuzzy ? normalize_for_fuzzy_match(edits[i].old_text) : edits[i].old_text; size_t occurrences = count_occurrences( normalize_for_fuzzy_match(original_content), normalize_for_fuzzy_match(edits[i].old_text)); if (occurrences > 1) { return {{"error", string_format( "found %zu occurrences of edits[%zu].old_text in %s, it must be unique", occurrences, i, path.c_str())}}; } size_t idx = base_content.find(needle); matched.push_back({i, idx, needle.size(), edits[i].new_text}); } std::sort(matched.begin(), matched.end(), [](const matched_edit & a, const matched_edit & b) { return a.match_index < b.match_index; }); for (size_t i = 1; i < matched.size(); i++) { if (matched[i - 1].match_index + matched[i - 1].match_length > matched[i].match_index) { return {{"error", string_format( "edits[%zu] and edits[%zu] overlap in %s; merge them into one edit or target disjoint regions", matched[i - 1].edit_index, matched[i].edit_index, path.c_str())}}; } } std::string new_content = any_fuzzy ? apply_replacements_preserving_unchanged_lines(original_content, base_content, matched) : apply_replacements(base_content, matched, 0); if (new_content == original_content) { return {{"error", "no changes made: the replacement(s) produced identical content"}}; } if (!io->write_file(path, new_content)) { return {{"error", "failed to write file: " + path}}; } return {{"result", "file edited successfully"}, {"path", path}, {"edits_applied", (int) matched.size()}}; } private: // strip trailing whitespace, normalize smart quotes/dashes/spaces to ASCII static std::string normalize_line_for_fuzzy_match(const std::string & line) { size_t end = line.size(); while (end > 0 && (line[end - 1] == ' ' || line[end - 1] == '\t' || line[end - 1] == '\r')) { end--; } std::string s = line.substr(0, end); auto replace_all = [](std::string & str, const std::string & from, const std::string & to) { if (from.empty()) return; size_t pos = 0; while ((pos = str.find(from, pos)) != std::string::npos) { str.replace(pos, from.size(), to); pos += to.size(); } }; // smart single quotes -> ' for (unsigned char b : {0x98, 0x99, 0x9A, 0x9B}) { replace_all(s, std::string("\xE2\x80") + (char) b, "'"); } // smart double quotes -> " for (unsigned char b : {0x9C, 0x9D, 0x9E, 0x9F}) { replace_all(s, std::string("\xE2\x80") + (char) b, "\""); } // various dashes -> - for (unsigned char b = 0x90; b <= 0x95; b++) { replace_all(s, std::string("\xE2\x80") + (char) b, "-"); } replace_all(s, "\xE2\x88\x92", "-"); // minus sign // special spaces -> ' ' replace_all(s, "\xC2\xA0", " "); // no-break space for (unsigned char b = 0x82; b <= 0x8A; b++) { replace_all(s, std::string("\xE2\x80") + (char) b, " "); } replace_all(s, "\xE2\x80\xAF", " "); // narrow no-break space replace_all(s, "\xE2\x81\x9F", " "); // medium mathematical space replace_all(s, "\xE3\x80\x80", " "); // ideographic space return s; } // applies the per-line transform above to every line; preserves line count/positions static std::string normalize_for_fuzzy_match(const std::string & content) { std::string result; result.reserve(content.size()); size_t start = 0; while (true) { size_t nl = content.find('\n', start); bool is_last = nl == std::string::npos; std::string line = is_last ? content.substr(start) : content.substr(start, nl - start); result += normalize_line_for_fuzzy_match(line); if (is_last) break; result += '\n'; start = nl + 1; } return result; } // lines with trailing '\n' kept, so untouched ones can be reconstructed verbatim static std::vector split_lines_with_endings(const std::string & content) { std::vector lines; size_t start = 0; while (start < content.size()) { size_t nl = content.find('\n', start); if (nl == std::string::npos) { lines.push_back(content.substr(start)); break; } lines.push_back(content.substr(start, nl - start + 1)); start = nl + 1; } return lines; } struct line_span { size_t start; size_t end; }; static std::vector get_line_spans(const std::string & content) { std::vector spans; size_t offset = 0; for (const auto & line : split_lines_with_endings(content)) { spans.push_back({offset, offset + line.size()}); offset += line.size(); } return spans; } // count non-overlapping occurrences of `needle` in `content` static size_t count_occurrences(const std::string & content, const std::string & needle) { if (needle.empty()) return 0; size_t count = 0, pos = 0; while ((pos = content.find(needle, pos)) != std::string::npos) { count++; pos += needle.size(); } return count; } struct matched_edit { size_t edit_index; size_t match_index; // offset into the "base content" (see below) size_t match_length; std::string new_text; }; // replacements must be sorted ascending by match_index and non-overlapping static std::string apply_replacements( const std::string & content, const std::vector & replacements, size_t offset) { std::string result = content; for (auto it = replacements.rbegin(); it != replacements.rend(); ++it) { size_t local_index = it->match_index - offset; result = result.substr(0, local_index) + it->new_text + result.substr(local_index + it->match_length); } return result; } // widen a replacement's byte range to the line(s) of `lines` it touches static bool get_replacement_line_range( const std::vector & lines, size_t match_index, size_t match_length, size_t & out_start_line, size_t & out_end_line /* exclusive */) { size_t replacement_start = match_index; size_t replacement_end = match_index + match_length; size_t start_line = (size_t) -1; for (size_t i = 0; i < lines.size(); i++) { if (replacement_start >= lines[i].start && replacement_start < lines[i].end) { start_line = i; break; } } if (start_line == (size_t) -1) return false; size_t end_line = start_line; while (end_line < lines.size() && lines[end_line].end < replacement_end) { end_line++; } if (end_line >= lines.size()) return false; out_start_line = start_line; out_end_line = end_line + 1; return true; } // like apply_replacements, but untouched lines come from `original_content` static std::string apply_replacements_preserving_unchanged_lines( const std::string & original_content, const std::string & base_content, const std::vector & replacements /* ascending, non-overlapping */) { auto original_lines = split_lines_with_endings(original_content); auto base_lines = get_line_spans(base_content); struct group { size_t start_line; size_t end_line; // exclusive std::vector reps; }; std::vector groups; for (const auto & rep : replacements) { size_t start_line = 0, end_line = 0; get_replacement_line_range(base_lines, rep.match_index, rep.match_length, start_line, end_line); if (!groups.empty() && start_line < groups.back().end_line) { groups.back().end_line = std::max(groups.back().end_line, end_line); groups.back().reps.push_back(rep); } else { groups.push_back({start_line, end_line, {rep}}); } } size_t original_line_index = 0; std::string result; for (auto & g : groups) { for (size_t i = original_line_index; i < g.start_line; i++) { result += original_lines[i]; } size_t group_start_offset = base_lines[g.start_line].start; size_t group_end_offset = base_lines[g.end_line - 1].end; std::string slice = base_content.substr(group_start_offset, group_end_offset - group_start_offset); result += apply_replacements(slice, g.reps, group_start_offset); original_line_index = g.end_line; } for (size_t i = original_line_index; i < original_lines.size(); i++) { result += original_lines[i]; } return result; } }; // // get_info: returns runtime info (OS name/version and cwd) // static constexpr size_t SERVER_TOOL_GET_INFO_MAX_OUTPUT = 4096; static constexpr int SERVER_TOOL_GET_INFO_TIMEOUT = 5; // seconds struct server_tool_get_info : server_tool { server_tool_get_info() { name = "get_info"; display_name = "Get Runtime Info"; uses_cwd = true; permission_write = false; } json get_definition() const override { return { {"type", "function"}, {"function", { {"name", name}, {"description", "Returns runtime info: the OS name/version and the current working directory"}, {"parameters", { {"type", "object"}, {"properties", json::object()}, }}, }}, }; } json invoke(json params, server_tool::stream *, const std::function &) const override { auto io = make_tools_io(params); // inside an isolate, we always use the linux command #ifdef _WIN32 std::vector args = !json_value(params, "runtime", std::string()).empty() ? std::vector{"uname", "-a"} : std::vector{"cmd", "/c", "ver"}; #else std::vector args = {"uname", "-a"}; #endif auto res = io->run(args, SERVER_TOOL_GET_INFO_MAX_OUTPUT, SERVER_TOOL_GET_INFO_TIMEOUT); // "ver" prints a blank line before the version, so the output is stripped on both ends; // a failed spawn or a timeout leaves a diagnostic in res.output, which is not an OS name std::string os_info = res.exit_code == 0 && !res.timed_out ? string_strip(res.output) : "unknown"; std::string cwd = json_value(params, "cwd", std::string()); if (cwd.empty()) { if (json_value(params, "runtime", std::string()).empty()) { std::error_code ec; cwd = fs::current_path(ec).generic_string(); } else { auto pwd = io->run({"pwd"}, SERVER_TOOL_GET_INFO_MAX_OUTPUT, SERVER_TOOL_GET_INFO_TIMEOUT); cwd = pwd.exit_code == 0 && !pwd.timed_out ? string_strip(pwd.output) : "unknown"; } } return { {"os", os_info}, {"cwd", cwd}, }; } }; 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) { 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()) { result["error"] = error_msg; } return result; } } }; void server_tool::stream::push(const std::string & chunk) { if (chunk.empty()) return; auto r = std::make_unique(); r->id = id; r->chunk = chunk; qr.send(std::move(r)); } void server_tool::stream::push_data(const json & data) { auto r = std::make_unique(); 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 int id = -1; ~server_tools_res() override { if (worker.joinable()) { worker.join(); } if (qr) { qr->remove_waiting_task_id(id); } } }; // // server_mcp_tool: exposes one tool from a running MCP server as a server_tool. // struct server_mcp_tool : server_tool { std::string server_name; std::string tool_name; server_mcp_tool_def def; server_mcp & mcp_mgr; server_mcp_tool(server_mcp_tool_def d, server_mcp & mgr) : server_name(d.server_name) , tool_name(d.name) , def(std::move(d)) , mcp_mgr(mgr) { name = server_name + "_" + tool_name; display_name = name; permission_write = false; support_stream = false; } std::string type() const override { return "mcp"; } json get_definition() const override { json schema = def.input_schema; if (schema.is_null() || !schema.is_object()) { schema = json::object(); } return { {"type", "function"}, {"function", { {"name", name}, {"description", def.description}, {"parameters", schema}, }}, }; } json invoke(json params, server_tool::stream *, const std::function & should_stop) const override { return mcp_mgr.call_tool(server_name, tool_name, params, should_stop); } }; // resolves --tools-runtime into the isolate that every tool call runs through // spec() returns the runtime string make_tools_io() takes, and runs once per tool call struct server_tools_runtime { virtual ~server_tools_runtime() = default; virtual std::string spec() = 0; }; // a target that already exists and needs no lifecycle // the spec is validated once at startup, then passed straight through struct server_tools_static_runtime : server_tools_runtime { explicit server_tools_static_runtime(std::string spec) : runtime_spec(std::move(spec)) {} std::string spec() override { return runtime_spec; } private: std::string runtime_spec; }; // owns the container the tools run in, as set by --tools-runtime ":" // it is spawned here and stopped when the server exits struct server_tools_container_runtime : server_tools_runtime { server_tools_container_runtime(const server_tools_container_runtime &) = delete; explicit server_tools_container_runtime(const std::string & spec) { container_runtime_spec parsed; if (!container_runtime_spec::parse(spec, parsed)) { throw std::runtime_error("unknown --tools-runtime option: " + spec); } bin = parsed.bin; image = parsed.arg; if (image.empty()) { throw std::runtime_error("--tools-runtime " + bin + ": requires an image name"); } spawn(); } ~server_tools_container_runtime() override { // closing stdin signals the container's shell (its pid 1) to exit; --rm then removes it proc.close_stdin(); proc.join(); } // respawns a container that died on its own, so the returned spec always names a running one std::string spec() override { std::lock_guard lock(mutex); if (!proc.alive()) { SRV_WRN("%s tools runtime container \"%s\" died, respawning\n", bin.c_str(), container_id.c_str()); spawn(); } return bin + "-container:" + container_id; } private: std::string bin; std::string image; std::string container_id; common_subproc proc; // ` run` client that keeps the container alive std::mutex mutex; // spawns " run --rm -i sh" and keeps its stdin open; the shell blocks reading stdin, // so the container stays alive until we close it (see destructor) or it is killed from the outside void spawn() { // create() writes over the handle it is given, so the previous one is released first proc.join(); std::error_code ec; fs::path cidfile = fs::temp_directory_path(ec) / string_format( "llama-tools-runtime-cid-%zu.tmp", std::hash{}(std::this_thread::get_id())); fs::remove(cidfile, ec); std::vector args = {bin, "run", "--rm", "-i", "--cidfile", cidfile.generic_string(), image, "sh"}; int options = subprocess_option_no_window | subprocess_option_inherit_environment | subprocess_option_search_user_path; if (!proc.create(args, options)) { throw std::runtime_error("failed to spawn " + bin + " container for tools runtime (image: " + image + ")"); } std::string cid; for (int i = 0; i < 100 && cid.empty(); i++) { std::ifstream f(cidfile); if (f) std::getline(f, cid); if (cid.empty()) std::this_thread::sleep_for(std::chrono::milliseconds(100)); } fs::remove(cidfile, ec); if (cid.empty()) { proc.terminate(); throw std::runtime_error("timed out waiting for " + bin + " container to start (image: " + image + ")"); } container_id = cid; } }; static server_tool & find_tool(std::vector> & tools, const std::string & name, bool require_stream) { for (auto & t : tools) { if (t->name == name) { if (require_stream && !t->support_stream) { throw std::invalid_argument(string_format("tool \"%s\" does not support stream = true", name.c_str())); } return *t; } } throw std::invalid_argument(string_format("unknown tool \"%s\"", name.c_str())); } // // public API // static std::vector> 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. // high-level functionality should be added either via MCP or Llama Chat std::vector> tools; tools.push_back(std::make_unique()); tools.push_back(std::make_unique()); tools.push_back(std::make_unique()); tools.push_back(std::make_unique(tasks)); tools.push_back(std::make_unique(tasks)); tools.push_back(std::make_unique()); tools.push_back(std::make_unique()); tools.push_back(std::make_unique()); return tools; } static std::string str_to_lower(const std::string & value) { std::string lowered(value.size(), '\0'); std::transform(value.begin(), value.end(), lowered.begin(), [](unsigned char c) { return std::tolower(c); }); return lowered; } static std::string get_header(const std::map & headers, const std::string & key, std::string default_value = "") { const auto lowered_key = str_to_lower(key); for (const auto & h : headers) { if (str_to_lower(h.first) == lowered_key) { return h.second; } } return default_value; } server_tools::server_tools() = default; server_tools::~server_tools() = default; // the ":" form owns a container lifecycle // anything else names an existing target, so only its spec is validated here at startup static std::unique_ptr make_tools_runtime(const std::string & spec) { container_runtime_spec parsed; if (container_runtime_spec::parse(spec, parsed) && !parsed.attach) { return std::make_unique(spec); } make_tools_io({{"runtime", spec}}); // nothing to own, just reject a bad spec now return std::make_unique(spec); } void server_tools::setup(const std::vector & enabled_tools, server_mcp & mcp_mgr, const std::string & tools_runtime) { if (!tools_runtime.empty()) { runtime = make_tools_runtime(tools_runtime); } if (!enabled_tools.empty()) { if (!common_subproc::is_supported()) { throw std::runtime_error("subprocess is not enabled on this build"); } std::unordered_set enabled_set(enabled_tools.begin(), enabled_tools.end()); tasks = std::make_unique(); auto all_tools = build_tools(tasks.get()); // collect all known tool names for validation std::vector known_names; known_names.reserve(all_tools.size()); for (const auto & t : all_tools) { known_names.push_back(t->name); } // validate that every requested tool is known for (const auto & name : enabled_tools) { if (name == "all") continue; if (std::find(known_names.begin(), known_names.end(), name) == known_names.end()) { throw std::runtime_error(string_format( "unknown tool \"%s\". available tools: %s", name.c_str(), string_join(known_names, ", ").c_str())); } } tools.clear(); for (auto & t : all_tools) { if (enabled_set.count(t->name) > 0 || enabled_set.count("all") > 0) { tools.push_back(std::move(t)); } } } // append MCP tools, skipping any that collide with a server tool or another MCP tool of the same "_" name if (!mcp_mgr.empty()) { std::unordered_set seen_names; for (auto & t : tools) { seen_names.insert(t->name); } size_t n_added = 0; for (const auto & def : mcp_mgr.list_tools()) { std::string mcp_name = def.server_name + "_" + def.name; if (seen_names.count(mcp_name)) { SRV_WRN("MCP tool \"%s\" from server \"%s\" collides with an existing tool, skipping\n", mcp_name.c_str(), def.server_name.c_str()); continue; } seen_names.insert(mcp_name); tools.push_back(std::make_unique(def, mcp_mgr)); n_added++; } if (n_added > 0) { SRV_INF("Added %zu MCP tools\n", n_added); } } handle_get = [this](const server_http_req &) -> server_http_res_ptr { auto res = std::make_unique(); try { json result = json::array(); for (const auto & t : tools) { result.push_back(t->to_json()); } res->data = safe_json_to_str(result); } catch (const std::exception & e) { SRV_ERR("got exception: %s\n", e.what()); res->status = 500; res->data = safe_json_to_str(format_error_response(e.what(), ERROR_TYPE_SERVER)); } return res; }; handle_post = [this](const server_http_req & req) -> server_http_res_ptr { auto res = std::make_unique(); try { json body = json::parse(req.body); std::string tool_name = body.at("tool").get(); json params = body.value("params", json::object()); bool stream = body.value("stream", false); // accept x-tool-cwd header to override of the process if (params.contains("cwd")) { params.erase("cwd"); } auto cwd = get_header(req.headers, "x-tool-cwd"); if (!cwd.empty()) { params["cwd"] = cwd; } // accept x-tool-runtime header to route tool I/O through an isolate, e.g. "docker-container:"; // --tools-runtime wins: it is the sandbox, the client must not move tools out of it if (params.contains("runtime")) { params.erase("runtime"); } auto runtime_header = get_header(req.headers, "x-tool-runtime"); if (runtime) { if (!runtime_header.empty()) { res->status = 403; res->data = safe_json_to_str(format_error_response("x-tool-runtime is not allowed when --tools-runtime is set", ERROR_TYPE_PERMISSION)); return res; } params["runtime"] = runtime->spec(); } else if (!runtime_header.empty()) { 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"); } auto resp_type = get_header(req.headers, "x-resp-type"); if (!resp_type.empty()) { params["resp_type"] = resp_type; } server_tool & tool = find_tool(tools, tool_name, stream); if (stream) { int id = res_id.fetch_add(1); queue_res.add_waiting_task_id(id); res->qr = &queue_res; res->id = id; res->worker = std::thread([this, id, &req, &tool, params]() mutable { server_tool::stream st{queue_res, id, [&req]() { return !req.should_stop(); }}; auto done = std::make_unique(); try { tool.invoke(params, &st, req.should_stop); } catch (const std::exception & e) { done->error_msg = e.what(); } catch (...) { done->error_msg = "An unknown error occurred"; } done->id = st.id; done->done = true; st.qr.send(std::move(done)); }); res->content_type = "text/event-stream"; res->status = 200; res->next = [this, id](std::string & output) -> bool { auto result = queue_res.recv(id); auto * r = dynamic_cast(result.get()); GGML_ASSERT(r != nullptr); output = "data: " + safe_json_to_str(r->to_json()) + "\n\n"; if (r->done) { queue_res.remove_waiting_task_id(id); return false; } return true; }; } else { json result = tool.invoke(params, nullptr, req.should_stop); res->status = 200; res->data = safe_json_to_str(result); } } catch (const common_json_error & e) { res->status = 400; res->data = safe_json_to_str(format_error_response(e.what(), ERROR_TYPE_INVALID_REQUEST)); } catch (const std::invalid_argument & e) { res->status = 404; res->data = safe_json_to_str(format_error_response(e.what(), ERROR_TYPE_INVALID_REQUEST)); } catch (const std::exception & e) { SRV_ERR("got exception: %s\n", e.what()); res->status = 500; res->data = safe_json_to_str(format_error_response(e.what(), ERROR_TYPE_SERVER)); } 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(); 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 conv_ids; for (const auto & id : string_split(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(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(); 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(); 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()); exec_id = body.at("from_exec_id").get(); } 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(); 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(); res->data = safe_json_to_str(tasks->to_json(*task)); return res; }; }