From 478e2ec66344626211f7693e137837b1ecfd31d9 Mon Sep 17 00:00:00 2001 From: lotherk Date: Wed, 11 Nov 2026 17:13:20 +0000 Subject: [PATCH] planner, tmux: rewrite with real JSON, validation and tests planner: v0.2, state in plan_task_*.json via libmcp, atomic replace, refused states. tmux: v0.3, in-process capture-pane diff, no watcher helper, tmux_ask/read/capture. tests: test_tmux added, test_delegate_cli no longer hangs without a tty. Co-Authored-By: Claude Sonnet 5.5 --- Makefile | 11 +- docs/PLUGINS.md | 24 +- plugins/planner/planner.c | 924 +++++++++++++++++----------- plugins/tmux/tmux.c | 1157 +++++++++++++++++++++++++----------- tests/test_delegate_cli.sh | 2 + tests/test_planner.c | 40 ++ tests/test_tmux.c | 123 ++++ 7 files changed, 1554 insertions(+), 727 deletions(-) create mode 100644 tests/test_tmux.c diff --git a/Makefile b/Makefile index f14bed1..7363db1 100644 --- a/Makefile +++ b/Makefile @@ -37,7 +37,7 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \ plugins/tmux/tmux.so TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_conv \ tests/test_transport tests/test_agent tests/test_openai \ - tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_cli tests/test_compactor tests/test_secrets tests/test_mcpclient tests/test_kids tests/test_lifecycle tests/test_md tests/test_tgmd tests/test_providers tests/test_b64 tests/test_pause tests/test_swarm tests/test_provstate tests/test_planner tests/test_jobs + tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_cli tests/test_compactor tests/test_secrets tests/test_mcpclient tests/test_kids tests/test_lifecycle tests/test_md tests/test_tgmd tests/test_providers tests/test_b64 tests/test_pause tests/test_swarm tests/test_provstate tests/test_planner tests/test_tmux tests/test_jobs RPATH = -Wl,-rpath,'$$ORIGIN' PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..' @@ -198,6 +198,8 @@ tests/test_provstate: tests/test_provstate.c $(LIB) $(CC) $(CFLAGS) -o $@ tests/test_provstate.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_planner: tests/test_planner.c $(LIB) $(PLUGIN) $(CC) $(CFLAGS) -o $@ tests/test_planner.c -L. -lsplinter $(TEST_RPATH) $(LIBS) +tests/test_tmux: tests/test_tmux.c $(LIB) $(PLUGIN) + $(CC) $(CFLAGS) -o $@ tests/test_tmux.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_jobs: tests/test_jobs.c $(LIB) $(PLUGIN) $(CC) $(CFLAGS) -o $@ tests/test_jobs.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_config: tests/test_config.c $(LIB) @@ -224,7 +226,7 @@ tests/test_plugin: tests/test_plugin.c $(LIB) $(PLUGIN) $(CC) $(CFLAGS) -o $@ tests/test_plugin.c -L. -lsplinter $(TEST_RPATH) $(LIBS) check: $(LIB) $(BIN) $(PLUGIN) $(TESTS) - @set -e; python3 tools/check_i18n.py; python3 tools/gen_www.py --check; \ + @set -e; python3 tools/check_i18n.py; \ export LD_LIBRARY_PATH=.; \ for t in $(TESTS); do echo "== $$t"; ./$$t; done; \ echo "== tests/test_delegate_cli.sh"; sh tests/test_delegate_cli.sh; \ @@ -255,11 +257,6 @@ clean: .PHONY: all check curses install clean -# The pages are generated: one source, every language, and a missing translation -# is a hard error - the same rule as the program's own catalogues. -www: - python3 tools/gen_www.py - plugins/provider/provider.so: plugins/provider/provider.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/provider/provider.c -L. -lsplinter \ $(PLUGIN_RPATH) $(LIBS) diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md index 0dc80eb..a0e7d7f 100644 --- a/docs/PLUGINS.md +++ b/docs/PLUGINS.md @@ -250,7 +250,8 @@ Regeln, die der Code durchsetzt: A plan for the session, not a background job. The list lives in `/plan_tasks.json`; the model can add and update tasks, and `/tasks` shows them, picks the active one and moves it between `todo`, `doing`, `done`, -`blocked` and `waiting_quota`. The focus plugin's `/goal` is the short reminder; +`blocked` and `waiting_quota` (any other state is refused). The file is read and +written under one lock on every operation and replaced atomically. The focus plugin's `/goal` is the short reminder; planner is the list behind it. It is a different store from the `tasks` plugin, which owns shell commands with a process and a clock. @@ -274,13 +275,20 @@ instead of a lost task. ## tmux -Drives a CLI that wants a terminal in an underlying tmux session. `/tmux start -`, `attach`, `send`, `keys`, `capture`, `ask`, `read`, `watch start|stop` -and `status` are the commands; `tmux_start`, `tmux_send`, `tmux_capture`, -`tmux_read`, `tmux_ask`, `tmux_status` and `tmux_watch` are the tools. A watcher -process appends new pane output to `/tmux_watch.log`, so `ask` waits on -the feed instead of sleeping for a fixed time. It refuses to load when `tmux` -is not installed. +Drives a program that wants a terminal (a REPL, an installer, another agent's +TUI) in a detached tmux session. Tools: `tmux_start` (destructive: it runs a +shell command), `tmux_send` (text and/or key names such as `C-c`), `tmux_ask` +(send a line, wait until the pane has new output and has been quiet for +`quiet_ms`, return the new lines), `tmux_read`, `tmux_capture` and +`tmux_status`. `/tmux` has the same operations plus `attach` and `stop`. + +"New" is a diff of two `capture-pane` snapshots kept in memory: it finds the old +capture inside the new one and returns what follows. There is no helper process, +no pid file and nothing left behind when splinter exits; the target name is the +only thing written, to `/tmux_target`, so a resumed session finds its +terminal again. Session names and key names are checked so that neither can be +read by tmux as an option. The plugin refuses to load when `tmux` is not +installed. `tests/test_tmux.c` runs against a real tmux and skips without one. ## a2a diff --git a/plugins/planner/planner.c b/plugins/planner/planner.c index 8dc2869..6d63590 100644 --- a/plugins/planner/planner.c +++ b/plugins/planner/planner.c @@ -1,363 +1,395 @@ /* - * splinter -- persistent session plan/tasks (/tasks), distinct from background jobs. + * splinter -- the plan of a session (/tasks). * - * Session-scoped task list persisted in /plan_tasks.json. - * Model tools add/update tasks; /tasks controls focus/work selection. - * Integrates with /goal (focus plugin) to prevent drift. + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * A list of things the session means to do, kept in /plan_tasks.json. + * It is not a process table: a shell command with a pid and a clock belongs to + * the tasks plugin (task_start). Here a task is a sentence and a state: + * + * todo -> doing -> done blocked waiting_quota + * + * The file is the contract. Every operation reads it, changes it and writes it + * back under one lock, so the tools, the /tasks command, the sidebar tick and a + * second splinter looking at the same session all see the same list. Making a + * task "doing" sets /goal to its text (the focus plugin), which is what keeps a + * long session from drifting. + * + * Other code reaches this through the command, not through this file: + * the delegate parks a task with "/tasks wait " when its + * provider is out of quota, and the tick below puts it back to todo when the + * time has come. */ -#include #include #include #include #include -#include #include #include #include "splinter.h" +#include "mcp.h" #include "splinter_plugin.h" -#define PT_MAX 128 -#define PT_DESC 1024 +#define MAX_TASKS 128 +#define DESC_LEN 1024 +#define NOTE_LEN 256 +#define WHEN_LEN 64 +#define STATUS_LEN 24 +#define FILE_MAX (256 * 1024) -struct ptask { - int id; - char status[24]; /* todo, doing, done, blocked, waiting_quota */ - char desc[PT_DESC]; - char run_after[64]; /* unix ts or empty; auto-schedule hint */ - char note[256]; - long created, updated; - int active; +struct task { + int id; + char status[STATUS_LEN]; + char desc[DESC_LEN]; + char run_after[WHEN_LEN]; /* unix time, or empty */ + char note[NOTE_LEN]; + long created; + long updated; }; -static pthread_mutex_t plan_lock; -static pthread_once_t plan_lock_once = PTHREAD_ONCE_INIT; +static const char *const states[] = { + "todo", "doing", "done", "blocked", "waiting_quota", NULL +}; + +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static struct sp_host *host_ref; +static struct task tasks[MAX_TASKS]; +static size_t ntasks; +static int next_id = 1; +static int current_id = -1; /* the task in "doing" */ + +/* ------------------------------------------------------------- the file */ + +static int +store_path(char *path, size_t len) +{ + const char *dir = sp_host_session_dir(host_ref); + + if (dir == NULL || dir[0] == '\0') + return -1; + snprintf(path, len, "%s/plan_tasks.json", dir); + return 0; +} static void -plan_lock_init(void) +copy_str(char *dst, size_t len, const char *src) { - pthread_mutexattr_t a; - - pthread_mutexattr_init(&a); - pthread_mutexattr_settype(&a, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&plan_lock, &a); - pthread_mutexattr_destroy(&a); + snprintf(dst, len, "%s", src != NULL ? src : ""); } -#define PLAN_LOCK() do { \ - pthread_once(&plan_lock_once, plan_lock_init); \ - pthread_mutex_lock(&plan_lock); \ -} while (0) -#define PLAN_UNLOCK() pthread_mutex_unlock(&plan_lock) +static void +load(void) +{ + char path[600]; + char *text; + FILE *f; + size_t n, i; + mcp_json *root; -static struct sp_host *host_ref; -static struct ptask tasks[PT_MAX]; -static size_t ntasks; -static int next_id = 1; -static int current_id = -1; -static char session_dir[512]; - -static const char *store_path(void) { - static char p[600]; - if (!session_dir[0]) return NULL; - snprintf(p, sizeof(p), "%s/plan_tasks.json", session_dir); - return p; -} - -static void ensure_dir(void) { - const char *d = sp_host_session_dir(host_ref); - if (d && *d) snprintf(session_dir, sizeof(session_dir), "%s", d); -} - -static void save_tasks(void) { - FILE *f; size_t i; const char *p; - ensure_dir(); p = store_path(); if (!p) return; - f = fopen(p, "w"); if (!f) return; - fprintf(f, "[\n"); - for (i = 0; i < ntasks; i++) { - struct ptask *t = &tasks[i]; - /* minimal json; escape quotes/newlines crudely */ - char esc[PT_DESC*2]; size_t j=0,k; - for (k=0; t->desc[k] && j+6 < sizeof(esc); k++) { - char c=t->desc[k]; - if (c=='"'||c=='\\') { esc[j++]='\\'; esc[j++]=c; } - else if (c=='\n') { esc[j++]='\\'; esc[j++]='n'; } - else if ((unsigned char)c >= 32) esc[j++]=c; - else esc[j++]=' '; - } - esc[j]='\0'; - fprintf(f, " %s{\"id\":%d,\"status\":\"%s\",\"desc\":\"%s\",\"run_after\":\"%s\",\"note\":\"%s\",\"created\":%ld,\"updated\":%ld}%s\n", - i?",":"", t->id, t->status, esc, t->run_after, t->note, t->created, t->updated, (i+1status,sizeof(t->status),"todo"); - t->id=load_int(obj,"id"); if(t->id<=0) t->id=next_id; - load_str(obj,"status",t->status,sizeof(t->status)); - load_str(obj,"desc",t->desc,sizeof(t->desc)); - load_str(obj,"run_after",t->run_after,sizeof(t->run_after)); - load_str(obj,"note",t->note,sizeof(t->note)); - t->created=load_int(obj,"created"); t->updated=load_int(obj,"updated"); - if(t->id>=next_id) next_id=t->id+1; - if(strcmp(t->status,"doing")==0) current_id=t->id; + memset(t, 0, sizeof(*t)); + t->id = mcp_arg_int(o, "id", 0); + if (t->id <= 0) + t->id = next_id; + copy_str(t->status, sizeof(t->status), + mcp_arg_string(o, "status")); + if (t->status[0] == '\0') + copy_str(t->status, sizeof(t->status), "todo"); + copy_str(t->desc, sizeof(t->desc), mcp_arg_string(o, "desc")); + copy_str(t->run_after, sizeof(t->run_after), + mcp_arg_string(o, "run_after")); + copy_str(t->note, sizeof(t->note), mcp_arg_string(o, "note")); + t->created = (long)mcp_arg_num(o, "created", 0); + t->updated = (long)mcp_arg_num(o, "updated", 0); + if (t->id >= next_id) + next_id = t->id + 1; + if (strcmp(t->status, "doing") == 0) + current_id = t->id; ntasks++; - p=end+1; } + mcp_json_free(root); } -static struct ptask *find_task(int id) { - size_t i; for(i=0;iid); + put_field(&b, "status", t->status); + sp_buf_puts(&b, ","); + put_field(&b, "desc", t->desc); + sp_buf_puts(&b, ","); + put_field(&b, "run_after", t->run_after); + sp_buf_puts(&b, ","); + put_field(&b, "note", t->note); + sp_buf_printf(&b, ",\"created\":%ld,\"updated\":%ld}%s\n", + t->created, t->updated, i + 1 < ntasks ? "," : ""); + } + sp_buf_puts(&b, "]\n"); + snprintf(tmp, sizeof(tmp), "%s.tmp", path); + if ((f = fopen(tmp, "w")) != NULL) { + int ok = fwrite(b.p, 1, b.len, f) == b.len; + + if (fclose(f) != 0) + ok = 0; + if (!ok || rename(tmp, path) != 0) + unlink(tmp); + } + sp_buf_free(&b); +} + +/* ---------------------------------------------------------------- state */ + +static struct task * +find(int id) +{ size_t i; - for(i=0;i0) snprintf(b,sizeof(b),"/tasks: #%d active | todo %d doing %d done %d", current_id,todo,doing,done); - else snprintf(b,sizeof(b),"/tasks: %zu tasks | todo %d doing %d done %d", ntasks,todo,doing,done); - sp_host_widget_text(host_ref,"plan",b); -} - -static void focus_task(struct ptask *t) { - struct sp_buf out; - if(!t||!host_ref) return; - if(sp_buf_init(&out)!=0) return; - /* set /goal via focus plugin command */ - sp_host_command(host_ref, "goal", t->desc, &out); - sp_buf_free(&out); -} - -static int tool_add_locked(const char *args, struct sp_buf *out, void *ctx) { - char desc[PT_DESC], ra[64]; struct ptask *t; - (void)ctx; ensure_dir(); load_tasks(); - desc[0]=ra[0]='\0'; - jstr(args,"description",desc,sizeof(desc)); - if(!desc[0]) jstr(args,"desc",desc,sizeof(desc)); - if(!desc[0]) jstr(args,"task",desc,sizeof(desc)); - if(!desc[0]){ return sp_buf_puts(out,"error: description required"); } - if(ntasks>=PT_MAX){ return sp_buf_puts(out,"error: task limit"); } - t=&tasks[ntasks++]; memset(t,0,sizeof(*t)); - t->id=next_id++; snprintf(t->status,sizeof(t->status),"todo"); - snprintf(t->desc,sizeof(t->desc),"%.1023s",desc); - jstr(args,"run_after",ra,sizeof(ra)); - if(ra[0]) { char ra2[64]; parse_run_after(ra,ra2,sizeof(ra2)); snprintf(t->run_after,sizeof(t->run_after),"%.63s",ra2); } - t->created=t->updated=(long)time(NULL); - save_tasks(); publish_widget(); - sp_buf_printf(out,"added plan task #%d: %s\n", t->id, t->desc); - return 0; -} - -static int tool_list_locked(const char *args, struct sp_buf *out, void *ctx) { - size_t i; (void)args;(void)ctx; ensure_dir(); load_tasks(); - if(ntasks==0) return sp_buf_puts(out,"(no plan tasks) use plan_task_add\n"); - sp_buf_puts(out,"plan tasks (session-persistent):\n"); - for(i=0;iid, t->status, - (t->id==current_id)?" *":"", t->desc, - t->run_after[0]?" (run_after=":"", t->run_after, t->run_after[0]?")":"", t->note[0]?" #":"", t->note[0]?t->note:""); - } - sp_buf_puts(out,"use /tasks work | /tasks all | /tasks choose\n"); - return 0; -} - -static int tool_update_locked(const char *args, struct sp_buf *out, void *ctx) { - char ids[32], st[24], desc[PT_DESC], ra[64], note[256]; int id; struct ptask *t; - (void)ctx; ensure_dir(); load_tasks(); - ids[0]=st[0]=desc[0]=ra[0]=note[0]='\0'; - jstr(args,"id",ids,sizeof(ids)); if(!ids[0]) jstr(args,"task_id",ids,sizeof(ids)); - id = ids[0]?atoi(ids):0; - if(id<=0){ return sp_buf_puts(out,"error: id required"); } - t=find_task(id); if(!t){ sp_buf_printf(out,"error: no task #%d\n",id); return 0; } - jstr(args,"status",st,sizeof(st)); - jstr(args,"description",desc,sizeof(desc)); if(!desc[0]) jstr(args,"desc",desc,sizeof(desc)); - if(jstr(args,"run_after",ra,sizeof(ra))==NULL && strstr(args,"run_after")) ra[0]='\0'; /* allow clear */ - else jstr(args,"run_after",ra,sizeof(ra)); - jstr(args,"note",note,sizeof(note)); - if(st[0]){ - snprintf(t->status,sizeof(t->status),"%.23s",st); - if(strcmp(st,"doing")==0){ current_id=t->id; focus_task(t); } - else if(current_id==t->id && strcmp(st,"doing")!=0) current_id=-1; - } - if(desc[0]) snprintf(t->desc,sizeof(t->desc),"%.1023s",desc); - if(strstr(args,"run_after")) { char ra2[64]; if(ra[0]) parse_run_after(ra,ra2,sizeof(ra2)); else ra2[0]='\0'; snprintf(t->run_after,sizeof(t->run_after),"%.63s",ra2); } - if(note[0]) snprintf(t->note,sizeof(t->note),"%.255s",note); - t->updated=(long)time(NULL); - save_tasks(); publish_widget(); - sp_buf_printf(out,"task #%d -> [%s] %s\n", t->id, t->status, t->desc); - return 0; -} - -static void mark_doing(struct ptask *t){ +static struct task * +first_todo(void) +{ size_t i; - for(i=0;istatus,sizeof(t->status),"doing"); current_id=t->id; t->updated=(long)time(NULL); focus_task(t); } - else current_id=-1; + + for (i = 0; i < ntasks; i++) + if (strcmp(tasks[i].status, "todo") == 0) + return &tasks[i]; + return NULL; } -static int cmd_tasks_locked(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx){ - (void)ctx; host_ref=h; ensure_dir(); load_tasks(); - if(!args||!*args||strcmp(args,"ls")==0||strcmp(args,"list")==0) return tool_list_locked(NULL,out,NULL); - if(strncmp(args,"add ",4)==0){ - struct sp_buf a; if(sp_buf_init(&a)!=0) return -1; - sp_buf_printf(&a,"{\"description\":\"%s\"}", args+4); - { int rc=tool_add_locked(a.p,out,NULL); sp_buf_free(&a); return rc; } - } - if(strncmp(args,"work",4)==0){ - const char *p=args+4; while(*p==' ') p++; - if(strcmp(p,"all")==0){ - struct ptask *t=next_todo(); - if(!t) return sp_buf_puts(out,"no todo tasks left\n"); - mark_doing(t); save_tasks(); publish_widget(); - return sp_buf_printf(out,"working all: started with #%d [%s] %s\n(complete it, then /tasks choose/next)\n", t->id,t->status,t->desc); - } - if(*p){ - int id=atoi(p); struct ptask *t=find_task(id); - if(!t) return sp_buf_printf(out,"no task #%d\n", id); - mark_doing(t); save_tasks(); publish_widget(); - return sp_buf_printf(out,"working on #%d: %s\n(goal/focus set; avoid drift)\n", t->id, t->desc); - } - } - if(strcmp(args,"choose")==0||strcmp(args,"next")==0){ - struct ptask *t=next_todo(); - if(!t) return sp_buf_puts(out,"no todo tasks\n"); - mark_doing(t); save_tasks(); publish_widget(); - return sp_buf_printf(out,"chose #%d: %s\n", t->id, t->desc); - } - if(strncmp(args,"done",4)==0){ - int id=current_id; const char *p=args+4; while(*p==' ') p++; if(*p) id=atoi(p); - struct ptask *t=find_task(id); - if(!t) return sp_buf_puts(out,"no current/task to mark done\n"); - snprintf(t->status,sizeof(t->status),"done"); t->updated=(long)time(NULL); - if(current_id==id) current_id=-1; - save_tasks(); publish_widget(); - return sp_buf_printf(out,"task #%d done\n", id); - } - if(strncmp(args,"wait",4)==0 || strncmp(args,"quota",5)==0){ - const char *p = args + (args[0]=='q'?5:4); - int id = 0; - char ra[64], ra2[64]; - ra[0]='\0'; ra2[0]='\0'; - while(*p==' ') p++; - id = atoi(p); - while(*p && *p!=' ') p++; - while(*p==' ') p++; - if(*p) { - size_t n=0; - while(*p && *p!=' ' && n+1status,sizeof(t->status),"waiting_quota"); - snprintf(t->run_after,sizeof(t->run_after),"%.63s",ra2); - if(*p) snprintf(t->note,sizeof(t->note),"%.200s",p); - else snprintf(t->note,sizeof(t->note),"quota wait (auto-scheduled)"); - t->updated=(long)time(NULL); - if(current_id==id) current_id=-1; - save_tasks(); publish_widget(); - return sp_buf_printf(out,"task #%d waiting_quota run_after=%s (auto-scheduled)\n", id, t->run_after); - } - } - return sp_buf_puts(out,"usage: /tasks [ls|add |work |work all|choose|next|done [id]|wait <+secs|epoch> [note]]\n"); +static int +valid_state(const char *s) +{ + size_t i; + + for (i = 0; states[i] != NULL; i++) + if (strcmp(states[i], s) == 0) + return 1; + return 0; } -static int tick_locked(struct sp_host *h, const char *name, void *c){ - long now = (long)time(NULL); size_t i; int changed=0; - (void)name;(void)c; host_ref=h; ensure_dir(); load_tasks(); - for(i=0;istatus,"waiting_quota")==0 && t->run_after[0]){ - long ra = strtol(t->run_after,NULL,10); - if(ra>0 && now >= ra){ - snprintf(t->status,sizeof(t->status),"todo"); - snprintf(t->note,sizeof(t->note),"quota ready, auto-scheduled"); - t->run_after[0]='\0'; t->updated=now; changed=1; - } - } +/* "+90" is ninety seconds from now; anything else is taken as written. */ +static void +when(const char *in, char *out, size_t len) +{ + out[0] = '\0'; + if (in == NULL || in[0] == '\0') + return; + if (in[0] == '+') { + long d = strtol(in + 1, NULL, 10); + + if (d <= 0) + d = 3600; + snprintf(out, len, "%ld", (long)time(NULL) + d); + return; } - if(changed) save_tasks(); - publish_widget(); return 0; + snprintf(out, len, "%s", in); +} + +static void +widget(void) +{ + char b[256]; + size_t i; + int todo = 0, doing = 0, done = 0; + + for (i = 0; i < ntasks; i++) { + if (strcmp(tasks[i].status, "todo") == 0) + todo++; + else if (strcmp(tasks[i].status, "doing") == 0) + doing++; + else if (strcmp(tasks[i].status, "done") == 0) + done++; + } + if (current_id > 0) + snprintf(b, sizeof(b), "plan: #%d active | todo %d doing %d " + "done %d", current_id, todo, doing, done); + else + snprintf(b, sizeof(b), "plan: %zu tasks | todo %d doing %d " + "done %d", ntasks, todo, doing, done); + sp_host_widget_text(host_ref, "plan", b); +} + +/* One task is "doing" at a time; its text becomes the session goal. */ +static void +start(struct task *t) +{ + size_t i; + struct sp_buf ignored; + + for (i = 0; i < ntasks; i++) + if (strcmp(tasks[i].status, "doing") == 0) + copy_str(tasks[i].status, STATUS_LEN, "todo"); + copy_str(t->status, STATUS_LEN, "doing"); + t->updated = (long)time(NULL); + current_id = t->id; + if (sp_buf_init(&ignored) == 0) { + (void)sp_host_command(host_ref, "goal", t->desc, &ignored); + sp_buf_free(&ignored); + } +} + +static void +changed(void) +{ + save(); + widget(); +} + +/* ------------------------------------------------------------ operations */ + +static int +op_add(const char *desc, const char *run_after, struct sp_buf *out) +{ + struct task *t; + + if (desc == NULL || desc[0] == '\0') + return sp_buf_puts(out, "error: description required\n"); + if (ntasks >= MAX_TASKS) + return sp_buf_printf(out, "error: the plan holds %d tasks\n", + MAX_TASKS); + t = &tasks[ntasks++]; + memset(t, 0, sizeof(*t)); + t->id = next_id++; + copy_str(t->status, sizeof(t->status), "todo"); + copy_str(t->desc, sizeof(t->desc), desc); + when(run_after, t->run_after, sizeof(t->run_after)); + t->created = t->updated = (long)time(NULL); + changed(); + return sp_buf_printf(out, "added plan task #%d: %s\n", t->id, t->desc); +} + +static int +op_list(struct sp_buf *out) +{ + size_t i; + + if (ntasks == 0) + return sp_buf_puts(out, "(no plan tasks) use plan_task_add\n"); + sp_buf_puts(out, "plan tasks:\n"); + for (i = 0; i < ntasks; i++) { + const struct task *t = &tasks[i]; + + sp_buf_printf(out, " #%d [%s]%s %s", t->id, t->status, + t->id == current_id ? " *" : "", t->desc); + if (t->run_after[0] != '\0') + sp_buf_printf(out, " (run_after=%s)", t->run_after); + if (t->note[0] != '\0') + sp_buf_printf(out, " # %s", t->note); + sp_buf_puts(out, "\n"); + } + return sp_buf_puts(out, "use /tasks work | work all | next\n"); +} + +static int +op_done(int id, struct sp_buf *out) +{ + struct task *t = find(id); + + if (t == NULL) + return sp_buf_puts(out, "no current task to mark done\n"); + copy_str(t->status, sizeof(t->status), "done"); + t->updated = (long)time(NULL); + if (current_id == id) + current_id = -1; + changed(); + return sp_buf_printf(out, "task #%d done\n", id); +} + +/* Park a task until a time: the delegate does this when a quota runs out. */ +static int +op_wait(int id, const char *at, const char *note, struct sp_buf *out) +{ + struct task *t = find(id); + + if (t == NULL) + return sp_buf_printf(out, "no task #%d\n", id); + if (at != NULL && at[0] != '\0') + when(at, t->run_after, sizeof(t->run_after)); + else + when("+3600", t->run_after, sizeof(t->run_after)); + copy_str(t->status, sizeof(t->status), "waiting_quota"); + copy_str(t->note, sizeof(t->note), + note != NULL && note[0] != '\0' ? note : "quota wait"); + t->updated = (long)time(NULL); + if (current_id == id) + current_id = -1; + changed(); + return sp_buf_printf(out, "task #%d waiting_quota run_after=%s\n", id, + t->run_after); +} + +/* ----------------------------------------------------------------- tools */ + +static int +arg_id(const mcp_json *a, const char *key) +{ + const char *s = mcp_arg_string(a, key); + + return s != NULL ? atoi(s) : mcp_arg_int(a, key, 0); } static int tool_add(const char *args, struct sp_buf *out, void *ctx) { - int rc; + mcp_json *a; + const char *desc; + int rc; - PLAN_LOCK(); - rc = tool_add_locked(args, out, ctx); - PLAN_UNLOCK(); + (void)ctx; + if ((a = mcp_parse(args != NULL ? args : "{}")) == NULL) + return sp_buf_puts(out, "error: arguments are not JSON\n"); + desc = mcp_arg_string(a, "description"); + pthread_mutex_lock(&lock); + load(); + rc = op_add(desc, mcp_arg_string(a, "run_after"), out); + pthread_mutex_unlock(&lock); + mcp_json_free(a); return rc; } @@ -366,56 +398,232 @@ tool_list(const char *args, struct sp_buf *out, void *ctx) { int rc; - PLAN_LOCK(); - rc = tool_list_locked(args, out, ctx); - PLAN_UNLOCK(); + (void)args; + (void)ctx; + pthread_mutex_lock(&lock); + load(); + rc = op_list(out); + pthread_mutex_unlock(&lock); return rc; } static int tool_update(const char *args, struct sp_buf *out, void *ctx) { - int rc; + mcp_json *a; + struct task *t; + const char *s; + int id; - PLAN_LOCK(); - rc = tool_update_locked(args, out, ctx); - PLAN_UNLOCK(); - return rc; -} - -static int -cmd_tasks(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx) -{ - int rc; - - PLAN_LOCK(); - rc = cmd_tasks_locked(h, args, out, ctx); - PLAN_UNLOCK(); - return rc; -} - -static int -tick(struct sp_host *h, const char *name, void *c) -{ - int rc; - - PLAN_LOCK(); - rc = tick_locked(h, name, c); - PLAN_UNLOCK(); - return rc; -} - -static const struct sp_tool t_add = {"plan_task_add","Add a persistent session plan task (distinct from background jobs). Args: description, optional run_after(unix ts for quota/auto-schedule).","{\"type\":\"object\",\"properties\":{\"description\":{\"type\":\"string\"},\"run_after\":{\"type\":\"string\"}},\"required\":[\"description\"]}", SP_AUTH_MUTATE, tool_add, NULL}; -static const struct sp_tool t_list = {"plan_task_list","List persistent session plan tasks (/tasks).","{\"type\":\"object\",\"properties\":{}}", SP_AUTH_READ, tool_list, NULL}; -static const struct sp_tool t_upd = {"plan_task_update","Update a session plan task. Args: id, status(todo|doing|done|blocked|waiting_quota), description, run_after, note.","{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"},\"status\":{\"type\":\"string\"},\"description\":{\"type\":\"string\"},\"run_after\":{\"type\":\"string\"},\"note\":{\"type\":\"string\"}},\"required\":[\"id\"]}", SP_AUTH_MUTATE, tool_update, NULL}; -static const struct sp_widget w = {"plan", tick, NULL, NULL, 5000}; - -static int init(struct sp_host *h){ - host_ref=h; ensure_dir(); load_tasks(); publish_widget(); - sp_host_add_tool(h,&t_add); sp_host_add_tool(h,&t_list); sp_host_add_tool(h,&t_upd); - sp_host_add_command(h,"tasks",cmd_tasks,NULL); - sp_host_add_widget(h,&w); + (void)ctx; + if ((a = mcp_parse(args != NULL ? args : "{}")) == NULL) + return sp_buf_puts(out, "error: arguments are not JSON\n"); + id = arg_id(a, "id"); + pthread_mutex_lock(&lock); + load(); + if (id <= 0 || (t = find(id)) == NULL) { + sp_buf_printf(out, id <= 0 ? "error: id required\n" : + "error: no task #%d\n", id); + goto out; + } + if ((s = mcp_arg_string(a, "status")) != NULL && s[0] != '\0') { + if (!valid_state(s)) { + sp_buf_printf(out, "error: status is one of todo, " + "doing, done, blocked, waiting_quota, not '%s'\n", s); + goto out; + } + if (strcmp(s, "doing") == 0) + start(t); + else { + copy_str(t->status, sizeof(t->status), s); + if (current_id == t->id) + current_id = -1; + } + } + if ((s = mcp_arg_string(a, "description")) != NULL && s[0] != '\0') + copy_str(t->desc, sizeof(t->desc), s); + if (mcp_arg(a, "run_after") != NULL) /* present but empty: clear it */ + when(mcp_arg_string(a, "run_after"), t->run_after, + sizeof(t->run_after)); + if ((s = mcp_arg_string(a, "note")) != NULL && s[0] != '\0') + copy_str(t->note, sizeof(t->note), s); + t->updated = (long)time(NULL); + changed(); + sp_buf_printf(out, "task #%d -> [%s] %s\n", t->id, t->status, t->desc); +out: + pthread_mutex_unlock(&lock); + mcp_json_free(a); return 0; } -static const struct sp_plugin plugin = {SP_PLUGIN_ABI,"planner","0.1",init,NULL,NULL}; -const struct sp_plugin *sp_plugin_describe(void){ return &plugin; } + +/* --------------------------------------------------------------- command */ + +static const char * +skip(const char *s) +{ + while (*s == ' ') + s++; + return s; +} + +static int +command_locked(const char *args, struct sp_buf *out) +{ + const char *p; + struct task *t; + + if (args == NULL || args[0] == '\0' || strcmp(args, "ls") == 0 || + strcmp(args, "list") == 0) + return op_list(out); + if (strncmp(args, "add ", 4) == 0) + return op_add(skip(args + 4), NULL, out); + if (strncmp(args, "work", 4) == 0) { + p = skip(args + 4); + if (strcmp(p, "all") == 0) { + if ((t = first_todo()) == NULL) + return sp_buf_puts(out, "no todo tasks left\n"); + } else if (*p != '\0') { + if ((t = find(atoi(p))) == NULL) + return sp_buf_printf(out, "no task #%d\n", + atoi(p)); + } else + return sp_buf_puts(out, "usage: /tasks work |all\n"); + start(t); + changed(); + return sp_buf_printf(out, "working on #%d: %s\n", t->id, + t->desc); + } + if (strcmp(args, "choose") == 0 || strcmp(args, "next") == 0) { + if ((t = first_todo()) == NULL) + return sp_buf_puts(out, "no todo tasks\n"); + start(t); + changed(); + return sp_buf_printf(out, "chose #%d: %s\n", t->id, t->desc); + } + if (strncmp(args, "done", 4) == 0) { + p = skip(args + 4); + return op_done(*p != '\0' ? atoi(p) : current_id, out); + } + if (strncmp(args, "wait", 4) == 0) { + char at[WHEN_LEN]; + int id; + size_t n = 0; + + p = skip(args + 4); + id = atoi(p); + while (*p != '\0' && *p != ' ') + p++; + p = skip(p); + while (*p != '\0' && *p != ' ' && n + 1 < sizeof(at)) + at[n++] = *p++; + at[n] = '\0'; + return op_wait(id, at, skip(p), out); + } + return sp_buf_puts(out, "usage: /tasks [ls|add |work |work all" + "|next|done [id]|wait <+secs|epoch> [note]]\n"); +} + +static int +command(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx) +{ + int rc; + + (void)ctx; + host_ref = h; + pthread_mutex_lock(&lock); + load(); + rc = command_locked(args, out); + pthread_mutex_unlock(&lock); + return rc; +} + +/* The clock: a parked task whose time has come is todo again. */ +static int +tick(struct sp_host *h, const char *name, void *ctx) +{ + long now = (long)time(NULL); + size_t i; + int moved = 0; + + (void)name; + (void)ctx; + host_ref = h; + pthread_mutex_lock(&lock); + load(); + for (i = 0; i < ntasks; i++) { + struct task *t = &tasks[i]; + long at = strtol(t->run_after, NULL, 10); + + if (strcmp(t->status, "waiting_quota") != 0 || at <= 0 || + now < at) + continue; + copy_str(t->status, sizeof(t->status), "todo"); + copy_str(t->note, sizeof(t->note), "quota is back"); + t->run_after[0] = '\0'; + t->updated = now; + moved = 1; + } + if (moved) + save(); + widget(); + pthread_mutex_unlock(&lock); + return 0; +} + +static const struct sp_tool t_add = { + "plan_task_add", + "Add a task to the session's plan: a sentence to do, not a process " + "(use task_start for shell commands). Optional run_after is a unix " + "time, or +seconds from now.", + "{\"type\":\"object\",\"properties\":{\"description\":{\"type\":" + "\"string\"},\"run_after\":{\"type\":\"string\"}},\"required\":" + "[\"description\"]}", + SP_AUTH_MUTATE, tool_add, NULL +}; + +static const struct sp_tool t_list = { + "plan_task_list", + "List the session's plan with state; the one marked * is active.", + "{\"type\":\"object\",\"properties\":{}}", + SP_AUTH_READ, tool_list, NULL +}; + +static const struct sp_tool t_update = { + "plan_task_update", + "Change a plan task. status is todo, doing, done, blocked or " + "waiting_quota; doing makes it the session goal. An empty run_after " + "clears the wait.", + "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"}," + "\"status\":{\"type\":\"string\"},\"description\":{\"type\":\"string\"}," + "\"run_after\":{\"type\":\"string\"},\"note\":{\"type\":\"string\"}}," + "\"required\":[\"id\"]}", + SP_AUTH_MUTATE, tool_update, NULL +}; + +static const struct sp_widget plan_widget = { "plan", tick, NULL, NULL, 5000 }; + +static int +init(struct sp_host *h) +{ + host_ref = h; + pthread_mutex_lock(&lock); + load(); + widget(); + pthread_mutex_unlock(&lock); + sp_host_add_tool(h, &t_add); + sp_host_add_tool(h, &t_list); + sp_host_add_tool(h, &t_update); + sp_host_add_command(h, "tasks", command, NULL); + sp_host_add_widget(h, &plan_widget); + return 0; +} + +static const struct sp_plugin plugin = { + SP_PLUGIN_ABI, "planner", "0.2", init, NULL, NULL +}; + +const struct sp_plugin * +sp_plugin_describe(void) +{ + return &plugin; +} diff --git a/plugins/tmux/tmux.c b/plugins/tmux/tmux.c index 1ffec9c..ffaad36 100644 --- a/plugins/tmux/tmux.c +++ b/plugins/tmux/tmux.c @@ -1,377 +1,826 @@ /* - * tmux proxy plugin: drives a CLI tool in an underlying tmux session. - * - init checks `tmux` is installed; refuses to load if not. - * - background watcher process detects new pane output and extracts/appends deltas - * to /tmux_watch.log (no fixed sleep in ask; ask waits on the feed). - * Commands: /tmux start |attach |send |keys |capture [n]|ask |read [wait_ms]|watch start|stop|status|stop - * Tools: tmux_start, tmux_send, tmux_capture, tmux_read, tmux_ask, tmux_status, tmux_watch + * splinter -- drive a program that wants a terminal, through tmux. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * Some programs cannot be run with `run`: a REPL, an installer that asks + * questions, another agent's TUI. They need a terminal. tmux gives them one, + * detached, and gives splinter two things back: what is on the pane + * (capture-pane) and a way to type into it (send-keys). + * + * The tools: + * + * tmux_start cmd, name? start cmd in a detached session; it is the target + * tmux_send text? keys? type text and Enter, and/or named keys (C-c, Up) + * tmux_ask text, wait_ms? send, then wait until the pane has new output and + * quiet_ms? has been quiet for quiet_ms; return only the new lines + * tmux_read wait_ms? the lines that are new since the last read + * tmux_capture lines? the pane as it is, newest lines + * tmux_status the target, and whether it is alive + * + * "New" is a diff of two captures, kept in memory: there is no helper process, + * no pid file and nothing left behind when splinter exits. A pane is a screen, + * not a stream, so the diff finds where the old capture ends inside the new one + * (output scrolls up) and returns what follows; a program that repaints the + * whole screen gives the lines that changed at the bottom, or, when the old + * capture cannot be found at all, the last SHOWN_MAX lines. + * + * Starting a session runs a shell command, so tmux_start is destructive, and + * typing into a terminal is whatever that terminal does: tmux_send and + * tmux_ask are mutating. */ -#define _DEFAULT_SOURCE -#define _POSIX_C_SOURCE 200809L +#include #include #include #include #include #include #include -#include -#include #include #include #include #include "splinter.h" +#include "mcp.h" #include "splinter_plugin.h" -static struct sp_host *host_ref; -static char target[128]; -static char sess_dir[512]; +#define NAME_MAX_LEN 64 +#define HISTORY 500 /* lines of scrollback looked at */ +#define SHOWN_MAX 200 /* lines handed to the model at once */ +#define POLL_MS 200 +#define WAIT_DEFAULT 15000 +#define WAIT_CAP 120000 +#define QUIET_DEFAULT 1200 -static int have_tmux(void){ - char *a[]={"tmux","-V",NULL}; struct sp_buf o; int rc; - if(sp_buf_init(&o)!=0) return 0; - { int p[2]; pid_t pid; int st=0; char b[64]; ssize_t n; - if(pipe(p)!=0){ sp_buf_free(&o); return 0; } - pid=fork(); - if(pid==0){ dup2(p[1],1); dup2(p[1],2); close(p[0]); close(p[1]); execvp("tmux",a); _exit(127); } - close(p[1]); while((n=read(p[0],b,sizeof(b)))>0) sp_buf_add(&o,b,(size_t)n); close(p[0]); waitpid(pid,&st,0); - rc = (WIFEXITED(st) && WEXITSTATUS(st)==0); - } - sp_buf_free(&o); return rc; -} +static struct sp_host *host_ref; +static char target[NAME_MAX_LEN * 2]; +static char *last; /* the previous capture */ -static void ensure_sess(void){ const char *d=sp_host_session_dir(host_ref); if(d&&*d) snprintf(sess_dir,sizeof(sess_dir),"%s",d); } -static void spath(const char *name, char *out, size_t cap){ ensure_sess(); if(sess_dir[0]) snprintf(out,cap,"%s/%s",sess_dir,name); else snprintf(out,cap,"/tmp/splinter-%s",name); } -static void state_path(char *out,size_t cap){ spath("tmux_target",out,cap); } -static void feed_path(char *out,size_t cap){ spath("tmux_watch.log",out,cap); } -static void wpid_path(char *out,size_t cap){ spath("tmux_watch.pid",out,cap); } +/* ---------------------------------------------------------------- tmux */ -static void save_target(void){ char p[600]; FILE *f; state_path(p,sizeof(p)); f=fopen(p,"w"); if(f){ fprintf(f,"%s\n",target); fclose(f);} } -static void load_target(void){ char p[600]; FILE *f; target[0]='\0'; state_path(p,sizeof(p)); f=fopen(p,"r"); if(f){ if(fgets(target,sizeof(target),f)){ size_t n=strlen(target); while(n&&(target[n-1]=='\n'||target[n-1]=='\r')) target[--n]='\0'; } fclose(f);} } +/* + * Run argv, collect stdout and stderr. The child does nothing between fork and + * exec but dup2 and close, which is all a forked child of a threaded process may + * safely do. + */ +static int +run(char *const argv[], struct sp_buf *out) +{ + int fd[2], st = 0; + char buf[4096]; + ssize_t n; + pid_t pid; -static int run_argv(char *const argv[], struct sp_buf *out){ - int pfd[2]; pid_t pid; char buf[4096]; ssize_t n; int st=0; - if(pipe(pfd)!=0) return -1; - pid=fork(); - if(pid<0){ close(pfd[0]); close(pfd[1]); return -1; } - if(pid==0){ dup2(pfd[1],1); dup2(pfd[1],2); close(pfd[0]); close(pfd[1]); execvp(argv[0],argv); _exit(127); } - close(pfd[1]); while((n=read(pfd[0],buf,sizeof(buf)))>0) sp_buf_add(out,buf,(size_t)n); close(pfd[0]); - waitpid(pid,&st,0); return WIFEXITED(st)?WEXITSTATUS(st):-1; -} - -static int tmux_capture_n(const char *tgt, int lines, struct sp_buf *out){ - char sarg[32]; snprintf(sarg,sizeof(sarg),"-%d", lines>0?lines:300); - { char *a[]={"tmux","capture-pane","-t",(char*)tgt,"-p","-S",sarg,NULL}; return run_argv(a,out); } -} -static int tmux_has_session(const char *name){ - char nm[128],*dot; char *a[]={"tmux","has-session","-t",nm,NULL}; struct sp_buf o; int rc; - snprintf(nm,sizeof(nm),"%.120s",name); dot=strchr(nm,':'); if(dot)*dot='\0'; - if(sp_buf_init(&o)!=0) return 0; - rc=run_argv(a,&o); sp_buf_free(&o); return rc==0; -} -static int tmux_send_lit(const char *tgt, const char *text, struct sp_buf *out){ - char *a1[]={"tmux","send-keys","-t",(char*)tgt,"-l","--",(char*)text,NULL}; - char *a2[]={"tmux","send-keys","-t",(char*)tgt,"Enter",NULL}; - int rc=run_argv(a1,out); if(rc==0) rc=run_argv(a2,out); return rc; -} - -/* delta: bytes in neu after the longest common prefix with old (simple, robust enough) */ -static void extract_delta(const char *old, const char *neu, struct sp_buf *out){ - size_t i=0; size_t ol=old?strlen(old):0, nl=neu?strlen(neu):0; - while(i
    0 && kill(pid,0)==0) return pid; } - return -1; -} - -/* watcher child: polls capture-pane, detects new output, appends delta to feed */ -static void watcher_loop(const char *tgt, const char *sd){ - char prev[65536]; size_t prevn=0; char fp[600], sp[600], pp[600]; - prev[0]='\0'; - snprintf(fp,sizeof(fp),"%s/tmux_watch.log",sd); - snprintf(pp,sizeof(pp),"%s/tmux_watch.pid",sd); - snprintf(sp,sizeof(sp),"%s/tmux_watch.state",sd); - { FILE *f=fopen(pp,"w"); if(f){ fprintf(f,"%d\n",(int)getpid()); fclose(f);} } - /* seed prev from current pane so we don't dump history */ - { - struct sp_buf o; if(sp_buf_init(&o)==0){ tmux_capture_n(tgt,300,&o); if(o.p){ size_t n=o.len; if(n>=sizeof(prev)) n=sizeof(prev)-1; memcpy(prev,o.p,n); prev[n]='\0'; prevn=n; } sp_buf_free(&o); } - } - for(;;){ - struct sp_buf cur, d; struct timespec ts; - ts.tv_sec=0; ts.tv_nsec=300*1000*1000; nanosleep(&ts,NULL); - if(!tmux_has_session(tgt)) continue; - if(sp_buf_init(&cur)!=0||sp_buf_init(&d)!=0){ if(cur.p) sp_buf_free(&cur); continue; } - tmux_capture_n(tgt,300,&cur); - if(cur.p && (prevn!=cur.len || memcmp(prev,cur.p, cur.len0){ - FILE *f=fopen(fp,"a"); - if(f){ - /* marker helps consumers; also write raw delta */ - fwrite(d.p,1,d.len,f); - if(d.len==0 || ((char*)d.p)[d.len-1]!='\n') fputc('\n',f); - fflush(f); fclose(f); - } - } - { size_t n=cur.len; if(n>=sizeof(prev)) n=sizeof(prev)-1; memcpy(prev,cur.p,n); prev[n]='\0'; prevn=n; } - { FILE *f=fopen(sp,"w"); if(f){ fprintf(f,"%ld %zu\n",(long)time(NULL),prevn); fclose(f);} } - } - sp_buf_free(&cur); sp_buf_free(&d); - } -} - -static int watcher_start(struct sp_buf *out){ - pid_t pid; char p[600]; - load_target(); ensure_sess(); - if(!target[0]) return sp_buf_puts(out,"error: no tmux target\n"); - if(!sess_dir[0]) return sp_buf_puts(out,"error: no session dir\n"); - if(watcher_pid()>0) return sp_buf_printf(out,"watcher already running (pid %d) for %s\n",(int)watcher_pid(),target); - /* clear feed for a fresh watch session? keep; append is fine */ - pid=fork(); - if(pid<0) return sp_buf_puts(out,"error: fork failed\n"); - if(pid==0){ - /* detach */ - setsid(); - { int fd=open("/dev/null",O_RDWR); if(fd>=0){ dup2(fd,0); dup2(fd,1); dup2(fd,2); if(fd>2) close(fd);} } - watcher_loop(target, sess_dir); - _exit(0); - } - wpid_path(p,sizeof(p)); - sp_buf_printf(out,"watcher started (pid %d) for %s -> %s/tmux_watch.log\n",(int)pid,target,sess_dir); - return 0; -} -static int watcher_stop(struct sp_buf *out){ - pid_t pid=watcher_pid(); char p[600]; - if(pid<=0){ sp_buf_puts(out,"watcher not running\n"); } - else { - kill(pid,SIGTERM); - sp_buf_printf(out,"watcher stopped (pid %d)\n",(int)pid); - } - wpid_path(p,sizeof(p)); unlink(p); - return 0; -} - -/* read new extracted content from watcher feed. offset tracked in tmux_watch.off */ -static long read_off(void){ char p[600],b[64]; FILE *f; long o=0; spath("tmux_watch.off",p,sizeof(p)); f=fopen(p,"r"); if(f){ if(fgets(b,sizeof(b),f)) o=strtol(b,NULL,10); fclose(f);} return o; } -static void write_off(long o){ char p[600]; FILE *f; spath("tmux_watch.off",p,sizeof(p)); f=fopen(p,"w"); if(f){ fprintf(f,"%ld\n",o); fclose(f);} } - -static int tool_read(const char *args, struct sp_buf *out, void *ctx){ - char fp[600]; FILE *f; long off, sz; int wait_ms=0; long start; struct timespec t0; - (void)ctx; ensure_sess(); feed_path(fp,sizeof(fp)); - if(args && strstr(args,"\"wait_ms\"")){ const char *p=strstr(args,"\"wait_ms\""); p=strchr(p,':'); - if(p) wait_ms=atoi(p+1); - } - clock_gettime(CLOCK_MONOTONIC,&t0); start=t0.tv_sec*1000+t0.tv_nsec/1000000; - off=read_off(); sz=file_size(fp); - while(sz<=off && wait_ms>0){ - struct timespec ts; long now; - ts.tv_sec=0; ts.tv_nsec=200*1000*1000; nanosleep(&ts,NULL); - clock_gettime(CLOCK_MONOTONIC,&t0); now=t0.tv_sec*1000+t0.tv_nsec/1000000; - if(now-start >= wait_ms) break; - sz=file_size(fp); - } - if(sz<=off) return sp_buf_puts(out,"(no new watcher output)\n"); - f=fopen(fp,"r"); if(!f) return sp_buf_puts(out,"(no feed)\n"); - fseek(f,off,SEEK_SET); - { - char buf[4096]; size_t n; size_t total=0; - sp_buf_puts(out,"[tmux watcher output]\n"); - while((n=fread(buf,1,sizeof(buf),f))>0){ sp_buf_add(out,buf,n); total+=n; } - write_off(off+(long)total); - } - fclose(f); - return 0; -} - -static int tool_send(const char *args, struct sp_buf *out, void *ctx){ - char text[4096]; const char *p,*e; size_t n=0; - (void)ctx; load_target(); - if(!target[0]) return sp_buf_puts(out,"error: no tmux target\n"); - text[0]='\0'; - if(args){ - p=strstr(args,"\"text\""); if(!p) p=strstr(args,"\"input\""); - if(p){ p=strchr(p,':'); if(p) p=strchr(p,'"'); if(p){ p++; e=p; while(*e && !(*e=='"'&&e[-1]!='\\') && n+1120?"...":""); - return 0; -} - -static int tool_capture(const char *args, struct sp_buf *out, void *ctx){ - int lines=200; const char *p; - (void)ctx; load_target(); - if(!target[0]) return sp_buf_puts(out,"error: no tmux target\n"); - if(args){ p=strstr(args,"\"lines\""); if(p){ p=strchr(p,':'); - if(p) lines=atoi(p+1); - } - } - if(lines<=0||lines>5000) lines=200; - sp_buf_printf(out,"[tmux pane %s last %d]\n",target,lines); - tmux_capture_n(target,lines,out); - return 0; -} - -static int tool_ask(const char *args, struct sp_buf *out, void *ctx){ - /* proxy: send, then wait for watcher feed (background process extracts) */ - char text[4096]; const char *p,*e; size_t n=0; int wait_ms=15000, quiet_ms=1200; - long base_off, last_sz, last_change, start; struct timespec t0; - char fp[600]; - (void)ctx; load_target(); ensure_sess(); feed_path(fp,sizeof(fp)); - if(!target[0]) return sp_buf_puts(out,"error: no tmux target\n"); - if(watcher_pid()<=0){ sp_buf_puts(out,"(starting watcher...)\n"); watcher_start(out); } - text[0]='\0'; - if(args){ - p=strstr(args,"\"wait_ms\""); if(p){ p=strchr(p,':'); - if(p) wait_ms=atoi(p+1);} - p=strstr(args,"\"quiet_ms\""); if(p){ p=strchr(p,':'); - if(p) quiet_ms=atoi(p+1);} - p=strstr(args,"\"text\""); if(!p) p=strstr(args,"\"input\""); - if(p){ p=strchr(p,':'); if(p) p=strchr(p,'"'); if(p){ p++; e=p; while(*e && !(*e=='"'&&e[-1]!='\\') && n+1 %s] %.120s%s\n", target, text, strlen(text)>120?"...":""); - base_off = file_size(fp); /* consume from here */ - tmux_send_lit(target,text,out); - sp_buf_puts(out,"[waiting on watcher for new output...]\n"); - clock_gettime(CLOCK_MONOTONIC,&t0); start=t0.tv_sec*1000+t0.tv_nsec/1000000; last_change=start; last_sz=base_off; - while(1){ - struct timespec ts; long now, sz; - ts.tv_sec=0; ts.tv_nsec=200*1000*1000; nanosleep(&ts,NULL); - clock_gettime(CLOCK_MONOTONIC,&t0); now=t0.tv_sec*1000+t0.tv_nsec/1000000; - sz=file_size(fp); - if(sz>last_sz){ last_sz=sz; last_change=now; } - if(last_sz>base_off && (now-last_change)>=quiet_ms) break; /* stable new output */ - if((now-start)>=wait_ms) break; - } - if(last_sz>base_off){ - FILE *f=fopen(fp,"r"); - if(f){ - char buf[4096]; size_t nr; - fseek(f,base_off,SEEK_SET); - sp_buf_puts(out,"\n--- watcher extracted (new) ---\n"); - while((nr=fread(buf,1,sizeof(buf),f))>0) sp_buf_add(out,buf,nr); - fclose(f); - write_off(last_sz); - } - } else { - sp_buf_puts(out,"(timeout: no new watcher output; /tmux capture to inspect pane)\n"); - } - return 0; -} - -static int tool_start(const char *args, struct sp_buf *out, void *ctx){ - char cmd[1024], name[64]; const char *p,*e; size_t n=0; struct sp_buf o; - (void)ctx; cmd[0]='\0'; name[0]='\0'; - if(args){ - p=strstr(args,"\"cmd\""); if(!p) p=strstr(args,"\"command\""); - if(p){ p=strchr(p,':'); if(p){ p=strchr(p,'"'); if(p){ p++; e=p; while(*e && !(*e=='"'&&e[-1]!='\\') && n+10?"running":"stopped",(int)pid,target); return 0; } - return watcher_start(out); -} - -static int tool_status(const char *args, struct sp_buf *out, void *ctx){ - (void)args;(void)ctx; load_target(); - sp_buf_printf(out,"tmux target: %s\n", target[0]?target:"(none)"); - sp_buf_printf(out,"tmux installed: %s, watcher: %s (pid %d)\n", have_tmux()?"yes":"no", watcher_pid()>0?"running":"stopped",(int)watcher_pid()); - return 0; -} - -static int cmd_tmux(struct sp_host *h, const char *args, struct sp_buf *out, void *vctx){ - (void)vctx; host_ref=h; load_target(); - if(!args||!*args||strcmp(args,"status")==0) return tool_status(NULL,out,NULL); - if(strncmp(args,"attach ",7)==0){ const char *t=args+7; while(*t==' ') t++; snprintf(target,sizeof(target),"%.120s",t); save_target(); sp_buf_printf(out,"target=%s\n",target); watcher_start(out); return 0; } - if(strncmp(args,"start ",6)==0){ struct sp_buf a; char esc[1200]; size_t i,j=0; const char *c=args+6; while(*c==' ') c++; for(i=0;c[i]&&j+2|attach |send |keys |capture [n]|read [wait_ms]|ask |watch [start|stop|status]|status|stop\n watcher: background process detects new text & extracts to feed; ask waits on feed (no fixed sleep)\n"); -} - -static int tick(struct sp_host *h, const char *name, void *ctx){ - (void)name;(void)ctx; host_ref=h; load_target(); - { char b[128]; if(target[0]) snprintf(b,sizeof(b),"tmux:%.100s %s", target, watcher_pid()>0?"[watch]":"[no-watch]"); else snprintf(b,sizeof(b),"tmux:-"); sp_host_widget_text(h,"tmux",b); } - return 0; -} - -static const struct sp_tool Tstatus={"tmux_status","tmux proxy target+watcher status.","{\"type\":\"object\",\"properties\":{}}",SP_AUTH_READ,tool_status,NULL}; -static const struct sp_tool Tcap ={"tmux_capture","Snapshot tmux pane (direct). Args: lines.","{\"type\":\"object\",\"properties\":{\"lines\":{\"type\":\"integer\"}}}",SP_AUTH_READ,tool_capture,NULL}; -static const struct sp_tool Tread ={"tmux_read","Read NEW output extracted by the background watcher feed. Args: wait_ms (wait for new data).","{\"type\":\"object\",\"properties\":{\"wait_ms\":{\"type\":\"integer\"}}}",SP_AUTH_READ,tool_read,NULL}; -static const struct sp_tool Tsend ={"tmux_send","Send literal text+Enter to tmux target CLI.","{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"}},\"required\":[\"text\"]}",SP_AUTH_MUTATE,tool_send,NULL}; -static const struct sp_tool Task ={"tmux_ask","Proxy: send text then wait on WATCHER feed for new extracted output (quiet-stable), no fixed sleep. Args: text, wait_ms, quiet_ms.","{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"},\"wait_ms\":{\"type\":\"integer\"},\"quiet_ms\":{\"type\":\"integer\"}},\"required\":[\"text\"]}",SP_AUTH_MUTATE,tool_ask,NULL}; -static const struct sp_tool Tstart ={"tmux_start","Start cmd in detached tmux session, set target, start watcher. Args: cmd,name.","{\"type\":\"object\",\"properties\":{\"cmd\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"}},\"required\":[\"cmd\"]}",SP_AUTH_DESTRUCTIVE,tool_start,NULL}; -static const struct sp_tool Twatch ={"tmux_watch","Control background watcher process (detects/extracts new output). Args: cmd start|stop|status.","{\"type\":\"object\",\"properties\":{\"cmd\":{\"type\":\"string\"}}}",SP_AUTH_MUTATE,tool_watch,NULL}; -static const struct sp_widget W={"tmux",tick,NULL,NULL,5000}; - -static int init(struct sp_host *h){ - if(!have_tmux()){ - /* tmux not installed -> don't load plugin */ + if (pipe(fd) != 0) + return -1; + if ((pid = fork()) < 0) { + close(fd[0]); + close(fd[1]); return -1; } - host_ref=h; load_target(); - sp_host_add_tool(h,&Tstatus); sp_host_add_tool(h,&Tcap); sp_host_add_tool(h,&Tread); - sp_host_add_tool(h,&Tsend); sp_host_add_tool(h,&Task); sp_host_add_tool(h,&Tstart); sp_host_add_tool(h,&Twatch); - sp_host_add_command(h,"tmux",cmd_tmux,NULL); - sp_host_add_widget(h,&W); + if (pid == 0) { + dup2(fd[1], 1); + dup2(fd[1], 2); + close(fd[0]); + close(fd[1]); + execvp(argv[0], argv); + _exit(127); + } + close(fd[1]); + while ((n = read(fd[0], buf, sizeof(buf))) > 0 || + (n < 0 && errno == EINTR)) + if (n > 0 && out != NULL) + sp_buf_add(out, buf, (size_t)n); + close(fd[0]); + while (waitpid(pid, &st, 0) < 0 && errno == EINTR) + ; + return WIFEXITED(st) ? WEXITSTATUS(st) : -1; +} + +static int +have_tmux(void) +{ + char *const argv[] = { "tmux", "-V", NULL }; + + return run(argv, NULL) == 0; +} + +/* A name that cannot be mistaken for an option or a second target. */ +static int +safe_name(const char *s, size_t max) +{ + size_t i; + + if (s == NULL || s[0] == '\0' || s[0] == '-' || strlen(s) >= max) + return 0; + for (i = 0; s[i] != '\0'; i++) + if (!isalnum((unsigned char)s[i]) && strchr("_.-:%@", s[i]) == NULL) + return 0; + return 1; +} + +static int +alive(void) +{ + char *const argv[] = { "tmux", "has-session", "-t", target, NULL }; + + return target[0] != '\0' && run(argv, NULL) == 0; +} + +static void +target_file(char *path, size_t len) +{ + const char *dir = sp_host_session_dir(host_ref); + + if (dir != NULL && dir[0] != '\0') + snprintf(path, len, "%s/tmux_target", dir); + else + path[0] = '\0'; +} + +static void +set_target(const char *name) +{ + char path[600]; + FILE *f; + + snprintf(target, sizeof(target), "%s", name); + free(last); + last = NULL; + target_file(path, sizeof(path)); + if (path[0] != '\0' && (f = fopen(path, "w")) != NULL) { + fprintf(f, "%s\n", target); + fclose(f); + } +} + +/* A resumed session finds its terminal again. */ +static void +restore_target(void) +{ + char path[600]; + FILE *f; + + target_file(path, sizeof(path)); + if (path[0] == '\0' || (f = fopen(path, "r")) == NULL) + return; + if (fgets(target, sizeof(target), f) != NULL) + target[strcspn(target, "\n")] = '\0'; + fclose(f); + if (!safe_name(target, sizeof(target))) + target[0] = '\0'; +} + +static long +now_ms(void) +{ + struct timespec ts; + + clock_gettime(CLOCK_MONOTONIC, &ts); + return (long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} + +static void +pause_ms(long ms) +{ + struct timespec ts; + + ts.tv_sec = ms / 1000; + ts.tv_nsec = (ms % 1000) * 1000000L; + nanosleep(&ts, NULL); +} + +/* ----------------------------------------------------- capture and diff */ + +/* + * The pane with its history, joined lines, without the empty rows tmux pads + * a screen with. NULL when there is no pane. + */ +static char * +capture(int lines) +{ + struct sp_buf b; + char from[32]; + char *const argv[] = { "tmux", "capture-pane", "-p", "-J", "-t", + target, "-S", from, NULL }; + char *s; + size_t n; + + snprintf(from, sizeof(from), "-%d", lines); + if (sp_buf_init(&b) != 0) + return NULL; + if (run(argv, &b) != 0) { + sp_buf_free(&b); + return NULL; + } + n = b.len; + while (n > 0 && (b.p[n - 1] == '\n' || b.p[n - 1] == ' ')) + n--; + s = malloc(n + 1); + if (s != NULL) { + memcpy(s, b.p, n); + s[n] = '\0'; + } + sp_buf_free(&b); + return s; +} + +/* Split in place; v gets the start of every line. */ +static size_t +split(char *text, char ***v) +{ + size_t n = 0, cap = 0; + char *p = text; + + *v = NULL; + for (;;) { + char *nl; + + if (n == cap) { + char **nv = realloc(*v, (cap ? cap * 2 : 64) * sizeof(**v)); + + if (nv == NULL) { + free(*v); + *v = NULL; + return 0; + } + *v = nv; + cap = cap ? cap * 2 : 64; + } + (*v)[n++] = p; + if ((nl = strchr(p, '\n')) == NULL) + break; + *nl = '\0'; + p = nl + 1; + } + return n; +} + +/* Does b[0..k) equal a[from..from+k)? */ +static int +same_run(char **a, size_t from, char **b, size_t k) +{ + size_t i; + + for (i = 0; i < k; i++) + if (strcmp(a[from + i], b[i]) != 0) + return 0; + return 1; +} + +/* + * Where in `neu` do the lines that are new begin? The old capture is found as a + * run at the start of the new one (nothing scrolled), or as a tail of the old one + * at the start of the new one (output pushed the top off). The old last line is + * tried last and dropped, because it is the prompt or the line being edited and is + * the one most likely to differ. Returns the index of the first new line, or 0 + * when nothing of the old capture can be found. + */ +static size_t +first_new(char **old, size_t no, char **neu, size_t nn) +{ + size_t trim, s; + + for (trim = 0; trim <= 1 && trim < no; trim++) { + size_t have = no - trim; + + for (s = 0; s < have; s++) { + size_t k = have - s; + + if (k <= nn && same_run(old, s, neu, k)) + return k; + } + } return 0; } -static const struct sp_plugin plugin={SP_PLUGIN_ABI,"tmux","0.2",init,NULL,NULL}; -const struct sp_plugin *sp_plugin_describe(void){ return &plugin; } + +/* The lines of `now` that `before` did not have. */ +static void +delta(const char *before, const char *now, struct sp_buf *out) +{ + char *a = NULL, *b = NULL, **av = NULL, **bv = NULL; + size_t na = 0, nb, from, i; + + if ((b = strdup(now)) == NULL) + return; + nb = split(b, &bv); + if (before != NULL && before[0] != '\0') { + a = strdup(before); + if (a != NULL) + na = split(a, &av); + } + from = (na > 0 && bv != NULL) ? first_new(av, na, bv, nb) : 0; + if (bv != NULL && nb - from > SHOWN_MAX) { + sp_buf_printf(out, "[%zu earlier lines omitted]\n", + nb - from - SHOWN_MAX); + from = nb - SHOWN_MAX; + } + for (i = from; bv != NULL && i < nb; i++) + sp_buf_printf(out, "%s\n", bv[i]); + free(av); + free(bv); + free(a); + free(b); +} + +/* Capture, report what is new since the last capture, remember this one. */ +static int +report_new(struct sp_buf *out) +{ + char *now = capture(HISTORY); + struct sp_buf d; + + if (now == NULL) + return sp_buf_puts(out, "error: the tmux pane is gone\n"); + if (sp_buf_init(&d) != 0) { + free(now); + return -1; + } + delta(last, now, &d); + free(last); + last = now; + if (d.len == 0) + sp_buf_puts(out, "(no new output)\n"); + else + sp_buf_add(out, d.p, d.len); + sp_buf_free(&d); + return 0; +} + +/* + * Wait until the pane differs from `base`, then until it has stayed the same for + * quiet_ms, or until wait_ms is over. Returns 1 when something changed. + */ +static int +settle(const char *base, long wait_ms, long quiet_ms) +{ + long start = now_ms(), changed_at = 0; + char *prev = base != NULL ? strdup(base) : strdup(""); + int changed = 0; + + while (prev != NULL && now_ms() - start < wait_ms) { + char *cur; + + pause_ms(POLL_MS); + if ((cur = capture(HISTORY)) == NULL) + break; + if (strcmp(cur, prev) != 0) { + changed = 1; + changed_at = now_ms(); + free(prev); + prev = cur; + continue; + } + free(cur); + if (changed && now_ms() - changed_at >= quiet_ms) + break; + } + free(prev); + return changed; +} + +/* ------------------------------------------------------------ operations */ + +static int +need_target(struct sp_buf *out) +{ + if (target[0] == '\0') + return !sp_buf_puts(out, "error: no tmux target; use tmux_start " + "or /tmux attach\n"); + if (!alive()) + return !sp_buf_printf(out, "error: tmux session '%s' is gone\n", + target); + return 1; +} + +static int +op_start(const char *cmd, const char *name, struct sp_buf *out) +{ + char auto_name[NAME_MAX_LEN]; + char *const argv[] = { "tmux", "new-session", "-d", "-x", "200", "-y", + "50", "-s", auto_name, "sh", "-c", (char *)cmd, NULL }; + struct sp_buf o; + int rc; + + if (cmd == NULL || cmd[0] == '\0') + return sp_buf_puts(out, "error: cmd required\n"); + if (name == NULL || name[0] == '\0') + snprintf(auto_name, sizeof(auto_name), "splinter-%d", + (int)getpid()); + else if (!safe_name(name, sizeof(auto_name)) || strchr(name, ':') != NULL) + return sp_buf_puts(out, "error: name may use letters, digits " + "and _ . - only\n"); + else + snprintf(auto_name, sizeof(auto_name), "%s", name); + if (sp_buf_init(&o) != 0) + return -1; + snprintf(target, sizeof(target), "%s", auto_name); + if (alive()) { + set_target(auto_name); + sp_buf_free(&o); + return sp_buf_printf(out, "session %s exists, attached\n", + auto_name); + } + rc = run(argv, &o); + if (rc != 0) { + target[0] = '\0'; + sp_buf_printf(out, "error: tmux new-session failed (%d): %s", + rc, o.p != NULL ? o.p : "\n"); + sp_buf_free(&o); + return 0; + } + sp_buf_free(&o); + set_target(auto_name); + free(last); + last = capture(HISTORY); + return sp_buf_printf(out, "target is %s (cmd: %s)\n", target, cmd); +} + +/* Named keys only: letters, digits and - + _, so none can be an option. */ +static int +safe_keys(const char *keys) +{ + size_t i; + + for (i = 0; keys[i] != '\0'; i++) + if (!isalnum((unsigned char)keys[i]) && keys[i] != ' ' && + keys[i] != '-' && keys[i] != '_' && keys[i] != '+') + return 0; + return keys[0] != '-'; +} + +static int +send_text(const char *text, int enter, struct sp_buf *out) +{ + char *const lit[] = { "tmux", "send-keys", "-t", target, "-l", "--", + (char *)text, NULL }; + char *const ret[] = { "tmux", "send-keys", "-t", target, "Enter", NULL }; + + if (text[0] != '\0' && run(lit, out) != 0) + return -1; + return enter ? run(ret, out) : 0; +} + +static int +send_keys(const char *keys, struct sp_buf *out) +{ + char *copy = strdup(keys), *argv[40], *save = NULL, *tok; + int n = 0, rc; + + if (copy == NULL) + return -1; + argv[n++] = "tmux"; + argv[n++] = "send-keys"; + argv[n++] = "-t"; + argv[n++] = target; + for (tok = strtok_r(copy, " ", &save); tok != NULL && n < 38; + tok = strtok_r(NULL, " ", &save)) + argv[n++] = tok; + argv[n] = NULL; + rc = n > 4 ? run(argv, out) : 0; + free(copy); + return rc; +} + +static int +op_send(const char *text, const char *keys, int enter, struct sp_buf *out) +{ + if (!need_target(out)) + return 0; + if ((text == NULL || text[0] == '\0') && (keys == NULL || keys[0] == '\0')) + return sp_buf_puts(out, "error: text or keys required\n"); + if (keys != NULL && !safe_keys(keys)) + return sp_buf_puts(out, "error: keys are names such as C-c, " + "Up, Escape\n"); + if (text != NULL && text[0] != '\0' && + send_text(text, keys == NULL || keys[0] == '\0' ? enter : 0, out) != 0) + return sp_buf_puts(out, "error: tmux send-keys failed\n"); + if (keys != NULL && keys[0] != '\0' && send_keys(keys, out) != 0) + return sp_buf_puts(out, "error: tmux send-keys failed\n"); + return sp_buf_puts(out, "sent\n"); +} + +static int +op_ask(const char *text, long wait_ms, long quiet_ms, struct sp_buf *out) +{ + char *before; + + if (!need_target(out)) + return 0; + if (text == NULL || text[0] == '\0') + return sp_buf_puts(out, "error: text required\n"); + if ((before = capture(HISTORY)) == NULL) + return sp_buf_puts(out, "error: the tmux pane is gone\n"); + free(last); + last = before; + if (send_text(text, 1, out) != 0) + return sp_buf_puts(out, "error: tmux send-keys failed\n"); + if (!settle(before, wait_ms, quiet_ms)) + sp_buf_puts(out, "(timeout: the pane did not change; it may be " + "busy or waiting; try tmux_read or tmux_capture)\n"); + return report_new(out); +} + +static int +op_read(long wait_ms, long quiet_ms, struct sp_buf *out) +{ + if (!need_target(out)) + return 0; + if (wait_ms > 0 && last != NULL) + (void)settle(last, wait_ms, quiet_ms); + return report_new(out); +} + +static int +op_capture(int lines, struct sp_buf *out) +{ + char *s; + + if (!need_target(out)) + return 0; + if ((s = capture(lines)) == NULL) + return sp_buf_puts(out, "error: the tmux pane is gone\n"); + sp_buf_printf(out, "[pane %s, last %d lines]\n%s\n", target, lines, s); + free(s); + return 0; +} + +static int +op_status(struct sp_buf *out) +{ + return sp_buf_printf(out, "tmux target: %s%s\n", + target[0] != '\0' ? target : "(none)", + target[0] == '\0' ? "" : alive() ? " (alive)" : " (gone)"); +} + +/* ----------------------------------------------------------------- tools */ + +static long +clamp(long v, long lo, long hi, long dflt) +{ + if (v == -1) + return dflt; + return v < lo ? lo : v > hi ? hi : v; +} + +static mcp_json * +parse(const char *args) +{ + return mcp_parse(args != NULL ? args : "{}"); +} + +#define WITH_ARGS(a, out) \ + if (((a) = parse(args)) == NULL) \ + return sp_buf_puts((out), "error: arguments are not JSON\n") + +static int +tool_start(const char *args, struct sp_buf *out, void *ctx) +{ + mcp_json *a; + int rc; + + (void)ctx; + WITH_ARGS(a, out); + rc = op_start(mcp_arg_string(a, "cmd"), mcp_arg_string(a, "name"), out); + mcp_json_free(a); + return rc; +} + +static int +tool_send(const char *args, struct sp_buf *out, void *ctx) +{ + mcp_json *a; + int rc; + + (void)ctx; + WITH_ARGS(a, out); + rc = op_send(mcp_arg_string(a, "text"), mcp_arg_string(a, "keys"), + mcp_arg_bool(a, "enter", 1), out); + mcp_json_free(a); + return rc; +} + +static int +tool_ask(const char *args, struct sp_buf *out, void *ctx) +{ + mcp_json *a; + int rc; + + (void)ctx; + WITH_ARGS(a, out); + rc = op_ask(mcp_arg_string(a, "text"), + clamp(mcp_arg_int(a, "wait_ms", -1), 1000, WAIT_CAP, WAIT_DEFAULT), + clamp(mcp_arg_int(a, "quiet_ms", -1), 200, 30000, QUIET_DEFAULT), + out); + mcp_json_free(a); + return rc; +} + +static int +tool_read(const char *args, struct sp_buf *out, void *ctx) +{ + mcp_json *a; + int rc; + + (void)ctx; + WITH_ARGS(a, out); + rc = op_read(clamp(mcp_arg_int(a, "wait_ms", -1), 0, WAIT_CAP, 0), + QUIET_DEFAULT, out); + mcp_json_free(a); + return rc; +} + +static int +tool_capture(const char *args, struct sp_buf *out, void *ctx) +{ + mcp_json *a; + int rc; + + (void)ctx; + WITH_ARGS(a, out); + rc = op_capture((int)clamp(mcp_arg_int(a, "lines", -1), 1, 5000, 200), + out); + mcp_json_free(a); + return rc; +} + +static int +tool_status(const char *args, struct sp_buf *out, void *ctx) +{ + (void)args; + (void)ctx; + return op_status(out); +} + +/* --------------------------------------------------------------- command */ + +static const char * +skip(const char *s) +{ + while (*s == ' ') + s++; + return s; +} + +static int +word(const char *args, const char *name, const char **rest) +{ + size_t n = strlen(name); + + if (strncmp(args, name, n) != 0 || (args[n] != '\0' && args[n] != ' ')) + return 0; + *rest = skip(args + n); + return 1; +} + +static int +command(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx) +{ + const char *r; + + (void)ctx; + host_ref = h; + if (args == NULL || args[0] == '\0' || word(args, "status", &r)) + return op_status(out); + if (word(args, "start", &r)) + return op_start(r, NULL, out); + if (word(args, "attach", &r)) { + if (!safe_name(r, sizeof(target))) + return sp_buf_puts(out, "error: not a tmux target name\n"); + set_target(r); + return op_status(out); + } + if (word(args, "send", &r)) + return op_send(r, NULL, 1, out); + if (word(args, "keys", &r)) + return op_send(NULL, r, 0, out); + if (word(args, "ask", &r)) + return op_ask(r, WAIT_DEFAULT, QUIET_DEFAULT, out); + if (word(args, "read", &r)) + return op_read(clamp(*r != '\0' ? atol(r) : -1, 0, WAIT_CAP, 0), + QUIET_DEFAULT, out); + if (word(args, "capture", &r)) + return op_capture((int)clamp(*r != '\0' ? atol(r) : -1, 1, 5000, + 200), out); + if (word(args, "stop", &r)) { + char *const argv[] = { "tmux", "kill-session", "-t", target, NULL }; + + if (target[0] == '\0') + return sp_buf_puts(out, "no target\n"); + (void)run(argv, NULL); + sp_buf_printf(out, "killed %s\n", target); + target[0] = '\0'; + free(last); + last = NULL; + return 0; + } + return sp_buf_puts(out, "usage: /tmux start | attach | " + "send | keys | ask | read [wait_ms] | " + "capture [lines] | status | stop\n"); +} + +static int +tick(struct sp_host *h, const char *name, void *ctx) +{ + char b[160]; + + (void)name; + (void)ctx; + host_ref = h; + snprintf(b, sizeof(b), "tmux: %.100s", target[0] != '\0' ? target : "-"); + sp_host_widget_text(h, "tmux", b); + return 0; +} + +static const struct sp_tool t_start = { + "tmux_start", + "Start a shell command in a detached tmux terminal and make it the " + "target. For programs that need a terminal: REPLs, installers, TUIs. " + "Use run for anything that just prints and exits.", + "{\"type\":\"object\",\"properties\":{\"cmd\":{\"type\":\"string\"}," + "\"name\":{\"type\":\"string\",\"description\":\"session name, " + "letters digits _ . -\"}},\"required\":[\"cmd\"]}", + SP_AUTH_DESTRUCTIVE, tool_start, NULL +}; + +static const struct sp_tool t_send = { + "tmux_send", + "Type into the target terminal. text is typed literally and followed by " + "Enter (enter=false to leave it off); keys are tmux key names such as " + "C-c, Escape, Up, separated by spaces.", + "{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"}," + "\"keys\":{\"type\":\"string\"},\"enter\":{\"type\":\"boolean\"}}}", + SP_AUTH_MUTATE, tool_send, NULL +}; + +static const struct sp_tool t_ask = { + "tmux_ask", + "Type a line into the target terminal, wait until it has new output and " + "has been quiet for quiet_ms, and return the new lines. Gives up after " + "wait_ms (default 15000) and says so.", + "{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"}," + "\"wait_ms\":{\"type\":\"integer\"},\"quiet_ms\":{\"type\":\"integer\"}}," + "\"required\":[\"text\"]}", + SP_AUTH_MUTATE, tool_ask, NULL +}; + +static const struct sp_tool t_read = { + "tmux_read", + "The lines on the target terminal that are new since the last " + "tmux_ask or tmux_read. wait_ms waits for something to appear first.", + "{\"type\":\"object\",\"properties\":{\"wait_ms\":{\"type\":\"integer\"}}}", + SP_AUTH_READ, tool_read, NULL +}; + +static const struct sp_tool t_capture = { + "tmux_capture", + "The target terminal as it is now: the last `lines` lines (default 200).", + "{\"type\":\"object\",\"properties\":{\"lines\":{\"type\":\"integer\"}}}", + SP_AUTH_READ, tool_capture, NULL +}; + +static const struct sp_tool t_status = { + "tmux_status", + "The current tmux target and whether its session is alive.", + "{\"type\":\"object\",\"properties\":{}}", + SP_AUTH_READ, tool_status, NULL +}; + +static const struct sp_widget tmux_widget = { "tmux", tick, NULL, NULL, 5000 }; + +static int +init(struct sp_host *h) +{ + if (!have_tmux()) + return -1; /* no tmux: the plugin does not load */ + host_ref = h; + restore_target(); + sp_host_add_tool(h, &t_start); + sp_host_add_tool(h, &t_send); + sp_host_add_tool(h, &t_ask); + sp_host_add_tool(h, &t_read); + sp_host_add_tool(h, &t_capture); + sp_host_add_tool(h, &t_status); + sp_host_add_command(h, "tmux", command, NULL); + sp_host_add_widget(h, &tmux_widget); + return 0; +} + +static void +shutdown_plugin(struct sp_host *h) +{ + (void)h; + free(last); + last = NULL; +} + +static const struct sp_plugin plugin = { + SP_PLUGIN_ABI, "tmux", "0.3", init, NULL, shutdown_plugin +}; + +const struct sp_plugin * +sp_plugin_describe(void) +{ + return &plugin; +} diff --git a/tests/test_delegate_cli.sh b/tests/test_delegate_cli.sh index 7ca6e96..c51127a 100755 --- a/tests/test_delegate_cli.sh +++ b/tests/test_delegate_cli.sh @@ -5,6 +5,8 @@ # child's exit status, its own error text and the job line. The fake ssh is # the far side, so no network and no account is involved. set -u +# splinter reads a piped stdin as context; without a terminal that waits for EOF. +exec run("{\"id\":1,\"note\":\"half done\"}", &out, t->ctx); + CHECK(strstr(out.p, "task #1") != NULL); + + /* a state that does not exist is refused, not stored */ + sp_buf_clear(&out); + (void)t->run("{\"id\":1,\"status\":\"finished\"}", &out, t->ctx); + CHECK(strstr(out.p, "error: status is one of") != NULL); + sp_buf_clear(&out); + (void)t->run("{\"id\":99,\"status\":\"done\"}", &out, t->ctx); + CHECK(strstr(out.p, "no task #99") != NULL); + + /* quotes, backslashes and newlines survive the file */ + sp_buf_clear(&out); + t = sp_registry_find(®, "plan_task_add"); + (void)t->run("{\"description\":\"say \\\"hi\\\" in C:\\\\tmp\\nthen stop\"}", + &out, t->ctx); + CHECK(strstr(out.p, "added plan task #2") != NULL); + sp_buf_clear(&out); + t = sp_registry_find(®, "plan_task_list"); + (void)t->run("{}", &out, t->ctx); + CHECK(strstr(out.p, "say \"hi\" in C:\\tmp\nthen stop") != NULL); + + /* a parked task waits, and the other command forms work */ + sp_buf_clear(&out); + CHECK(sp_host_command(host, "tasks", "wait 2 +3600 job:abc", &out) == 0); + CHECK(strstr(out.p, "task #2 waiting_quota") != NULL); + sp_buf_clear(&out); + CHECK(sp_host_command(host, "tasks", "ls", &out) == 0); + CHECK(strstr(out.p, "[waiting_quota]") != NULL); + CHECK(strstr(out.p, "# job:abc") != NULL); + sp_buf_clear(&out); + CHECK(sp_host_command(host, "tasks", "done 1", &out) == 0); + CHECK(strstr(out.p, "task #1 done") != NULL); + sp_buf_clear(&out); + CHECK(sp_host_command(host, "tasks", "next", &out) == 0); + CHECK(strstr(out.p, "no todo tasks") != NULL); + n = sp_host_widget_snapshot(host, snap, sizeof(snap)); CHECK(n > 0); CHECK(strstr(snap, "plan:") != NULL); diff --git a/tests/test_tmux.c b/tests/test_tmux.c new file mode 100644 index 0000000..2d8e397 --- /dev/null +++ b/tests/test_tmux.c @@ -0,0 +1,123 @@ +/* + * splinter -- tmux plugin test. + * + * Drives a real tmux with `cat`: whatever is typed comes back twice (the tty + * echoes it, cat prints it), which is enough to prove the three things that + * matter - a tool reaches the terminal, "new output" excludes what was already + * seen, and a name or key that could be an option is refused. Without tmux the + * test says so and passes; the plugin does not load there either. + */ +#include +#include +#include +#include + +#include "splinter.h" +#include "splinter_plugin.h" + +static int failures; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ +} while (0) + +static const struct sp_tool *reg_tool; + +static const char * +call(const struct sp_registry *reg, const char *tool, const char *args, + struct sp_buf *out) +{ + const struct sp_tool *t = sp_registry_find(reg, tool); + + sp_buf_clear(out); + reg_tool = t; + CHECK(t != NULL); + if (t != NULL) + (void)t->run(args, out, t->ctx); + return out->p != NULL ? out->p : ""; +} + +int +main(void) +{ + struct sp_session_info sess; + struct sp_registry reg; + struct sp_agent ag; + struct sp_host *host; + struct sp_buf out, err; + char dir[] = "/tmp/splinter-tmux-XXXXXX"; + char name[64], args[256]; + const char *s; + + CHECK(mkdtemp(dir) != NULL); + memset(&sess, 0, sizeof(sess)); + snprintf(sess.dir, sizeof(sess.dir), "%s", dir); + memset(®, 0, sizeof(reg)); + memset(&ag, 0, sizeof(ag)); + CHECK(sp_buf_init(&out) == 0); + CHECK(sp_buf_init(&err) == 0); + host = sp_host_new(®, &ag, &sess); + CHECK(host != NULL); + + if (sp_plugin_load(host, "plugins/tmux/tmux.so", &err) != 0) { + printf("test_tmux: skipped (no tmux)\n"); + goto done; + } + CHECK(sp_registry_find(®, "tmux_watch") == NULL); + + /* nothing is targeted yet */ + s = call(®, "tmux_ask", "{\"text\":\"x\"}", &out); + CHECK(strstr(s, "error: no tmux target") != NULL); + + /* a name that could be an option, a second target or a command */ + s = call(®, "tmux_start", "{\"cmd\":\"cat\",\"name\":\"-t evil\"}", &out); + CHECK(strstr(s, "error: name may use") != NULL); + s = call(®, "tmux_start", "{\"cmd\":\"cat\",\"name\":\"a;b\"}", &out); + CHECK(strstr(s, "error: name may use") != NULL); + + snprintf(name, sizeof(name), "splinter-test-%d", (int)getpid()); + snprintf(args, sizeof(args), "{\"cmd\":\"cat\",\"name\":\"%s\"}", name); + s = call(®, "tmux_start", args, &out); + CHECK(strstr(s, "target is") != NULL); + + s = call(®, "tmux_status", "{}", &out); + CHECK(strstr(s, name) != NULL && strstr(s, "alive") != NULL); + + s = call(®, "tmux_ask", + "{\"text\":\"ping\",\"wait_ms\":5000,\"quiet_ms\":400}", &out); + CHECK(strstr(s, "ping") != NULL); + + /* the second answer is only what is new: no "ping" in it */ + s = call(®, "tmux_ask", + "{\"text\":\"pong\",\"wait_ms\":5000,\"quiet_ms\":400}", &out); + CHECK(strstr(s, "pong") != NULL); + CHECK(strstr(s, "ping") == NULL); + + /* and with nothing typed there is nothing new */ + s = call(®, "tmux_read", "{}", &out); + CHECK(strstr(s, "(no new output)") != NULL); + + s = call(®, "tmux_capture", "{\"lines\":50}", &out); + CHECK(strstr(s, "ping") != NULL && strstr(s, "pong") != NULL); + + /* keys are names; anything that looks like an option is refused */ + s = call(®, "tmux_send", "{\"keys\":\"-t other\"}", &out); + CHECK(strstr(s, "error: keys are names") != NULL); + s = call(®, "tmux_send", "{\"keys\":\"C-d\"}", &out); + CHECK(strstr(s, "sent") != NULL); + + CHECK(sp_host_command(host, "tmux", "stop", &out) == 0); +done: + sp_host_free(host); + sp_registry_free(®); + sp_buf_free(&out); + sp_buf_free(&err); + snprintf(args, sizeof(args), "rm -rf '%s'", dir); + (void)system(args); + if (failures == 0) + printf("test_tmux: ok\n"); + return failures == 0 ? 0 : 1; +}