1122 lines · 31.9 KB · C
RawDownload
// SPDX-License-Identifier: ISC#include <errno.h>#include <fcntl.h>#include <getopt.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/stat.h>#include <time.h>#include <unistd.h>#include <uv.h> #include "clm/clm.h"#include "clm/host_uv.h"#include "clm/provider.h"#include "frontend.h"#include "version.h"#include "clm/lua_plugin.h"#include "seed_plugins.h"#include "clm/cleanup.h"#include "clm/session.h"#include "clm/peer.h"#include "mcp_setup.h"#include "sysinfo.h" /* How long a session log outlives its last write, unless config says * otherwise (session_keep_days = 0 keeps everything). */#define CLM_SESSION_KEEP_DAYS 90#include "cfg_tuning.h"#include "loop_drain.h"#include "model_spec.h"#include "templates.h"#include "xdg.h" static voidusage(const char *prog){	fprintf(stderr,	    "usage: %s setup\n"	    "       %s [-o|--oneshot PROMPT] [-f|--forever PROMPT] "	    "[-H|--headless] [-u|--url BASE] "	    "[-m|--model PROVIDER/MODEL-ID] [--provider NAME] "	    "[-p|--plugins DIR] [-S|--no-stream] [--allow-all-tools] "	    "[-r|--resume [ID]] "	    "[-V|--version] [-h|--help]\n",	    prog, prog);	fprintf(stderr,	    "  setup                 write a starter config.lua and seed "	    "builtin plugins\n"	    "  -o, --oneshot PROMPT  run one prompt headless and exit\n"	    "  -f, --forever PROMPT  TUI mode: submit PROMPT, then "	    "auto-resubmit it\n"	    "                        every time a turn completes with nothing "	    "queued,\n"	    "                        so the agent keeps going without a human "	    "re-prompting it\n"	    "  -H, --headless        force the plain stdio REPL\n"	    "  -u, --url BASE        base API endpoint "	    "(default http://127.0.0.1:8081/v1);\n"	    "                        \"/messages\" is appended for an "	    "anthropic "	    "provider,\n"	    "                        \"/chat/completions\" otherwise\n"	    "  -m, --model PROVIDER/MODEL-ID\n"	    "                        a config.lua providers[PROVIDER].models"	    "[MODEL-ID] entry,\n"	    "                        or a literal model id (no \"/\") to "	    "request "	    "on whatever\n"	    "                        connection is otherwise active\n"	    "  --provider NAME       name of an entry in config.lua's "	    "`providers` table,\n"	    "                        overriding the connection --model's "	    "provider half names\n"	    "  -p, --plugins DIR     plugin directory "	    "(default $XDG_CONFIG_HOME/clm/plugins)\n"	    "  -S, --no-stream       disable streamed (SSE) responses\n"	    "      --allow-all-tools run every tool call without asking; for\n"	    "                        an agent nobody is watching, in a\n"	    "                        directory you can afford to lose\n"	    "  -r, --resume [ID]     resume a saved session in the TUI; with "	    "no ID,\n"	    "                        pick from a list of saved sessions\n"	    "  -V, --version         print version and exit\n"	    "  -h, --help            show this help\n"	    "\n"	    "  With no options it runs the interactive ncurses UI on a "	    "terminal.\n"	    "  Set CLM_API_KEY in the environment to send a bearer token.\n");} /* * Escapes for the non-TUI output paths, resolved once in main(): colour, or * attributes only under NO_COLOR, or nothing when stdout is not a terminal. */static const char *esc_warn = "\033[33m";static const char *esc_err = "\033[31m";static const char *esc_dim = "\033[2m";static const char *esc_reset = "\033[0m"; static voidinit_escapes(void){	const char *term = getenv("TERM"); 	if (!isatty(STDOUT_FILENO) || term == NULL ||	    strcmp(term, "dumb") == 0) {		esc_warn = esc_err = esc_dim = esc_reset = "";		return;	}	if (getenv("NO_COLOR") != NULL) {		esc_warn = "\033[1m";		esc_err = "\033[1;7m";	}} struct cli_state {	uv_loop_t *loop;	struct clm_host *host;	struct clm_agent *agent;	struct clm_lua_env *lua_env;	struct clm_lua_cfg *lua_cfg;	struct clm_peer *peer;	struct clm_mcp_client **mcp_clients;	size_t mcp_client_count;	uv_pipe_t stdin_pipe;	char prompt_line[1024];	size_t prompt_len;	int oneshot;	int batch;	int turn_done;	int turn_status;}; static voidcb_mcp_status(const char *msg, void *user){	(void)user;	fprintf(stderr, "%s\n", msg);} static voidcb_assistant_text(const char *text, void *user){	struct cli_state *state = (struct cli_state *)user;	if (state->oneshot)		printf("%s", text);	else		printf("assistant> %s", text);	fflush(stdout);} static voidcb_reasoning(const char *text, void *user){	(void)user;	printf("%s%s%s", esc_dim, text, esc_reset);	fflush(stdout);} static voidcb_finish_reason(enum clm_finish_reason reason, void *user){	(void)user;	if (reason == CLM_FINISH_LENGTH)		printf("\n%s[truncated: hit token limit]%s\n", esc_warn,		    esc_reset);	else if (reason == CLM_FINISH_CONTENT_FILTER)		printf("\n%s[stopped: content filter]%s\n", esc_err, esc_reset);	fflush(stdout);} static voidcb_usage(const struct clm_usage *usage, void *user){	(void)user;	printf("%s[%d+%d tok", esc_dim, usage->prompt_tokens,	    usage->completion_tokens);	if (usage->cache_read_tokens > 0)		printf(", %d cached", usage->cache_read_tokens);	if (usage->tokens_per_sec > 0)		printf(", %.1f tok/s", usage->tokens_per_sec);	printf("]%s\n", esc_reset);	fflush(stdout);} static voidcb_tool_begin(const char *name, const char *args, void *user){	(void)user;	printf("[tool: %s %s]\n", name, args ? args : "");	fflush(stdout);} static voidcb_tool_result(const char *name, const char *content,    enum clm_tool_outcome outcome, void *user){	(void)user;	switch (outcome) {	case CLM_TOOL_OK:		printf("[result: %s]\n%s\n", name, content ? content : "");		break;	case CLM_TOOL_FAILED:		printf("%s[x %s]%s %s\n", esc_err, name, esc_reset,		    content ? content : "");		break;	case CLM_TOOL_TIMEDOUT:		printf("%s[timeout %s]%s %s\n", esc_warn, name, esc_reset,		    content ? content : "");		break;	}	fflush(stdout);} static voidcb_tool_batch(size_t completed, size_t total, void *user){	(void)user;	printf("[tools %zu/%zu]\n", completed, total);	fflush(stdout);} static voidcb_state(enum clm_agent_state state, void *user){} static voidcb_notice(const char *text, void *user){	(void)user;	fprintf(stderr, "notice: %s\n", text ? text : "");} static voidcb_turn_done(int status, void *user){	struct cli_state *state = (struct cli_state *)user;	if (status != 0) {		fprintf(stderr, "error: %s\n",		    clm_agent_get_last_error(state->agent));	}	if (state->oneshot || state->batch) {		state->turn_done = 1;		state->turn_status = status;	}	if (state->oneshot)		return;	printf("\nuser> ");	fflush(stdout);} /* * Auto-allow permission handler: preserves the CLI's pre-gate behaviour under * the library's default-deny. A future refinement could gate this behind an * explicit --yes/--allow flag for unattended runs. */static voidcb_permission(const struct clm_permission_req *req, void *user){	struct cli_state *state = (struct cli_state *)user;	clm_tool_permission_respond(state->agent, req, CLM_PERM_ALLOW_ONCE);} static const struct clm_callbacks cli_callbacks = {    .on_assistant_text = cb_assistant_text,    .on_reasoning = cb_reasoning,    .on_tool_begin = cb_tool_begin,    .on_permission = cb_permission,    .on_tool_result = cb_tool_result,    .on_tool_batch = cb_tool_batch,    .on_finish_reason = cb_finish_reason,    .on_usage = cb_usage,    .on_state = cb_state,    .on_turn_done = cb_turn_done,    .on_notice = cb_notice,}; static voidon_alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf){	buf->base = malloc(suggested_size);	if (buf->base == NULL) {		buf->len = 0;		return;	}	buf->len = suggested_size;} /* * Line-at-a-time REPL over a stdin that epoll cannot watch: a regular file, * /dev/null, anything uv_guess_handle() reports as UV_FILE. uv_pipe_open() * takes such a descriptor, then libuv aborts the process when the kernel * refuses to poll it. Read with stdio, run the loop only during a turn. */static voidrun_stdin_batch(struct cli_state *state, uv_loop_t *loop){	state->batch = 1; 	while (fgets(state->prompt_line, sizeof(state->prompt_line), stdin) !=	    NULL) {		size_t n = strcspn(state->prompt_line, "\r\n"); 		/* Longer than the buffer: submit what fits and drop the		 * rest of the line, as the streaming path does. */		if (state->prompt_line[n] == '\0') {			int c;			while ((c = fgetc(stdin)) != EOF && c != '\n')				;		}		state->prompt_line[n] = '\0'; 		if (state->prompt_line[0] == '\0')			continue;		if (strcmp(state->prompt_line, "quit") == 0 ||		    strcmp(state->prompt_line, "exit") == 0)			break; 		state->turn_done = 0;		if (clm_agent_submit(state->agent, state->prompt_line) < 0) {			fprintf(stderr, "error: %s\n",			    clm_agent_get_last_error(state->agent));			continue;		}		while (!state->turn_done)			uv_run(loop, UV_RUN_ONCE);	} 	printf("\n");	fflush(stdout);} static voidon_stdin_close(uv_handle_t *handle){	struct cli_state *state = (struct cli_state *)handle->data;	uv_stop(state->loop);} static voidon_stdin_read(uv_stream_t *stream, ssize_t n_read, const uv_buf_t *buf){	struct cli_state *state = (struct cli_state *)stream->data; 	if (n_read < 0) {		if (n_read == UV_ENOBUFS)			return;		if (n_read == UV_EOF) {			free(buf->base);			printf("\n");			fflush(stdout);			uv_close((uv_handle_t *)stream, on_stdin_close);			return;		}		fprintf(stderr, "read error: %s\n", uv_err_name(n_read));		uv_close((uv_handle_t *)stream, on_stdin_close);		return;	} 	if (n_read == 0) {		free(buf->base);		return;	} 	for (ssize_t i = 0; i < n_read; i++) {		if (state->prompt_len < sizeof(state->prompt_line) - 1) {			state->prompt_line[state->prompt_len++] = buf->base[i];		}		if (buf->base[i] == '\n' || buf->base[i] == '\r') {			if (state->prompt_len > 0 &&			    state->prompt_line[state->prompt_len - 1] == '\r')				state->prompt_len--;			if (state->prompt_len > 0 &&			    state->prompt_line[state->prompt_len - 1] == '\n')				state->prompt_len--;			state->prompt_line[state->prompt_len] = '\0'; 			if (state->prompt_len > 0) {				if (strcmp(state->prompt_line, "quit") == 0 ||				    strcmp(state->prompt_line, "exit") == 0) {					free(buf->base);					uv_close((uv_handle_t *)stream,					    on_stdin_close);					return;				} 				int r = clm_agent_submit(				    state->agent, state->prompt_line);				if (r < 0) {					fprintf(stderr, "error: %s\n",					    clm_agent_get_last_error(					        state->agent));				}			} 			state->prompt_len = 0;			break;		}	} 	free(buf->base);} /* Writes content to path unless it already exists. Returns 0 if written, * 1 if it already existed (left untouched), or -errno on failure. */static intwrite_new_file(const char *path, const char *content, mode_t mode){	int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, mode);	if (fd < 0)		return errno == EEXIST ? 1 : -errno; 	size_t len = strlen(content);	size_t off = 0;	while (off < len) {		ssize_t n = write(fd, content + off, len - off);		if (n < 0) {			int err = -errno;			close(fd);			(void)unlink(path);			return err;		}		off += (size_t)n;	}	close(fd);	return 0;} /* * --resume with no id: print a numbered listing of saved sessions and read * a choice from stdin. Returns a malloc'd session id, or NULL (no sessions, * bad choice, or EOF). *//* * Expand a fragment of a session id into the full one. Matches any session * whose id contains the fragment, so the 8-hex tail shown in the status bar * is enough. Returns NULL (after reporting) when nothing or more than one * session matches. *//* Drop scratch directories whose session log no longer exists, and any * left behind past the retention window. */static voidsweep_scratch(int64_t keep_days){	struct clm_session_info *infos = NULL;	const char **live = NULL;	size_t n = 0, i; 	if (clm_session_list(NULL, &infos, &n) != 0)		return;	if (n > 0) {		live = calloc(n, sizeof(*live));		if (live == NULL) {			clm_session_list_free(infos, n);			return;		}		for (i = 0; i < n; i++)			live[i] = infos[i].id;	}	(void)clm_cli_scratch_gc(	    live, n, (unsigned)(keep_days > 0 ? keep_days : 0));	free(live);	clm_session_list_free(infos, n);} /* * Give the agent a private directory for throwaway files: exported to tools * as CLM_SCRATCH and named in the system prompt, since a model that is not * told where to put scratch files puts them in the user's tree. */static char *attach_scratch(    const char *key, const char *sysinfo, bool is_session, char **dir_out){	char *dir = clm_cli_scratch_dir(key);	char *block = NULL; 	*dir_out = NULL;	if (dir == NULL)		return NULL;	(void)setenv("CLM_SCRATCH", dir, 1);	if (asprintf(&block,	        "%s\n\nscratch directory for this session: %s\n"	        "Put working files, downloads, and intermediate output there "	        "rather than in the user's tree or /tmp. It is also "	        "$CLM_SCRATCH in any command you run.%s%s",	        sysinfo != NULL ? sysinfo : "", dir,	        is_session ? "\n\nthis session's id: " : "",	        is_session ? key : "") < 0) {		free(dir);		return NULL;	}	*dir_out = dir;	return block;} static char *resolve_session_prefix(const char *frag)

Lines 1–500 of 1122.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t