#ifndef _DEFAULT_SOURCE #define _DEFAULT_SOURCE #endif #include #include #include #include #include #include "cJSON.h" #include "cst_clipboard.h" #include "cst_parliament.h" #include "cst_runtime.h" #include "cst_tools.h" #include "cst_util.h" #include "tools_internal.h" static int run_read_file(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c, cst_tool_result_t *r) { return cst_tool_read_file2(ctx, c, r); } static int run_write_file(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c, cst_tool_result_t *r) { return cst_tool_write_file(ctx->workspace_root, c, r); } static int run_apply_patch(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c, cst_tool_result_t *r) { return cst_tool_apply_patch(ctx->workspace_root, c, r); } static int run_shell(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *c, cst_tool_result_t *r) { if (ctx->agent && ctx->compact) { const cst_agent_config_t *cfg = cst_agent_config(ctx->agent); if (cfg->runtime && !cfg->depth) return cst_runtime_shell(ctx, c, r); } int rc = cst_tool_run_shell_ex(ctx->workspace_root, c, r, ctx->sandbox); if (rc == 0 && ctx->compact && r->out) { size_t n = 0; char *s = cst_shell_compact(r->out, r->out_len, &n); if (s) { free(r->out); r->out = s; r->out_len = n; } } return rc; } #define S "string" #define I "integer" #define B "boolean" #define NO_DYN NULL, NULL, NULL, NULL, NULL #define NO_META NULL, NULL, NULL static const cst_tool_def_t TOOLS[] = { {"read_file", "Read a text file. Output starts with `path · lines a-b of N` and " "prefixes lines with `N|` (not part of the file — never copy it into " "edits). Returns up to 2000 lines; continue with the offset it prints.", "Read a UTF-8 text file under the workspace.", {{"path", S, 1, "file path relative to the workspace"}, {"offset", I, 0, "first line to return (1-based)"}, {"limit", I, 0, "maximum number of lines"}, {"line_numbers", B, 0, "`N|` line prefixes (default true)"}}, CST_TP_READ, 1, run_read_file, NULL, NO_DYN, NO_META}, {"view_image", "Show a local image to yourself: PNG, JPEG, GIF, WebP or BMP, checked by " "content. The file is copied into the session store and comes back as an " "image you can actually see (not as text). Use it for screenshots, " "diagrams and UI checks; path resolves like read_file's.", NULL, {{"path", S, 1, "image file path relative to the workspace"}, {"detail", S, 0, "low or high (provider hint; default auto)"}}, CST_TP_READ, 0, cst_tool_view_image, NULL, NO_DYN, NO_META}, {"deliver_file", "Hand a finished file to the person: it is copied into the session store " "and shown in the transcript as a card they can open or share. Use it " "whenever the answer is a file -- a report, an export, a patch, a " "picture, a build. You are not shown the copy again, so say what it " "contains in your answer.", "Deliver a workspace file to the user (a file card in the transcript, " "openable and shareable from there).", {{"path", S, 1, "file path relative to the workspace"}, {"title", S, 0, "display name (default: the file name)"}}, CST_TP_READ, 0, cst_tool_deliver_file, NULL, NO_DYN, NO_META}, {"run_shell", "Run a non-interactive shell command in the workspace root: builds, " "tests, git, scripts, computations, data processing, other CLIs " "(stdin is empty; long runs are killed). " "Returns stdout+stderr with colors stripped and long output cut to head " "+ tail. Prefer read_file/grep/glob/list_dir over cat/grep/find.", "Run a shell command in the workspace root (non-interactive, stdin is " "empty, killed after a timeout). Returns combined stdout+stderr.", {{"cmd", S, 1, "shell command"}, {"effect", S, 0, "workspace (interruptible) or external (protected; default)"}, {"resource", S, 0, "resource lock such as a device identifier"}}, CST_TP_SHELL, 1, run_shell, NULL, NO_DYN, NO_META}, {"write_file", "Create a file or replace a whole file (parent directories are " "created). For changes to existing files prefer edit_file.", "Create or overwrite a whole file under the workspace (parent " "directories are created).", {{"path", S, 1, "file path"}, {"content", S, 1, "complete new content"}}, CST_TP_WRITE, 1, run_write_file, cst_preview_write_file, NO_DYN, NO_META}, {"apply_patch", "Apply a unified diff (---/+++ headers, @@ -a,b +c,d @@ hunks, 3 " "context lines) across one or more files; all hunks apply or nothing " "changes. Use for multi-hunk or multi-file edits.", "Apply a unified diff (---/+++ headers, @@ -a,b +c,d @@ hunks with " "context lines) to one or more files. All hunks must apply or nothing " "changes.", {{"patch", S, 1, "unified diff text"}}, CST_TP_WRITE, 1, run_apply_patch, cst_preview_apply_patch, NO_DYN, NO_META}, {"edit_file", "Replace an exact snippet in a file — the default for small edits. " "old_string must match byte-for-byte (indentation included, without " "read_file's `N|` prefixes) and be unique unless replace_all=true.", NULL, {{"path", S, 1, "file path"}, {"old_string", S, 1, "exact text to replace"}, {"new_string", S, 1, "replacement text"}, {"replace_all", B, 0, "replace every occurrence"}}, CST_TP_WRITE, 0, cst_tool_edit_file, cst_preview_edit_file, NO_DYN, NO_META}, {"list_dir", "Show a directory tree (dirs end with /, files show sizes, dirs at the " "depth limit show entry counts). Skips .git, node_modules and " ".gitignore'd paths.", NULL, {{"path", S, 0, "directory (default: workspace root)"}, {"depth", I, 0, "levels to descend (default 2, max 6)"}}, CST_TP_READ, 0, cst_tool_list_dir, NULL, NO_DYN, NO_META}, {"glob", "Find files by name, newest first (max 200). `*`/`?` stay within one " "path segment, `**` spans directories (`src/**/*.c`); a pattern without " "/ matches file names at any depth.", NULL, {{"pattern", S, 1, "glob relative to path"}, {"path", S, 0, "directory to search (default: workspace root)"}}, CST_TP_READ, 0, cst_tool_glob, NULL, NO_DYN, NO_META}, {"grep", "Search file contents with an extended regex (\\d \\w \\s work). " "Results are grouped by file as `line:text` under each path, with a " "total count first; narrow with path/glob when it is cut.", NULL, {{"pattern", S, 1, "extended regular expression"}, {"path", S, 0, "file or directory (default: workspace root)"}, {"glob", S, 0, "only files whose name matches, e.g. *.c"}, {"ignore_case", B, 0, "case-insensitive"}, {"context", I, 0, "lines of context around each match (max 5)"}}, CST_TP_READ, 0, cst_tool_grep, NULL, NO_DYN, NO_META}, {"delete_file", "Delete one file (not directories). Undoable with /undo.", NULL, {{"path", S, 1, "file path"}}, CST_TP_WRITE, 0, cst_tool_delete_file, cst_preview_delete_file, NO_DYN, "delete", NULL, NULL}, {"move_file", "Move or rename a file; fails if the destination exists.", NULL, {{"from", S, 1, "existing file"}, {"to", S, 1, "new path"}}, CST_TP_WRITE, 0, cst_tool_move_file, cst_preview_move_file, NO_DYN, NO_META}, {"todo_write", "Replace your task list for work with 3+ steps; keep exactly one item " "in progress. One item per line: `[ ] todo`, `[~] in progress`, `[x] " "done`.", NULL, {{"todos", S, 1, "the whole list, one item per line"}}, CST_TP_META, 0, cst_tool_todo_write, NULL, NO_DYN, NO_META}, {"parliament_note", "Publish a short note into the shared parliament context so other seats " "see progress (synced over the sealed peer channel). Use after finishing " "a block of cross-seat work, when posting agenda, or when handing over. " "kind: status | agenda | result | handover | note.", NULL, {{"note", S, 1, "short note body for other seats"}, {"kind", S, 0, "status|agenda|result|handover|note (default status)"}}, CST_TP_META, 0, cst_tool_parliament_note, NULL, NO_DYN, NO_META}, {"web_search", "Search the live web through the current Kimi or DeepSeek provider and " "return titles, URLs and snippets. Use web_fetch to read a result.", NULL, {{"query", S, 1, "search query"}, {"count", I, 0, "number of results (default 5, max 20)"}, {"include_content", B, 0, "include provider-returned page content"}}, CST_TP_NET, 0, cst_tool_web_search, NULL, NO_DYN, NO_META}, {"web_fetch", "Fetch an http(s) URL (docs, issues, APIs) and return its text; HTML " "is reduced to readable text.", NULL, {{"url", S, 1, "http:// or https:// URL"}, {"max_bytes", I, 0, "maximum bytes to return (default 65536)"}}, CST_TP_NET, 0, cst_tool_web_fetch, NULL, NO_DYN, NO_META}, {"download", "Fetch an http(s) URL into the workspace as a file (up to 128 MB) — a " "release, a dataset, an image, a PDF. The bytes stay on disk: this " "answer only says what was saved. Use web_fetch when you want to read " "the content yourself.", "Download an http(s) URL to a file in the workspace.", {{"url", S, 1, "http:// or https:// URL"}, {"path", S, 0, "file path (default: the URL's own file name)"}, {"max_bytes", I, 0, "give up above this size (default 128 MB)"}}, CST_TP_NET, 0, cst_tool_download, NULL, NO_DYN, NO_META}, {"read_pdf", "Read a PDF's text layer, page count and all — what read_file refuses " "because the bytes are binary. Layout, tables and images are not " "reproduced.", "Read the text of a PDF file in the workspace.", {{"path", S, 1, "PDF file path relative to the workspace"}, {"max_bytes", I, 0, "cap on the returned text (default 256 KiB)"}}, CST_TP_READ, 0, cst_tool_read_pdf, NULL, NO_DYN, NO_META}, {"md_to_html", "Write a document: markdown in, one self-contained HTML file out " "(the engine's own renderer — no script, safe to open anywhere), saved " "in the workspace and handed to the person as a card they can open or " "share. Use it when the answer should be a document to keep.", "Render markdown into a standalone HTML document and hand it over.", {{"markdown", S, 0, "markdown text to render"}, {"file", S, 0, "workspace .md file to render instead"}, {"out", S, 0, "output path (default: the source's name + .html)"}, {"title", S, 0, "document title (default: the file name)"}}, CST_TP_WRITE, 0, cst_tool_md_to_html, cst_preview_md_to_html, NO_DYN, NO_META}, {"session_search", "Search the workspace's stored sessions (this one and every earlier " "conversation) for a substring and get the matching lines with their " "session, message number and context. Answers \"what did we decide " "before\" without a shell.", "Search earlier and current sessions for text.", {{"query", S, 1, "text to look for"}, {"max_matches", I, 0, "stop after this many matches (default 20)"}, {"ignore_case", B, 0, "case-insensitive (default true)"}, {"max_bytes", I, 0, "stop after this many bytes of transcripts (default 32 MB, newest " "sessions first); 0 or unset means the default"}, {"max_seconds", I, 0, "stop after this many seconds of searching (default 5)"}}, CST_TP_READ, 0, cst_tool_session_search, NULL, NO_DYN, NO_META}, {"device_info", "Where this agent is running: system and CPU count, workspace, sandbox, " "model and permissions, config/temp/program directories, pid. Call it " "instead of guessing the environment.", "Report the machine and session the agent runs on.", {{"section", S, 0, "unused; the whole report is always returned"}}, CST_TP_READ, 0, cst_tool_device_info, NULL, NO_DYN, "device", NULL, NULL}, {"ask_user", "Ask the user and wait for the answer. Only for decisions that are " "truly theirs (preferences, credentials, destructive choices).", NULL, {{"question", S, 1, "the question"}, {"options", S, 0, "suggested answers, one per line"}}, CST_TP_ASK, 0, cst_tool_ask_user, NULL, NO_DYN, NO_META}, {"clipboard_read", "Read the text on the system clipboard — what the user copied outside " "the workspace. Returns UTF-8 text.", NULL, {{"max_bytes", I, 0, "cap on the returned text (default 65536)"}}, CST_TP_READ, 0, cst_tool_clipboard_read, NULL, NO_DYN, "read", CST_PLAT_DESKTOP, cst_clipboard_available}, {"clipboard_write", "Replace the system clipboard with text, so the user can paste it into " "another app. Overwrites what they had copied.", NULL, {{"text", S, 1, "text to put on the clipboard"}}, CST_TP_WRITE, 0, cst_tool_clipboard_write, cst_preview_clipboard_write, NO_DYN, "write", CST_PLAT_DESKTOP, cst_clipboard_available}, }; #define NTOOLS ((int)(sizeof(TOOLS) / sizeof(TOOLS[0]))) #undef S #undef I #undef B #undef NO_DYN #undef NO_META int cst_tool_profile_parse(const char *s, int *out) { if (!s || !out) return -1; if (strcmp(s, "default") == 0 || strcmp(s, "full") == 0) { *out = CST_TOOLS_DEFAULT; return 0; } if (strcmp(s, "minimal") == 0) { *out = CST_TOOLS_MINIMAL; return 0; } return -1; } const char *cst_tool_profile_name(int p) { return p == CST_TOOLS_MINIMAL ? "minimal" : "default"; } /* Dynamic tools: published append-only into a fixed table so readers on * other threads never see a half-built entry. */ #define DYN_MAX 256 static cst_tool_def_t *g_dyn[DYN_MAX]; static atomic_int g_ndyn; static pthread_mutex_t g_dyn_mu = PTHREAD_MUTEX_INITIALIZER; #define DYN_LOCK() pthread_mutex_lock(&g_dyn_mu) #define DYN_UNLOCK() pthread_mutex_unlock(&g_dyn_mu) int cst_tool_count(void) { return NTOOLS + atomic_load(&g_ndyn); } const cst_tool_def_t *cst_tool_at(int i) { if (i < 0) return NULL; if (i < NTOOLS) return &TOOLS[i]; i -= NTOOLS; return i < atomic_load(&g_ndyn) ? g_dyn[i] : NULL; } int cst_tool_index(const char *name) { if (!name) return -1; int n = cst_tool_count(); for (int i = 0; i < n; i++) { const cst_tool_def_t *t = cst_tool_at(i); if (t && strcmp(t->name, name) == 0) return i; } return -1; } const cst_tool_def_t *cst_tool_find(const char *name) { if (!name) return NULL; /* An app-provided tool of the same name shadows the built-in: it could * only be registered while that built-in cannot run on this host. */ int n = atomic_load(&g_ndyn); for (int i = 0; i < n; i++) if (g_dyn[i] && strcmp(g_dyn[i]->name, name) == 0) return g_dyn[i]; return cst_tool_at(cst_tool_index(name)); } int cst_tool_known(const char *name) { return cst_tool_find(name) != NULL; } /* --- capability metadata ------------------------------------------------- */ const char *const CST_PLAT_DESKTOP[] = {"desktop", NULL}; const char *cst_platform_name(void) { const char *over = getenv("CST_PLATFORM"); if (over && over[0]) return over; /* tests, cross checks, a launcher that knows better */ #if defined(_WIN32) return "win"; #elif defined(__APPLE__) return "macos"; #elif defined(__ANDROID__) return getenv("TERMUX_VERSION") ? "termux" : "android"; #elif defined(__linux__) return "linux"; #else return "other"; #endif } int cst_tool_platform_ok(const cst_tool_def_t *t) { if (!t || !t->platforms) return 1; const char *cur = cst_platform_name(); for (int i = 0; t->platforms[i]; i++) { const char *p = t->platforms[i]; if (strcmp(p, cur) == 0) return 1; if (strcmp(p, "desktop") == 0 && (strcmp(cur, "linux") == 0 || strcmp(cur, "win") == 0 || strcmp(cur, "macos") == 0)) return 1; /* A Termux host is an Android device, so "android" covers it; the other * way round is not true: Termux helpers are absent in an app sandbox. */ if (strcmp(cur, "termux") == 0 && strcmp(p, "android") == 0) return 1; } return 0; } /* Probes are cached by def pointer: built-ins are static, dynamic entries * keep their address while registered. */ #define META_CACHE_MAX 256 static struct { const cst_tool_def_t *t; int ok; char why[128]; } g_meta[META_CACHE_MAX]; static int g_nmeta; static pthread_mutex_t g_meta_mu = PTHREAD_MUTEX_INITIALIZER; void cst_tool_meta_reload(void) { pthread_mutex_lock(&g_meta_mu); g_nmeta = 0; pthread_mutex_unlock(&g_meta_mu); } int cst_tool_available(const cst_tool_def_t *t, char *why, size_t why_sz) { if (why && why_sz) why[0] = 0; if (!t) return -1; pthread_mutex_lock(&g_meta_mu); for (int i = 0; i < g_nmeta; i++) { if (g_meta[i].t != t) continue; int ok = g_meta[i].ok; if (why && why_sz) snprintf(why, why_sz, "%s", g_meta[i].why); pthread_mutex_unlock(&g_meta_mu); return ok; } pthread_mutex_unlock(&g_meta_mu); char tmp[128] = ""; int ok = 0; if (!cst_tool_platform_ok(t)) { snprintf(tmp, sizeof(tmp), "it exists on %s only and this host is %s", t->platforms && t->platforms[0] ? t->platforms[0] : "another platform", cst_platform_name()); ok = -1; } else if (t->available && t->available(tmp, sizeof(tmp)) != 0) { if (!tmp[0]) snprintf(tmp, sizeof(tmp), "a service it needs is missing here"); ok = -1; } pthread_mutex_lock(&g_meta_mu); if (g_nmeta < META_CACHE_MAX) { g_meta[g_nmeta].t = t; g_meta[g_nmeta].ok = ok; snprintf(g_meta[g_nmeta].why, sizeof(g_meta[g_nmeta].why), "%s", tmp); g_nmeta++; } pthread_mutex_unlock(&g_meta_mu); if (why && why_sz) snprintf(why, why_sz, "%s", tmp); return ok; } const char *cst_tool_perm_name(const cst_tool_def_t *t) { static const char *const class_names[] = {"read", "write", "shell", "net", "ask", "meta"}; if (t && t->perm_name && t->perm_name[0]) return t->perm_name; int p = t ? (int)t->perm : (int)CST_TP_READ; return p >= 0 && p < 6 ? class_names[p] : "?"; } void cst_tool_sanitize_name(const char *in, char *out, size_t out_sz) { size_t o = 0; for (size_t i = 0; in && in[i] && o + 1 < out_sz && o < 63; i++) { char c = in[i]; int ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-'; out[o++] = ok ? c : '_'; } if (out_sz) out[o] = 0; } static char *dup_or_null(const char *s) { return s ? strdup(s) : NULL; } static void dyn_free(cst_tool_def_t *t) { if (!t) return; free((char *)t->name); free((char *)t->desc); free((char *)t->perm_name); free((char *)t->schema_json); free((char *)t->owner); free(t); } int cst_tool_register(const cst_tool_def_t *def) { if (!def || !def->name || !def->name[0] || (!def->run && !def->run_ex)) return -1; DYN_LOCK(); int rc = -1; int n = atomic_load(&g_ndyn); /* The name is free, or held by a tool that cannot run on this host (the * app's Android clipboard taking over the name of the desktop one). */ const cst_tool_def_t *taken = cst_tool_find(def->name); if (n < DYN_MAX && (!taken || cst_tool_available(taken, NULL, 0) != 0)) { cst_tool_def_t *t = calloc(1, sizeof(*t)); if (t) { *t = *def; t->min_desc = NULL; t->minimal = 0; t->name = dup_or_null(def->name); t->desc = dup_or_null(def->desc ? def->desc : ""); t->perm_name = dup_or_null(def->perm_name); t->schema_json = dup_or_null(def->schema_json); t->owner = dup_or_null(def->owner); if (t->name && t->desc) { g_dyn[n] = t; atomic_store(&g_ndyn, n + 1); rc = 0; } else { dyn_free(t); } } } DYN_UNLOCK(); if (rc == 0) cst_tool_meta_reload(); /* a new entry may shadow an old probe */ return rc; } int cst_tool_unregister_owner(const char *owner) { if (!owner) return 0; DYN_LOCK(); int n = atomic_load(&g_ndyn), k = 0, removed = 0; for (int i = 0; i < n; i++) { if (g_dyn[i]->owner && strcmp(g_dyn[i]->owner, owner) == 0) { dyn_free(g_dyn[i]); removed++; } else { g_dyn[k++] = g_dyn[i]; } } for (int i = k; i < n; i++) g_dyn[i] = NULL; atomic_store(&g_ndyn, k); DYN_UNLOCK(); if (removed) cst_tool_meta_reload(); /* drop probes of defs that are now gone */ return removed; } int cst_tool_disabled(const cst_agent_config_t *cfg, const char *name) { if (!cfg || !name || !cfg->tools_off[0]) return 0; char key[CTL_MAX_NAME + 2]; snprintf(key, sizeof(key), ",%s,", name); return strstr(cfg->tools_off, key) != NULL; } void cst_tool_set_disabled(cst_agent_config_t *cfg, const char *name, int off) { if (!cfg || !name || !name[0]) return; char key[CTL_MAX_NAME + 2]; snprintf(key, sizeof(key), ",%s,", name); char *hit = strstr(cfg->tools_off, key); if (off && !hit) { size_t n = strlen(cfg->tools_off); if (n == 0) snprintf(cfg->tools_off, sizeof(cfg->tools_off), "%s", key); else if (n + strlen(key) < sizeof(cfg->tools_off)) snprintf(cfg->tools_off + n, sizeof(cfg->tools_off) - n, "%s", key + 1); } else if (!off && hit) { /* drop ",name" keeping the trailing comma */ size_t kl = strlen(key) - 1; memmove(hit, hit + kl, strlen(hit + kl) + 1); if (strcmp(cfg->tools_off, ",") == 0) cfg->tools_off[0] = 0; } } int cst_tool_is_shell(const char *name) { const cst_tool_def_t *t = cst_tool_find(name); return t && t->perm == CST_TP_SHELL; } int cst_tool_is_write(const char *name) { const cst_tool_def_t *t = cst_tool_find(name); return t && t->perm == CST_TP_WRITE; } int cst_tool_active(const cst_agent_config_t *cfg, const cst_tool_def_t *t) { if (!t) return 0; /* A tool this host cannot run is never offered: the prompt, tools[] and the * /tools panel all go through here. */ if (cst_tool_available(t, NULL, 0) != 0) return 0; if (!cfg) return 1; if (cfg->tool_profile == CST_TOOLS_MINIMAL && !t->minimal) return 0; /* plan_mode is enforced when a call runs, so tools[] stays the same */ if (cfg->read_only && (t->perm == CST_TP_WRITE || t->perm == CST_TP_SHELL)) return 0; if (cfg->read_only && strcmp(t->name, "download") == 0) return 0; /* network download writes a workspace file */ if (cfg->depth > 0 && strcmp(t->name, "task") == 0) return 0; if (cfg->depth > 0 && (!strcmp(t->owner ? t->owner : "", "builtin:runtime") || !strncmp(t->name, "worker_", 7))) return 0; /* Parliament seats coordinate via sealed peer sync, not in-process workers. */ if (cst_parliament_is_active()) { if (!strcmp(t->name, "task") || !strncmp(t->name, "worker_", 7)) return 0; if (t->owner && !strcmp(t->owner, "builtin:runtime")) return 0; } else if (!strcmp(t->name, "parliament_note")) { return 0; } if (cfg->tools_only[0]) { char key[CTL_MAX_NAME + 2]; snprintf(key, sizeof(key), ",%s,", t->name); if (!strstr(cfg->tools_only, key)) return 0; } return !cst_tool_disabled(cfg, t->name); } /* Parsed schema of a dynamic tool, or NULL. */ static cJSON *tool_schema(const cst_tool_def_t *t) { if (!t->schema_json) return NULL; cJSON *s = cJSON_Parse(t->schema_json); if (s && !cJSON_IsObject(s)) { cJSON_Delete(s); return NULL; } return s; } static int schema_required(const cJSON *schema, const char *key) { const cJSON *req = cJSON_GetObjectItemCaseSensitive(schema, "required"); const cJSON *it = NULL; cJSON_ArrayForEach(it, req) { if (cJSON_IsString(it) && strcmp(it->valuestring, key) == 0) return 1; } return 0; } char *cst_tool_args_json(const cst_tool_def_t *t, const ctl_tool_call_t *c) { cJSON *schema = t ? tool_schema(t) : NULL; const cJSON *props = cJSON_GetObjectItemCaseSensitive(schema, "properties"); cJSON *o = cJSON_CreateObject(); for (int i = 0; i < c->nargs; i++) { const char *k = c->args[i].key; const char *v = c->args[i].value ? c->args[i].value : ""; const char *type = NULL; const cJSON *pp = cJSON_GetObjectItemCaseSensitive(props, k); const cJSON *ty = cJSON_GetObjectItemCaseSensitive(pp, "type"); if (cJSON_IsString(ty)) type = ty->valuestring; for (int j = 0; !type && t && j < CST_TOOL_MAX_PARAMS && t->params[j].name; j++) { if (strcmp(t->params[j].name, k) == 0) type = t->params[j].type; } cJSON *val = NULL; if (!type || strcmp(type, "string") != 0) { const char *p = v; while (*p == ' ' || *p == '\n') p++; /* untyped: only structured values are taken as JSON */ if (type || *p == '{' || *p == '[') val = cJSON_Parse(v); if (val && type && strcmp(type, "integer") == 0 && !cJSON_IsNumber(val)) { cJSON_Delete(val); val = NULL; } } if (!val) val = cJSON_CreateString(v); cJSON_AddItemToObject(o, k, val); } char *s = cJSON_PrintUnformatted(o); cJSON_Delete(o); cJSON_Delete(schema); return s; } static int is_minimal(const cst_agent_config_t *cfg) { return cfg && cfg->tool_profile == CST_TOOLS_MINIMAL; } static int is_external(const cst_tool_def_t *t) { return t->owner && strncmp(t->owner, "builtin:", 8) != 0; } static int by_name(const void *x, const void *y) { const cst_tool_def_t *a = *(const cst_tool_def_t *const *)x; const cst_tool_def_t *b = *(const cst_tool_def_t *const *)y; return strcmp(a->name, b->name); } void *cst_tools_schema_cfg(const cst_agent_config_t *cfg) { cJSON *arr = cJSON_CreateArray(); if (!arr) return NULL; int legacy = is_minimal(cfg); int n = cst_tool_count(); /* Built-ins in registry order, then plugin/MCP tools by name: servers * finish starting in any order, and tools[] is part of the cached prefix. */ const cst_tool_def_t **order = calloc((size_t)(n ? n : 1), sizeof(*order)); if (!order) { cJSON_Delete(arr); return NULL; } int nb = 0, no = 0; for (int i = 0; i < n; i++) { const cst_tool_def_t *t = cst_tool_at(i); if (t && cst_tool_active(cfg, t) && !is_external(t)) order[no++] = t; } nb = no; for (int i = 0; i < n; i++) { const cst_tool_def_t *t = cst_tool_at(i); if (t && cst_tool_active(cfg, t) && is_external(t)) order[no++] = t; } qsort(order + nb, (size_t)(no - nb), sizeof(*order), by_name); for (int i = 0; i < no; i++) { const cst_tool_def_t *t = order[i]; cJSON *tool = cJSON_CreateObject(); cJSON_AddStringToObject(tool, "type", "function"); cJSON *fn = cJSON_AddObjectToObject(tool, "function"); cJSON_AddStringToObject(fn, "name", t->name); cJSON_AddStringToObject(fn, "description", legacy && t->min_desc ? t->min_desc : t->desc); cJSON *schema = tool_schema(t); if (t->schema_json) { if (!schema) { schema = cJSON_CreateObject(); cJSON_AddStringToObject(schema, "type", "object"); cJSON_AddObjectToObject(schema, "properties"); } cJSON_AddItemToObject(fn, "parameters", schema); cJSON_AddItemToArray(arr, tool); continue; } cJSON *params = cJSON_AddObjectToObject(fn, "parameters"); cJSON_AddStringToObject(params, "type", "object"); cJSON *props = cJSON_AddObjectToObject(params, "properties"); cJSON *req = cJSON_AddArrayToObject(params, "required"); for (int k = 0; k < CST_TOOL_MAX_PARAMS && t->params[k].name; k++) { const cst_tool_param_t *pp = &t->params[k]; if (legacy && !pp->required) continue; cJSON *p = cJSON_AddObjectToObject(props, pp->name); cJSON_AddStringToObject(p, "type", pp->type); if (!legacy && pp->desc) cJSON_AddStringToObject(p, "description", pp->desc); if (pp->required) cJSON_AddItemToArray(req, cJSON_CreateString(pp->name)); } cJSON_AddItemToArray(arr, tool); } free(order); return arr; } void *cst_tools_schema(void) { return cst_tools_schema_cfg(NULL); } char *cst_tools_prompt(const cst_agent_config_t *cfg) { cst_buf_t b = {0}; cst_buf_puts(&b, "Tools:\n"); int n = cst_tool_count(); for (int i = 0; i < n; i++) { const cst_tool_def_t *t = cst_tool_at(i); if (!t || !cst_tool_active(cfg, t)) continue; cst_buf_printf(&b, "- %s(", t->name); if (t->schema_json) { cJSON *schema = tool_schema(t); const cJSON *props = cJSON_GetObjectItemCaseSensitive(schema, "properties"); const cJSON *it = NULL; int k = 0; cJSON_ArrayForEach(it, props) { cst_buf_printf(&b, "%s%s%s", k++ ? ", " : "", it->string, schema_required(schema, it->string) ? "" : "?"); } cJSON_Delete(schema); } for (int k = 0; !t->schema_json && k < CST_TOOL_MAX_PARAMS && t->params[k].name; k++) cst_buf_printf(&b, "%s%s%s", k ? ", " : "", t->params[k].name, t->params[k].required ? "" : "?"); /* first line of a long description is enough in the prompt */ const char *d = t->desc ? t->desc : ""; size_t dl = strlen(d); if (t->schema_json && dl > 300) dl = cst_utf8_floor(d, 300); cst_buf_printf(&b, "): %.*s%s\n", (int)dl, d, dl < strlen(d) ? "…" : ""); } return cst_buf_steal(&b); } char *cst_tools_names(const cst_agent_config_t *cfg) { cst_buf_t b = {0}; int n = 0, cnt = cst_tool_count(); for (int i = 0; i < cnt; i++) { const cst_tool_def_t *t = cst_tool_at(i); if (t && cst_tool_active(cfg, t)) cst_buf_printf(&b, "%s%s", n++ ? ", " : "", t->name); } if (!b.buf) cst_buf_puts(&b, ""); return cst_buf_steal(&b); } static int parse_int_value(const char *v, long *out) { while (*v == ' ' || *v == '"' || *v == '\'') v++; char *end = NULL; long x = strtol(v, &end, 10); if (end == v) return -1; while (*end == ' ' || *end == '"' || *end == '\'' || *end == '\n') end++; if (*end) return -1; *out = x; return 0; } int cst_tool_validate(const cst_tool_def_t *t, const ctl_tool_call_t *call, char *err, size_t err_sz) { if (t->schema_json) { cJSON *schema = tool_schema(t); const cJSON *req = cJSON_GetObjectItemCaseSensitive(schema, "required"); const cJSON *it = NULL; int rc = 0; cJSON_ArrayForEach(it, req) { if (cJSON_IsString(it) && !tool_arg(call, it->valuestring)) { snprintf(err, err_sz, "error: %s needs argument \"%s\"", t->name, it->valuestring); rc = -1; break; } } cJSON_Delete(schema); return rc; } for (int k = 0; k < CST_TOOL_MAX_PARAMS && t->params[k].name; k++) { const cst_tool_param_t *p = &t->params[k]; const char *v = tool_arg(call, p->name); if (!v && strcmp(t->name, "run_shell") == 0) v = tool_arg(call, "command"); if (!v) { if (p->required) { snprintf(err, err_sz, "error: %s needs argument \"%s\"", t->name, p->name); return -1; } continue; } long x; if (strcmp(p->type, "integer") == 0 && v[0] && parse_int_value(v, &x)) { snprintf(err, err_sz, "error: %s: argument \"%s\" must be an integer", t->name, p->name); return -1; } } return 0; } int cst_tool_run(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *call, cst_tool_result_t *r) { if (!ctx || !call || !r) return -1; memset(r, 0, sizeof(*r)); const cst_tool_def_t *t = cst_tool_find(call->name); if (!t) return tool_set_resultf(r, 1, "error: unknown tool: %.64s", call->name); char why[160]; if (cst_tool_available(t, why, sizeof(why)) != 0) return tool_set_resultf(r, 1, "error: %.64s cannot run here: %.120s", call->name, why[0] ? why : "not supported"); char err[256]; if (cst_tool_validate(t, call, err, sizeof(err)) != 0) return tool_set_result(r, err, 1); if (t->run_ex) return t->run_ex(ctx, call, r, t->ud); return t->run(ctx, call, r); } int cst_tool_preview(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *call, char **out) { *out = NULL; const cst_tool_def_t *t = cst_tool_find(call->name); if (!t || !t->preview) return -1; char err[256]; if (cst_tool_validate(t, call, err, sizeof(err)) != 0) { *out = strdup(err); return -1; } return t->preview(ctx, call, out); } int cst_tool_dispatch(const char *workspace_root, const ctl_tool_call_t *call, cst_tool_result_t *r) { cst_tool_ctx_t ctx = {0}; ctx.workspace_root = workspace_root; return cst_tool_run(&ctx, call, r); }