delegates and cli_env: hardcoded environment per cli program; swarm, provider, planner, scheduler, tmux
env=NAME=VALUE on a delegate line (repeatable) is set in the child right before exec and beats what the parent exported, so two delegates can run the same cli with two accounts. Remotely it goes in front as `env 'NAME=VALUE'`, quoted like the rest. cli_env = NAME=VALUE does the same for the main cli transport. A bad name is an error with the line. Also in this commit, the work in progress from the tree: swarm and provider state, the provider/scheduler/planner/tmux plugins, the ui test, whose tmux session name is now per run so parallel runs do not collide. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
25a616a87f
commit
75d8beeaa4
44 files changed
+5721
-1674
No files matched your search
@@ -23,13 +23,17 @@ CURSES_A = $(CURSES_DIR)/libcurses/libcurses.a \
|
||||
LIB = libsplinter.so
|
||||
LIBOBJ = src/buf.o src/tool.o src/session.o src/conv.o src/transport.o \
|
||||
src/json.o src/sse.o src/openai.o src/transport_openai.o src/builtin.o \
|
||||
src/agent.o src/theme.o src/palettes.o src/decomp.o src/i18n.o src/delegate.o src/telegram.o src/log.o src/cmdscript.o src/folder.o src/interview.o src/ack.o src/mcpserver.o src/skills.o src/memory.o src/prompt.o src/config.o src/plugin.o src/curl.o
|
||||
src/agent.o src/theme.o src/palettes.o src/decomp.o src/i18n.o src/delegate.o src/telegram.o src/log.o src/cmdscript.o src/folder.o src/interview.o src/ack.o src/mcpserver.o src/skills.o src/memory.o src/prompt.o src/config.o src/plugin.o src/curl.o src/swarm.o src/provstate.o
|
||||
BIN = splinter
|
||||
BINOBJ = src/main.o src/ui.o
|
||||
PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \
|
||||
plugins/cli/cli.so plugins/focus/focus.so plugins/mcp/mcp.so \
|
||||
plugins/ring/ring.so plugins/reminder/reminder.so \
|
||||
plugins/kids/kids.so plugins/status/status.so plugins/tasks/tasks.so
|
||||
plugins/kids/kids.so plugins/status/status.so plugins/tasks/tasks.so \
|
||||
plugins/provider/provider.so \
|
||||
plugins/scheduler/scheduler.so \
|
||||
plugins/planner/planner.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
|
||||
@@ -201,6 +205,7 @@ check: $(LIB) $(BIN) $(PLUGIN) $(TESTS)
|
||||
export LD_LIBRARY_PATH=.; \
|
||||
for t in $(TESTS); do echo "== $$t"; ./$$t; done; \
|
||||
echo "== tests/test_gateway.sh"; sh tests/test_gateway.sh; \
|
||||
echo "== tests/test_ui.sh"; sh tests/test_ui.sh; \
|
||||
echo "all tests passed"
|
||||
|
||||
# The installed binary finds its own library through an rpath relative to itself
|
||||
@@ -224,3 +229,17 @@ clean:
|
||||
# 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)
|
||||
|
||||
plugins/scheduler/scheduler.so: plugins/scheduler/scheduler.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/scheduler/scheduler.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/planner/planner.so: plugins/planner/planner.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/planner/planner.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/tmux/tmux.so: plugins/tmux/tmux.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/tmux/tmux.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
@@ -375,8 +375,8 @@ the prompt.
|
||||
error, because an ambiguous edit is a wrong edit waiting to happen.
|
||||
- `run` (destructive): a shell command; the exit status is an observation.
|
||||
Its own process group, stdin `/dev/null`, killed after `SPLINTER_RUN_TIMEOUT`
|
||||
seconds (default 300), and an environment without splinter's API keys and
|
||||
tokens, so `run env` cannot hand them to the model.
|
||||
seconds (default 600) or `run_timeout` in the config, and an environment without
|
||||
splinter's API keys and tokens, so `run env` cannot hand them to the model.
|
||||
- `webfetch` (mutate): http(s) only, curl started without a shell. Not read:
|
||||
a URL the model picks is a message out of the machine.
|
||||
- `echo` (read), `clock` (read).
|
||||
|
||||
+19
-1
@@ -43,7 +43,7 @@ lies about what it does.
|
||||
| `theme` | CDE palette name (`splinter --list-themes`) |
|
||||
| `locale` | language code (`de`, `en`); catalogues live in `share/locale` |
|
||||
| `autonomous` | `1` runs mutating/destructive tools without asking |
|
||||
| `steps` | tool rounds per turn (default 8) |
|
||||
| `steps` | tool rounds per turn (default 150) |
|
||||
| `max_bytes` | conversation budget in bytes, `0` = no limit |
|
||||
| `session_dir` | where session logs go (default `~/.splinter`) |
|
||||
| `system_prompt` | sent once at the start of a conversation |
|
||||
@@ -68,6 +68,7 @@ exit = groq | Groq free tier | endpoint=https://api.groq.com/openai/v1/chat/comp
|
||||
delegate = coder | C99, POSIX, kennt den Quellbaum | endpoint=http://kontron:8080/v1/chat/completions | model=qwen | tags=code,review | prio=5 | max_parallel=2
|
||||
delegate = far | the same, on another machine | host=buildbox | endpoint=... | model=...
|
||||
delegate = claude-cli | Claude Code | kind=cli | cmd=claude -p | tags=plan
|
||||
delegate = claude-b | Claude Code, second account | kind=cli | cmd=claude -p | env=CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-...
|
||||
```
|
||||
|
||||
`exit` fields: `endpoint`, `model`, `key_env`; the second field is the label.
|
||||
@@ -76,6 +77,12 @@ delegate = claude-cli | Claude Code | kind=cli | cmd=claude -p | tags=plan
|
||||
ssh target: the child splinter runs there, with that machine's keys. An unnamed
|
||||
field is the description the selection reads.
|
||||
|
||||
`env=NAME=VALUE` (repeatable, up to 8) sets a variable for the delegate's
|
||||
child right before it starts, overwriting whatever the parent exported - so two
|
||||
delegates can run the same CLI with two different accounts. With `host=` it is
|
||||
sent in front of the remote command as `env 'NAME=VALUE'`. A value cannot
|
||||
contain `|`. A literal token in the file is a secret in the file: `chmod 600`.
|
||||
|
||||
## Example: local model
|
||||
|
||||
```
|
||||
@@ -94,10 +101,21 @@ session_dir = /home/lotherk/.splinter
|
||||
```
|
||||
transport = cli
|
||||
cli_cmd = claude -p
|
||||
cli_timeout = 1800
|
||||
plugin = /home/lotherk/src/splinter/plugins/cli/cli.so
|
||||
theme = Delphinium
|
||||
```
|
||||
|
||||
`cli_env = NAME=VALUE` (repeatable, up to 8) sets a variable for the cli
|
||||
program, e.g. `cli_env = CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-...`. It
|
||||
overwrites an exported variable of the same name.
|
||||
|
||||
`cli_cmd` may contain `{file}` (the prompt temp-file path) or `{prompt}` (a
|
||||
shell-quoted prompt). Without a placeholder the prompt is fed on stdin, which
|
||||
works for `claude -p`, `ollama run`, and similar tools. For CLIs that take the
|
||||
message as an argument, use e.g. `cli_cmd = opencode run --format default {file}`
|
||||
or pass the prompt via a flag your CLI supports.
|
||||
|
||||
With both `endpoint` and `transport` set, `transport` wins — it is the more
|
||||
specific instruction.
|
||||
|
||||
|
||||
+2
-1
@@ -156,7 +156,8 @@ SPLINTER_CLI_CMD="opencode run" ./splinter -p "hi" --plugin plugins/cli/cli.so
|
||||
- `SPLINTER_CLI_CMD` — the program, default `claude -p`
|
||||
- `SPLINTER_CLI_FULL=1` — send the whole transcript instead of the last user
|
||||
message (for programs that keep no history of their own)
|
||||
- `SPLINTER_CLI_TIMEOUT` — seconds, default 600
|
||||
- `SPLINTER_CLI_TIMEOUT` — seconds, default 1800 (or `cli_timeout` in the config)
|
||||
- `SPLINTER_CLI_CMD` may include `{file}` (prompt file path) or `{prompt}` (shell-quoted prompt); without a placeholder the prompt is passed on stdin
|
||||
|
||||
The command comes from the operator's environment and runs through `/bin/sh -c`;
|
||||
it is never built from model output. Output is capped at 4 MiB, a non-zero exit
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ This needs no network and is how the test suite drives the loop.
|
||||
Run mutating tools without asking.
|
||||
Read-only tools never ask.
|
||||
.It Fl -steps Ar N
|
||||
Maximum tool rounds per turn (default 8).
|
||||
Maximum tool rounds per turn (default 150).
|
||||
.It Fl -max-bytes Ar N
|
||||
Request budget in bytes; 0 means no limit.
|
||||
.It Fl -session Ar DIR
|
||||
|
||||
@@ -114,6 +114,7 @@ struct sp_reply {
|
||||
long status;
|
||||
long tokens_in; /* provider-reported, 0 when unknown */
|
||||
long tokens_out;
|
||||
long retry_after_s; /* parsed Retry-After header, 0 unknown */
|
||||
char *content; /* assistant text, may be "" */
|
||||
struct sp_toolcall *calls;
|
||||
char *calls_json; /* the provider's own tool_calls array */
|
||||
@@ -145,6 +146,9 @@ struct sp_transport {
|
||||
struct sp_reply *out, struct sp_buf *err,
|
||||
sp_stream_cb, void *cbctx);
|
||||
void *ctx;
|
||||
/* optional: provider/key identity for quota/usage tracking (plugins) */
|
||||
const char *provider; /* e.g. "openai-compat", "ollama", "opencode" */
|
||||
const char *key_id; /* stable key fingerprint/id, never the secret */
|
||||
};
|
||||
|
||||
void sp_reply_free(struct sp_reply *);
|
||||
@@ -231,6 +235,11 @@ struct sp_agent_config {
|
||||
const char *observation);
|
||||
void *tool_end_ctx;
|
||||
|
||||
/* Called when the conversation was compacted to fit the budget. */
|
||||
void (*on_compact)(void *ctx, size_t before, size_t after,
|
||||
size_t msgs_before, size_t msgs_after);
|
||||
void *on_compact_ctx;
|
||||
|
||||
/* incremental output, if the transport and the caller both support it */
|
||||
sp_stream_cb stream;
|
||||
void *stream_ctx;
|
||||
|
||||
@@ -150,6 +150,14 @@ int sp_host_add_gate(struct sp_host *, const struct sp_gate *);
|
||||
int sp_host_add_status(struct sp_host *, const struct sp_status *);
|
||||
const struct sp_meter *sp_host_meter(struct sp_host *);
|
||||
void sp_host_set_meter(struct sp_host *, const struct sp_meter *);
|
||||
/*
|
||||
* Thread-safe: a copy under the host lock, and a change of only the caller's
|
||||
* fields under the lock. Use these from any thread but the UI's; the two above
|
||||
* remain for the UI thread and for reading a single field.
|
||||
*/
|
||||
void sp_host_meter_get(struct sp_host *, struct sp_meter *out);
|
||||
void sp_host_meter_update(struct sp_host *,
|
||||
void (*fn)(struct sp_meter *, void *), void *ctx);
|
||||
size_t sp_host_status_text(struct sp_host *, char *buf, size_t len);
|
||||
void sp_host_set_task_ops(struct sp_host *, const struct sp_task_ops *);
|
||||
int sp_host_task_begin(struct sp_host *, const char *label, const char *detail);
|
||||
@@ -166,6 +174,46 @@ size_t sp_host_command_help(struct sp_host *, struct sp_buf *out);
|
||||
int sp_host_add_transport(struct sp_host *, const char *name,
|
||||
struct sp_transport);
|
||||
struct sp_transport *sp_host_transport(struct sp_host *, const char *name);
|
||||
|
||||
/* ---- provider: quota/usage/burst policy, pluggable (per key, shared state) ---- */
|
||||
enum sp_prov_decision { SP_PROV_ADMIT = 0, SP_PROV_DELAY, SP_PROV_WAIT_QUOTA, SP_PROV_DENY };
|
||||
struct sp_prov_result {
|
||||
enum sp_prov_decision decision;
|
||||
long retry_after_s; /* seconds to wait (DELAY) */
|
||||
long ready_at; /* unix timestamp when quota/backoff ends (WAIT_QUOTA) */
|
||||
char reason[256];
|
||||
};
|
||||
struct sp_provider_ops {
|
||||
void *ctx;
|
||||
int (*preflight)(void *ctx, const char *provider, const char *key_id,
|
||||
struct sp_prov_result *out);
|
||||
void (*account)(void *ctx, const char *provider, const char *key_id,
|
||||
long http_status, size_t tokens_in, size_t tokens_out);
|
||||
};
|
||||
void sp_host_set_provider(struct sp_host *, const struct sp_provider_ops *);
|
||||
enum sp_prov_decision sp_host_provider_preflight(struct sp_host *, const char *provider,
|
||||
const char *key_id, struct sp_prov_result *out);
|
||||
void sp_host_provider_account(struct sp_host *, const char *provider, const char *key_id,
|
||||
long http_status, size_t tokens_in, size_t tokens_out);
|
||||
|
||||
/* shared per-(provider,key_id) usage/quota state (~/.splinter/providers/...), flock+atomic.
|
||||
* Provider plugins use this for cross-instance, per-key tracking. */
|
||||
struct sp_prov_state {
|
||||
long quota_ready_at; long backoff_until;
|
||||
unsigned req_count; unsigned long tok_in, tok_out;
|
||||
long last_status, last_update, last_429_at;
|
||||
char note[128];
|
||||
};
|
||||
int sp_provstate_load(const char *provider, const char *key_id, struct sp_prov_state *out);
|
||||
int sp_provstate_update(const char *provider, const char *key_id,
|
||||
void (*fn)(struct sp_prov_state *s, void *ctx), void *ctx);
|
||||
void sp_provstate_account(const char *provider, const char *key_id,
|
||||
long http_status, size_t tok_in, size_t tok_out, long retry_after_s);
|
||||
int sp_provstate_preflight(const char *provider, const char *key_id,
|
||||
long now, long *ready_at, char *reason, size_t reason_cap);
|
||||
/* Stable fingerprint of a secret key (never stores/returns the secret). */
|
||||
char *sp_key_fingerprint(const char *secret, char *buf, size_t cap);
|
||||
|
||||
int sp_host_compact(struct sp_host *, struct sp_conv *, size_t budget);
|
||||
size_t sp_host_compaction_stats(struct sp_host *, size_t *compactions,
|
||||
size_t *failed, unsigned *turns);
|
||||
@@ -180,6 +228,11 @@ struct sp_registry *sp_host_registry(struct sp_host *);
|
||||
struct sp_host *sp_host_new(struct sp_registry *, struct sp_agent *,
|
||||
struct sp_session_info *);
|
||||
void sp_host_free(struct sp_host *);
|
||||
const char *sp_host_session_dir(struct sp_host *);
|
||||
/* Retry a durable delegation job (scheduler/worker). 0 on handled (see out). */
|
||||
int sp_delegate_retry_job(const char *id, int force, struct sp_buf *out);
|
||||
/* Scheduler tick: retry one due waiting_quota/waiting_poll job if any. */
|
||||
int sp_delegate_tick(struct sp_buf *out);
|
||||
int sp_plugin_load(struct sp_host *, const char *path,
|
||||
struct sp_buf *err);
|
||||
size_t sp_host_widget_snapshot(struct sp_host *, char *buf, size_t len);
|
||||
|
||||
+46
-23
@@ -12,15 +12,19 @@
|
||||
*
|
||||
* Configuration is by environment, deliberately: no config file to drift.
|
||||
*
|
||||
* SPLINTER_CLI_CMD the program, default "claude -p"
|
||||
* SPLINTER_CLI_CMD the program, default "claude -p". If it contains
|
||||
* {file}, the prompt file path is substituted there;
|
||||
* {prompt} substitutes a shell-quoted prompt. Without
|
||||
* a placeholder the prompt is fed on stdin.
|
||||
* SPLINTER_CLI_FULL=1 send the whole transcript instead of the last user
|
||||
* message (the program keeps no history of its own)
|
||||
* SPLINTER_CLI_TIMEOUT seconds, default 600
|
||||
* SPLINTER_CLI_TIMEOUT seconds, default 1800
|
||||
*
|
||||
* Trust note, because it matters: the command runs through /bin/sh -c, so the
|
||||
* string comes from the operator's environment, never from the model. Output is
|
||||
* capped at 4 MiB and a non-zero exit is an error with the program's own
|
||||
* stderr attached -- a silent empty answer is the one thing this must not do.
|
||||
* string comes from the operator's environment, never from the model. Output
|
||||
* grows dynamically (capped at 64 MiB) and a non-zero exit is an error with the
|
||||
* program's own stderr attached -- a silent empty answer is the one thing this
|
||||
* must not do.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
@@ -33,7 +37,7 @@
|
||||
#include "splinter_plugin.h"
|
||||
#include "i18n.h"
|
||||
|
||||
#define OUT_CAP (4u << 20)
|
||||
#define OUT_CAP (64u << 20)
|
||||
|
||||
struct cli_cfg {
|
||||
char cmd[512];
|
||||
@@ -123,18 +127,41 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
}
|
||||
|
||||
/*
|
||||
* The program reads the prompt on stdin; timeout guards a hang. Its
|
||||
* stderr goes to a file next to the prompt: on the terminal it landed in
|
||||
* the middle of the curses screen, and the error message below promised
|
||||
* "the program's own stderr" while it quoted stdout. The paths are quoted;
|
||||
* TMPDIR is the operator's, but a space in it still broke the command.
|
||||
* The program reads the prompt on stdin unless the command names where it
|
||||
* goes: {file} becomes the prompt file path, {prompt} becomes the prompt
|
||||
* as a shell word. timeout guards a hang. stderr goes to a file next to
|
||||
* the prompt so it never lands in the middle of a curses screen.
|
||||
*/
|
||||
snprintf(errpath, sizeof(errpath), "%s.err", path);
|
||||
sp_buf_printf(&cmd, "timeout %s %s < ", c->timeout, c->cmd);
|
||||
if (sh_word(&cmd, path) != 0 || sp_buf_puts(&cmd, " 2> ") != 0 ||
|
||||
sh_word(&cmd, errpath) != 0) {
|
||||
unlink(path);
|
||||
goto fail;
|
||||
sp_buf_printf(&cmd, "timeout %s ", c->timeout);
|
||||
if (strstr(c->cmd, "{file}") != NULL || strstr(c->cmd, "{prompt}") != NULL) {
|
||||
const char *p = c->cmd;
|
||||
|
||||
while (*p != '\0') {
|
||||
if (strncmp(p, "{file}", 6) == 0) {
|
||||
if (sh_word(&cmd, path) != 0)
|
||||
goto fail_build;
|
||||
p += 6;
|
||||
} else if (strncmp(p, "{prompt}", 8) == 0) {
|
||||
if (sh_word(&cmd, body.p != NULL ? body.p : "") != 0)
|
||||
goto fail_build;
|
||||
p += 8;
|
||||
} else if (sp_buf_add(&cmd, p, 1) != 0) {
|
||||
goto fail_build;
|
||||
} else
|
||||
p++;
|
||||
}
|
||||
if (sp_buf_puts(&cmd, " 2> ") != 0 || sh_word(&cmd, errpath) != 0)
|
||||
goto fail_build;
|
||||
} else {
|
||||
sp_buf_printf(&cmd, "%s < ", c->cmd);
|
||||
if (sh_word(&cmd, path) != 0 || sp_buf_puts(&cmd, " 2> ") != 0 ||
|
||||
sh_word(&cmd, errpath) != 0) {
|
||||
fail_build:
|
||||
unlink(path);
|
||||
unlink(errpath);
|
||||
goto fail;
|
||||
}
|
||||
}
|
||||
p = popen(cmd.p, "r");
|
||||
if (p == NULL) {
|
||||
@@ -147,12 +174,8 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
size_t got;
|
||||
|
||||
while ((got = fread(chunk, 1, sizeof(chunk), p)) > 0) {
|
||||
if (raw.len + got > OUT_CAP) {
|
||||
sp_buf_puts(err, "cli: output over 4 MiB, aborted");
|
||||
pclose(p);
|
||||
unlink(path);
|
||||
goto fail;
|
||||
}
|
||||
if (raw.len + got > OUT_CAP)
|
||||
break;
|
||||
if (sp_buf_add(&raw, chunk, got) != 0) {
|
||||
pclose(p);
|
||||
unlink(path);
|
||||
@@ -225,7 +248,7 @@ cli_init(struct sp_host *h)
|
||||
snprintf(cfg.cmd, sizeof(cfg.cmd), "%s",
|
||||
cmd != NULL && *cmd != '\0' ? cmd : "claude -p");
|
||||
snprintf(cfg.timeout, sizeof(cfg.timeout), "%s",
|
||||
to != NULL && *to != '\0' ? to : "600");
|
||||
to != NULL && *to != '\0' ? to : "1800");
|
||||
cfg.full = full != NULL && strcmp(full, "0") != 0;
|
||||
|
||||
tr.send = cli_send;
|
||||
|
||||
+5
-1
@@ -93,9 +93,13 @@ cps_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
* Comparing against cps.n, which stops at SNAP_MAX, meant that past 256
|
||||
* messages no plan ever applied - compaction just stopped.
|
||||
*/
|
||||
if (budget == 0) {
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
return 0; /* no byte budget: nothing to do */
|
||||
}
|
||||
if (cps.ready && cps.total == conv->n &&
|
||||
cps.bytes == sp_conv_bytes(conv) &&
|
||||
(budget == 0 || sp_conv_bytes(conv) > budget)) {
|
||||
sp_conv_bytes(conv) > budget) {
|
||||
apply = 1;
|
||||
} else {
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
|
||||
+46
-15
@@ -22,6 +22,7 @@
|
||||
* not appended after it: the model then reads goal -> request and answers the
|
||||
* request, instead of reading the request and treating the goal as a reply.
|
||||
*/
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -32,6 +33,13 @@
|
||||
|
||||
#define GOAL_MAX 1000
|
||||
|
||||
/*
|
||||
* goal, force and reminders are shared by three threads: /goal and /recap run
|
||||
* on the UI thread, the compactor on the turn thread, the tick on its own.
|
||||
* One lock for all of them; the tick used to read the goal while /goal was
|
||||
* rewriting it.
|
||||
*/
|
||||
static pthread_mutex_t focus_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static char goal[GOAL_MAX + 1];
|
||||
static unsigned every = 5;
|
||||
static unsigned last_reminder;
|
||||
@@ -47,21 +55,27 @@ focus_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
struct sp_msg m;
|
||||
size_t at;
|
||||
|
||||
char g[GOAL_MAX + 1];
|
||||
|
||||
(void)budget;
|
||||
(void)h;
|
||||
if (goal[0] == '\0' || conv == NULL || conv->n == 0)
|
||||
if (conv == NULL || conv->n == 0)
|
||||
return 0;
|
||||
if (!force && (turn == 0 || (turn % every) != 0))
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
if (goal[0] == '\0' || (!force && (turn == 0 || (turn % every) != 0)) ||
|
||||
turn == last_reminder) { /* one reminder per turn, always */
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
return 0;
|
||||
if (turn == last_reminder)
|
||||
return 0; /* one reminder per turn, always */
|
||||
}
|
||||
snprintf(g, sizeof(g), "%s", goal);
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
|
||||
{
|
||||
char rem[1024];
|
||||
|
||||
snprintf(rem, sizeof(rem), sp_td("focus.reminder",
|
||||
"Before answering, check whether the last step moved closer "
|
||||
"to the goal. If not, say so and name the next step. Goal: %s"), goal);
|
||||
"to the goal. If not, say so and name the next step. Goal: %s"), g);
|
||||
snprintf(text, sizeof(text), "[focus] %s", rem);
|
||||
}
|
||||
|
||||
@@ -77,11 +91,13 @@ focus_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
if (sp_conv_insert(conv, at, &m) != 0)
|
||||
return -1;
|
||||
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
last_reminder = turn;
|
||||
force = 0;
|
||||
reminders++;
|
||||
snprintf(widget_text, sizeof(widget_text), "%u reminders, every %u turns",
|
||||
reminders, every);
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -94,13 +110,19 @@ static int
|
||||
focus_command(struct sp_host *h, const char *args, struct sp_buf *out,
|
||||
void *ctx)
|
||||
{
|
||||
char g[GOAL_MAX + 1];
|
||||
unsigned n;
|
||||
|
||||
(void)ctx;
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
if (args == NULL || *args == '\0') {
|
||||
if (goal[0] == '\0')
|
||||
snprintf(g, sizeof(g), "%s", goal);
|
||||
n = reminders;
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
if (g[0] == '\0')
|
||||
return sp_buf_puts(out, sp_td("focus.none", "no goal set (/goal <text>)"));
|
||||
return sp_buf_printf(out, sp_td("focus.status",
|
||||
"goal: %s (%u reminders, every %u turns)"), goal,
|
||||
reminders, every);
|
||||
"goal: %s (%u reminders, every %u turns)"), g, n, every);
|
||||
}
|
||||
snprintf(goal, sizeof(goal), "%.*s", GOAL_MAX, args);
|
||||
if (strlen(args) > GOAL_MAX)
|
||||
@@ -108,15 +130,17 @@ focus_command(struct sp_host *h, const char *args, struct sp_buf *out,
|
||||
reminders = 0;
|
||||
last_reminder = 0;
|
||||
force = 0;
|
||||
snprintf(g, sizeof(g), "%s", goal);
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
/* publish now, so the sidebar does not wait for the next tick */
|
||||
{
|
||||
char line[192];
|
||||
|
||||
snprintf(line, sizeof(line), "%.60s%s", goal,
|
||||
strlen(goal) > 60 ? "..." : "");
|
||||
snprintf(line, sizeof(line), "%.60s%s", g,
|
||||
strlen(g) > 60 ? "..." : "");
|
||||
(void)sp_host_widget_text(h, "focus", line);
|
||||
}
|
||||
return sp_buf_printf(out, sp_td("focus.set", "goal set: %s"), goal);
|
||||
return sp_buf_printf(out, sp_td("focus.set", "goal set: %s"), g);
|
||||
}
|
||||
|
||||
static int
|
||||
@@ -126,10 +150,15 @@ recap_command(struct sp_host *h, const char *args, struct sp_buf *out,
|
||||
(void)h;
|
||||
(void)args;
|
||||
(void)ctx;
|
||||
if (goal[0] == '\0')
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
if (goal[0] == '\0') {
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
return sp_buf_puts(out, sp_td("focus.none", "no goal set (/goal <text>)"));
|
||||
}
|
||||
force = 1; /* the next turn gets a reminder */
|
||||
return sp_buf_puts(out, "Erinnerung fuer den naechsten Turn eingeplant");
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
return sp_buf_puts(out, sp_td("focus.recap",
|
||||
"reminder scheduled for the next turn"));
|
||||
}
|
||||
|
||||
static int
|
||||
@@ -138,12 +167,14 @@ focus_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
char line[192];
|
||||
|
||||
(void)ctx;
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
if (goal[0] == '\0')
|
||||
snprintf(line, sizeof(line), "%s", sp_td("focus.widget_none",
|
||||
"no goal (/goal <text>)"));
|
||||
else
|
||||
snprintf(line, sizeof(line), "%.44s%s | %u",
|
||||
goal, strlen(goal) > 44 ? "..." : "", reminders);
|
||||
snprintf(line, sizeof(line), "%.44s%s | %u",
|
||||
goal, strlen(goal) > 44 ? "..." : "", reminders);
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
return sp_host_widget_text(h, name, line);
|
||||
}
|
||||
|
||||
|
||||
+3
-1
@@ -45,8 +45,10 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
(void)h;
|
||||
if (conv == NULL || conv->n <= KEEP_TAIL + 1)
|
||||
return 0;
|
||||
if (budget == 0)
|
||||
return 0; /* no byte budget: nothing to do */
|
||||
bytes = sp_conv_bytes(conv);
|
||||
if (budget > 0 && bytes <= budget)
|
||||
if (bytes <= budget)
|
||||
return 0; /* fits: nothing to do */
|
||||
|
||||
/* a leading system prompt stays; everything else may go */
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
/*
|
||||
* splinter -- persistent session plan/tasks (/tasks), distinct from background jobs.
|
||||
*
|
||||
* Session-scoped task list persisted in <session>/plan_tasks.json.
|
||||
* Model tools add/update tasks; /tasks controls focus/work selection.
|
||||
* Integrates with /goal (focus plugin) to prevent drift.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
#define PT_MAX 128
|
||||
#define PT_DESC 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;
|
||||
};
|
||||
|
||||
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+1<ntasks)?",":"");
|
||||
}
|
||||
fprintf(f, "]\n");
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static int load_int(const char *s, const char *k) {
|
||||
char pat[64]; const char *p;
|
||||
snprintf(pat,sizeof(pat),"\"%s\":",k);
|
||||
p=strstr(s,pat); if(!p) return 0; p+=strlen(pat);
|
||||
return (int)strtol(p,NULL,10);
|
||||
}
|
||||
static void load_str(const char *s, const char *k, char *out, size_t cap) {
|
||||
char pat[64]; const char *p,*e; size_t n=0;
|
||||
out[0]='\0'; snprintf(pat,sizeof(pat),"\"%s\":\"",k);
|
||||
p=strstr(s,pat); if(!p) return; p+=strlen(pat);
|
||||
for (e=p; *e && !(*e=='"' && e[-1]!='\\') && n+1<cap; e++) {
|
||||
if (*e=='\\' && e[1]) { e++; if (*e=='n') out[n++]='\n'; else out[n++]=*e; }
|
||||
else out[n++]=*e;
|
||||
}
|
||||
out[n]='\0';
|
||||
}
|
||||
|
||||
static void load_tasks(void) {
|
||||
FILE *f; char buf[65536]; size_t nr; char *p; const char *path;
|
||||
ensure_dir(); path = store_path(); if (!path) return;
|
||||
f=fopen(path,"r"); if(!f) return;
|
||||
nr=fread(buf,1,sizeof(buf)-1,f); fclose(f); buf[nr]='\0';
|
||||
ntasks=0; next_id=1; current_id=-1;
|
||||
for (p=buf; (p=strchr(p,'{'))!=NULL && ntasks<PT_MAX; ) {
|
||||
char *end=strchr(p,'}'); char obj[4096]; struct ptask *t;
|
||||
if(!end) break;
|
||||
snprintf(obj,sizeof(obj),"%.*s",(int)(end-p+1),p);
|
||||
t=&tasks[ntasks]; memset(t,0,sizeof(*t));
|
||||
snprintf(t->status,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;
|
||||
ntasks++;
|
||||
p=end+1;
|
||||
}
|
||||
}
|
||||
|
||||
static struct ptask *find_task(int id) {
|
||||
size_t i; for(i=0;i<ntasks;i++) if(tasks[i].id==id) return &tasks[i]; return NULL;
|
||||
}
|
||||
static struct ptask *next_todo(void) {
|
||||
size_t i;
|
||||
for(i=0;i<ntasks;i++) if(strcmp(tasks[i].status,"todo")==0) return &tasks[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
static const char *jstr(const char *json, const char *key, char *out, size_t cap){
|
||||
char pat[128]; const char *p,*end; size_t n=0;
|
||||
out[0]='\0'; if(!json||!key) return NULL;
|
||||
snprintf(pat,sizeof(pat),"\"%s\"",key);
|
||||
p=strstr(json,pat); if(!p) return NULL; p+=strlen(pat);
|
||||
while(*p && *p!=':') p++;
|
||||
if(*p==':') p++;
|
||||
while(*p==' '||*p=='\t'||*p=='\n'||*p=='\r') p++;
|
||||
if(*p!='"') return NULL;
|
||||
p++;
|
||||
for(end=p; *end && !(*end=='"' && end[-1]!='\\') && n+1<cap; end++){
|
||||
if(*end=='\\'&&end[1]){ end++; out[n++]=(*end=='n')?'\n':*end; }
|
||||
else { out[n++]=*end; }
|
||||
}
|
||||
out[n]='\0'; return out[0]?out:NULL;
|
||||
}
|
||||
|
||||
|
||||
static void parse_run_after(const char *in, char *out, size_t cap){
|
||||
out[0]='\0'; if(!in||!*in) return;
|
||||
if(in[0]=='+'){
|
||||
long d=strtol(in+1,NULL,10); if(d<=0) d=3600;
|
||||
snprintf(out,cap,"%ld",(long)time(NULL)+d); return;
|
||||
}
|
||||
snprintf(out,cap,"%.63s",in);
|
||||
}
|
||||
|
||||
static void publish_widget(void) {
|
||||
char b[256]; int doing=0,todo=0,done=0; size_t i;
|
||||
for(i=0;i<ntasks;i++){
|
||||
if(strcmp(tasks[i].status,"doing")==0) doing++;
|
||||
else if(strcmp(tasks[i].status,"todo")==0) todo++;
|
||||
else if(strcmp(tasks[i].status,"done")==0) done++;
|
||||
}
|
||||
if(current_id>0) 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(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(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;i<ntasks;i++){
|
||||
struct ptask *t=&tasks[i];
|
||||
sp_buf_printf(out," #%d [%s]%s %s%s%s%s\n", t->id, 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 <id> | /tasks all | /tasks choose\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int tool_update(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){
|
||||
size_t i;
|
||||
for(i=0;i<ntasks;i++) if(strcmp(tasks[i].status,"doing")==0) snprintf(tasks[i].status,sizeof(tasks[i].status),"todo");
|
||||
if(t){ snprintf(t->status,sizeof(t->status),"doing"); current_id=t->id; t->updated=(long)time(NULL); focus_task(t); }
|
||||
else current_id=-1;
|
||||
}
|
||||
|
||||
static int cmd_tasks(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(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(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+1<sizeof(ra)) { ra[n++]=*p++; }
|
||||
ra[n]='\0';
|
||||
}
|
||||
while(*p==' ') p++;
|
||||
{
|
||||
struct ptask *t = find_task(id);
|
||||
if(!t) return sp_buf_printf(out,"no task #%d\n", id);
|
||||
if(ra[0]) parse_run_after(ra,ra2,sizeof(ra2));
|
||||
else snprintf(ra2,sizeof(ra2),"%ld",(long)time(NULL)+3600);
|
||||
snprintf(t->status,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 <desc>|work <id>|work all|choose|next|done [id]|wait <id> <+secs|epoch> [note]]\n");
|
||||
}
|
||||
|
||||
static int tick(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;i<ntasks;i++){
|
||||
struct ptask *t=&tasks[i];
|
||||
if(strcmp(t->status,"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;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(changed) save_tasks();
|
||||
publish_widget(); return 0;
|
||||
}
|
||||
|
||||
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);
|
||||
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; }
|
||||
@@ -0,0 +1,277 @@
|
||||
/*
|
||||
* splinter -- provider adapters (OpenCode/Ollama/openai-compat), per-key quota/usage.
|
||||
*
|
||||
* Plugin-format adapters: dispatch by tr.provider ("opencode","ollama","openai-compat").
|
||||
* Shared per-(provider,key_id) state in ~/.splinter/providers/ (flock+atomic), so
|
||||
* multiple instances sharing a key see the same quota/burst view.
|
||||
*
|
||||
* - preflight: blocks on quota_ready_at; short backoff delays (<=30s) allowed by caller.
|
||||
* - account: records status/tokens; 429/402/529 -> quota wait (Retry-After honored by
|
||||
* transport/agent when known; defaults here). 503/408 -> short backoff.
|
||||
* - Ollama (local): quota gating relaxed (transient/backoff only) unless explicit quota.
|
||||
* - OpenCode/cloud: quota exhausted -> WAIT_QUOTA with ready_at; "quota back in N days"
|
||||
* surfaced via reason/note and durable delegation jobs (waiting_quota+run_after) +
|
||||
* scheduler auto-retry. Optional probe via SPLINTER_QUOTA_PROBE_URL (GET, bearer from
|
||||
* SPLINTER_QUOTA_PROBE_KEY) when SPLINTER_PROVIDER_PROBE=1.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <errno.h>
|
||||
#include <dirent.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
static int is_ollama(const char *p) { return p && strcmp(p,"ollama")==0; }
|
||||
static int is_opencode(const char *p){ return p && (strcmp(p,"opencode")==0 || strcmp(p,"open-code")==0); }
|
||||
|
||||
struct probe_apply { long ready; long now; };
|
||||
static void probe_apply_fn(struct sp_prov_state *s, void *p){
|
||||
struct probe_apply *c=p;
|
||||
if (c->ready > s->quota_ready_at) s->quota_ready_at = c->ready;
|
||||
if (c->ready > 0) snprintf(s->note,sizeof(s->note),"quota probe ready_at=%ld", c->ready);
|
||||
s->last_update = c->now;
|
||||
}
|
||||
static void probe_apply(const char *provider, const char *key_id, long ready){
|
||||
struct probe_apply c; c.ready=ready; c.now=(long)time(NULL);
|
||||
sp_provstate_update(provider,key_id,probe_apply_fn,&c);
|
||||
}
|
||||
|
||||
static void run_probe(const char *provider, const char *key_id)
|
||||
{
|
||||
const char *on = getenv("SPLINTER_PROVIDER_PROBE");
|
||||
const char *url = getenv("SPLINTER_QUOTA_PROBE_URL");
|
||||
const char *key = getenv("SPLINTER_QUOTA_PROBE_KEY");
|
||||
const char *kenv = getenv("SPLINTER_QUOTA_PROBE_KEY_ENV");
|
||||
char buf[4096];
|
||||
size_t n = 0;
|
||||
long ready = 0, ra = 0;
|
||||
const char *q;
|
||||
int in_pipe[2], out_pipe[2], devnull;
|
||||
pid_t pid;
|
||||
int st = 0;
|
||||
char cfg[4096];
|
||||
size_t off = 0, len;
|
||||
ssize_t wr, rd;
|
||||
|
||||
if (!on || strcmp(on, "1") != 0 || !url || !*url) return;
|
||||
if ((!key || !*key) && kenv && *kenv) key = getenv(kenv);
|
||||
if (strncmp(url, "http://", 7) != 0 && strncmp(url, "https://", 8) != 0) return;
|
||||
if (strpbrk(url, "\"\\\n\r") != NULL) return;
|
||||
if (key && *key && strpbrk(key, "\"\\\n\r") != NULL) return;
|
||||
|
||||
if (pipe(in_pipe) != 0) return;
|
||||
if (pipe(out_pipe) != 0) {
|
||||
close(in_pipe[0]);
|
||||
close(in_pipe[1]);
|
||||
return;
|
||||
}
|
||||
pid = fork();
|
||||
if (pid < 0) {
|
||||
close(in_pipe[0]); close(in_pipe[1]);
|
||||
close(out_pipe[0]); close(out_pipe[1]);
|
||||
return;
|
||||
}
|
||||
if (pid == 0) {
|
||||
char *const argv[] = {"curl", "-fsS", "-m", "10", "-K", "-", NULL};
|
||||
dup2(in_pipe[0], 0);
|
||||
dup2(out_pipe[1], 1);
|
||||
devnull = open("/dev/null", O_WRONLY);
|
||||
if (devnull >= 0) {
|
||||
dup2(devnull, 2);
|
||||
close(devnull);
|
||||
}
|
||||
close(in_pipe[0]); close(in_pipe[1]);
|
||||
close(out_pipe[0]); close(out_pipe[1]);
|
||||
execvp(argv[0], argv);
|
||||
_exit(127);
|
||||
}
|
||||
|
||||
close(in_pipe[0]);
|
||||
close(out_pipe[1]);
|
||||
len = (size_t)snprintf(cfg, sizeof(cfg), "url = \"%s\"\n", url);
|
||||
if (len < sizeof(cfg) && key && *key) {
|
||||
int m = snprintf(cfg + len, sizeof(cfg) - len,
|
||||
"header = \"Authorization: Bearer %s\"\n", key);
|
||||
len = (m < 0 || (size_t)m >= sizeof(cfg) - len) ? sizeof(cfg) : len + (size_t)m;
|
||||
}
|
||||
/* An over-long config is never sent: curl then reads an empty config and
|
||||
* fails, and the exit status below discards the result. */
|
||||
if (len >= sizeof(cfg))
|
||||
len = 0;
|
||||
{
|
||||
void (*old_pipe)(int) = signal(SIGPIPE, SIG_IGN);
|
||||
off = 0;
|
||||
while (off < len) {
|
||||
wr = write(in_pipe[1], cfg + off, len - off);
|
||||
if (wr <= 0) break;
|
||||
off += (size_t)wr;
|
||||
}
|
||||
close(in_pipe[1]);
|
||||
signal(SIGPIPE, old_pipe);
|
||||
}
|
||||
|
||||
n = 0;
|
||||
for (;;) {
|
||||
char rbuf[1024];
|
||||
rd = read(out_pipe[0], rbuf, sizeof(rbuf));
|
||||
if (rd <= 0) break;
|
||||
if (n < sizeof(buf) - 1) {
|
||||
size_t take = (size_t)rd;
|
||||
if (take > sizeof(buf) - 1 - n) take = sizeof(buf) - 1 - n;
|
||||
memcpy(buf + n, rbuf, take);
|
||||
n += take;
|
||||
}
|
||||
}
|
||||
buf[n] = '\0';
|
||||
close(out_pipe[0]);
|
||||
while (waitpid(pid, &st, 0) < 0 && errno == EINTR)
|
||||
;
|
||||
|
||||
if (WIFEXITED(st) && WEXITSTATUS(st) == 0) {
|
||||
q = strstr(buf, "\"quota_ready_at\""); if (q) { q = strchr(q, ':'); if (q) ready = strtol(q + 1, NULL, 10); }
|
||||
q = strstr(buf, "\"retry_after\""); if (q) { q = strchr(q, ':'); if (q) ra = strtol(q + 1, NULL, 10); }
|
||||
if (ready <= 0 && ra > 0) ready = (long)time(NULL) + ra;
|
||||
if (ready > 0) probe_apply(provider, key_id, ready);
|
||||
}
|
||||
}
|
||||
|
||||
static int
|
||||
prov_preflight(void *ctx, const char *provider, const char *key_id,
|
||||
struct sp_prov_result *out)
|
||||
{
|
||||
long now = (long)time(NULL);
|
||||
long ready = 0;
|
||||
int r;
|
||||
(void)ctx;
|
||||
if (!out) return 0;
|
||||
out->decision = SP_PROV_ADMIT;
|
||||
if (!provider || !*provider || !key_id || !*key_id)
|
||||
return 0;
|
||||
/* ollama local: no cloud quota gating unless state explicitly says quota */
|
||||
if (is_ollama(provider)) {
|
||||
struct sp_prov_state st;
|
||||
if (sp_provstate_load(provider,key_id,&st)==0 && st.quota_ready_at > now) {
|
||||
out->decision = SP_PROV_WAIT_QUOTA;
|
||||
out->ready_at = st.quota_ready_at;
|
||||
out->retry_after_s = st.quota_ready_at - now;
|
||||
snprintf(out->reason,sizeof(out->reason),"ollama quota/backoff until %ld", st.quota_ready_at);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
r = sp_provstate_preflight(provider, key_id, now, &ready,
|
||||
out->reason, sizeof(out->reason));
|
||||
if (r == 1) {
|
||||
out->decision = SP_PROV_WAIT_QUOTA;
|
||||
out->ready_at = ready;
|
||||
out->retry_after_s = ready > now ? ready - now : 0;
|
||||
if (out->retry_after_s > 3600)
|
||||
snprintf(out->reason, sizeof(out->reason),
|
||||
"%s quota exhausted: wait ~%ldh (ready_at=%ld), auto-scheduled when quota returns",
|
||||
is_opencode(provider)?"opencode":"provider",
|
||||
out->retry_after_s/3600, ready);
|
||||
else if (!out->reason[0])
|
||||
snprintf(out->reason, sizeof(out->reason),
|
||||
"quota/backoff until %ld (auto-schedule)", ready);
|
||||
/* optional probe to refine ready_at */
|
||||
run_probe(provider, key_id);
|
||||
} else if (r == 2) {
|
||||
out->decision = SP_PROV_DELAY;
|
||||
out->ready_at = ready;
|
||||
out->retry_after_s = ready > now ? ready - now : 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
prov_account(void *ctx, const char *provider, const char *key_id,
|
||||
long http_status, size_t tokens_in, size_t tokens_out)
|
||||
{
|
||||
long ra = 0;
|
||||
(void)ctx;
|
||||
if (!provider || !*provider || !key_id || !*key_id)
|
||||
return;
|
||||
if (is_ollama(provider) && (http_status==429||http_status==402||http_status==529)) {
|
||||
/* local ollama shouldn't quota like cloud, but handle gracefully */
|
||||
ra = 30;
|
||||
}
|
||||
/* retry_after_s: transport/agent apply parsed Retry-After via quota_hint/provstate;
|
||||
* here we record status/tokens and apply status-based defaults. */
|
||||
sp_provstate_account(provider, key_id, http_status, tokens_in, tokens_out, ra);
|
||||
/* on quota exhaustion, probe for accurate ready_at (opt-in) */
|
||||
if (http_status==429 || http_status==402 || http_status==529)
|
||||
run_probe(provider, key_id);
|
||||
}
|
||||
|
||||
static const struct sp_provider_ops ops = { .ctx=NULL, .preflight=prov_preflight, .account=prov_account };
|
||||
|
||||
static void fmt_dur(long s, char *out, size_t cap){
|
||||
if(s>=86400) snprintf(out,cap,"%ldd%ldh",s/86400,(s%86400)/3600);
|
||||
else if(s>=3600) snprintf(out,cap,"%ldh%ldm",s/3600,(s%3600)/60);
|
||||
else snprintf(out,cap,"%lds",s);
|
||||
}
|
||||
|
||||
static int
|
||||
cmd_quota(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char dir[512]; DIR *dp; struct dirent *prov;
|
||||
const char *home = getenv("HOME");
|
||||
long now=(long)time(NULL);
|
||||
(void)h;(void)args;(void)ctx;
|
||||
if(!home) home="/tmp";
|
||||
snprintf(dir,sizeof(dir),"%s/.splinter/providers", home);
|
||||
sp_buf_puts(out,"per-key provider quota/usage (shared):\n");
|
||||
dp=opendir(dir);
|
||||
if(!dp){ sp_buf_puts(out," (no provider state yet)\n"); return 0; }
|
||||
while((prov=readdir(dp))!=NULL){
|
||||
char pdir[600]; DIR *dp2; struct dirent *kf;
|
||||
if(prov->d_name[0]=='.') continue;
|
||||
snprintf(pdir,sizeof(pdir),"%.300s/%.255s",dir,prov->d_name);
|
||||
dp2=opendir(pdir); if(!dp2) continue;
|
||||
while((kf=readdir(dp2))!=NULL){
|
||||
char *dot, path[700], kid[64]; struct sp_prov_state st; char dur[32];
|
||||
if(kf->d_name[0]=='.') continue;
|
||||
dot=strstr(kf->d_name,".json"); if(!dot) continue;
|
||||
{ size_t kl=(size_t)(dot-kf->d_name); if(kl>=sizeof(kid)) kl=sizeof(kid)-1; memcpy(kid,kf->d_name,kl); kid[kl]='\0'; }
|
||||
snprintf(path,sizeof(path),"%.400s/%.255s",pdir,kf->d_name);
|
||||
(void)path;
|
||||
if(sp_provstate_load(prov->d_name,kid,&st)==0){
|
||||
sp_buf_printf(out," %s/%s req=%u tok=%lu/%lu status=%ld",
|
||||
prov->d_name,kid,st.req_count,st.tok_in,st.tok_out,st.last_status);
|
||||
if(st.quota_ready_at>now){ fmt_dur(st.quota_ready_at-now,dur,sizeof(dur)); sp_buf_printf(out," WAIT_QUOTA %s (ready_at=%ld)",dur,st.quota_ready_at); }
|
||||
else if(st.backoff_until>now){ fmt_dur(st.backoff_until-now,dur,sizeof(dur)); sp_buf_printf(out," backoff %s",dur); }
|
||||
if(st.note[0]) sp_buf_printf(out," [%s]",st.note);
|
||||
sp_buf_puts(out,"\n");
|
||||
}
|
||||
}
|
||||
closedir(dp2);
|
||||
}
|
||||
closedir(dp);
|
||||
sp_buf_puts(out,"adapters: opencode, ollama, openai-compat (per-key). probe: SPLINTER_PROVIDER_PROBE=1 + SPLINTER_QUOTA_PROBE_URL/KEY.\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
provider_init(struct sp_host *h)
|
||||
{
|
||||
sp_host_set_provider(h, &ops);
|
||||
sp_host_add_command(h, "quota", cmd_quota, NULL);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI, "provider", "0.2", provider_init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &plugin;
|
||||
}
|
||||
+21
-3
@@ -21,6 +21,7 @@
|
||||
* failure: asking the next exit would show the operator a second answer after
|
||||
* half of the first one.
|
||||
*/
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -38,9 +39,11 @@ struct ring {
|
||||
size_t n;
|
||||
int last; /* which exit served the last turn */
|
||||
int used[MAX_EXITS];
|
||||
/* last and used are written by the turn thread, read by the widget */
|
||||
pthread_mutex_t lock;
|
||||
};
|
||||
|
||||
static struct ring ring;
|
||||
static struct ring ring = { .lock = PTHREAD_MUTEX_INITIALIZER };
|
||||
|
||||
/* Pressure - a limit or a provider that is down - is worth another exit. */
|
||||
static int
|
||||
@@ -89,8 +92,16 @@ build(void)
|
||||
e->key_env : "SPLINTER_API_KEY";
|
||||
const char *key = getenv(env);
|
||||
|
||||
ring.tr[ring.n] = sp_openai_transport(e->endpoint, e->model,
|
||||
key, sp_host_registry(ring.host), 300);
|
||||
{
|
||||
const char *hto = getenv("SPLINTER_HTTP_TIMEOUT");
|
||||
long hto_s = hto != NULL && *hto != '\0' ?
|
||||
strtol(hto, NULL, 10) : 0;
|
||||
|
||||
if (hto_s <= 0)
|
||||
hto_s = 900;
|
||||
ring.tr[ring.n] = sp_openai_transport(e->endpoint, e->model,
|
||||
key, sp_host_registry(ring.host), hto_s);
|
||||
}
|
||||
if (ring.tr[ring.n].send == NULL) {
|
||||
publish("ring: cannot build an exit");
|
||||
return -1;
|
||||
@@ -121,8 +132,10 @@ ring_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
rc = r->tr[i].send(r->tr[i].ctx, conv, out, &e);
|
||||
status = out->status;
|
||||
if (rc == 0) {
|
||||
pthread_mutex_lock(&r->lock);
|
||||
r->last = (int)i;
|
||||
r->used[i]++;
|
||||
pthread_mutex_unlock(&r->lock);
|
||||
snprintf(line, sizeof(line), "%s (%zu/%zu)",
|
||||
r->cfg->exit[i].label, i + 1, r->n);
|
||||
(void)sp_host_widget_text(r->host, "ring", line);
|
||||
@@ -191,8 +204,10 @@ ring_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
&seen);
|
||||
status = out->status;
|
||||
if (rc == 0) {
|
||||
pthread_mutex_lock(&r->lock);
|
||||
r->last = (int)i;
|
||||
r->used[i]++;
|
||||
pthread_mutex_unlock(&r->lock);
|
||||
snprintf(line, sizeof(line), "%s (%zu/%zu)",
|
||||
r->cfg->exit[i].label, i + 1, r->n);
|
||||
(void)sp_host_widget_text(r->host, "ring", line);
|
||||
@@ -232,6 +247,7 @@ ring_widget(struct sp_host *h, const char *name, void *ctx)
|
||||
(void)sp_host_widget_text(ring.host, name, "no exits");
|
||||
return 0;
|
||||
}
|
||||
pthread_mutex_lock(&r->lock);
|
||||
snprintf(line, sizeof(line), "%.16s |", r->cfg->exit[r->last].label);
|
||||
for (i = 0; i < r->n; i++) {
|
||||
char bit[16];
|
||||
@@ -239,6 +255,7 @@ ring_widget(struct sp_host *h, const char *name, void *ctx)
|
||||
snprintf(bit, sizeof(bit), " %d", r->used[i]);
|
||||
strncat(line, bit, sizeof(line) - strlen(line) - 1);
|
||||
}
|
||||
pthread_mutex_unlock(&r->lock);
|
||||
(void)sp_host_widget_text(ring.host, name, line);
|
||||
return 0;
|
||||
}
|
||||
@@ -257,6 +274,7 @@ ring_init(struct sp_host *h)
|
||||
struct sp_transport t;
|
||||
|
||||
memset(&ring, 0, sizeof(ring));
|
||||
(void)pthread_mutex_init(&ring.lock, NULL);
|
||||
ring.host = h;
|
||||
ring.cfg = sp_host_config(h);
|
||||
if (ring.cfg == NULL || ring.cfg->nexits == 0) {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* splinter -- delegation scheduler (auto-retry due jobs).
|
||||
*
|
||||
* Ticks periodically and retries one due durable delegation job
|
||||
* (waiting_quota / waiting_poll / queued with run_after/next_poll_at reached).
|
||||
* This enables "quota back in N days -> auto-scheduled" when combined with
|
||||
* provider preflight/account and durable job records.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
static struct sp_host *host_ref;
|
||||
static char last_status[256];
|
||||
static long last_run;
|
||||
|
||||
static void
|
||||
publish(struct sp_host *h)
|
||||
{
|
||||
char buf[320];
|
||||
if (!h) return;
|
||||
if (last_status[0])
|
||||
snprintf(buf, sizeof(buf), "sched: %s", last_status);
|
||||
else
|
||||
snprintf(buf, sizeof(buf), "sched: idle");
|
||||
sp_host_widget_text(h, "scheduler", buf);
|
||||
}
|
||||
|
||||
static int
|
||||
sched_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
struct sp_buf out;
|
||||
long now = (long)time(NULL);
|
||||
int rc;
|
||||
(void)name; (void)ctx;
|
||||
if (now - last_run < 15)
|
||||
return 0;
|
||||
last_run = now;
|
||||
if (sp_buf_init(&out) != 0)
|
||||
return 0;
|
||||
rc = sp_delegate_tick(&out);
|
||||
if (out.p && strstr(out.p, "none due") == NULL) {
|
||||
snprintf(last_status, sizeof(last_status), "%.200s",
|
||||
out.p ? out.p : (rc == 0 ? "ok" : "err"));
|
||||
} else if (last_status[0] == '\0') {
|
||||
snprintf(last_status, sizeof(last_status), "idle");
|
||||
}
|
||||
sp_buf_free(&out);
|
||||
publish(h ? h : host_ref);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_widget widget = {
|
||||
"scheduler",
|
||||
sched_tick,
|
||||
NULL,
|
||||
NULL,
|
||||
30000 /* 30s */
|
||||
};
|
||||
|
||||
static int
|
||||
scheduler_init(struct sp_host *h)
|
||||
{
|
||||
host_ref = h;
|
||||
snprintf(last_status, sizeof(last_status), "idle");
|
||||
(void)sp_host_add_widget(h, &widget);
|
||||
publish(h);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI,
|
||||
"scheduler",
|
||||
"0.1",
|
||||
scheduler_init,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &plugin;
|
||||
}
|
||||
+18
-6
@@ -56,10 +56,12 @@ render_clock(struct sp_host *h, char *buf, size_t len)
|
||||
static void
|
||||
render_ctx(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
const struct sp_meter *m = sp_host_meter(h);
|
||||
struct sp_meter mm;
|
||||
const struct sp_meter *m = &mm;
|
||||
char used[24], max[24], bar[BAR_WIDTH + 1];
|
||||
size_t filled = 0, i;
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
human(m->ctx_used, used, sizeof(used));
|
||||
if (m->ctx_max == 0) {
|
||||
snprintf(buf, len, "ctx %s", used);
|
||||
@@ -80,8 +82,10 @@ render_ctx(struct sp_host *h, char *buf, size_t len)
|
||||
static void
|
||||
render_rate(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
const struct sp_meter *m = sp_host_meter(h);
|
||||
struct sp_meter mm;
|
||||
const struct sp_meter *m = &mm;
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
if (m->tps <= 0) {
|
||||
buf[0] = '\0';
|
||||
return;
|
||||
@@ -92,9 +96,11 @@ render_rate(struct sp_host *h, char *buf, size_t len)
|
||||
static void
|
||||
render_tokens(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
const struct sp_meter *m = sp_host_meter(h);
|
||||
struct sp_meter mm;
|
||||
const struct sp_meter *m = &mm;
|
||||
char in[24], out[24];
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
human(m->tok_in, in, sizeof(in));
|
||||
human(m->tok_out, out, sizeof(out));
|
||||
snprintf(buf, len, "%s in / %s out", in, out);
|
||||
@@ -103,8 +109,10 @@ render_tokens(struct sp_host *h, char *buf, size_t len)
|
||||
static void
|
||||
render_cost(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
const struct sp_meter *m = sp_host_meter(h);
|
||||
struct sp_meter mm;
|
||||
const struct sp_meter *m = &mm;
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
if (price_in == 0 && price_out == 0) {
|
||||
buf[0] = '\0';
|
||||
return;
|
||||
@@ -122,9 +130,11 @@ render_cost(struct sp_host *h, char *buf, size_t len)
|
||||
static void
|
||||
render_cache(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
const struct sp_meter *m = sp_host_meter(h);
|
||||
struct sp_meter mm;
|
||||
const struct sp_meter *m = &mm;
|
||||
char hit[24];
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
if (m->ctx_used == 0 || m->cached == 0) {
|
||||
buf[0] = '\0';
|
||||
return;
|
||||
@@ -137,8 +147,10 @@ render_cache(struct sp_host *h, char *buf, size_t len)
|
||||
static void
|
||||
render_tasks(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
const struct sp_meter *m = sp_host_meter(h);
|
||||
struct sp_meter mm;
|
||||
const struct sp_meter *m = &mm;
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
if (m->tasks_max == 0) {
|
||||
buf[0] = '\0';
|
||||
return;
|
||||
|
||||
+35
-21
@@ -72,20 +72,26 @@ running_count(void)
|
||||
return n;
|
||||
}
|
||||
|
||||
static void
|
||||
set_task_fields(struct sp_meter *m, void *ctx)
|
||||
{
|
||||
const unsigned *run = ctx;
|
||||
|
||||
m->tasks_running = *run;
|
||||
m->tasks_max = max_parallel;
|
||||
}
|
||||
|
||||
/*
|
||||
* Only the task fields, under the host's lock. A copy of the whole meter,
|
||||
* changed and written back, raced with the UI doing the same with the token
|
||||
* fields: whichever wrote last erased the other's update.
|
||||
*/
|
||||
static void
|
||||
publish_meter(struct sp_host *h)
|
||||
{
|
||||
struct sp_meter m = *sp_host_meter(h);
|
||||
int i, run = 0;
|
||||
unsigned run = (unsigned)running_count();
|
||||
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
for (i = 0; i < ntasks; i++)
|
||||
if (tasks[i].running)
|
||||
run++;
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
m.tasks_running = (unsigned)run;
|
||||
m.tasks_max = max_parallel;
|
||||
sp_host_set_meter(h, &m);
|
||||
sp_host_meter_update(h, set_task_fields, &run);
|
||||
}
|
||||
|
||||
static void
|
||||
@@ -121,6 +127,22 @@ refresh_widget(struct sp_host *h)
|
||||
|
||||
extern char **environ;
|
||||
|
||||
/*
|
||||
* The end of a task, under tasks_lock: that is the lock task_list, the widget
|
||||
* and running_count read 'running', 'status' and 'ended' under. They used to
|
||||
* be written under the task's own lock only - two locks guarding one field
|
||||
* guard nothing.
|
||||
*/
|
||||
static void
|
||||
task_finish(struct task *t, int status)
|
||||
{
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
t->status = status;
|
||||
t->ended = time(NULL);
|
||||
t->running = 0;
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
}
|
||||
|
||||
/*
|
||||
* Run the task in its own process group, so task_kill can stop the shell and
|
||||
* everything it started. popen() gave no pid: t->pid stayed 0, and
|
||||
@@ -146,10 +168,8 @@ task_run(void *arg)
|
||||
free(envp);
|
||||
pthread_mutex_lock(&t->lock);
|
||||
sp_buf_printf(&t->out, "error: %s", strerror(errno));
|
||||
t->status = 127;
|
||||
t->running = 0;
|
||||
t->ended = time(NULL);
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
task_finish(t, 127);
|
||||
return NULL;
|
||||
}
|
||||
for (i = 0, j = 0; i < n; i++)
|
||||
@@ -179,10 +199,8 @@ task_run(void *arg)
|
||||
close(fds[0]);
|
||||
pthread_mutex_lock(&t->lock);
|
||||
sp_buf_printf(&t->out, "error: fork: %s", strerror(errno));
|
||||
t->status = 127;
|
||||
t->running = 0;
|
||||
t->ended = time(NULL);
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
task_finish(t, 127);
|
||||
return NULL;
|
||||
}
|
||||
(void)setpgid(child, child);
|
||||
@@ -206,11 +224,7 @@ task_run(void *arg)
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
t->pid = 0; /* reaped: the id may be reused */
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
pthread_mutex_lock(&t->lock);
|
||||
t->status = st;
|
||||
t->running = 0;
|
||||
t->ended = time(NULL);
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
task_finish(t, st);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
/*
|
||||
* 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 <session>/tmux_watch.log (no fixed sleep in ask; ask waits on the feed).
|
||||
* Commands: /tmux start <cmd>|attach <t>|send <text>|keys <k>|capture [n]|ask <text>|read [wait_ms]|watch start|stop|status|stop
|
||||
* Tools: tmux_start, tmux_send, tmux_capture, tmux_read, tmux_ask, tmux_status, tmux_watch
|
||||
*/
|
||||
#define _DEFAULT_SOURCE
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
static struct sp_host *host_ref;
|
||||
static char target[128];
|
||||
static char sess_dir[512];
|
||||
|
||||
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 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); }
|
||||
|
||||
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);} }
|
||||
|
||||
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<ol && i<nl && old[i]==neu[i]) i++;
|
||||
if(i<nl) sp_buf_add(out, neu+i, nl-i);
|
||||
}
|
||||
|
||||
static long file_size(const char *p){ struct stat st; if(stat(p,&st)!=0) return 0; return (long)st.st_size; }
|
||||
|
||||
static pid_t watcher_pid(void){
|
||||
char p[600], buf[64]; FILE *f; wpid_path(p,sizeof(p));
|
||||
f=fopen(p,"r"); if(!f) return -1;
|
||||
if(!fgets(buf,sizeof(buf),f)){ fclose(f); return -1; }
|
||||
fclose(f);
|
||||
{ pid_t pid=(pid_t)atoi(buf); if(pid>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.len<prevn?cur.len:prevn)!=0)){
|
||||
extract_delta(prev, cur.p, &d);
|
||||
if(d.len>0){
|
||||
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+1<sizeof(text)){ if(*e=='\\'&&e[1]){e++; text[n++]=(*e=='n')?'\n':(*e=='t')?'\t':*e;} else text[n++]=*e; e++; } text[n]='\0'; } }
|
||||
if(!text[0] && args[0] && args[0]!='{') snprintf(text,sizeof(text),"%.4000s",args);
|
||||
}
|
||||
if(!text[0]) return sp_buf_puts(out,"error: text required\n");
|
||||
if(tmux_send_lit(target,text,out)!=0) sp_buf_puts(out,"(tmux send-keys failed)\n");
|
||||
else sp_buf_printf(out,"sent to %s: %.120s%s\n", target, text, strlen(text)>120?"...":"");
|
||||
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<sizeof(text)){ if(*e=='\\'&&e[1]){e++; text[n++]=(*e=='n')?'\n':(*e=='t')?'\t':*e;} else text[n++]=*e; e++; } text[n]='\0'; } }
|
||||
if(!text[0] && args[0] && args[0]!='{') snprintf(text,sizeof(text),"%.4000s",args);
|
||||
}
|
||||
if(!text[0]) return sp_buf_puts(out,"error: text required\n");
|
||||
sp_buf_printf(out,"[proxy -> %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+1<sizeof(cmd)){ if(*e=='\\'&&e[1]){e++; cmd[n++]=*e;} else cmd[n++]=*e; e++; } cmd[n]='\0'; } } }
|
||||
p=strstr(args,"\"name\""); if(p){ p=strchr(p,':'); if(p){ p=strchr(p,'"'); if(p){ char *q=name; p++; while(*p&&*p!='"'&&q<name+sizeof(name)-1) *q++=*p++; *q='\0'; } } }
|
||||
}
|
||||
if(!cmd[0]) return sp_buf_puts(out,"error: cmd required\n");
|
||||
if(!name[0]) snprintf(name,sizeof(name),"splinter-%d",(int)getpid());
|
||||
if(sp_buf_init(&o)!=0) return -1;
|
||||
if(!tmux_has_session(name)){
|
||||
char *a[]={"tmux","new-session","-d","-s",name,"sh","-lc",cmd,NULL};
|
||||
if(run_argv(a,&o)!=0){ sp_buf_puts(out,"error: tmux new-session failed: "); if(o.p) sp_buf_puts(out,o.p); sp_buf_free(&o); return 0; }
|
||||
} else { sp_buf_puts(out,"(session exists, attaching)\n"); }
|
||||
snprintf(target,sizeof(target),"%s",name); save_target(); sp_buf_free(&o);
|
||||
sp_buf_printf(out,"target set to %s (cmd: %s)\n", name, cmd);
|
||||
watcher_start(out);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int tool_watch(const char *args, struct sp_buf *out, void *ctx){
|
||||
(void)ctx; load_target(); ensure_sess();
|
||||
if(args && strstr(args,"stop")) return watcher_stop(out);
|
||||
if(args && strstr(args,"status")){ pid_t pid=watcher_pid(); sp_buf_printf(out,"watcher %s (pid %d) target=%s\n", pid>0?"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<sizeof(esc);i++){ char ch=c[i]; if(ch=='"'||ch=='\\'){esc[j++]='\\';esc[j++]=ch;} else esc[j++]=ch;} esc[j]='\0'; if(sp_buf_init(&a)!=0) return -1; sp_buf_printf(&a,"{\"cmd\":\"%s\"}",esc); {
|
||||
int rc=tool_start(a.p,out,NULL);
|
||||
sp_buf_free(&a);
|
||||
return rc;
|
||||
} }
|
||||
if(strncmp(args,"send ",5)==0){ struct sp_buf a; char esc[4200]; size_t i,j=0; const char *t=args+5; for(i=0;t[i]&&j+2<sizeof(esc);i++){ char c=t[i]; if(c=='"'||c=='\\'){esc[j++]='\\';esc[j++]=c;} else if(c=='\n'){esc[j++]='\\';esc[j++]='n';} else esc[j++]=c;} esc[j]='\0'; if(sp_buf_init(&a)!=0) return -1; sp_buf_printf(&a,"{\"text\":\"%s\"}",esc); {
|
||||
int rc=tool_send(a.p,out,NULL);
|
||||
sp_buf_free(&a);
|
||||
return rc;
|
||||
} }
|
||||
if(strncmp(args,"keys ",5)==0){ if(!target[0]) return sp_buf_puts(out,"no target\n"); { char *a[]={"tmux","send-keys","-t",target,(char*)(args+5),NULL}; run_argv(a,out); }
|
||||
return sp_buf_puts(out,"keys sent\n"); }
|
||||
if(strcmp(args,"capture")==0||strncmp(args,"capture ",8)==0){ struct sp_buf a; int l=200; if(strncmp(args,"capture ",8)==0) l=atoi(args+8); if(sp_buf_init(&a)!=0) return -1; sp_buf_printf(&a,"{\"lines\":%d}",l); {
|
||||
int rc=tool_capture(a.p,out,NULL);
|
||||
sp_buf_free(&a);
|
||||
return rc;
|
||||
} }
|
||||
if(strcmp(args,"read")==0||strncmp(args,"read ",5)==0){ struct sp_buf a; int w=0; if(strncmp(args,"read ",5)==0) w=atoi(args+5); if(sp_buf_init(&a)!=0) return -1; sp_buf_printf(&a,"{\"wait_ms\":%d}",w); {
|
||||
int rc=tool_read(a.p,out,NULL);
|
||||
sp_buf_free(&a);
|
||||
return rc;
|
||||
} }
|
||||
if(strncmp(args,"ask ",4)==0){ struct sp_buf a; char esc[4200]; size_t i,j=0; const char *t=args+4; for(i=0;t[i]&&j+2<sizeof(esc);i++){ char c=t[i]; if(c=='"'||c=='\\'){esc[j++]='\\';esc[j++]=c;} else esc[j++]=c;} esc[j]='\0'; if(sp_buf_init(&a)!=0) return -1; sp_buf_printf(&a,"{\"text\":\"%s\"}",esc); {
|
||||
int rc=tool_ask(a.p,out,NULL);
|
||||
sp_buf_free(&a);
|
||||
return rc;
|
||||
} }
|
||||
if(strncmp(args,"watch",5)==0){ struct sp_buf a; if(strstr(args,"stop")) { if(sp_buf_init(&a)!=0) return -1; sp_buf_puts(&a,"{\"cmd\":\"stop\"}"); } else if(strstr(args,"status")) { if(sp_buf_init(&a)!=0) return -1; sp_buf_puts(&a,"{\"cmd\":\"status\"}"); } else { if(sp_buf_init(&a)!=0) return -1; sp_buf_puts(&a,"{\"cmd\":\"start\"}"); } {
|
||||
int rc=tool_watch(a.p,out,NULL);
|
||||
sp_buf_free(&a);
|
||||
return rc;
|
||||
} }
|
||||
if(strcmp(args,"stop")==0){ watcher_stop(out); if(target[0]){ char *a[]={"tmux","kill-session","-t",target,NULL}; struct sp_buf o; sp_buf_init(&o); run_argv(a,&o); sp_buf_free(&o); sp_buf_printf(out,"killed %s\n",target); target[0]='\0'; save_target(); } return 0; }
|
||||
return sp_buf_puts(out,"usage: /tmux start <cmd>|attach <t>|send <text>|keys <k>|capture [n]|read [wait_ms]|ask <text>|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 */
|
||||
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);
|
||||
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; }
|
||||
+32
-3
@@ -31,7 +31,6 @@ role.error = fehler
|
||||
|
||||
cmd.unknown = unbekanntes Kommando: /%s
|
||||
cmd.available = verfuegbar:
|
||||
shell.no_output = (keine Ausgabe, exit %d)
|
||||
|
||||
err.oom = kein Speicher
|
||||
err.theme = Farbschema
|
||||
@@ -39,10 +38,8 @@ err.session = Sitzung
|
||||
err.plugin_failed = Plugin fehlgeschlagen
|
||||
|
||||
role.tool = werkzeug
|
||||
ui.running_steer = laeuft %lds | Enter steuert, Ctrl-C bricht ab
|
||||
err.thread = Turn-Thread laesst sich nicht starten
|
||||
err.turn_failed = Turn fehlgeschlagen
|
||||
err.followup_failed = Nachfrage fehlgeschlagen
|
||||
sidebar.script = Skript
|
||||
focus.reminder = Pruefe vor der Antwort, ob der letzte Schritt naeher am Ziel war; wenn nicht, sage das und nenne den naechsten Schritt. Ziel: %s
|
||||
focus.set = Ziel gesetzt: %s
|
||||
@@ -55,9 +52,41 @@ cli.timeout = cli: '%s' lief nach %s s in das Zeitlimit
|
||||
cli.failed = cli: '%s' scheiterte (exit %d): %.400s
|
||||
focus.widget_none = kein Ziel (/goal <text>)
|
||||
ui.prompt_mark = >
|
||||
ui.steer_mark = steuern>
|
||||
ui.swarm_locked = [Schwarm gesperrt]
|
||||
sidebar.ms = %ld ms
|
||||
ui.empty = -
|
||||
ui.approve = %s ausfuehren (%s) %.60s? y/N
|
||||
auth.mutate = aendert Dateien
|
||||
auth.destructive = zerstoerend
|
||||
role.diff = aenderung
|
||||
|
||||
# Zustimmung (ack): Kanalnachrichten, Antworten des Gateways, Terminal
|
||||
ack.request = Zustimmung %d: %s %s
|
||||
ack.how = Antwort: ok %d / no %d
|
||||
ack.prompt = Zustimmung %d: %s %s (%ds) - 'splinter --ack %d yes' oder hier y/N:
|
||||
ack.pending = Zustimmung %d: %s %s (%ds)
|
||||
ack.approved_by = splinter: zugestimmt von %s
|
||||
ack.none = keine offenen Anfragen
|
||||
ack.granted = Zustimmung erteilt.
|
||||
ack.refused = Abgelehnt.
|
||||
ack.gone = Diese Anfrage gibt es nicht (mehr).
|
||||
ack.waiting = Ich warte noch auf eine Zustimmung: ok %d / no %d
|
||||
focus.recap = Erinnerung fuer den naechsten Turn eingeplant
|
||||
|
||||
# openai transport
|
||||
openai.oom = openai: kein Speicher
|
||||
openai.build_request = openai: Anfrage kann nicht gebaut werden
|
||||
openai.fdopen = openai: fdopen: %s
|
||||
openai.mkstemp = openai: mkstemp: %s
|
||||
openai.short_write = openai: kurzer Schreibvorgang: %s
|
||||
openai.read_failed = openai: Lesen fehlgeschlagen
|
||||
openai.transfer_failed = openai: Uebertragung fehlgeschlagen fuer %s
|
||||
openai.unparseable = openai: Antwort nicht lesbar (kein Status)
|
||||
openai.stream_failed = openai: Stream fehlgeschlagen fuer %s: %.300s
|
||||
openai.no_sse = openai: Endpoint sendete keine SSE-Daten: %.300s
|
||||
openai.stream_no_answer = openai: Stream endete ohne Antwort: %.300s
|
||||
|
||||
# delegate
|
||||
delegate.timeout = Delegate: '%s' Zeitueberschreitung
|
||||
delegate.parallel_timeout = [parallel: Zeitueberschreitung, Rest wird beendet]
|
||||
+32
-3
@@ -30,7 +30,6 @@ role.error = error
|
||||
|
||||
cmd.unknown = unknown command: /%s
|
||||
cmd.available = available:
|
||||
shell.no_output = (no output, exit %d)
|
||||
|
||||
err.oom = out of memory
|
||||
err.theme = theme
|
||||
@@ -38,10 +37,8 @@ err.session = session
|
||||
err.plugin_failed = plugin failed
|
||||
|
||||
role.tool = tool
|
||||
ui.running_steer = running %lds | Enter steers, Ctrl-C cancels
|
||||
err.thread = cannot start the turn thread
|
||||
err.turn_failed = turn failed
|
||||
err.followup_failed = follow-up failed
|
||||
sidebar.script = script
|
||||
focus.reminder = Before answering, check whether the last step moved closer to the goal. If not, say so and name the next step. Goal: %s
|
||||
focus.set = goal set: %s
|
||||
@@ -54,9 +51,41 @@ cli.timeout = cli: '%s' timed out after %s s
|
||||
cli.failed = cli: '%s' failed (exit %d): %.400s
|
||||
focus.widget_none = no goal (/goal <text>)
|
||||
ui.prompt_mark = >
|
||||
ui.steer_mark = steer>
|
||||
ui.swarm_locked = [swarm locked]
|
||||
sidebar.ms = %ld ms
|
||||
ui.empty = -
|
||||
ui.approve = run %s (%s) %.60s? y/N
|
||||
auth.mutate = changes files
|
||||
auth.destructive = destructive
|
||||
role.diff = diff
|
||||
|
||||
# approvals (ack): channel messages, the gateway's replies, the terminal
|
||||
ack.request = Approval %d: %s %s
|
||||
ack.how = Answer: ok %d / no %d
|
||||
ack.prompt = approval %d: %s %s (%ds) - 'splinter --ack %d yes' or y/N here:
|
||||
ack.pending = approval %d: %s %s (%ds)
|
||||
ack.approved_by = splinter: approved by %s
|
||||
ack.none = no open requests
|
||||
ack.granted = Approved.
|
||||
ack.refused = Refused.
|
||||
ack.gone = There is no such request (any more).
|
||||
ack.waiting = Still waiting for an approval: ok %d / no %d
|
||||
focus.recap = reminder scheduled for the next turn
|
||||
|
||||
# openai transport
|
||||
openai.oom = openai: out of memory
|
||||
openai.build_request = openai: cannot build the request
|
||||
openai.fdopen = openai: fdopen: %s
|
||||
openai.mkstemp = openai: mkstemp: %s
|
||||
openai.short_write = openai: short write: %s
|
||||
openai.read_failed = openai: read failed
|
||||
openai.transfer_failed = openai: transfer failed for %s
|
||||
openai.unparseable = openai: unparseable response (no status)
|
||||
openai.stream_failed = openai: stream failed for %s: %.300s
|
||||
openai.no_sse = openai: endpoint sent no SSE data: %.300s
|
||||
openai.stream_no_answer = openai: stream ended with no answer: %.300s
|
||||
|
||||
# delegate
|
||||
delegate.timeout = delegate: '%s' timed out
|
||||
delegate.parallel_timeout = [parallel: timeout, killing the rest]
|
||||
+32
-3
@@ -6,9 +6,10 @@
|
||||
|
||||
ui.ready = pronto. Enter envia, Ctrl-D sai.
|
||||
ui.working = trabalhando...
|
||||
ui.running_steer = rodando %lds | Enter direciona, Ctrl-C cancela
|
||||
ui.steering_queued = direcionamento na fila
|
||||
ui.prompt_mark = >
|
||||
ui.steer_mark = direcionar>
|
||||
ui.swarm_locked = [enxame bloqueado]
|
||||
ui.approve = executar %s (%s) %.60s? y/N
|
||||
|
||||
sidebar.session = sessao
|
||||
@@ -38,7 +39,6 @@ role.diff = alteracao
|
||||
|
||||
cmd.unknown = comando desconhecido: /%s
|
||||
cmd.available = disponiveis:
|
||||
shell.no_output = (sem saida, exit %d)
|
||||
|
||||
err.oom = sem memoria
|
||||
err.theme = tema
|
||||
@@ -46,7 +46,6 @@ err.session = sessao
|
||||
err.plugin_failed = plugin falhou
|
||||
err.thread = nao foi possivel iniciar a thread do turno
|
||||
err.turn_failed = turno falhou
|
||||
err.followup_failed = continuacao falhou
|
||||
ui.empty = -
|
||||
|
||||
auth.mutate = altera arquivos
|
||||
@@ -64,3 +63,33 @@ cps.plan = plano pronto: corte %zu/%zu, %zu -> %zu B
|
||||
cli.no_output = cli: '%s' nao produziu saida
|
||||
cli.timeout = cli: '%s' passou do limite de %s s
|
||||
cli.failed = cli: '%s' falhou (exit %d): %.400s
|
||||
|
||||
# aprovacoes (ack): mensagens dos canais, respostas do gateway, terminal
|
||||
ack.request = Aprovacao %d: %s %s
|
||||
ack.how = Resposta: ok %d / no %d
|
||||
ack.prompt = aprovacao %d: %s %s (%ds) - 'splinter --ack %d yes' ou y/N aqui:
|
||||
ack.pending = aprovacao %d: %s %s (%ds)
|
||||
ack.approved_by = splinter: aprovado por %s
|
||||
ack.none = nenhum pedido aberto
|
||||
ack.granted = Aprovado.
|
||||
ack.refused = Recusado.
|
||||
ack.gone = Esse pedido nao existe (mais).
|
||||
ack.waiting = Ainda aguardando uma aprovacao: ok %d / no %d
|
||||
focus.recap = lembrete agendado para o proximo turno
|
||||
|
||||
# openai transport
|
||||
openai.oom = openai: sem memoria
|
||||
openai.build_request = openai: nao foi possivel montar a requisicao
|
||||
openai.fdopen = openai: fdopen: %s
|
||||
openai.mkstemp = openai: mkstemp: %s
|
||||
openai.short_write = openai: escrita incompleta: %s
|
||||
openai.read_failed = openai: falha na leitura
|
||||
openai.transfer_failed = openai: falha na transferencia para %s
|
||||
openai.unparseable = openai: resposta ilegivel (sem status)
|
||||
openai.stream_failed = openai: stream falhou para %s: %.300s
|
||||
openai.no_sse = openai: endpoint nao enviou dados SSE: %.300s
|
||||
openai.stream_no_answer = openai: stream terminou sem resposta: %.300s
|
||||
|
||||
# delegate
|
||||
delegate.timeout = delegate: '%s' excedeu o tempo
|
||||
delegate.parallel_timeout = [paralelo: tempo esgotado, encerrando o resto]
|
||||
@@ -34,6 +34,7 @@
|
||||
#include <sys/wait.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "i18n.h"
|
||||
#include "ack.h"
|
||||
|
||||
static char ack_root[512];
|
||||
@@ -245,9 +246,15 @@ sp_ack_notify(int id, struct sp_buf *log)
|
||||
request_field(id, "args", args, sizeof(args));
|
||||
if (strlen(args) > 300)
|
||||
memcpy(args + 297, "...", 4);
|
||||
snprintf(msg, sizeof(msg), "Zustimmung %d: %s %s\n"
|
||||
"Antwort: ok %d / no %d", id, tool[0] != '\0' ? tool : "?", args,
|
||||
id, id);
|
||||
{
|
||||
char head[480], how[100];
|
||||
|
||||
snprintf(head, sizeof(head), sp_td("ack.request",
|
||||
"Approval %d: %s %s"), id, tool[0] != '\0' ? tool : "?", args);
|
||||
snprintf(how, sizeof(how), sp_td("ack.how",
|
||||
"Answer: ok %d / no %d"), id, id);
|
||||
snprintf(msg, sizeof(msg), "%s\n%s", head, how);
|
||||
}
|
||||
snprintf(list, sizeof(list), "%s", chans);
|
||||
for (tok = strtok_r(list, ",", &save); tok != NULL;
|
||||
tok = strtok_r(NULL, ",", &save)) {
|
||||
@@ -387,7 +394,8 @@ sp_ack_list(struct sp_buf *out)
|
||||
snprintf(dir, sizeof(dir), "%s/pending", root);
|
||||
n = scandir(dir, &ents, NULL, alphasort);
|
||||
if (n < 0) {
|
||||
sp_buf_puts(out, "keine offenen Anfragen\n");
|
||||
sp_buf_printf(out, "%s\n", sp_td("ack.none",
|
||||
"no open requests"));
|
||||
return 0;
|
||||
}
|
||||
for (i = 0; i < n; i++) {
|
||||
|
||||
+74
-9
@@ -26,6 +26,7 @@
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "i18n.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "ack.h"
|
||||
#include "log.h"
|
||||
@@ -42,6 +43,26 @@ struct ack_thread {
|
||||
int stop; /* read end of the stop pipe */
|
||||
};
|
||||
|
||||
|
||||
struct quota_set_ctx { long status; long now; long retry_after_s; };
|
||||
static void quota_set_fn(struct sp_prov_state *st, void *p) {
|
||||
struct quota_set_ctx *c = p;
|
||||
long ra = 0;
|
||||
if (c->retry_after_s > 0) ra = c->now + c->retry_after_s;
|
||||
else if (c->status == 429 || c->status == 402) ra = c->now + 60;
|
||||
else if (c->status == 529) ra = c->now + 120;
|
||||
if (ra > 0 && st->quota_ready_at < ra) st->quota_ready_at = ra;
|
||||
if (ra > 0) st->last_429_at = c->now;
|
||||
if (ra > 0) snprintf(st->note, sizeof(st->note), "quota %ld ready_at=%ld", c->status, ra);
|
||||
}
|
||||
static void quota_hint(const char *provider, const char *key_id, long status, long retry_after_s) {
|
||||
struct quota_set_ctx c;
|
||||
if (!provider||!*provider||!key_id||!*key_id) return;
|
||||
if (status!=429 && status!=402 && status!=529) return;
|
||||
c.status = status; c.now = (long)time(NULL); c.retry_after_s = retry_after_s;
|
||||
sp_provstate_update(provider, key_id, quota_set_fn, &c);
|
||||
}
|
||||
|
||||
static void *
|
||||
ack_stdin_thread(void *arg)
|
||||
{
|
||||
@@ -112,12 +133,12 @@ ack_approval(struct sp_agent *a, const struct sp_tool *t, const char *args)
|
||||
sp_buf_free(&log);
|
||||
}
|
||||
if (a->cfg->approval_out != NULL)
|
||||
fprintf(a->cfg->approval_out, "Zustimmung %d: %s %s "
|
||||
"(%ds) - 'splinter --ack %d yes' oder hier y/N: ", id, t->name,
|
||||
args, ttl, id);
|
||||
fprintf(a->cfg->approval_out, sp_td("ack.prompt",
|
||||
"approval %d: %s %s (%ds) - 'splinter --ack %d yes' or y/N "
|
||||
"here: "), id, t->name, args, ttl, id);
|
||||
else
|
||||
fprintf(stderr, "Zustimmung %d: %s %s (%ds)\n", id, t->name, args,
|
||||
ttl);
|
||||
fprintf(stderr, sp_td("ack.pending", "approval %d: %s %s (%ds)\n"),
|
||||
id, t->name, args, ttl);
|
||||
if (a->cfg->approval_out != NULL)
|
||||
fflush(a->cfg->approval_out);
|
||||
|
||||
@@ -139,7 +160,8 @@ ack_approval(struct sp_agent *a, const struct sp_tool *t, const char *args)
|
||||
close(stop[1]);
|
||||
}
|
||||
if (yes && who[0] != '\0')
|
||||
fprintf(stderr, "splinter: zugestimmt von %s\n", who);
|
||||
fprintf(stderr, sp_td("ack.approved_by",
|
||||
"splinter: approved by %s\n"), who);
|
||||
return yes;
|
||||
}
|
||||
|
||||
@@ -299,9 +321,16 @@ sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer,
|
||||
sp_buf_free(&steer);
|
||||
}
|
||||
/* compaction happens before the budget is judged, never after */
|
||||
if (a->host != NULL &&
|
||||
sp_host_compact(a->host, conv, a->cfg->max_bytes) > 0)
|
||||
a->stats.compactions++;
|
||||
if (a->host != NULL) {
|
||||
size_t cb = sp_conv_bytes(conv), cn = conv->n;
|
||||
|
||||
if (sp_host_compact(a->host, conv, a->cfg->max_bytes) > 0) {
|
||||
a->stats.compactions++;
|
||||
if (a->cfg != NULL && a->cfg->on_compact != NULL)
|
||||
a->cfg->on_compact(a->cfg->on_compact_ctx,
|
||||
cb, sp_conv_bytes(conv), cn, conv->n);
|
||||
}
|
||||
}
|
||||
sent = sp_conv_bytes(conv);
|
||||
if (a->cfg->max_bytes > 0 && sent > a->cfg->max_bytes) {
|
||||
sp_buf_printf(err, "agent: conversation budget exceeded "
|
||||
@@ -312,6 +341,31 @@ sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer,
|
||||
a->stats.bytes_sent += sent;
|
||||
a->stats.steps++;
|
||||
|
||||
{
|
||||
struct sp_prov_result pr;
|
||||
enum sp_prov_decision pd;
|
||||
|
||||
pd = sp_host_provider_preflight(a->host, a->tr.provider,
|
||||
a->tr.key_id, &pr);
|
||||
if (pd == SP_PROV_WAIT_QUOTA || pd == SP_PROV_DENY) {
|
||||
sp_buf_printf(err,
|
||||
"provider quota/policy: %s (ready_at=%ld retry_after=%lds)",
|
||||
pr.reason[0] ? pr.reason : "denied",
|
||||
pr.ready_at, pr.retry_after_s);
|
||||
goto out;
|
||||
}
|
||||
if (pd == SP_PROV_DELAY && pr.retry_after_s > 0) {
|
||||
if (pr.retry_after_s <= 30)
|
||||
sleep((unsigned)pr.retry_after_s);
|
||||
else {
|
||||
sp_buf_printf(err,
|
||||
"provider quota/policy: %s (ready_at=%ld retry_after=%lds)",
|
||||
pr.reason[0] ? pr.reason : "delay",
|
||||
pr.ready_at, pr.retry_after_s);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
int sent_rc;
|
||||
|
||||
@@ -324,11 +378,18 @@ sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer,
|
||||
sent_rc = a->tr.send(a->tr.ctx, conv, &reply,
|
||||
err);
|
||||
if (sent_rc != 0) {
|
||||
sp_host_provider_account(a->host, a->tr.provider,
|
||||
a->tr.key_id, reply.status, 0, 0);
|
||||
sp_reply_free(&reply);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
if (reply.status < 200 || reply.status > 299) {
|
||||
sp_host_provider_account(a->host, a->tr.provider,
|
||||
a->tr.key_id, reply.status,
|
||||
(size_t)(reply.tokens_in > 0 ? reply.tokens_in : 0),
|
||||
(size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0));
|
||||
quota_hint(a->tr.provider, a->tr.key_id, reply.status, reply.retry_after_s);
|
||||
sp_buf_printf(err, "agent: transport status %ld",
|
||||
reply.status);
|
||||
sp_reply_free(&reply);
|
||||
@@ -339,6 +400,10 @@ sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer,
|
||||
reply.tokens_in : 0);
|
||||
a->stats.tokens_out += (size_t)(reply.tokens_out > 0 ?
|
||||
reply.tokens_out : 0);
|
||||
sp_host_provider_account(a->host, a->tr.provider, a->tr.key_id,
|
||||
reply.status,
|
||||
(size_t)(reply.tokens_in > 0 ? reply.tokens_in : 0),
|
||||
(size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0));
|
||||
|
||||
if (reply.ncalls == 0) {
|
||||
const char *text = reply.content != NULL ?
|
||||
|
||||
@@ -115,25 +115,54 @@ int
|
||||
sp_json_escape(struct sp_buf *b, const char *s)
|
||||
{
|
||||
static const char hex[] = "0123456789abcdef";
|
||||
unsigned char c;
|
||||
const unsigned char *p = (const unsigned char *)s;
|
||||
|
||||
while (*p != '\0') {
|
||||
unsigned char c = *p;
|
||||
|
||||
for (; *s != '\0'; s++) {
|
||||
c = (unsigned char)*s;
|
||||
switch (c) {
|
||||
case '"': if (sp_buf_puts(b, "\\\"") != 0) return -1; break;
|
||||
case '\\': if (sp_buf_puts(b, "\\\\") != 0) return -1; break;
|
||||
case '\n': if (sp_buf_puts(b, "\\n") != 0) return -1; break;
|
||||
case '\r': if (sp_buf_puts(b, "\\r") != 0) return -1; break;
|
||||
case '\t': if (sp_buf_puts(b, "\\t") != 0) return -1; break;
|
||||
case '"': if (sp_buf_puts(b, "\\\"") != 0) return -1; p++; break;
|
||||
case '\\': if (sp_buf_puts(b, "\\\\") != 0) return -1; p++; break;
|
||||
case '\n': if (sp_buf_puts(b, "\\n") != 0) return -1; p++; break;
|
||||
case '\r': if (sp_buf_puts(b, "\\r") != 0) return -1; p++; break;
|
||||
case '\t': if (sp_buf_puts(b, "\\t") != 0) return -1; p++; break;
|
||||
default:
|
||||
if (c < 0x20) {
|
||||
char esc[7] = { '\\', 'u', '0', '0',
|
||||
hex[c >> 4], hex[c & 0xf], '\0' };
|
||||
if (sp_buf_puts(b, esc) != 0)
|
||||
return -1;
|
||||
} else {
|
||||
if (sp_buf_add(b, (const char *)&c, 1) != 0)
|
||||
p++;
|
||||
} else if (c < 0x80) {
|
||||
if (sp_buf_add(b, (const char *)p, 1) != 0)
|
||||
return -1;
|
||||
p++;
|
||||
} else {
|
||||
/* Valid UTF-8 passes through; invalid bytes become \u00XX
|
||||
* so the JSON string stays well-formed UTF-8. */
|
||||
size_t n = 0;
|
||||
|
||||
if ((c & 0xe0) == 0xc0 && (p[1] & 0xc0) == 0x80 &&
|
||||
c >= 0xc2)
|
||||
n = 2;
|
||||
else if ((c & 0xf0) == 0xe0 && (p[1] & 0xc0) == 0x80 &&
|
||||
(p[2] & 0xc0) == 0x80)
|
||||
n = 3;
|
||||
else if ((c & 0xf8) == 0xf0 && (p[1] & 0xc0) == 0x80 &&
|
||||
(p[2] & 0xc0) == 0x80 && (p[3] & 0xc0) == 0x80 &&
|
||||
c <= 0xf4)
|
||||
n = 4;
|
||||
if (n > 0) {
|
||||
if (sp_buf_add(b, (const char *)p, n) != 0)
|
||||
return -1;
|
||||
p += n;
|
||||
} else {
|
||||
char esc[7] = { '\\', 'u', '0', '0',
|
||||
hex[c >> 4], hex[c & 0xf], '\0' };
|
||||
if (sp_buf_puts(b, esc) != 0)
|
||||
return -1;
|
||||
p++;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
+1
-1
@@ -127,7 +127,7 @@ sp_secret_env_is(const char *entry)
|
||||
extern char **environ;
|
||||
|
||||
#define RUN_MAX_OUTPUT (1u << 20)
|
||||
#define RUN_TIMEOUT_S 300
|
||||
#define RUN_TIMEOUT_S 600
|
||||
|
||||
/*
|
||||
* Run a shell command for the model.
|
||||
|
||||
+2
-2
@@ -29,8 +29,8 @@
|
||||
#include "splinter.h"
|
||||
#include "cmdscript.h"
|
||||
|
||||
#define CMD_TIMEOUT_MS 60000
|
||||
#define CMD_MAX_BYTES 262144
|
||||
#define CMD_TIMEOUT_MS 300000
|
||||
#define CMD_MAX_BYTES (4u << 20)
|
||||
|
||||
/*
|
||||
* Where the programs live: $SPLINTER_COMMANDS_DIR, else ~/.splinter/commands.
|
||||
|
||||
+94
-1
@@ -146,6 +146,68 @@ parse_exit(struct sp_exit *e, const char *val, struct sp_buf *err,
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* NAME=VALUE with a name the shell would accept. A bad name is an error, not
|
||||
* a silently dropped variable: the whole point is that the program sees it.
|
||||
*/
|
||||
static int
|
||||
valid_env(const char *s)
|
||||
{
|
||||
const char *p = s;
|
||||
|
||||
if (!((*p >= 'A' && *p <= 'Z') || (*p >= 'a' && *p <= 'z') || *p == '_'))
|
||||
return 0;
|
||||
for (p++; *p != '\0' && *p != '='; p++)
|
||||
if (!((*p >= 'A' && *p <= 'Z') || (*p >= 'a' && *p <= 'z') ||
|
||||
(*p >= '0' && *p <= '9') || *p == '_'))
|
||||
return 0;
|
||||
return *p == '=';
|
||||
}
|
||||
|
||||
static int
|
||||
add_env(char (*env)[SP_CONFIG_ENV_LEN], size_t *n, const char *val,
|
||||
struct sp_buf *err, const char *path, unsigned lineno)
|
||||
{
|
||||
if (!valid_env(val)) {
|
||||
sp_buf_printf(err, "config: %s:%u: env wants NAME=VALUE, got "
|
||||
"'%.40s'", path, lineno, val);
|
||||
return -1;
|
||||
}
|
||||
if (*n == SP_CONFIG_MAX_ENV) {
|
||||
sp_buf_printf(err, "config: %s:%u: more than %d env entries",
|
||||
path, lineno, SP_CONFIG_MAX_ENV);
|
||||
return -1;
|
||||
}
|
||||
if (strlen(val) >= SP_CONFIG_ENV_LEN) {
|
||||
sp_buf_printf(err, "config: %s:%u: env entry longer than %d",
|
||||
path, lineno, SP_CONFIG_ENV_LEN - 1);
|
||||
return -1;
|
||||
}
|
||||
snprintf(env[(*n)++], SP_CONFIG_ENV_LEN, "%s", val);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void
|
||||
sp_config_apply_env(const char (*env)[SP_CONFIG_ENV_LEN], size_t n)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < n; i++) {
|
||||
char name[128];
|
||||
const char *eq = strchr(env[i], '=');
|
||||
size_t len;
|
||||
|
||||
if (eq == NULL)
|
||||
continue;
|
||||
len = (size_t)(eq - env[i]);
|
||||
if (len >= sizeof(name))
|
||||
continue;
|
||||
memcpy(name, env[i], len);
|
||||
name[len] = '\0';
|
||||
(void)setenv(name, eq + 1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
static int
|
||||
parse_delegate(struct sp_delegate *d, const char *val, struct sp_buf *err,
|
||||
const char *path, unsigned lineno)
|
||||
@@ -196,6 +258,13 @@ parse_delegate(struct sp_delegate *d, const char *val, struct sp_buf *err,
|
||||
snprintf(d->model, sizeof(d->model), "%s", s + 6);
|
||||
else if (!strncmp(s, "key_env=", 8))
|
||||
snprintf(d->key_env, sizeof(d->key_env), "%s", s + 8);
|
||||
else if (!strncmp(s, "env=", 4)) {
|
||||
if (add_env(d->env, &d->nenv, s + 4, err, path,
|
||||
lineno) != 0) {
|
||||
free(copy);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else if (strchr(s, '=') == NULL) {
|
||||
snprintf(d->about, sizeof(d->about), "%s", s);
|
||||
first = 0;
|
||||
@@ -350,10 +419,26 @@ load_one(struct sp_config *c, const char *path, struct sp_buf *err)
|
||||
set_str(c->session_dir, sizeof(c->session_dir), val);
|
||||
else if (!strcmp(key, "cli_cmd"))
|
||||
set_str(c->cli_cmd, sizeof(c->cli_cmd), val);
|
||||
else if (!strcmp(key, "cli_env")) {
|
||||
if (add_env(c->cli_env, &c->ncli_env, val, err, path,
|
||||
lineno) != 0) {
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else if (!strcmp(key, "steps"))
|
||||
c->steps = (size_t)strtoul(val, NULL, 10);
|
||||
else if (!strcmp(key, "max_bytes"))
|
||||
c->max_bytes = (size_t)strtoul(val, NULL, 10);
|
||||
else if (!strcmp(key, "http_timeout") ||
|
||||
!strcmp(key, "request_timeout"))
|
||||
c->http_timeout = strtol(val, NULL, 10);
|
||||
else if (!strcmp(key, "cli_timeout"))
|
||||
c->cli_timeout = strtol(val, NULL, 10);
|
||||
else if (!strcmp(key, "delegate_timeout"))
|
||||
c->delegate_timeout = strtol(val, NULL, 10);
|
||||
else if (!strcmp(key, "run_timeout"))
|
||||
c->run_timeout = strtol(val, NULL, 10);
|
||||
else if (!strcmp(key, "env_delegates"))
|
||||
c->env_delegates = (!strcmp(val, "1") ||
|
||||
!strcmp(val, "true") || !strcmp(val, "yes")) ? 1 : 0;
|
||||
@@ -463,6 +548,7 @@ sp_config_write_example(const char *path, struct sp_buf *err)
|
||||
"# model. Use either this or endpoint/model, not both.\n"
|
||||
"#transport = cli\n"
|
||||
"#cli_cmd = claude -p\n"
|
||||
"#cli_env = CLAUDE_CODE_OAUTH_TOKEN=sk-ant-...\n"
|
||||
"\n"
|
||||
"# Plugins to load, one per line. Paths are relative to the working\n"
|
||||
"# directory unless absolute.\n"
|
||||
@@ -481,9 +567,16 @@ sp_config_write_example(const char *path, struct sp_buf *err)
|
||||
"\n"
|
||||
"# Tool rounds per turn, and the conversation budget in bytes\n"
|
||||
"# (0 = no limit).\n"
|
||||
"steps = 8\n"
|
||||
"steps = 150\n"
|
||||
"max_bytes = 0\n"
|
||||
"\n"
|
||||
"# Timeouts in seconds. Local models can take long to answer: raise\n"
|
||||
"# these instead of failing mid-turn. 0 means the built-in default.\n"
|
||||
"#http_timeout = 900\n"
|
||||
"#cli_timeout = 1800\n"
|
||||
"#delegate_timeout = 900\n"
|
||||
"#run_timeout = 600\n"
|
||||
"\n"
|
||||
"# Where session logs go (default ~/.splinter).\n"
|
||||
"#session_dir = ~/.splinter\n"
|
||||
"\n"
|
||||
|
||||
@@ -30,6 +30,14 @@
|
||||
*/
|
||||
#define SP_CONFIG_MAX_DELEGATES 8
|
||||
|
||||
/*
|
||||
* Extra environment for a program splinter starts: NAME=VALUE, set in the
|
||||
* child right before exec. Lets two delegates run the same cli with two
|
||||
* different accounts.
|
||||
*/
|
||||
#define SP_CONFIG_MAX_ENV 8
|
||||
#define SP_CONFIG_ENV_LEN 512
|
||||
|
||||
/*
|
||||
* An exit is one way to reach a model: an endpoint, a model name and where its
|
||||
* key lives. The ring tries them in order, so a rate limit costs a step, not the
|
||||
@@ -56,6 +64,8 @@ struct sp_delegate {
|
||||
char endpoint[512];
|
||||
char model[256];
|
||||
char key_env[64];
|
||||
char env[SP_CONFIG_MAX_ENV][SP_CONFIG_ENV_LEN]; /* NAME=VALUE */
|
||||
size_t nenv;
|
||||
};
|
||||
|
||||
struct sp_config {
|
||||
@@ -73,6 +83,8 @@ struct sp_config {
|
||||
char system_prompt[1024];
|
||||
char session_dir[512];
|
||||
char cli_cmd[512];
|
||||
char cli_env[SP_CONFIG_MAX_ENV][SP_CONFIG_ENV_LEN]; /* NAME=VALUE */
|
||||
size_t ncli_env;
|
||||
char memory_url[512];
|
||||
char memory_key_env[64];
|
||||
char telegram_allow[256]; /* comma separated user ids */
|
||||
@@ -81,6 +93,10 @@ struct sp_config {
|
||||
size_t nplugins;
|
||||
size_t steps; /* 0: not set */
|
||||
size_t max_bytes; /* 0: not set */
|
||||
long http_timeout; /* seconds for HTTP/SSE requests, 0: default */
|
||||
long cli_timeout; /* seconds for cli transport, 0: default */
|
||||
long delegate_timeout; /* seconds for delegate children, 0: default */
|
||||
long run_timeout; /* seconds for the run tool, 0: default */
|
||||
int autonomous; /* -1 not set, 0 off, 1 on */
|
||||
/*
|
||||
* Delegates built from environment tokens (CLAUDE_CODE_OAUTH_TOKEN and the
|
||||
@@ -114,4 +130,7 @@ int sp_config_load(struct sp_config *, const char *path, struct sp_buf *err);
|
||||
/* Write a commented starter file. Returns 0 or -1. */
|
||||
int sp_config_write_example(const char *path, struct sp_buf *err);
|
||||
|
||||
/* Set every NAME=VALUE of 'env' in this process, overwriting. */
|
||||
void sp_config_apply_env(const char (*env)[SP_CONFIG_ENV_LEN], size_t n);
|
||||
|
||||
#endif /* SPLINTER_CONFIG_H */
|
||||
+951
-85
File diff suppressed because it is too large.
Load diff
+709
-599
File diff suppressed because it is too large.
Load diff
+77
-2
@@ -50,6 +50,7 @@ struct widget {
|
||||
struct sp_host {
|
||||
struct sp_registry *reg;
|
||||
const void *conf; /* the loaded config, for plugins */
|
||||
const char *session_dir; /* session directory, for persistence */
|
||||
struct widget widgets[MAX_WIDGETS];
|
||||
size_t nwidgets;
|
||||
char note[MAX_NOTE];
|
||||
@@ -81,6 +82,8 @@ struct sp_host {
|
||||
/* loaded plugins, in load order, so shutdown() runs in reverse */
|
||||
const struct sp_plugin *loaded[MAX_PLUGINS];
|
||||
size_t nloaded;
|
||||
/* quota/usage/burst policy hook (dispatches by provider/key_id) */
|
||||
const struct sp_provider_ops *provider;
|
||||
};
|
||||
|
||||
static void *
|
||||
@@ -238,8 +241,42 @@ sp_host_meter(struct sp_host *h)
|
||||
void
|
||||
sp_host_set_meter(struct sp_host *h, const struct sp_meter *m)
|
||||
{
|
||||
if (h != NULL && m != NULL)
|
||||
h->meter = *m;
|
||||
if (h == NULL || m == NULL)
|
||||
return;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
h->meter = *m;
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
/*
|
||||
* The meter is written from the UI thread (tokens), from turn threads (tools
|
||||
* of the tasks plugin) and from widget threads. These two are the safe way:
|
||||
* a copy taken under the lock, and a change of only the fields the caller
|
||||
* owns, under the lock.
|
||||
*/
|
||||
void
|
||||
sp_host_meter_get(struct sp_host *h, struct sp_meter *out)
|
||||
{
|
||||
if (out == NULL)
|
||||
return;
|
||||
if (h == NULL) {
|
||||
memset(out, 0, sizeof(*out));
|
||||
return;
|
||||
}
|
||||
pthread_mutex_lock(&h->lock);
|
||||
*out = h->meter;
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_meter_update(struct sp_host *h,
|
||||
void (*fn)(struct sp_meter *, void *), void *ctx)
|
||||
{
|
||||
if (h == NULL || fn == NULL)
|
||||
return;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
fn(&h->meter, ctx);
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
size_t
|
||||
@@ -655,10 +692,48 @@ sp_host_new(struct sp_registry *reg, struct sp_agent *agent,
|
||||
h->reg = reg;
|
||||
h->agent = agent;
|
||||
h->sess = sess;
|
||||
h->session_dir = (sess != NULL) ? sess->dir : NULL;
|
||||
pthread_mutex_init(&h->lock, NULL);
|
||||
return h;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_session_dir(struct sp_host *h)
|
||||
{
|
||||
return (h != NULL) ? h->session_dir : NULL;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_set_provider(struct sp_host *h, const struct sp_provider_ops *ops)
|
||||
{
|
||||
if (h != NULL)
|
||||
h->provider = ops;
|
||||
}
|
||||
|
||||
enum sp_prov_decision
|
||||
sp_host_provider_preflight(struct sp_host *h, const char *provider,
|
||||
const char *key_id, struct sp_prov_result *out)
|
||||
{
|
||||
if (out != NULL) {
|
||||
memset(out, 0, sizeof(*out));
|
||||
out->decision = SP_PROV_ADMIT;
|
||||
}
|
||||
if (h == NULL || h->provider == NULL || h->provider->preflight == NULL)
|
||||
return SP_PROV_ADMIT;
|
||||
(void)h->provider->preflight(h->provider->ctx, provider, key_id, out);
|
||||
return (out != NULL) ? out->decision : SP_PROV_ADMIT;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_provider_account(struct sp_host *h, const char *provider,
|
||||
const char *key_id, long http_status, size_t tokens_in, size_t tokens_out)
|
||||
{
|
||||
if (h == NULL || h->provider == NULL || h->provider->account == NULL)
|
||||
return;
|
||||
h->provider->account(h->provider->ctx, provider, key_id, http_status,
|
||||
tokens_in, tokens_out);
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_free(struct sp_host *h)
|
||||
{
|
||||
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
/*
|
||||
* splinter -- shared provider/key state (quota/usage), cross-instance.
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "provstate.h"
|
||||
|
||||
/* djb2-ish hash -> hex, stable key identity (not secret storage) */
|
||||
static void
|
||||
keyhash(const char *s, char out[17])
|
||||
{
|
||||
unsigned long h = 5381;
|
||||
int c;
|
||||
while (s && (c = (unsigned char)*s++))
|
||||
h = ((h << 5) + h) ^ (unsigned long)c;
|
||||
snprintf(out, 17, "%016lx", h);
|
||||
}
|
||||
|
||||
static void
|
||||
mkdirs(const char *path)
|
||||
{
|
||||
char buf[512], *p;
|
||||
snprintf(buf, sizeof(buf), "%s", path);
|
||||
for (p = buf + 1; *p; p++) {
|
||||
if (*p == '/') { *p = '\0'; mkdir(buf, 0700); *p = '/'; }
|
||||
}
|
||||
mkdir(buf, 0700);
|
||||
}
|
||||
|
||||
char *
|
||||
sp_provstate_base(const char *provider, const char *key_id,
|
||||
char *buf, size_t cap)
|
||||
{
|
||||
const char *home = getenv("HOME");
|
||||
char kh[17], dir[512];
|
||||
if (!provider || !*provider || !key_id || !*key_id || !home)
|
||||
return NULL;
|
||||
keyhash(key_id, kh);
|
||||
snprintf(dir, sizeof(dir), "%s/.splinter/providers/%s", home, provider);
|
||||
mkdirs(dir);
|
||||
snprintf(buf, cap, "%s/%s", dir, kh);
|
||||
return buf;
|
||||
}
|
||||
|
||||
static void
|
||||
state_zero(struct sp_prov_state *s)
|
||||
{
|
||||
memset(s, 0, sizeof(*s));
|
||||
}
|
||||
|
||||
static const char *
|
||||
jnum(const char *json, const char *key, char *tmp, size_t cap)
|
||||
{
|
||||
char pat[96]; const char *p; size_t n;
|
||||
tmp[0]='\0';
|
||||
snprintf(pat, sizeof(pat), "\"%s\"", key);
|
||||
p = json ? strstr(json, pat) : NULL; if(!p) return tmp;
|
||||
p = strchr(p+strlen(pat), ':'); if(!p) return tmp;
|
||||
while (*p && (*p==' '||*p=='\t'||*p==':')) p++;
|
||||
n = strcspn(p, ", \t\r\n}");
|
||||
if (n >= cap) n = cap-1;
|
||||
memcpy(tmp, p, n); tmp[n]='\0';
|
||||
return tmp;
|
||||
}
|
||||
static void
|
||||
jstr(const char *json, const char *key, char *out, size_t cap)
|
||||
{
|
||||
char pat[96]; const char *p,*q; size_t n;
|
||||
out[0]='\0';
|
||||
snprintf(pat, sizeof(pat), "\"%s\"", key);
|
||||
p = json ? strstr(json, pat) : NULL; if(!p) return;
|
||||
p = strchr(p+strlen(pat), ':'); if(!p) return;
|
||||
p = strchr(p, '"'); if(!p) return; p++; q=strchr(p,'"'); if(!q) return;
|
||||
n=(size_t)(q-p); if(n>=cap) n=cap-1; memcpy(out,p,n); out[n]='\0';
|
||||
}
|
||||
|
||||
static void
|
||||
parse_state(const char *buf, struct sp_prov_state *s)
|
||||
{
|
||||
char t[64];
|
||||
state_zero(s);
|
||||
jstr(buf,"note",s->note,sizeof(s->note));
|
||||
s->quota_ready_at = strtol(jnum(buf,"quota_ready_at",t,sizeof(t)),NULL,10);
|
||||
s->backoff_until = strtol(jnum(buf,"backoff_until",t,sizeof(t)),NULL,10);
|
||||
s->req_count = (unsigned)strtoul(jnum(buf,"req_count",t,sizeof(t)),NULL,10);
|
||||
s->tok_in = strtoul(jnum(buf,"tok_in",t,sizeof(t)),NULL,10);
|
||||
s->tok_out = strtoul(jnum(buf,"tok_out",t,sizeof(t)),NULL,10);
|
||||
s->last_status = strtol(jnum(buf,"last_status",t,sizeof(t)),NULL,10);
|
||||
s->last_update = strtol(jnum(buf,"last_update",t,sizeof(t)),NULL,10);
|
||||
s->last_429_at = strtol(jnum(buf,"last_429_at",t,sizeof(t)),NULL,10);
|
||||
}
|
||||
|
||||
int
|
||||
sp_provstate_load(const char *provider, const char *key_id,
|
||||
struct sp_prov_state *out)
|
||||
{
|
||||
char base[512], path[530], buf[2048];
|
||||
FILE *fp; size_t n;
|
||||
state_zero(out);
|
||||
if (!sp_provstate_base(provider,key_id,base,sizeof(base))) return -1;
|
||||
snprintf(path,sizeof(path),"%s.json",base);
|
||||
fp = fopen(path,"r"); if(!fp) return -1;
|
||||
n = fread(buf,1,sizeof(buf)-1,fp); fclose(fp); buf[n]='\0';
|
||||
parse_state(buf,out);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
write_state(const char *base, const struct sp_prov_state *s)
|
||||
{
|
||||
char path[530], tmp[550];
|
||||
FILE *fp;
|
||||
snprintf(path,sizeof(path),"%s.json",base);
|
||||
snprintf(tmp,sizeof(tmp),"%s.tmp",path);
|
||||
fp = fopen(tmp,"w"); if(!fp) return -1;
|
||||
fprintf(fp, "{\n \"quota_ready_at\":%ld,\n \"backoff_until\":%ld,\n \"req_count\":%u,\n \"tok_in\":%lu,\n \"tok_out\":%lu,\n \"last_status\":%ld,\n \"last_update\":%ld,\n \"last_429_at\":%ld,\n \"note\":\"%s\"\n}\n",
|
||||
s->quota_ready_at, s->backoff_until, s->req_count, s->tok_in, s->tok_out,
|
||||
s->last_status, s->last_update, s->last_429_at, s->note);
|
||||
fclose(fp);
|
||||
return rename(tmp,path)==0 ? 0 : -1;
|
||||
}
|
||||
|
||||
int
|
||||
sp_provstate_update(const char *provider, const char *key_id,
|
||||
void (*fn)(struct sp_prov_state *s, void *ctx), void *ctx)
|
||||
{
|
||||
char base[512], lpath[530], jpath[530], buf[2048];
|
||||
struct sp_prov_state st;
|
||||
int fd; FILE *fp; size_t n;
|
||||
if (!sp_provstate_base(provider,key_id,base,sizeof(base)) || !fn) return -1;
|
||||
snprintf(lpath,sizeof(lpath),"%s.lock",base);
|
||||
snprintf(jpath,sizeof(jpath),"%s.json",base);
|
||||
fd = open(lpath, O_CREAT|O_RDWR, 0600);
|
||||
if (fd < 0) return -1;
|
||||
if (flock(fd, LOCK_EX) != 0) { close(fd); return -1; }
|
||||
state_zero(&st);
|
||||
fp = fopen(jpath,"r");
|
||||
if (fp) { n=fread(buf,1,sizeof(buf)-1,fp); fclose(fp); buf[n]='\0'; parse_state(buf,&st); }
|
||||
fn(&st, ctx);
|
||||
st.last_update = (long)time(NULL);
|
||||
write_state(base, &st);
|
||||
flock(fd, LOCK_UN);
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct acct_ctx { long status; size_t ti,to; long retry_after_s; long now; };
|
||||
static void acct_fn(struct sp_prov_state *s, void *p) {
|
||||
struct acct_ctx *c=p;
|
||||
s->req_count++;
|
||||
s->tok_in += (unsigned long)c->ti;
|
||||
s->tok_out += (unsigned long)c->to;
|
||||
s->last_status = c->status;
|
||||
if (c->status == 429 || c->status == 402 || c->status == 529) {
|
||||
s->last_429_at = c->now;
|
||||
if (c->retry_after_s > 0)
|
||||
s->quota_ready_at = c->now + c->retry_after_s;
|
||||
else if (c->status == 529 && s->quota_ready_at < c->now + 120)
|
||||
s->quota_ready_at = c->now + 120;
|
||||
else if (s->quota_ready_at < c->now + 60)
|
||||
s->quota_ready_at = c->now + 60;
|
||||
snprintf(s->note, sizeof(s->note), "quota/rate limit (status %ld)", c->status);
|
||||
} else if (c->status == 503 || c->status == 408) {
|
||||
s->backoff_until = c->now + (c->retry_after_s > 0 ? c->retry_after_s : 30);
|
||||
snprintf(s->note, sizeof(s->note), "transient backoff (status %ld)", c->status);
|
||||
} else if (c->status >= 200 && c->status < 300) {
|
||||
/* success: clear short backoff; clear expired quota */
|
||||
s->backoff_until = 0;
|
||||
if (s->quota_ready_at > 0 && s->quota_ready_at <= c->now) s->quota_ready_at = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
sp_provstate_account(const char *provider, const char *key_id,
|
||||
long http_status, size_t tok_in, size_t tok_out, long retry_after_s)
|
||||
{
|
||||
struct acct_ctx c;
|
||||
if (!provider || !key_id) return;
|
||||
c.status = http_status; c.ti=tok_in; c.to=tok_out;
|
||||
c.retry_after_s = retry_after_s; c.now = (long)time(NULL);
|
||||
sp_provstate_update(provider, key_id, acct_fn, &c);
|
||||
}
|
||||
|
||||
int
|
||||
sp_provstate_preflight(const char *provider, const char *key_id,
|
||||
long now, long *ready_at, char *reason, size_t reason_cap)
|
||||
{
|
||||
struct sp_prov_state st;
|
||||
if (ready_at) *ready_at = 0;
|
||||
if (reason && reason_cap) reason[0]='\0';
|
||||
if (sp_provstate_load(provider, key_id, &st) != 0)
|
||||
return 0; /* no state => admit */
|
||||
if (st.quota_ready_at > now) {
|
||||
if (ready_at) *ready_at = st.quota_ready_at;
|
||||
if (reason && reason_cap)
|
||||
snprintf(reason, reason_cap, "%s", st.note[0]?st.note:"quota wait");
|
||||
return 1; /* wait */
|
||||
}
|
||||
if (st.backoff_until > now) {
|
||||
if (ready_at) *ready_at = st.backoff_until;
|
||||
if (reason && reason_cap)
|
||||
snprintf(reason, reason_cap, "backoff");
|
||||
return 2; /* delay */
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
char *
|
||||
sp_key_fingerprint(const char *secret, char *buf, size_t cap)
|
||||
{
|
||||
char kh[17];
|
||||
if (!secret || !*secret || !buf || cap < 17) return NULL;
|
||||
keyhash(secret, kh);
|
||||
snprintf(buf, cap, "%s", kh);
|
||||
return buf;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
#ifndef SP_PROVSTATE_H
|
||||
#define SP_PROVSTATE_H
|
||||
/*
|
||||
* Shared provider/key quota & usage state (persistent, cross-instance per key).
|
||||
* Files under ~/.splinter/providers/<provider>/<keyhash>.{json,lock}.
|
||||
*/
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_prov_state {
|
||||
long quota_ready_at; /* unix timestamp: requests blocked until then (0=ok) */
|
||||
long backoff_until; /* short backoff until (0=ok) */
|
||||
unsigned req_count;
|
||||
unsigned long tok_in;
|
||||
unsigned long tok_out;
|
||||
long last_status;
|
||||
long last_update; /* unix */
|
||||
long last_429_at; /* unix */
|
||||
char note[128]; /* e.g. "quota reset in 4d" */
|
||||
};
|
||||
|
||||
/* Compute state/lock base path for (provider,key_id). Returns buf or NULL. */
|
||||
char *sp_provstate_base(const char *provider, const char *key_id,
|
||||
char *buf, size_t cap);
|
||||
/* Load state (no lock held across return; best-effort). 0 ok, -1 missing/err. */
|
||||
int sp_provstate_load(const char *provider, const char *key_id,
|
||||
struct sp_prov_state *out);
|
||||
/* Atomically: lock, load, call fn to mutate, save, unlock. 0 ok. */
|
||||
int sp_provstate_update(const char *provider, const char *key_id,
|
||||
void (*fn)(struct sp_prov_state *s, void *ctx), void *ctx);
|
||||
/* Convenience: record a response; sets quota_ready_at on 429/402 with hints. */
|
||||
void sp_provstate_account(const char *provider, const char *key_id,
|
||||
long http_status, size_t tok_in, size_t tok_out, long retry_after_s);
|
||||
/* Preflight from shared state: fills decision/reason/ready_at. */
|
||||
int sp_provstate_preflight(const char *provider, const char *key_id,
|
||||
long now, long *ready_at, char *reason, size_t reason_cap);
|
||||
|
||||
char *sp_key_fingerprint(const char *secret, char *buf, size_t cap);
|
||||
#endif
|
||||
+424
@@ -0,0 +1,424 @@
|
||||
/*
|
||||
* splinter -- swarm: fleet of instances in one working directory.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/un.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "swarm.h"
|
||||
|
||||
static void
|
||||
set_nb(int fd)
|
||||
{
|
||||
int fl = fcntl(fd, F_GETFL, 0);
|
||||
if (fl >= 0)
|
||||
(void)fcntl(fd, F_SETFL, fl | O_NONBLOCK);
|
||||
}
|
||||
|
||||
static int
|
||||
send_line(int fd, const char *s)
|
||||
{
|
||||
size_t n = strlen(s);
|
||||
return write(fd, s, n) == (ssize_t)n && write(fd, "\n", 1) == 1 ? 0 : -1;
|
||||
}
|
||||
|
||||
static int
|
||||
json_get_int(const char *s, const char *key, int def)
|
||||
{
|
||||
char pat[64];
|
||||
const char *p;
|
||||
snprintf(pat, sizeof(pat), "\"%s\"", key);
|
||||
p = strstr(s, pat);
|
||||
if (!p) return def;
|
||||
p = strchr(p, ':');
|
||||
if (!p) return def;
|
||||
return (int)strtol(p + 1, NULL, 10);
|
||||
}
|
||||
|
||||
static const char *
|
||||
json_get_str(const char *s, const char *key, char *buf, size_t cap)
|
||||
{
|
||||
char pat[64];
|
||||
const char *p, *q;
|
||||
size_t n;
|
||||
buf[0] = '\0';
|
||||
snprintf(pat, sizeof(pat), "\"%s\"", key);
|
||||
p = strstr(s, pat);
|
||||
if (!p) return buf;
|
||||
p = strchr(p, ':');
|
||||
if (!p) return buf;
|
||||
p = strchr(p, '"');
|
||||
if (!p) return buf;
|
||||
p++;
|
||||
q = strchr(p, '"');
|
||||
if (!q) return buf;
|
||||
n = (size_t)(q - p);
|
||||
if (n >= cap) n = cap - 1;
|
||||
memcpy(buf, p, n);
|
||||
buf[n] = '\0';
|
||||
return buf;
|
||||
}
|
||||
|
||||
static void
|
||||
path_for(struct swarm *s, const char *cwd)
|
||||
{
|
||||
snprintf(s->path, sizeof(s->path), "%s/%s", cwd && *cwd ? cwd : ".", SWARM_PATH);
|
||||
}
|
||||
|
||||
/* No unlink before bind: if a master is alive the bind fails with EADDRINUSE
|
||||
* and the caller connects as a slave instead; a stale socket is removed by
|
||||
* swarm_init only after the connect failed. */
|
||||
static int
|
||||
try_become_master(struct swarm *s)
|
||||
{
|
||||
struct sockaddr_un a;
|
||||
int fd;
|
||||
|
||||
fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (fd < 0) return -1;
|
||||
memset(&a, 0, sizeof(a));
|
||||
a.sun_family = AF_UNIX;
|
||||
snprintf(a.sun_path, sizeof(a.sun_path), "%.107s", s->path);
|
||||
if (bind(fd, (struct sockaddr *)&a, sizeof(a)) != 0) {
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
(void)chmod(s->path, 0600);
|
||||
if (listen(fd, 8) != 0) { close(fd); unlink(s->path); return -1; }
|
||||
set_nb(fd);
|
||||
s->listen_fd = fd;
|
||||
s->role = SWARM_MASTER;
|
||||
s->id = 0;
|
||||
s->npeers = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
try_connect_master(struct swarm *s)
|
||||
{
|
||||
struct sockaddr_un a;
|
||||
int fd;
|
||||
char msg[128];
|
||||
|
||||
fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (fd < 0) return -1;
|
||||
memset(&a, 0, sizeof(a));
|
||||
a.sun_family = AF_UNIX;
|
||||
snprintf(a.sun_path, sizeof(a.sun_path), "%.107s", s->path);
|
||||
if (connect(fd, (struct sockaddr *)&a, sizeof(a)) != 0) {
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
set_nb(fd);
|
||||
snprintf(msg, sizeof(msg), "{\"t\":\"hello\",\"pid\":%d}", (int)getpid());
|
||||
send_line(fd, msg);
|
||||
s->master_fd = fd;
|
||||
s->role = SWARM_SLAVE;
|
||||
s->id = -1;
|
||||
s->locked = 1; /* taken over until master says otherwise / by default slave */
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
swarm_init(struct swarm *s, const char *cwd)
|
||||
{
|
||||
memset(s, 0, sizeof(*s));
|
||||
s->listen_fd = -1;
|
||||
s->master_fd = -1;
|
||||
s->role = SWARM_NONE;
|
||||
s->id = -1;
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
path_for(s, cwd);
|
||||
if (try_become_master(s) == 0)
|
||||
return 0;
|
||||
/* stale socket? try connect; if connect fails, remove and retry bind */
|
||||
if (try_connect_master(s) == 0)
|
||||
return 0;
|
||||
unlink(s->path);
|
||||
if (try_become_master(s) == 0)
|
||||
return 0;
|
||||
return -1; /* standalone */
|
||||
}
|
||||
|
||||
|
||||
static struct swarm_peer *
|
||||
peer_by_id(struct swarm *s, int id)
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < s->npeers; i++)
|
||||
if (s->peers[i].alive && s->peers[i].id == id)
|
||||
return &s->peers[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void
|
||||
master_accept(struct swarm *s)
|
||||
{
|
||||
int fd, i, id = 1;
|
||||
struct swarm_peer *p;
|
||||
char msg[128];
|
||||
if (s->listen_fd < 0) return;
|
||||
fd = accept(s->listen_fd, NULL, NULL);
|
||||
if (fd < 0) return;
|
||||
set_nb(fd);
|
||||
/* find free id, 0 is master */
|
||||
for (id = 1; id < 1000; id++) {
|
||||
int used = 0;
|
||||
for (i = 0; i < s->npeers; i++)
|
||||
if (s->peers[i].alive && s->peers[i].id == id) used = 1;
|
||||
if (!used) break;
|
||||
}
|
||||
if (s->npeers < SWARM_MAX_PEERS) p = &s->peers[s->npeers++];
|
||||
else { /* reuse dead slot */
|
||||
p = NULL;
|
||||
for (i = 0; i < s->npeers; i++) if (!s->peers[i].alive) { p = &s->peers[i]; break; }
|
||||
if (!p) { close(fd); return; }
|
||||
}
|
||||
memset(p, 0, sizeof(*p));
|
||||
p->fd = fd; p->id = id; p->alive = 1; p->busy = 0;
|
||||
snprintf(msg, sizeof(msg), "{\"t\":\"welcome\",\"id\":%d,\"master\":%d}", id, (int)getpid());
|
||||
send_line(fd, msg);
|
||||
}
|
||||
|
||||
static void
|
||||
master_handle_line(struct swarm *s, struct swarm_peer *p, const char *line)
|
||||
{
|
||||
(void)s;
|
||||
if (strstr(line, "\"hello\"")) {
|
||||
p->pid = json_get_int(line, "pid", 0);
|
||||
} else if (strstr(line, "\"status\"")) {
|
||||
p->busy = json_get_int(line, "busy", p->busy);
|
||||
} else if (strstr(line, "\"pong\"")) {
|
||||
p->alive = 1;
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
slave_handle_line(struct swarm *s, const char *line)
|
||||
{
|
||||
char text[3800];
|
||||
if (strstr(line, "\"welcome\"")) {
|
||||
s->id = json_get_int(line, "id", s->id);
|
||||
s->locked = 1;
|
||||
} else if (strstr(line, "\"exec\"")) {
|
||||
json_get_str(line, "text", text, sizeof(text));
|
||||
if (text[0]) {
|
||||
snprintf(s->inbox, sizeof(s->inbox), "%s", text);
|
||||
s->has_inbox = 1;
|
||||
s->inbox_remote = 1;
|
||||
}
|
||||
} else if (strstr(line, "\"unlock\"")) {
|
||||
s->locked = 0;
|
||||
} else if (strstr(line, "\"lock\"")) {
|
||||
s->locked = 1;
|
||||
} else if (strstr(line, "\"ping\"")) {
|
||||
send_line(s->master_fd, "{\"t\":\"pong\"}");
|
||||
} else if (strstr(line, "\"result\"") || strstr(line, "\"event\"")) {
|
||||
/* master receives results in its own inbox/handling path as needed */
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
process_line(struct swarm *s, int is_master, struct swarm_peer *peer, char *line)
|
||||
{
|
||||
size_t l = strlen(line);
|
||||
while (l > 0 && (line[l - 1] == '\r' || line[l - 1] == '\n'))
|
||||
line[--l] = '\0';
|
||||
if (l == 0)
|
||||
return;
|
||||
if (is_master && peer)
|
||||
master_handle_line(s, peer, line);
|
||||
else if (!is_master)
|
||||
slave_handle_line(s, line);
|
||||
}
|
||||
|
||||
static void
|
||||
read_lines_fd(struct swarm *s, int fd, int is_master, struct swarm_peer *peer)
|
||||
{
|
||||
char buf[1024];
|
||||
char *ibuf;
|
||||
size_t *ilen, cap;
|
||||
ssize_t n;
|
||||
char *nl;
|
||||
|
||||
if (peer) { ibuf = peer->ibuf; ilen = &peer->ilen; cap = sizeof(peer->ibuf); }
|
||||
else { ibuf = s->mibuf; ilen = &s->milen; cap = sizeof(s->mibuf); }
|
||||
n = read(fd, buf, sizeof(buf));
|
||||
if (n == 0) {
|
||||
if (peer) { peer->alive = 0; if (peer->fd >= 0) close(peer->fd); peer->fd = -1; }
|
||||
else if (s->master_fd >= 0) { close(s->master_fd); s->master_fd = -1; s->role = SWARM_NONE; }
|
||||
return;
|
||||
}
|
||||
if (n < 0) return;
|
||||
if (*ilen + (size_t)n >= cap) *ilen = 0; /* overflow: drop partial */
|
||||
memcpy(ibuf + *ilen, buf, (size_t)n);
|
||||
*ilen += (size_t)n;
|
||||
ibuf[*ilen] = '\0';
|
||||
while ((nl = memchr(ibuf, '\n', *ilen)) != NULL) {
|
||||
*nl = '\0';
|
||||
process_line(s, is_master, peer, ibuf);
|
||||
{
|
||||
size_t rest = *ilen - (size_t)(nl - ibuf) - 1;
|
||||
memmove(ibuf, nl + 1, rest);
|
||||
*ilen = rest;
|
||||
ibuf[*ilen] = '\0';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
swarm_poll(struct swarm *s)
|
||||
{
|
||||
int i;
|
||||
if (!s || s->role == SWARM_NONE) return;
|
||||
if (s->role == SWARM_MASTER) {
|
||||
master_accept(s);
|
||||
for (i = 0; i < s->npeers; i++) {
|
||||
if (s->peers[i].alive && s->peers[i].fd >= 0)
|
||||
read_lines_fd(s, s->peers[i].fd, 1, &s->peers[i]);
|
||||
}
|
||||
} else if (s->role == SWARM_SLAVE && s->master_fd >= 0) {
|
||||
read_lines_fd(s, s->master_fd, 0, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void
|
||||
json_escape(char *dst, size_t cap, const char *src)
|
||||
{
|
||||
size_t i = 0, j = 0;
|
||||
unsigned char c;
|
||||
if (cap == 0) return;
|
||||
while (src[i] != '\0' && j + 6 < cap) {
|
||||
c = (unsigned char)src[i++];
|
||||
if (c == '"' || c == '\\') { dst[j++]='\\'; dst[j++]=(char)c; }
|
||||
else if (c == '\n') { dst[j++]='\\'; dst[j++]='n'; }
|
||||
else if (c == '\r') { dst[j++]='\\'; dst[j++]='r'; }
|
||||
else if (c == '\t') { dst[j++]='\\'; dst[j++]='t'; }
|
||||
else if (c < 0x20) { j += snprintf(dst+j, cap-j, "\\u%04x", c); }
|
||||
else dst[j++] = (char)c;
|
||||
}
|
||||
dst[j] = '\0';
|
||||
}
|
||||
|
||||
int
|
||||
swarm_route(struct swarm *s, int id, const char *text)
|
||||
{
|
||||
struct swarm_peer *p;
|
||||
char msg[4096];
|
||||
int best = -1, best_busy = 1<<30, i;
|
||||
if (!s || s->role != SWARM_MASTER || !text) return -1;
|
||||
if (id < 0) {
|
||||
/* least busy slave */
|
||||
for (i = 0; i < s->npeers; i++) {
|
||||
if (!s->peers[i].alive) continue;
|
||||
if (s->peers[i].busy < best_busy) { best_busy = s->peers[i].busy; best = s->peers[i].id; }
|
||||
}
|
||||
id = best;
|
||||
}
|
||||
if (id == 0) {
|
||||
/* route to master self: put in inbox */
|
||||
snprintf(s->inbox, sizeof(s->inbox), "%s", text);
|
||||
s->has_inbox = 1;
|
||||
s->inbox_remote = 1;
|
||||
return 0;
|
||||
}
|
||||
p = peer_by_id(s, id);
|
||||
if (!p || p->fd < 0) return -1;
|
||||
{
|
||||
char esc[3500];
|
||||
json_escape(esc, sizeof(esc), text);
|
||||
snprintf(msg, sizeof(msg), "{\"t\":\"exec\",\"text\":\"%s\"}", esc);
|
||||
}
|
||||
send_line(p->fd, msg);
|
||||
return id;
|
||||
}
|
||||
|
||||
void
|
||||
swarm_list(struct swarm *s, char *buf, size_t cap)
|
||||
{
|
||||
int i, off = 0;
|
||||
if (!s || cap == 0) return;
|
||||
buf[0] = '\0';
|
||||
if (s->role == SWARM_NONE) { snprintf(buf, cap, "swarm: standalone (no fleet)"); return; }
|
||||
off += snprintf(buf+off, cap-off, "0: master (self)%s\n", s->role==SWARM_MASTER?"":"");
|
||||
if (s->role == SWARM_MASTER) {
|
||||
for (i = 0; i < s->npeers && off+2 < (int)cap; i++) {
|
||||
if (!s->peers[i].alive) continue;
|
||||
off += snprintf(buf+off, cap-off, "%d: slave pid=%d busy=%d%s\n",
|
||||
s->peers[i].id, s->peers[i].pid, s->peers[i].busy,
|
||||
s->peers[i].fd>=0?"":" (dc)");
|
||||
}
|
||||
} else {
|
||||
off += snprintf(buf+off, cap-off, "%d: this slave (locked=%d)\n", s->id, s->locked);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
swarm_report_busy(struct swarm *s, int busy)
|
||||
{
|
||||
char msg[64];
|
||||
if (!s || s->role != SWARM_SLAVE || s->master_fd < 0) return;
|
||||
snprintf(msg, sizeof(msg), "{\"t\":\"status\",\"busy\":%d}", busy);
|
||||
send_line(s->master_fd, msg);
|
||||
}
|
||||
|
||||
int
|
||||
swarm_take_inbox(struct swarm *s, char *buf, size_t cap)
|
||||
{
|
||||
if (!s || !s->has_inbox) return 0;
|
||||
snprintf(buf, cap, "%s", s->inbox);
|
||||
s->inbox[0] = '\0';
|
||||
s->has_inbox = 0;
|
||||
/* inbox_remote remains readable until next set; caller can check before/after? */
|
||||
return 1;
|
||||
}
|
||||
|
||||
int
|
||||
swarm_inbox_remote(struct swarm *s)
|
||||
{
|
||||
int r;
|
||||
if (!s) return 0;
|
||||
r = s->inbox_remote;
|
||||
s->inbox_remote = 0;
|
||||
return r;
|
||||
}
|
||||
|
||||
void
|
||||
swarm_status(struct swarm *s, char *buf, size_t cap)
|
||||
{
|
||||
int alive = 0, i;
|
||||
if (!s || s->role == SWARM_NONE) { if (cap) buf[0] = '\0'; return; }
|
||||
if (s->role == SWARM_MASTER) {
|
||||
for (i=0;i<s->npeers;i++) if (s->peers[i].alive) alive++;
|
||||
snprintf(buf, cap, "swarm: master 0 (%d slaves)", alive);
|
||||
} else {
|
||||
snprintf(buf, cap, "swarm: slave %d%s", s->id, s->locked?" [locked]":"");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
swarm_close(struct swarm *s)
|
||||
{
|
||||
int i;
|
||||
if (!s) return;
|
||||
if (s->role == SWARM_MASTER) {
|
||||
for (i=0;i<s->npeers;i++) if (s->peers[i].fd>=0) close(s->peers[i].fd);
|
||||
if (s->listen_fd>=0) { close(s->listen_fd); unlink(s->path); }
|
||||
} else if (s->role == SWARM_SLAVE) {
|
||||
if (s->master_fd>=0) close(s->master_fd);
|
||||
}
|
||||
s->role = SWARM_NONE;
|
||||
s->listen_fd = s->master_fd = -1;
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#ifndef SPLINTER_SWARM_H
|
||||
#define SPLINTER_SWARM_H
|
||||
/*
|
||||
* splinter -- swarm: fleet of instances in one working directory.
|
||||
*
|
||||
* A Unix socket in CWD (.splinter-swarm.sock). First to bind becomes master
|
||||
* (id 0); others connect as slaves (id 1..N). Newline-delimited JSON IPC.
|
||||
*/
|
||||
#include <stddef.h>
|
||||
|
||||
#define SWARM_MAX_PEERS 16
|
||||
#define SWARM_PATH ".splinter-swarm.sock"
|
||||
|
||||
enum swarm_role { SWARM_NONE = 0, SWARM_MASTER, SWARM_SLAVE };
|
||||
|
||||
struct swarm_peer {
|
||||
int id;
|
||||
int fd;
|
||||
int pid;
|
||||
int busy; /* load metric: higher = busier */
|
||||
int alive;
|
||||
char ibuf[4096]; /* partial line buffer */
|
||||
size_t ilen;
|
||||
};
|
||||
|
||||
struct swarm {
|
||||
enum swarm_role role;
|
||||
int id; /* 0 master, 1..N slave */
|
||||
int listen_fd; /* master */
|
||||
int master_fd; /* slave: connection to master */
|
||||
char mibuf[4096]; /* slave: partial line buffer from master */
|
||||
size_t milen;
|
||||
char path[512];
|
||||
struct swarm_peer peers[SWARM_MAX_PEERS];
|
||||
int npeers;
|
||||
int locked; /* slave: user input disabled */
|
||||
char inbox[4096]; /* routed command/text for this instance */
|
||||
int has_inbox;
|
||||
int inbox_remote; /* inbox came from master/peer */
|
||||
};
|
||||
|
||||
/* Discover/join the fleet in cwd. Returns 0 on success (role set), -1 on error
|
||||
* but swarm may still be SWARM_NONE (run standalone). */
|
||||
int swarm_init(struct swarm *s, const char *cwd);
|
||||
void swarm_close(struct swarm *s);
|
||||
/* Poll for IPC activity (accept, read). Non-blocking. */
|
||||
void swarm_poll(struct swarm *s);
|
||||
/* Master: route text/command to instance id; id<0 picks least busy. Returns
|
||||
* target id or -1. */
|
||||
int swarm_route(struct swarm *s, int id, const char *text);
|
||||
/* List peers into buf. */
|
||||
void swarm_list(struct swarm *s, char *buf, size_t cap);
|
||||
/* Slave: report busy metric to master. */
|
||||
void swarm_report_busy(struct swarm *s, int busy);
|
||||
/* Take pending routed text, if any. Returns 1 if taken. */
|
||||
int swarm_take_inbox(struct swarm *s, char *buf, size_t cap);
|
||||
/* Was the last taken/set inbox from a remote peer/master? Clears flag. */
|
||||
int swarm_inbox_remote(struct swarm *s);
|
||||
/* Role label for status bar. */
|
||||
void swarm_status(struct swarm *s, char *buf, size_t cap);
|
||||
|
||||
#endif
|
||||
+12
-7
@@ -34,6 +34,7 @@
|
||||
#include "ack.h"
|
||||
#include "curl.h"
|
||||
#include "splinter.h"
|
||||
#include "i18n.h"
|
||||
#include "mcp.h"
|
||||
#include "log.h"
|
||||
#include "cmdscript.h"
|
||||
@@ -323,11 +324,13 @@ tg_ack_reply(const char *token, long chat_id, const char *text)
|
||||
return 0;
|
||||
yes = text[0] == 'o' || text[0] == 'j';
|
||||
if (sp_ack_answer(id, yes, "telegram") == 0)
|
||||
(void)send_message(token, chat_id, yes ? "Zustimmung erteilt." :
|
||||
"Abgelehnt.", NULL);
|
||||
(void)send_message(token, chat_id, yes ?
|
||||
sp_td("ack.granted", "Approved.") :
|
||||
sp_td("ack.refused", "Refused."), NULL);
|
||||
else
|
||||
(void)send_message(token, chat_id,
|
||||
"Diese Anfrage gibt es nicht (mehr).", NULL);
|
||||
sp_td("ack.gone", "There is no such request (any more)."),
|
||||
NULL);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -361,8 +364,10 @@ tg_approve(void *ctx, const char *name, int auth, const char *args)
|
||||
if (sp_buf_init(&msg) != 0 || sp_buf_init(&url) != 0 ||
|
||||
sp_buf_init(&reply) != 0 || sp_buf_init(&err) != 0)
|
||||
return 0;
|
||||
sp_buf_printf(&msg, "Zustimmung %d: %s %s\nAntwort: ok %d / no %d",
|
||||
id, name, shown, id, id);
|
||||
sp_buf_printf(&msg, sp_td("ack.request", "Approval %d: %s %s"), id,
|
||||
name, shown);
|
||||
sp_buf_puts(&msg, "\n");
|
||||
sp_buf_printf(&msg, sp_td("ack.how", "Answer: ok %d / no %d"), id, id);
|
||||
(void)send_message(tg_cur.token, tg_cur.chat_id, msg.p, NULL);
|
||||
|
||||
end = time(NULL) + ttl;
|
||||
@@ -402,8 +407,8 @@ tg_approve(void *ctx, const char *name, int auth, const char *args)
|
||||
if (tg_ack_reply(tg_cur.token, chat, text))
|
||||
continue;
|
||||
sp_buf_clear(&msg);
|
||||
sp_buf_printf(&msg, "Ich warte noch auf eine Zustimmung: "
|
||||
"ok %d / no %d", id, id);
|
||||
sp_buf_printf(&msg, sp_td("ack.waiting",
|
||||
"Still waiting for an approval: ok %d / no %d"), id, id);
|
||||
(void)send_message(tg_cur.token, chat, msg.p, NULL);
|
||||
}
|
||||
if (v != NULL)
|
||||
|
||||
@@ -183,6 +183,7 @@ sp_mock_transport(struct sp_mock *m)
|
||||
{
|
||||
struct sp_transport t;
|
||||
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.send = mock_send;
|
||||
t.ctx = m;
|
||||
return t;
|
||||
|
||||
+183
-66
@@ -19,12 +19,14 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "curl.h"
|
||||
#include "i18n.h"
|
||||
#include "log.h"
|
||||
|
||||
struct openai_ctx {
|
||||
@@ -83,10 +85,10 @@ read_all_cancel(FILE *f, struct sp_buf *out, const volatile int *cancel,
|
||||
*/
|
||||
static FILE *
|
||||
openai_curl(const struct openai_ctx *c, const char *body_path, int stream,
|
||||
pid_t *pid, struct sp_buf *err)
|
||||
pid_t *pid, struct sp_buf *err, const char *hdr_path)
|
||||
{
|
||||
char tmo[32], data[600], auth[sizeof(c->key) + 32];
|
||||
const char *args[16];
|
||||
const char *args[20];
|
||||
const char *hdrs[2] = { NULL, NULL };
|
||||
int n = 0, fd;
|
||||
FILE *f;
|
||||
@@ -104,9 +106,13 @@ openai_curl(const struct openai_ctx *c, const char *body_path, int stream,
|
||||
args[n++] = "Content-Type: application/json";
|
||||
args[n++] = "--data-binary";
|
||||
args[n++] = data;
|
||||
if (hdr_path && *hdr_path) {
|
||||
args[n++] = "-D";
|
||||
args[n++] = hdr_path;
|
||||
}
|
||||
if (!stream) {
|
||||
args[n++] = "-w";
|
||||
args[n++] = "\\n%{http_code}";
|
||||
args[n++] = "\n%{http_code}";
|
||||
}
|
||||
args[n] = NULL;
|
||||
if (c->key[0] != '\0') {
|
||||
@@ -122,7 +128,7 @@ openai_curl(const struct openai_ctx *c, const char *body_path, int stream,
|
||||
close(fd);
|
||||
(void)kill(*pid, SIGKILL);
|
||||
(void)waitpid(*pid, NULL, 0);
|
||||
sp_buf_printf(err, "openai: fdopen: %s", strerror(errno));
|
||||
sp_buf_printf(err, sp_td("openai.fdopen", "openai: fdopen: %s"), strerror(errno));
|
||||
}
|
||||
return f;
|
||||
}
|
||||
@@ -160,51 +166,82 @@ temp_template(char *dst, size_t cap, const char *name)
|
||||
snprintf(dst, cap, "%s/splinter-%s-XXXXXX", dir, name);
|
||||
}
|
||||
|
||||
|
||||
static long
|
||||
parse_retry_after_file(const char *path)
|
||||
{
|
||||
FILE *f;
|
||||
char line[512];
|
||||
long ra = 0;
|
||||
if (!path || !*path) return 0;
|
||||
f = fopen(path, "r");
|
||||
if (!f) return 0;
|
||||
while (fgets(line, sizeof(line), f)) {
|
||||
char *p = line, *v;
|
||||
/* case-insensitive prefix */
|
||||
if (strncasecmp(p, "Retry-After:", 12) != 0) continue;
|
||||
v = p + 12;
|
||||
while (*v == ' ' || *v == '\t') v++;
|
||||
ra = strtol(v, NULL, 10);
|
||||
/* if 0, could be HTTP-date - skip parsing date for now; use 60s floor on 429 caller */
|
||||
break;
|
||||
}
|
||||
fclose(f);
|
||||
return ra > 0 ? ra : 0;
|
||||
}
|
||||
|
||||
static int
|
||||
openai_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
struct openai_ctx *c = ctx;
|
||||
struct sp_buf body, cmd, raw;
|
||||
char path[512];
|
||||
char path[512], hdr_path[512];
|
||||
pid_t child = -1;
|
||||
int fd, rc = -1;
|
||||
int fd, hfd = -1, rc = -1;
|
||||
FILE *p;
|
||||
ssize_t w;
|
||||
size_t n;
|
||||
char *nl;
|
||||
long status;
|
||||
hdr_path[0] = '\0';
|
||||
|
||||
if (c == NULL)
|
||||
return -1;
|
||||
if (sp_buf_init(&body) != 0 || sp_buf_init(&cmd) != 0 ||
|
||||
sp_buf_init(&raw) != 0) {
|
||||
sp_buf_puts(err, "openai: out of memory");
|
||||
sp_buf_puts(err, sp_td("openai.oom", "openai: out of memory"));
|
||||
return -1;
|
||||
}
|
||||
if (sp_openai_request(conv, c->model, c->reg, 0, &body) != 0) {
|
||||
sp_buf_puts(err, "openai: cannot build the request");
|
||||
sp_buf_puts(err, sp_td("openai.build_request",
|
||||
"openai: cannot build the request"));
|
||||
goto out;
|
||||
}
|
||||
|
||||
temp_template(path, sizeof(path), "sse");
|
||||
temp_template(path, sizeof(path), "req");
|
||||
fd = mkstemp(path);
|
||||
if (fd < 0) {
|
||||
sp_buf_printf(err, "openai: mkstemp: %s", strerror(errno));
|
||||
sp_buf_printf(err, sp_td("openai.mkstemp", "openai: mkstemp: %s"), strerror(errno));
|
||||
goto out;
|
||||
}
|
||||
temp_template(hdr_path, sizeof(hdr_path), "hdr");
|
||||
hfd = mkstemp(hdr_path);
|
||||
if (hfd < 0) { hdr_path[0] = '\0'; }
|
||||
else close(hfd);
|
||||
dump_request(body.p, body.len);
|
||||
sp_log_wire(sp_log_dir(), "request", body.p, body.len);
|
||||
n = body.len;
|
||||
w = write(fd, body.p, n);
|
||||
close(fd);
|
||||
if (w < 0 || (size_t)w != n) {
|
||||
sp_buf_printf(err, "openai: short write: %s", strerror(errno));
|
||||
sp_buf_printf(err, sp_td("openai.short_write", "openai: short write: %s"), strerror(errno));
|
||||
unlink(path);
|
||||
if (hdr_path[0]) unlink(hdr_path);
|
||||
goto out;
|
||||
}
|
||||
|
||||
p = openai_curl(c, path, 0, &child, err);
|
||||
p = openai_curl(c, path, 0, &child, err, hdr_path[0]?hdr_path:NULL);
|
||||
if (p == NULL) {
|
||||
unlink(path);
|
||||
goto out;
|
||||
@@ -214,10 +251,11 @@ openai_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
sp_buf_puts(err, "cancelled");
|
||||
(void)kill(child, SIGKILL);
|
||||
} else
|
||||
sp_buf_puts(err, "openai: read failed");
|
||||
sp_buf_puts(err, sp_td("openai.read_failed", "openai: read failed"));
|
||||
fclose(p);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
unlink(path);
|
||||
if (hdr_path[0]) unlink(hdr_path);
|
||||
goto out;
|
||||
}
|
||||
{
|
||||
@@ -226,9 +264,10 @@ openai_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
fclose(p);
|
||||
if (waitpid(child, &status_child, 0) < 0 ||
|
||||
!WIFEXITED(status_child) || WEXITSTATUS(status_child) != 0) {
|
||||
sp_buf_printf(err, "openai: transfer failed for %s",
|
||||
sp_buf_printf(err, sp_td("openai.transfer_failed", "openai: transfer failed for %s"),
|
||||
c->url);
|
||||
unlink(path);
|
||||
if (hdr_path[0]) unlink(hdr_path);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
@@ -237,11 +276,17 @@ openai_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
sp_log_wire(sp_log_dir(), "response", raw.p != NULL ? raw.p : "",
|
||||
raw.len);
|
||||
if (raw.len < 2 || (nl = strrchr(raw.p, '\n')) == NULL) {
|
||||
sp_buf_puts(err, "openai: unparseable response (no status)");
|
||||
sp_buf_puts(err, sp_td("openai.unparseable", "openai: unparseable response (no status)"));
|
||||
if (hdr_path[0]) unlink(hdr_path);
|
||||
goto out;
|
||||
}
|
||||
status = strtol(nl + 1, NULL, 10);
|
||||
*nl = '\0';
|
||||
if (hdr_path[0]) {
|
||||
out->retry_after_s = parse_retry_after_file(hdr_path);
|
||||
unlink(hdr_path);
|
||||
hdr_path[0] = '\0';
|
||||
}
|
||||
|
||||
if (status < 200 || status > 299) {
|
||||
out->status = status;
|
||||
@@ -280,7 +325,6 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
int fd, rc = -1;
|
||||
ssize_t w;
|
||||
size_t n;
|
||||
char line[8192];
|
||||
int saw_data = 0;
|
||||
|
||||
if (c == NULL)
|
||||
@@ -290,18 +334,20 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
return -1;
|
||||
sse = sp_sse_new();
|
||||
if (sse == NULL) {
|
||||
sp_buf_puts(err, "openai: out of memory");
|
||||
sp_buf_puts(err, sp_td("openai.oom", "openai: out of memory"));
|
||||
return -1;
|
||||
}
|
||||
if (sp_openai_request(conv, c->model, c->reg, 1, &body) != 0) {
|
||||
sp_buf_puts(err, "openai: cannot build the request");
|
||||
sp_buf_puts(err, sp_td("openai.build_request",
|
||||
"openai: cannot build the request"));
|
||||
goto out;
|
||||
}
|
||||
|
||||
temp_template(path, sizeof(path), "sse");
|
||||
fd = mkstemp(path);
|
||||
if (fd < 0) {
|
||||
sp_buf_printf(err, "openai: mkstemp: %s", strerror(errno));
|
||||
sp_buf_printf(err, sp_td("openai.mkstemp", "openai: mkstemp: %s"),
|
||||
strerror(errno));
|
||||
goto out;
|
||||
}
|
||||
dump_request(body.p, body.len);
|
||||
@@ -310,66 +356,136 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
w = write(fd, body.p, n);
|
||||
close(fd);
|
||||
if (w < 0 || (size_t)w != n) {
|
||||
sp_buf_printf(err, "openai: short write: %s", strerror(errno));
|
||||
sp_buf_printf(err, sp_td("openai.short_write", "openai: short write: %s"), strerror(errno));
|
||||
unlink(path);
|
||||
goto out;
|
||||
}
|
||||
|
||||
p = openai_curl(c, path, 1, &child, err);
|
||||
p = openai_curl(c, path, 1, &child, err, NULL);
|
||||
if (p == NULL) {
|
||||
unlink(path);
|
||||
goto out;
|
||||
}
|
||||
for (;;) {
|
||||
struct pollfd pfd;
|
||||
int produced, pr;
|
||||
{
|
||||
struct sp_buf lbuf;
|
||||
char chunk[4096];
|
||||
|
||||
if (g_cancel != NULL && *g_cancel) {
|
||||
(void)kill(child, SIGKILL);
|
||||
sp_buf_puts(err, "cancelled");
|
||||
if (sp_buf_init(&lbuf) != 0) {
|
||||
sp_buf_puts(err, sp_td("openai.oom", "openai: out of memory"));
|
||||
fclose(p);
|
||||
(void)kill(child, SIGKILL);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
unlink(path);
|
||||
goto out;
|
||||
}
|
||||
pfd.fd = fileno(p);
|
||||
pfd.events = POLLIN;
|
||||
pfd.revents = 0;
|
||||
pr = poll(&pfd, 1, 200);
|
||||
if (pr < 0) {
|
||||
if (errno == EINTR)
|
||||
for (;;) {
|
||||
struct pollfd pfd;
|
||||
int pr;
|
||||
ssize_t got;
|
||||
size_t i, start;
|
||||
|
||||
if (g_cancel != NULL && *g_cancel) {
|
||||
(void)kill(child, SIGKILL);
|
||||
sp_buf_puts(err, "cancelled");
|
||||
sp_buf_free(&lbuf);
|
||||
fclose(p);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
unlink(path);
|
||||
goto out;
|
||||
}
|
||||
pfd.fd = fileno(p);
|
||||
pfd.events = POLLIN;
|
||||
pfd.revents = 0;
|
||||
pr = poll(&pfd, 1, 200);
|
||||
if (pr < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
if (pr == 0)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
if (pr == 0)
|
||||
continue; /* keepalive window passed */
|
||||
if (fgets(line, sizeof(line), p) == NULL)
|
||||
break;
|
||||
got = read(fileno(p), chunk, sizeof(chunk));
|
||||
if (got < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
if (got == 0)
|
||||
break;
|
||||
if (sp_buf_add(&lbuf, chunk, (size_t)got) != 0) {
|
||||
sp_buf_puts(err, sp_td("openai.oom", "openai: out of memory"));
|
||||
sp_buf_free(&lbuf);
|
||||
fclose(p);
|
||||
(void)kill(child, SIGKILL);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
unlink(path);
|
||||
goto out;
|
||||
}
|
||||
start = 0;
|
||||
for (i = 0; i < lbuf.len; i++) {
|
||||
int produced, kind;
|
||||
|
||||
if (strncmp(line, "data:", 5) == 0)
|
||||
saw_data = 1;
|
||||
else if (tail.len < 4096)
|
||||
sp_buf_puts(&tail, line);
|
||||
sp_buf_clear(&delta);
|
||||
produced = sp_sse_line(sse, line, &delta, err);
|
||||
if (produced < 0) {
|
||||
fclose(p);
|
||||
(void)kill(child, SIGKILL);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
unlink(path);
|
||||
goto out;
|
||||
}
|
||||
if (produced > 0 && cb != NULL && delta.len > 0) {
|
||||
int kind = SP_STREAM_TEXT;
|
||||
if (lbuf.p[i] != '\n')
|
||||
continue;
|
||||
lbuf.p[i] = '\0';
|
||||
{
|
||||
char *ln = lbuf.p + start;
|
||||
size_t lnlen = i - start;
|
||||
|
||||
/* the line itself says which kind of delta this is */
|
||||
if (strstr(line, "\"reasoning_content\"") != NULL)
|
||||
kind = SP_STREAM_THINK;
|
||||
else if (strstr(line, "tool_calls") != NULL &&
|
||||
strstr(line, "\"content\"") == NULL)
|
||||
kind = SP_STREAM_TOOL;
|
||||
cb(cbctx, kind, delta.p);
|
||||
if (lnlen > 0 && ln[lnlen - 1] == '\r')
|
||||
ln[lnlen - 1] = '\0';
|
||||
if (strncmp(ln, "data:", 5) == 0)
|
||||
saw_data = 1;
|
||||
else if (ln[0] != '\0' && tail.len < 4096) {
|
||||
sp_buf_puts(&tail, ln);
|
||||
sp_buf_puts(&tail, "\n");
|
||||
}
|
||||
sp_buf_clear(&delta);
|
||||
produced = sp_sse_line(sse, ln, &delta, err);
|
||||
if (produced < 0) {
|
||||
sp_buf_free(&lbuf);
|
||||
fclose(p);
|
||||
(void)kill(child, SIGKILL);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
unlink(path);
|
||||
goto out;
|
||||
}
|
||||
if (produced > 0 && cb != NULL && delta.len > 0) {
|
||||
kind = SP_STREAM_TEXT;
|
||||
if (strstr(ln, "\"reasoning_content\"") != NULL)
|
||||
kind = SP_STREAM_THINK;
|
||||
else if (strstr(ln, "tool_calls") != NULL &&
|
||||
strstr(ln, "\"content\"") == NULL)
|
||||
kind = SP_STREAM_TOOL;
|
||||
cb(cbctx, kind, delta.p);
|
||||
}
|
||||
}
|
||||
start = i + 1;
|
||||
}
|
||||
if (start > 0) {
|
||||
memmove(lbuf.p, lbuf.p + start, lbuf.len - start);
|
||||
lbuf.len -= start;
|
||||
lbuf.p[lbuf.len] = '\0';
|
||||
}
|
||||
}
|
||||
/* process a final line without trailing newline */
|
||||
if (lbuf.len > 0) {
|
||||
char *ln = lbuf.p;
|
||||
size_t lnlen = lbuf.len;
|
||||
|
||||
lbuf.p[lbuf.len] = '\0';
|
||||
if (lnlen > 0 && ln[lnlen - 1] == '\r')
|
||||
ln[lnlen - 1] = '\0';
|
||||
if (strncmp(ln, "data:", 5) == 0)
|
||||
saw_data = 1;
|
||||
else if (ln[0] != '\0' && tail.len < 4096)
|
||||
sp_buf_puts(&tail, ln);
|
||||
sp_buf_clear(&delta);
|
||||
if (sp_sse_line(sse, ln, &delta, err) > 0 && cb != NULL &&
|
||||
delta.len > 0)
|
||||
cb(cbctx, SP_STREAM_TEXT, delta.p);
|
||||
}
|
||||
sp_buf_free(&lbuf);
|
||||
}
|
||||
{
|
||||
int st;
|
||||
@@ -377,7 +493,7 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
fclose(p);
|
||||
if (waitpid(child, &st, 0) < 0 || !WIFEXITED(st) ||
|
||||
WEXITSTATUS(st) != 0) {
|
||||
sp_buf_printf(err, "openai: stream failed for %s: %.300s",
|
||||
sp_buf_printf(err, sp_td("openai.stream_failed", "openai: stream failed for %s: %.300s"),
|
||||
c->url, tail.p != NULL ? tail.p : "");
|
||||
unlink(path);
|
||||
goto out;
|
||||
@@ -386,7 +502,7 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
unlink(path);
|
||||
|
||||
if (!saw_data) {
|
||||
sp_buf_printf(err, "openai: endpoint sent no SSE data: %.300s",
|
||||
sp_buf_printf(err, sp_td("openai.no_sse", "openai: endpoint sent no SSE data: %.300s"),
|
||||
tail.p != NULL ? tail.p : "(empty)");
|
||||
goto out;
|
||||
}
|
||||
@@ -394,7 +510,7 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
goto out;
|
||||
sp_logf("reply", "%s", out->content != NULL ? out->content : "");
|
||||
if (out->content != NULL && out->content[0] == '\0' && out->ncalls == 0) {
|
||||
sp_buf_printf(err, "openai: stream ended with no answer: %.300s",
|
||||
sp_buf_printf(err, sp_td("openai.stream_no_answer", "openai: stream ended with no answer: %.300s"),
|
||||
tail.p != NULL ? tail.p : "(empty)");
|
||||
sp_reply_free(out);
|
||||
goto out;
|
||||
@@ -416,6 +532,7 @@ sp_openai_transport(const char *url, const char *model, const char *api_key,
|
||||
struct openai_ctx *ctx;
|
||||
struct sp_transport t;
|
||||
|
||||
memset(&t, 0, sizeof(t));
|
||||
/*
|
||||
* One context per transport, on the heap: with a static one every
|
||||
* transport shared a single endpoint, so building several of them (the
|
||||
@@ -423,13 +540,13 @@ sp_openai_transport(const char *url, const char *model, const char *api_key,
|
||||
*/
|
||||
ctx = malloc(sizeof(*ctx));
|
||||
if (ctx == NULL)
|
||||
return t; /* zeroed: send is NULL, caller reports */
|
||||
return t; /* send/provider/key_id all NULL */
|
||||
memset(ctx, 0, sizeof(*ctx));
|
||||
snprintf(ctx->url, sizeof(ctx->url), "%s", url != NULL ? url : "");
|
||||
snprintf(ctx->model, sizeof(ctx->model), "%s", model != NULL ? model : "");
|
||||
snprintf(ctx->key, sizeof(ctx->key), "%s", api_key != NULL ? api_key : "");
|
||||
ctx->reg = reg;
|
||||
ctx->timeout_s = timeout_s > 0 ? timeout_s : 180;
|
||||
ctx->timeout_s = timeout_s > 0 ? timeout_s : 900;
|
||||
t.send = openai_send;
|
||||
t.send_stream = openai_stream;
|
||||
t.ctx = ctx;
|
||||
|
||||
@@ -4,14 +4,16 @@
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "swarm.h"
|
||||
|
||||
/*
|
||||
* Run the interactive chat loop until the user quits. `theme_name` is a CDE
|
||||
* palette name; NULL selects the default. `host` may be NULL (no plugins).
|
||||
* `sw` enables the local swarm (fleet) when not NULL.
|
||||
* Returns 0 on a clean quit.
|
||||
*/
|
||||
int sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model,
|
||||
const char *theme_name, struct sp_host *host);
|
||||
const char *theme_name, struct sp_host *host, struct swarm *sw);
|
||||
|
||||
/*
|
||||
* UTF-8 -> ASCII for the screen. The vendored curses writes Latin-1 bytes for
|
||||
|
||||
+20
-1
@@ -63,6 +63,9 @@ main(void)
|
||||
"plugin = plugins/lcm/lcm.so\n"
|
||||
"plugin = plugins/cps/cps.so\n"
|
||||
"cli_cmd = claude -p\n"
|
||||
"cli_env = CLAUDE_CODE_OAUTH_TOKEN=tok=with=eq\n"
|
||||
"delegate = c2 | zweites Konto | kind=cli | cmd=claude -p | "
|
||||
"env=CLAUDE_CODE_OAUTH_TOKEN=abc | env=FOO=bar baz\n"
|
||||
"system_prompt = sei knapp\n");
|
||||
|
||||
sp_config_init(&c);
|
||||
@@ -78,6 +81,15 @@ main(void)
|
||||
CHECK(c.nplugins == 2);
|
||||
CHECK(strcmp(c.plugins[1], "plugins/cps/cps.so") == 0);
|
||||
CHECK(strcmp(c.cli_cmd, "claude -p") == 0);
|
||||
CHECK(c.ncli_env == 1);
|
||||
CHECK(strcmp(c.cli_env[0], "CLAUDE_CODE_OAUTH_TOKEN=tok=with=eq") == 0);
|
||||
CHECK(c.ndelegates == 1);
|
||||
CHECK(c.delegate[0].nenv == 2);
|
||||
CHECK(strcmp(c.delegate[0].env[0], "CLAUDE_CODE_OAUTH_TOKEN=abc") == 0);
|
||||
CHECK(strcmp(c.delegate[0].env[1], "FOO=bar baz") == 0);
|
||||
sp_config_apply_env((const char (*)[SP_CONFIG_ENV_LEN])c.delegate[0].env,
|
||||
c.delegate[0].nenv);
|
||||
CHECK(getenv("FOO") != NULL && strcmp(getenv("FOO"), "bar baz") == 0);
|
||||
CHECK(strcmp(c.system_prompt, "sei knapp") == 0);
|
||||
/* untouched defaults survive */
|
||||
CHECK(strcmp(c.key_env, "SPLINTER_API_KEY") == 0);
|
||||
@@ -91,6 +103,13 @@ main(void)
|
||||
CHECK(strstr(err.p, ":2:") != NULL);
|
||||
CHECK(strstr(err.p, "wolke") != NULL);
|
||||
|
||||
/* ---- env without a proper NAME= is refused ---- */
|
||||
write_file(path, "cli_env = 1BAD=x\n");
|
||||
sp_config_init(&c);
|
||||
sp_buf_clear(&err);
|
||||
CHECK(sp_config_load(&c, path, &err) == -1);
|
||||
CHECK(strstr(err.p, "NAME=VALUE") != NULL);
|
||||
|
||||
/* ---- a line without '=' is refused too ---- */
|
||||
write_file(path, "endpoint\n");
|
||||
sp_config_init(&c);
|
||||
@@ -112,7 +131,7 @@ main(void)
|
||||
sp_buf_clear(&err);
|
||||
CHECK(sp_config_load(&c, path, &err) == 0);
|
||||
CHECK(strcmp(c.theme, "Delphinium") == 0);
|
||||
CHECK(c.steps == 8);
|
||||
CHECK(c.steps == 150);
|
||||
CHECK(c.autonomous == 0);
|
||||
|
||||
/* ---- the path honours SPLINTER_CONFIG ---- */
|
||||
|
||||
+11
-2
@@ -109,7 +109,7 @@ main(void)
|
||||
struct sp_buf out;
|
||||
struct stat st;
|
||||
FILE *f;
|
||||
int n = 0, task_ok = 0;
|
||||
int n = 0, task_ok = 0, env_ok = 0;
|
||||
|
||||
CHECK(mkdtemp(tdir) != NULL);
|
||||
snprintf(mark, sizeof(mark), "%s/pwned", tdir);
|
||||
@@ -135,6 +135,10 @@ main(void)
|
||||
add(&c, "far", "remote", "far");
|
||||
snprintf(c.delegate[0].host, sizeof(c.delegate[0].host), "farhost");
|
||||
c.delegate[0].max_parallel = 1;
|
||||
/* env= travels in front as `env 'NAME=VALUE'`, quoted like the rest */
|
||||
snprintf(c.delegate[0].env[0], sizeof(c.delegate[0].env[0]),
|
||||
"TOK=a b'c");
|
||||
c.delegate[0].nenv = 1;
|
||||
memset(&r, 0, sizeof(r));
|
||||
CHECK(sp_delegate_register(&r, &c, NULL) == 0);
|
||||
snprintf(task, sizeof(task), "it's x'; touch %s; echo '", mark);
|
||||
@@ -157,13 +161,18 @@ main(void)
|
||||
if (f != NULL) {
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
line[strcspn(line, "\n")] = '\0';
|
||||
if (n == 3 && strcmp(line, task) == 0)
|
||||
if (n == 0 && strcmp(line, "env") == 0)
|
||||
env_ok = 1;
|
||||
if (n == 1 && strcmp(line, "TOK=a b'c") == 0)
|
||||
env_ok++;
|
||||
if (n == 5 && strcmp(line, task) == 0)
|
||||
task_ok = 1;
|
||||
n++;
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
CHECK(task_ok);
|
||||
CHECK(env_ok == 2);
|
||||
sp_buf_free(&out);
|
||||
sp_registry_free(&r);
|
||||
(void)setenv("PATH", oldpath != NULL ? oldpath : "/usr/bin:/bin", 1);
|
||||
|
||||
@@ -24,7 +24,7 @@ run() { # $1 = answer word; leaves $D/sent.log and maybe $D/out.txt
|
||||
curl -s -o /dev/null "http://127.0.0.1:$P/x" && break
|
||||
sleep 0.2
|
||||
done
|
||||
HOME="$D/home" SPLINTER_TELEGRAM_TOKEN=tok \
|
||||
HOME="$D/home" SPLINTER_LOCALE=de SPLINTER_TELEGRAM_TOKEN=tok \
|
||||
SPLINTER_TELEGRAM_API="http://127.0.0.1:$P" \
|
||||
SPLINTER_ACK_DIR="$D/home/ack" SPLINTER_ACK_TTL=20 \
|
||||
./splinter --config "$D/home/splinter.conf" --daemon \
|
||||
|
||||
Executable
+103
@@ -0,0 +1,103 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# splinter -- the curses UI, driven through tmux against a fake model.
|
||||
#
|
||||
# What it guards, as found: a tool call is asked on the screen and runs after
|
||||
# 'y'; Ctrl-C during that question cancels the turn (it used to be swallowed,
|
||||
# leaving y or n as the only way out); Ctrl-L repaints instead of sending the
|
||||
# half-typed line; Backspace edits the buffer, not only the screen; '!' and '/'
|
||||
# lines are handled; a resize does not end the program; Ctrl-D quits with 0.
|
||||
# Skipped, and says so, where tmux is not installed.
|
||||
set -u
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
if ! command -v tmux >/dev/null 2>&1; then
|
||||
echo "test_ui: skipped (no tmux)"
|
||||
exit 0
|
||||
fi
|
||||
D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-ui-XXXXXX") || exit 1
|
||||
# Our own socket, never the user's. $TMUX wins over both -L and TMUX_TMPDIR
|
||||
# (tmux.c: when $TMUX is set the client takes the socket path out of it), so a
|
||||
# run started from inside the user's tmux would drive the user's server -- and
|
||||
# the kill-server below would take every session in it down. Drop $TMUX, keep
|
||||
# TMUX_TMPDIR pointed at $D, and never signal a server this test does not own.
|
||||
unset TMUX TMUX_PANE
|
||||
export TMUX_TMPDIR="$D"
|
||||
own_server() {
|
||||
if [ -n "${TMUX:-}" ] || [ "${TMUX_TMPDIR:-}" != "$D" ]; then
|
||||
echo "test_ui: refusing to touch a tmux server this test does not own" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
killserver() { own_server; tmux kill-server 2>/dev/null; }
|
||||
S=splinter-ui-$$
|
||||
fails=0
|
||||
F=
|
||||
cleanup() {
|
||||
killserver
|
||||
[ -n "$F" ] && kill "$F" 2>/dev/null
|
||||
rm -rf "$D"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
check() { if "$@"; then :; else echo "FAIL $*"; fails=$((fails + 1)); fi; }
|
||||
shows() { # wait until the screen contains $1
|
||||
for i in $(seq 1 30); do
|
||||
tmux capture-pane -t $S -p | grep -q -- "$1" && return 0
|
||||
sleep 0.5
|
||||
done
|
||||
return 1
|
||||
}
|
||||
start() { # a fresh fake model and a fresh UI
|
||||
[ -n "$F" ] && kill "$F" 2>/dev/null
|
||||
killserver
|
||||
P=$((20000 + ($$ + $1) % 30000))
|
||||
rm -rf "$D/home" "$D/out.txt" "$D/rc"
|
||||
mkdir -p "$D/home"
|
||||
python3 -I tests/fake_telegram.py "$P" "$D/out.txt" "$D/sent.log" ok &
|
||||
F=$!
|
||||
for i in $(seq 1 50); do
|
||||
curl -s -o /dev/null "http://127.0.0.1:$P/x" && break
|
||||
sleep 0.2
|
||||
done
|
||||
tmux new-session -d -s $S -x 110 -y 30 "HOME=$D/home SPLINTER_LOCALE=en \
|
||||
./splinter --no-config --endpoint http://127.0.0.1:$P/v1/chat/completions \
|
||||
--model m --chat 2>/dev/null; echo \$? > $D/rc"
|
||||
shows 'Enter sends'
|
||||
}
|
||||
typed() { tmux send-keys -t $S -l "$1"; }
|
||||
key() { tmux send-keys -t $S "$@"; }
|
||||
quit_code() {
|
||||
key C-u C-d
|
||||
for i in $(seq 1 20); do [ -s "$D/rc" ] && break; sleep 0.5; done
|
||||
cat "$D/rc" 2>/dev/null
|
||||
}
|
||||
|
||||
start 0
|
||||
typed '!echo hallo-shell'; key Enter
|
||||
check shows 'hallo-shell'
|
||||
typed '/xyz'; key Enter
|
||||
check shows 'unknown command: /xyz'
|
||||
typed 'schreib die datei'; key Enter
|
||||
check shows 'changes files'
|
||||
key y
|
||||
check shows 'fertig'
|
||||
check grep -q 'vom gateway' "$D/out.txt"
|
||||
typed 'halb'; key C-l; sleep 1
|
||||
check shows '^>halb'
|
||||
key BSpace BSpace; key C-l; sleep 1
|
||||
check shows '^>ha *$'
|
||||
tmux resize-window -t $S -x 70 -y 20; sleep 1
|
||||
check shows '^>'
|
||||
check test "$(quit_code)" = 0
|
||||
|
||||
start 1
|
||||
typed 'schreib die datei'; key Enter
|
||||
check shows 'changes files'
|
||||
key C-c; sleep 2
|
||||
check test ! -e "$D/out.txt"
|
||||
typed '!echo noch-da'; key Enter
|
||||
check shows 'noch-da'
|
||||
check test "$(quit_code)" = 0
|
||||
|
||||
if [ "$fails" -eq 0 ]; then echo "test_ui: ok"; exit 0; fi
|
||||
exit 1
|
||||
Reference in new issue
Block a user