anthropic transport, provider usage APIs, endpoints as /v1 base
- kind = anthropic: the Messages API over curl, OAuth tokens (sk-ant-oat) as Bearer with the oauth beta, tool_use/tool_result blocks. - --doctor spends no tokens: it asks /models and the provider's own usage route (ollama /api/balance, opencode go /v1/usage) instead of a tiny turn; cli providers are only checked for the program. /usage shows the same provider figures, cached for a minute. - endpoint names the API base (https://host/v1); sp_endpoint_url() builds chat/completions (default), messages, models and usage from it. A full route is still accepted and cut back to the base. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
62a041a61b
commit
05c8d936e7
38 files changed
+3290
-226
No files matched your search
@@ -22,7 +22,8 @@ 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/json.o src/sse.o src/openai.o src/transport_openai.o \
|
||||
src/anthropic.o src/transport_anthropic.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/swarm.o src/provstate.o src/md.o src/tgmd.o src/b64.o src/a2aserver.o src/providers.o src/usage.o src/confblock.o src/agents.o src/catalogs.o
|
||||
BIN = splinter
|
||||
BINOBJ = src/main.o src/ui.o
|
||||
@@ -37,7 +38,7 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \
|
||||
plugins/tmux/tmux.so
|
||||
TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_conv \
|
||||
tests/test_transport tests/test_agent tests/test_openai \
|
||||
tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_cli tests/test_compactor tests/test_secrets tests/test_mcpclient tests/test_kids tests/test_lifecycle tests/test_md tests/test_tgmd tests/test_providers tests/test_b64 tests/test_pause tests/test_swarm tests/test_provstate tests/test_planner tests/test_tmux tests/test_usage tests/test_agents tests/test_confblock tests/test_jobs
|
||||
tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_anthropic tests/test_cli tests/test_compactor tests/test_secrets tests/test_mcpclient tests/test_kids tests/test_lifecycle tests/test_md tests/test_tgmd tests/test_providers tests/test_b64 tests/test_pause tests/test_swarm tests/test_provstate tests/test_planner tests/test_tmux tests/test_usage tests/test_agents tests/test_confblock tests/test_jobs
|
||||
|
||||
RPATH = -Wl,-rpath,'$$ORIGIN'
|
||||
PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..'
|
||||
@@ -130,6 +131,8 @@ src/json.o: vendor/libmcp/mcp.h
|
||||
src/sse.o: include/splinter.h vendor/libmcp/mcp.h
|
||||
src/openai.o: include/splinter.h vendor/libmcp/mcp.h
|
||||
src/transport_openai.o: include/splinter.h src/curl.h src/log.h
|
||||
src/anthropic.o: include/splinter.h vendor/libmcp/mcp.h
|
||||
src/transport_anthropic.o: include/splinter.h src/curl.h src/log.h vendor/libmcp/mcp.h
|
||||
src/curl.o: src/curl.h include/splinter.h
|
||||
src/builtin.o: include/splinter.h
|
||||
src/theme.o: src/theme.h src/palettes.h include/splinter.h
|
||||
@@ -222,6 +225,8 @@ tests/test_jobs: tests/test_jobs.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_jobs.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_config: tests/test_config.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_config.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_anthropic: tests/test_anthropic.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_anthropic.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_sse: tests/test_sse.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_sse.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_cli: tests/test_cli.c $(LIB) $(PLUGIN)
|
||||
@@ -256,6 +261,7 @@ check: $(LIB) $(BIN) $(PLUGIN) $(TESTS)
|
||||
echo "== tests/test_a2a_context.sh"; sh tests/test_a2a_context.sh; \
|
||||
echo "== tests/test_limit_wait.sh"; sh tests/test_limit_wait.sh; \
|
||||
echo "== tests/test_pools.sh"; sh tests/test_pools.sh; \
|
||||
echo "== tests/test_anthropic.sh"; sh tests/test_anthropic.sh; \
|
||||
echo "== tests/test_agents_ui.sh"; sh tests/test_agents_ui.sh; \
|
||||
echo "== tests/test_a2a_input.sh"; sh tests/test_a2a_input.sh; \
|
||||
echo "== tests/test_ui.sh"; sh tests/test_ui.sh; \
|
||||
|
||||
@@ -93,7 +93,7 @@ Delphinium. `--list-themes` prints the names, `--theme NAME` picks one.
|
||||
## Talking to a model
|
||||
|
||||
```sh
|
||||
./splinter -p "say hi" --endpoint http://127.0.0.1:8080/v1/chat/completions \
|
||||
./splinter -p "say hi" --endpoint http://127.0.0.1:8080/v1 \
|
||||
--model qwen2.5-coder-7b --api-key-env SPLINTER_API_KEY
|
||||
```
|
||||
|
||||
@@ -115,6 +115,36 @@ The `cli` transport runs a program and takes its stdout as the answer, so
|
||||
`claude -p`, `opencode run`, `ollama run` or a script can be the brains. The
|
||||
OpenAI adapter stays the default for local endpoints.
|
||||
|
||||
## Claude without the CLI
|
||||
|
||||
Anthropic speaks its own shape, not `chat/completions`, so it is a transport of
|
||||
its own (`kind = anthropic`). It is called over the API with the operator's own
|
||||
token -- no `claude` process, no child, nothing to freeze:
|
||||
|
||||
```
|
||||
provider claude-a {
|
||||
kind = anthropic
|
||||
endpoint = https://api.anthropic.com/v1
|
||||
model = claude-sonnet-5-5
|
||||
key = "sk-ant-oat01-..." # or key_env = CLAUDE_CODE_OAUTH_TOKEN
|
||||
limit = 40/5h
|
||||
}
|
||||
```
|
||||
|
||||
A `sk-ant-oat` token (Claude Code) is sent as a Bearer token with the oauth
|
||||
beta and Claude Code's first system block, which the API insists on; an
|
||||
`sk-ant-api` key goes as `x-api-key`. Tools become `tool_use` blocks and their
|
||||
observations `tool_result` blocks; the system prompt is the top-level `system`
|
||||
field. Three accounts are three providers and one pool:
|
||||
|
||||
```sh
|
||||
splinter -m claude # the pool: the account with the most room first
|
||||
splinter -m claude-a # one account
|
||||
splinter -m claude/claude-opus-5-5 # the pool, another of its models
|
||||
```
|
||||
|
||||
`--doctor` checks each one by asking for its model list and reading the local usage record; it never sends a completion request, so it spends no tokens.
|
||||
|
||||
## Another agent: A2A
|
||||
|
||||
```sh
|
||||
@@ -250,7 +280,7 @@ claude, opencode or another splinter run where the model or the network is:
|
||||
about = "on a remote host"
|
||||
tags = [remote]
|
||||
host = build.example.org
|
||||
endpoint = http://10.0.0.2:8080/v1/chat/completions
|
||||
endpoint = http://10.0.0.2:8080/v1
|
||||
model = ...
|
||||
}
|
||||
|
||||
@@ -392,7 +422,7 @@ Nothing to configure if the keys are already there:
|
||||
CLAUDE_CODE_OAUTH_TOKEN CLAUDE_CODE_OAUTH_TOKEN_0 .. _N
|
||||
|
||||
Each Ollama key becomes a delegate *and* an exit in the ring, with the endpoint
|
||||
from `OLLAMA_ENDPOINT` (default `https://ollama.com/v1/chat/completions`) and the
|
||||
from `OLLAMA_ENDPOINT` (default `https://ollama.com/v1`) and the
|
||||
model from `OLLAMA_MODEL`. Each Claude token becomes a `cli` delegate that runs
|
||||
`claude -p`. Several keys mean several accounts, and the ring uses them in order.
|
||||
|
||||
@@ -440,7 +470,7 @@ config - no profiles, no directories, nothing to keep in sync:
|
||||
tags = [code, c99, review]
|
||||
prio = 5
|
||||
max_parallel = 2
|
||||
endpoint = http://127.0.0.1:8080/v1/chat/completions
|
||||
endpoint = http://127.0.0.1:8080/v1
|
||||
model = Qwen3.6-35B
|
||||
}
|
||||
provider quick { about = "short answers" tags = [chat, cheap] endpoint = ... model = ... }
|
||||
|
||||
+39
-10
@@ -37,7 +37,7 @@ telegram { allow = [123456789] }
|
||||
provider ocgo {
|
||||
about = "fast and cheap, good at planning"
|
||||
tags = [cloud, code, fast]
|
||||
endpoint = https://api.example.org/v1/chat/completions
|
||||
endpoint = https://api.example.org/v1
|
||||
model = some-model
|
||||
key_env = EXAMPLE_API_KEY
|
||||
prio = 10
|
||||
@@ -50,10 +50,35 @@ provider claude-a {
|
||||
limit = 40/5h
|
||||
env { CLAUDE_CODE_OAUTH_TOKEN = "${CLAUDE_A_TOKEN}" }
|
||||
}
|
||||
provider anthropic-a {
|
||||
kind = anthropic
|
||||
about = "Claude via the API, account A"
|
||||
tags = [analyze, decide, review, big]
|
||||
endpoint = https://api.anthropic.com/v1
|
||||
model = claude-sonnet-5-5
|
||||
limit = 40/5h
|
||||
key = "sk-ant-oat01-..." # or key_env = CLAUDE_CODE_OAUTH_TOKEN
|
||||
}
|
||||
|
||||
pool claude { members = [claude-a, claude-b] strategy = balance }
|
||||
pool claude { members = [claude-a, claude-b, anthropic-a] strategy = balance }
|
||||
```
|
||||
|
||||
`kind` says which shape the endpoint speaks:
|
||||
|
||||
| kind | endpoint | auth |
|
||||
|-------------|--------------------------------------------|-------------------------------------------------------------|
|
||||
| `openai` (default) | `.../v1` (POSTs to `/chat/completions`) | `Authorization: Bearer`, from `key_env` or `key` |
|
||||
| `anthropic` | `https://api.anthropic.com/v1` (POSTs to `/messages`) | `sk-ant-oat...` as a Bearer token with the oauth beta (a Claude Code token); `sk-ant-api...` as `x-api-key` |
|
||||
| `cli` | none; a program (`cmd`) | its own, from `env { }` |
|
||||
|
||||
A `kind = anthropic` provider is called directly, without the `claude` CLI:
|
||||
tools become `tool_use` blocks, their observations `tool_result` blocks, and
|
||||
the system prompt is sent as the top-level `system` field. One provider per
|
||||
OAuth token, one pool over them, and `-m POOL` spreads the work over the
|
||||
accounts. An `sk-ant-oat` token gets Claude Code's first system block added,
|
||||
because the API refuses such a token without it (with a 429 whose message is
|
||||
only "Error").
|
||||
|
||||
Blocks: `core` (everything that is not a provider; bare `name = value` lines at
|
||||
the top level also go there), `telegram`, `provider NAME`, `pool NAME`,
|
||||
`exit NAME`. A provider is anything the run or a delegation can talk to: the
|
||||
@@ -115,7 +140,10 @@ moves it back.
|
||||
|
||||
## Pools
|
||||
|
||||
A pool is a name for providers that stand in for each other:
|
||||
A pool is a name for providers that stand in for each other. Naming it is
|
||||
naming a model: `-m POOL`, `/model POOL` and `POOL/model` all work. A pool is
|
||||
not a fan-out - one member carries the turn, and the pool is what happens when
|
||||
that member cannot:
|
||||
|
||||
- `failover` takes the first member that has room, in the order listed;
|
||||
- `balance` takes the member with the most left of its allowance.
|
||||
@@ -176,7 +204,7 @@ lies about what it does.
|
||||
|
||||
| key | meaning |
|
||||
|-----|---------|
|
||||
| `endpoint` | OpenAI-compatible URL, e.g. `http://127.0.0.1:8080/v1/chat/completions` |
|
||||
| `endpoint` | the API base, e.g. `http://127.0.0.1:8080/v1`; splinter appends `/chat/completions` (or `/messages` for `kind = anthropic`), `/models`, and the usage routes. A full route still works: it is cut back to the base |
|
||||
| `model` | model name the endpoint expects |
|
||||
| `api_key_env` | name of the env var holding the key (default `SPLINTER_API_KEY`) |
|
||||
| `transport` | a transport a plugin provides, e.g. `cli` |
|
||||
@@ -196,6 +224,7 @@ lies about what it does.
|
||||
| `env_delegates` | `1` turns `CLAUDE_CODE_OAUTH_TOKEN(_N)` into delegates (default off) |
|
||||
| `on_limit` | `wait` (default) or `fail`: what a usage limit does |
|
||||
| `max_wait` | longest wait for a limit, e.g. `6h`, `2d` (default 12h) |
|
||||
| `kind` | of the main provider: `openai` (default) or `anthropic` |
|
||||
| `default` | the provider or pool the conversation starts on |
|
||||
| `pool` | `pool = id \| strategy=failover\|balance \| members=a,b` |
|
||||
| `limit`, `tokens` | allowance of the main provider, see Usage limits |
|
||||
@@ -221,9 +250,9 @@ delegate = claude-b | Claude Code, second account | kind=cli | cmd=claude -p |
|
||||
|
||||
`exit` fields: `endpoint`, `model`, `key_env`; the second field is the label.
|
||||
`delegate` fields: `endpoint`, `model`, `key_env`, `tags`, `prio`,
|
||||
`max_parallel`, `kind` (`openai` or `cli`), `cmd` (for `cli`), and `host` - an
|
||||
ssh target: the child splinter runs there, with that machine's keys. An unnamed
|
||||
field is the description the selection reads.
|
||||
`max_parallel`, `kind` (`openai`, `anthropic` or `cli`), `cmd` (for `cli`), and
|
||||
`host` - an ssh target: the child splinter runs there, with that machine's
|
||||
keys. An unnamed field is the description the selection reads.
|
||||
|
||||
### Usage limits
|
||||
|
||||
@@ -321,7 +350,7 @@ single-server environment variable from before still works:
|
||||
## Example: local model
|
||||
|
||||
```
|
||||
endpoint = http://127.0.0.1:8080/v1/chat/completions
|
||||
endpoint = http://127.0.0.1:8080/v1
|
||||
model = /models/unsloth/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q8_K_XL.gguf
|
||||
theme = Delphinium
|
||||
autonomous = 1
|
||||
@@ -393,8 +422,8 @@ variable that holds the key, then writes one `delegate` line to
|
||||
`--config` works too. Adding the same name again replaces its line. The
|
||||
provider is usable in that run at once: the delegate table in memory is the one
|
||||
the running agent reads. `ollama` and `opencode` are accepted instead of a URL
|
||||
and stand for `http://127.0.0.1:11434/v1/chat/completions` and
|
||||
`https://opencode.ai/zen/go/v1/chat/completions` (the latter with
|
||||
and stand for `http://127.0.0.1:11434/v1` and
|
||||
`https://opencode.ai/zen/go/v1` (the latter with
|
||||
`OPENCODE_GO_API_KEY`).
|
||||
|
||||
`/model` offers the models the config names and switches the transport; the
|
||||
|
||||
+4
-4
@@ -5,7 +5,7 @@ nach Modellgröße:
|
||||
|
||||
| Rolle | wer | Tags | Pool |
|
||||
|-------|-----|------|------|
|
||||
| analysieren, entscheiden, reviewen, planen | Claude, zwei Konten | `analyze decide review plan big` | `analyst` (balance) |
|
||||
| analysieren, entscheiden, reviewen, planen | Claude, zwei Konten | `analyze decide review plan big` | `claudeapi` (balance) |
|
||||
| umsetzen: lesen, ändern, bauen, testen | deepseek-flash bei opencode-go und bei ollama cloud | `code fast chat summary test doc` | `work` (balance) |
|
||||
| privat, nichts verlässt den Rechner | lokales Modell | `local private code` | – |
|
||||
|
||||
@@ -45,7 +45,7 @@ splinter # Chat auf "work"
|
||||
allein. Erste Nachricht: "Lies GOAL.md und AGENTS.md, halte dich daran."
|
||||
3. **Arbeiten**: normal beschreiben, was getan werden soll. Umsetzung macht
|
||||
der Pool `work`; Aufgaben mit Wörtern wie *analysiere, entscheide, bewerte,
|
||||
review, Architektur, Ursache* gehen an `analyst`.
|
||||
review, Architektur, Ursache* gehen an `claudeapi`.
|
||||
4. **Plan führen**: `/tasks` zeigt den Plan der Sitzung, `/tasks work next`
|
||||
nimmt den nächsten Punkt.
|
||||
5. **Verbrauch sehen**: Statusleiste und `/usage` (Balken je Provider).
|
||||
@@ -55,10 +55,10 @@ splinter # Chat auf "work"
|
||||
Direkt mit Claude arbeiten, wenn das Gespräch selbst Analyse ist:
|
||||
|
||||
```
|
||||
splinter -m analyst
|
||||
splinter -m claudeapi
|
||||
```
|
||||
|
||||
Ohne Chat: `splinter -p "..."` (mit `-m analyst` für eine einzelne Analyse).
|
||||
Ohne Chat: `splinter -p "..."` (mit `-m claudeapi` für eine einzelne Analyse).
|
||||
|
||||
## 3. Wer bekommt was
|
||||
|
||||
|
||||
+23
-2
@@ -50,6 +50,26 @@ Transport: POST the line protocol to
|
||||
.Ar URL
|
||||
using
|
||||
.Xr curl 1 .
|
||||
.It Fl -kind Ar NAME
|
||||
The vendor shape of
|
||||
.Fl -endpoint :
|
||||
.Ar openai
|
||||
(the default,
|
||||
.Pa /v1/chat/completions )
|
||||
or
|
||||
.Ar anthropic
|
||||
(the Messages API, which takes an
|
||||
.Pa sk-ant-oat...
|
||||
Claude Code token or an
|
||||
.Pa sk-ant-api...
|
||||
key).
|
||||
.It Fl -select Ar SEL , m Ar SEL
|
||||
Use a provider or a pool from the configuration:
|
||||
.Ar ID ,
|
||||
.Ar POOL ,
|
||||
.Ar ID/model
|
||||
or
|
||||
.Ar POOL/model .
|
||||
.It Fl -delegate Ar ID
|
||||
Run that configured delegate with
|
||||
.Fl p Ar TEXT ,
|
||||
@@ -97,8 +117,9 @@ reply answer <text>
|
||||
reply tool <name> <arguments>
|
||||
.Ed
|
||||
.Pp
|
||||
A provider adapter translates an OpenAI-compatible endpoint into this shape
|
||||
and back.
|
||||
A provider adapter translates an OpenAI-compatible endpoint, the Anthropic
|
||||
Messages API (a provider with `kind = anthropic`) or a program's stdout
|
||||
(`--transport cli`) into this shape and back.
|
||||
The harness itself never parses vendor JSON, which is why the loop is testable
|
||||
with no network at all.
|
||||
.Sh EXIT STATUS
|
||||
|
||||
@@ -69,12 +69,17 @@ struct sp_registry {
|
||||
size_t len;
|
||||
size_t cap;
|
||||
void *ctx; /* the builtin that owns the tools, if any */
|
||||
void **retired; /* outgrown arrays, kept: a reader on another */
|
||||
size_t nretired; /* thread may still hold a pointer into one */
|
||||
};
|
||||
|
||||
int sp_registry_add(struct sp_registry *, const struct sp_tool *);
|
||||
const struct sp_tool *sp_registry_find(const struct sp_registry *,
|
||||
const char *);
|
||||
size_t sp_registry_count(const struct sp_registry *);
|
||||
/* tools may be added from another thread (an MCP server that connects late):
|
||||
* read len first, then the array, as this does */
|
||||
const struct sp_tool *sp_registry_tools(const struct sp_registry *, size_t *n);
|
||||
void sp_registry_free(struct sp_registry *);
|
||||
|
||||
/* ---------------------------------------------------------- conversation */
|
||||
@@ -366,6 +371,12 @@ int sp_delegate_choose(const struct sp_config *, const char *task,
|
||||
/* transport_openai.c -- OpenAI-compatible chat completions, via curl(1) */
|
||||
/* The turn's cancellation flag; set by the UI before a turn, cleared after. */
|
||||
void sp_openai_set_cancel(const volatile int *flag);
|
||||
/*
|
||||
* The same flag for transports that are not this one: the cli plugin kills its
|
||||
* child process with it, so Ctrl-C ends a `claude -p` too. NULL when no turn
|
||||
* is running.
|
||||
*/
|
||||
const volatile int *sp_cancel_flag(void);
|
||||
/*
|
||||
* The session whose id goes to providers that want one (opencode-go routes
|
||||
* and caches by "x-opencode-session"). A pointer, so /new is seen.
|
||||
@@ -373,6 +384,14 @@ void sp_openai_set_cancel(const volatile int *flag);
|
||||
void sp_openai_set_session(const char *id);
|
||||
size_t sp_openai_session_header(const char *url, char *buf, size_t cap);
|
||||
|
||||
/*
|
||||
* One route of an endpoint: the config names the API base (https://host/v1),
|
||||
* this appends "chat/completions", "messages", "models", ... An old full
|
||||
* route is cut back to the base first. NULL route: the base. Returns out.
|
||||
*/
|
||||
char *sp_endpoint_url(const char *endpoint, const char *route, char *out,
|
||||
size_t cap);
|
||||
|
||||
struct sp_transport sp_openai_transport(const char *url, const char *model,
|
||||
const char *api_key, const struct sp_registry *, long timeout_s);
|
||||
|
||||
@@ -397,4 +416,35 @@ int sp_sse_done(const struct sp_sse *);
|
||||
int sp_sse_usage(const struct sp_sse *, long *in, long *out);
|
||||
const char *sp_sse_tool_start(const struct sp_sse *, size_t index);
|
||||
|
||||
/*
|
||||
* transport_anthropic.c -- the Anthropic Messages API, via curl(1).
|
||||
*
|
||||
* Same seam as the OpenAI transport: a conversation in, a reply out. A token
|
||||
* that starts with "sk-ant-oat" is a Claude Code OAuth token and is sent as a
|
||||
* Bearer token with the oauth beta (and Claude Code's first system block);
|
||||
* anything else goes as x-api-key.
|
||||
*/
|
||||
struct sp_transport sp_anthropic_transport(const char *url, const char *model,
|
||||
const char *api_key, const struct sp_registry *, long timeout_s);
|
||||
|
||||
/* anthropic.c -- pure JSON shaping, testable without a network */
|
||||
int sp_anthropic_request(const struct sp_conv *, const char *model,
|
||||
const struct sp_registry *, int streaming, int oauth,
|
||||
struct sp_buf *out);
|
||||
int sp_anthropic_reply(const char *json, struct sp_reply *out,
|
||||
struct sp_buf *err);
|
||||
|
||||
/* Anthropic event accumulation, one line at a time */
|
||||
struct sp_as_sse;
|
||||
struct sp_as_sse *sp_as_sse_new(void);
|
||||
void sp_as_sse_free(struct sp_as_sse *);
|
||||
/* Returns 0 for an event that carries nothing, an SP_STREAM_* kind for what it
|
||||
* produced (in out), or -1 with the event quoted in err. */
|
||||
int sp_as_sse_line(struct sp_as_sse *, const char *line, struct sp_buf *out,
|
||||
struct sp_buf *err);
|
||||
int sp_as_sse_finish(struct sp_as_sse *, struct sp_reply *out,
|
||||
struct sp_buf *err);
|
||||
int sp_as_sse_done(const struct sp_as_sse *);
|
||||
int sp_as_sse_usage(const struct sp_as_sse *, long *in, long *out);
|
||||
|
||||
#endif /* SPLINTER_H */
|
||||
@@ -145,6 +145,9 @@ int sp_host_add_widget(struct sp_host *, const struct sp_widget *);
|
||||
int sp_host_widget_text(struct sp_host *, const char *widget,
|
||||
const char *text);
|
||||
int sp_host_note(struct sp_host *, const char *text);
|
||||
/* a line for the chat transcript; safe from any thread */
|
||||
int sp_host_status_msg(struct sp_host *, const char *text);
|
||||
int sp_host_status_take(struct sp_host *, char *buf, size_t len);
|
||||
int sp_host_add_compactor(struct sp_host *, const struct sp_compactor *);
|
||||
int sp_host_add_gate(struct sp_host *, const struct sp_gate *);
|
||||
int sp_host_add_status(struct sp_host *, const struct sp_status *);
|
||||
|
||||
+89
-18
@@ -34,6 +34,8 @@
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <time.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
@@ -306,31 +308,104 @@ build_cmd(const struct cli_cfg *c, const char *path, const char *prompt,
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* run one shell line; stdout into raw, stderr text into errtext */
|
||||
/*
|
||||
* Run one shell line; stdout into raw, stderr text into errtext.
|
||||
*
|
||||
* Not popen(): popen hands back a stream, not a process id, so a cancelled
|
||||
* turn could only end when the program decided to. `claude -p` under its
|
||||
* 30-minute timeout therefore held Ctrl-C hostage: the UI set the flag, joined
|
||||
* the worker, and the worker was still blocked reading a pipe. The child gets
|
||||
* its own process group (the shell, `timeout`, and the program under it), and
|
||||
* the read loop polls it, so a cancellation kills the whole tree.
|
||||
*/
|
||||
static int
|
||||
run_cmd(const char *line, const char *errpath, struct sp_buf *raw,
|
||||
char *errtext, size_t errcap, int *status, struct sp_buf *err)
|
||||
{
|
||||
FILE *p, *ef;
|
||||
char chunk[4096];
|
||||
size_t got, en = 0;
|
||||
const volatile int *cancel = sp_cancel_flag();
|
||||
char chunk[4096];
|
||||
FILE *ef;
|
||||
int fds[2], st = 0, rc = 0;
|
||||
pid_t child;
|
||||
size_t en = 0;
|
||||
|
||||
sp_buf_clear(raw);
|
||||
p = popen(line, "r");
|
||||
if (p == NULL) {
|
||||
sp_buf_printf(err, "cli: popen: %s", strerror(errno));
|
||||
*status = 0;
|
||||
if (pipe(fds) != 0) {
|
||||
sp_buf_printf(err, "cli: pipe: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
while ((got = fread(chunk, 1, sizeof(chunk), p)) > 0) {
|
||||
if (raw->len + got > OUT_CAP)
|
||||
child = fork();
|
||||
if (child < 0) {
|
||||
sp_buf_printf(err, "cli: fork: %s", strerror(errno));
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
return -1;
|
||||
}
|
||||
if (child == 0) {
|
||||
/*
|
||||
* Both sides call setpgid: whoever runs first wins the race, and the
|
||||
* kill below always reaches the whole tree.
|
||||
*/
|
||||
(void)setpgid(0, 0);
|
||||
close(fds[0]);
|
||||
if (dup2(fds[1], STDOUT_FILENO) < 0)
|
||||
_exit(127);
|
||||
close(fds[1]);
|
||||
execl("/bin/sh", "sh", "-c", line, (char *)NULL);
|
||||
_exit(127);
|
||||
}
|
||||
(void)setpgid(child, child);
|
||||
close(fds[1]);
|
||||
for (;;) {
|
||||
struct pollfd pfd;
|
||||
ssize_t got;
|
||||
int pr;
|
||||
|
||||
if (cancel != NULL && *cancel) {
|
||||
(void)kill(-child, SIGKILL);
|
||||
sp_buf_puts(err, "cancelled");
|
||||
rc = -1;
|
||||
break;
|
||||
if (sp_buf_add(raw, chunk, got) != 0) {
|
||||
pclose(p);
|
||||
}
|
||||
pfd.fd = fds[0];
|
||||
pfd.events = POLLIN;
|
||||
pfd.revents = 0;
|
||||
pr = poll(&pfd, 1, 200);
|
||||
if (pr < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
sp_buf_printf(err, "cli: poll: %s", strerror(errno));
|
||||
rc = -1;
|
||||
break;
|
||||
}
|
||||
if (pr == 0)
|
||||
continue;
|
||||
got = read(fds[0], chunk, sizeof(chunk));
|
||||
if (got < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
sp_buf_printf(err, "cli: read: %s", strerror(errno));
|
||||
rc = -1;
|
||||
break;
|
||||
}
|
||||
if (got == 0)
|
||||
break;
|
||||
if (raw->len + (size_t)got > OUT_CAP) {
|
||||
/* over the cap: stop the program instead of holding it */
|
||||
(void)kill(-child, SIGKILL);
|
||||
break;
|
||||
}
|
||||
if (sp_buf_add(raw, chunk, (size_t)got) != 0) {
|
||||
(void)kill(-child, SIGKILL);
|
||||
sp_buf_puts(err, "cli: out of memory");
|
||||
return -1;
|
||||
rc = -1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
*status = pclose(p);
|
||||
close(fds[0]);
|
||||
(void)waitpid(child, &st, 0);
|
||||
*status = st;
|
||||
ef = fopen(errpath, "r");
|
||||
if (ef != NULL) {
|
||||
en = fread(errtext, 1, errcap - 1, ef);
|
||||
@@ -338,11 +413,7 @@ run_cmd(const char *line, const char *errpath, struct sp_buf *raw,
|
||||
}
|
||||
errtext[en] = '\0';
|
||||
(void)unlink(errpath);
|
||||
if (*status < 0) {
|
||||
sp_buf_printf(err, "cli: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
|
||||
+195
-46
@@ -37,6 +37,8 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
#include <strings.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
@@ -67,8 +69,14 @@ struct server {
|
||||
int next_id;
|
||||
int dead;
|
||||
int ntools;
|
||||
int up; /* handshake done and answering */
|
||||
int registered; /* its tools are in the registry (once) */
|
||||
pthread_mutex_t lock; /* one round trip at a time */
|
||||
};
|
||||
|
||||
#define RETRY_S 10
|
||||
static volatile int stopping;
|
||||
|
||||
static struct server sv[MAX_SERVERS];
|
||||
static size_t nsv;
|
||||
static struct sp_host *host;
|
||||
@@ -454,16 +462,33 @@ accept_reply(char *line, const char *method, struct sp_buf *err)
|
||||
* One JSON-RPC round trip. The result is the raw reply line; NULL means the
|
||||
* server is gone or answered with an error, and 'err' says which.
|
||||
*/
|
||||
static char *rpc_locked(size_t which, const char *method, const char *params,
|
||||
struct sp_buf *err);
|
||||
|
||||
static char *
|
||||
rpc(size_t which, const char *method, const char *params, struct sp_buf *err)
|
||||
{
|
||||
char *r;
|
||||
|
||||
pthread_mutex_lock(&sv[which].lock);
|
||||
r = rpc_locked(which, method, params, err);
|
||||
pthread_mutex_unlock(&sv[which].lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static char *
|
||||
rpc_locked(size_t which, const char *method, const char *params,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
struct server *s = &sv[which];
|
||||
int id = ++s->next_id;
|
||||
struct sp_buf line;
|
||||
char *raw;
|
||||
|
||||
if (s->dead)
|
||||
if (s->dead) {
|
||||
sp_buf_puts(err, "mcp: server not connected (reconnecting)");
|
||||
return NULL;
|
||||
}
|
||||
if (s->http)
|
||||
return accept_reply(http_rpc(s, method, params, id, err), method,
|
||||
err);
|
||||
@@ -635,6 +660,9 @@ call_tool(const char *args, struct sp_buf *out, void *ctx)
|
||||
reply = rpc(tool->srv, "tools/call", params.p, &err);
|
||||
sp_buf_free(¶ms);
|
||||
if (reply == NULL) {
|
||||
/* not an answer from the server: the link is gone, reconnect */
|
||||
if (err.p == NULL || strstr(err.p, " failed: ") == NULL)
|
||||
sv[tool->srv].dead = 1;
|
||||
sp_buf_printf(out, "error: %s", err.p != NULL ? err.p : "mcp call");
|
||||
sp_buf_free(&err);
|
||||
return 0;
|
||||
@@ -784,12 +812,12 @@ mcp_widget_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
|
||||
(void)ctx;
|
||||
for (i = 0; i < nsv; i++) {
|
||||
total += sv[i].ntools;
|
||||
if (!sv[i].dead)
|
||||
total += sv[i].up ? sv[i].ntools : 0;
|
||||
if (sv[i].up)
|
||||
alive++;
|
||||
}
|
||||
if (nsv > 0 && alive == 0)
|
||||
snprintf(line, sizeof(line), "%d tools, server gone", total);
|
||||
snprintf(line, sizeof(line), "%d tools, offline", total);
|
||||
else
|
||||
snprintf(line, sizeof(line), "%d tools", total);
|
||||
(void)sp_host_widget_text(h, name, line);
|
||||
@@ -826,18 +854,162 @@ handshake(size_t which, struct sp_buf *err)
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Close a stdio child and its pipes, so the next connect starts clean. */
|
||||
static void
|
||||
teardown(struct server *s)
|
||||
{
|
||||
if (!s->http && s->pid > 0) {
|
||||
(void)kill(s->pid, SIGTERM);
|
||||
(void)waitpid(s->pid, NULL, 0);
|
||||
s->pid = 0;
|
||||
if (s->to != NULL)
|
||||
fclose(s->to);
|
||||
s->to = NULL;
|
||||
if (s->from > 0)
|
||||
close(s->from);
|
||||
s->from = 0;
|
||||
if (s->in.p != NULL)
|
||||
sp_buf_free(&s->in);
|
||||
}
|
||||
s->session[0] = '\0';
|
||||
s->up = 0;
|
||||
}
|
||||
|
||||
/* Everything one connect attempt needs: start, handshake, tools (once). */
|
||||
static int
|
||||
connect_server(size_t i, struct sp_buf *err)
|
||||
{
|
||||
struct server *s = &sv[i];
|
||||
|
||||
s->dead = 0;
|
||||
if (!s->http && spawn(s, err) != 0)
|
||||
return -1;
|
||||
if (handshake(i, err) != 0)
|
||||
return -1;
|
||||
if (!s->registered) {
|
||||
int n = register_tools(s, i, nsv > 1, err);
|
||||
|
||||
if (n <= 0) {
|
||||
if (err->p == NULL)
|
||||
sp_buf_puts(err, "mcp: the server offered no tools");
|
||||
return -1;
|
||||
}
|
||||
s->ntools = n;
|
||||
s->registered = 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Sleep RETRY_S seconds in small steps so shutdown is not kept waiting. */
|
||||
static void
|
||||
nap(void)
|
||||
{
|
||||
int k;
|
||||
|
||||
for (k = 0; k < RETRY_S * 10 && !stopping; k++) {
|
||||
struct timespec ts = { 0, 100000000L };
|
||||
|
||||
nanosleep(&ts, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
say(const char *id, const char *what, const char *more)
|
||||
{
|
||||
char line[200];
|
||||
|
||||
snprintf(line, sizeof(line), "mcp %.40s: %.60s%.80s", id, what,
|
||||
more != NULL ? more : "");
|
||||
(void)sp_host_status_msg(host, line);
|
||||
}
|
||||
|
||||
/* A reply error from the server proves it is alive; anything else is a loss. */
|
||||
static int
|
||||
alive_after(const char *err)
|
||||
{
|
||||
return err != NULL && strstr(err, " failed: ") != NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* One thread per server: connect in the background (a host that is down must
|
||||
* not delay the start), say what happened, ping every RETRY_S seconds and
|
||||
* reconnect when the link is gone.
|
||||
*/
|
||||
static void *
|
||||
server_thread(void *arg)
|
||||
{
|
||||
size_t i = (size_t)(uintptr_t)arg;
|
||||
struct server *s = &sv[i];
|
||||
int failed_said = 0, ever_up = 0;
|
||||
|
||||
while (!stopping) {
|
||||
struct sp_buf err;
|
||||
|
||||
if (sp_buf_init(&err) != 0)
|
||||
return NULL;
|
||||
if (!s->up) {
|
||||
/* rpc() takes the lock itself, so connect runs without it */
|
||||
if (connect_server(i, &err) == 0) {
|
||||
s->up = 1;
|
||||
{
|
||||
char n[40];
|
||||
|
||||
snprintf(n, sizeof(n), " (%d tools)",
|
||||
s->ntools);
|
||||
say(s->id, ever_up ? "reconnected" :
|
||||
"connected", n);
|
||||
}
|
||||
ever_up = 1;
|
||||
failed_said = 0;
|
||||
} else {
|
||||
teardown(s);
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
if (!failed_said) {
|
||||
char why[120];
|
||||
|
||||
snprintf(why, sizeof(why), " -- %.100s",
|
||||
err.p != NULL ? err.p : "no answer");
|
||||
say(s->id, "not reachable, retrying every 10 s",
|
||||
why);
|
||||
failed_said = 1;
|
||||
}
|
||||
sp_buf_free(&err);
|
||||
nap();
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
char *r;
|
||||
|
||||
nap();
|
||||
if (stopping) {
|
||||
sp_buf_free(&err);
|
||||
break;
|
||||
}
|
||||
r = s->dead ? NULL : rpc(i, "ping", NULL, &err);
|
||||
if (r != NULL)
|
||||
free(r);
|
||||
else if (s->dead || !alive_after(err.p)) {
|
||||
pthread_mutex_lock(&s->lock);
|
||||
teardown(s);
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
say(s->id, "connection lost, reconnecting", NULL);
|
||||
failed_said = 1; /* stay quiet until it is back */
|
||||
}
|
||||
}
|
||||
sp_buf_free(&err);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int
|
||||
mcp_init(struct sp_host *h)
|
||||
{
|
||||
const struct sp_config *conf;
|
||||
struct sp_buf err;
|
||||
size_t i;
|
||||
int total = 0;
|
||||
|
||||
host = h;
|
||||
if (sp_buf_init(&err) != 0)
|
||||
return -1;
|
||||
nsv = 0;
|
||||
stopping = 0;
|
||||
conf = sp_host_config(h);
|
||||
|
||||
if (conf != NULL) {
|
||||
@@ -869,44 +1041,20 @@ mcp_init(struct sp_host *h)
|
||||
}
|
||||
if (nsv == 0) {
|
||||
(void)sp_host_note(h, "mcp: no server configured");
|
||||
sp_buf_free(&err);
|
||||
return -1;
|
||||
}
|
||||
|
||||
for (i = 0; i < nsv; i++) {
|
||||
int n;
|
||||
|
||||
if (!sv[i].http && spawn(&sv[i], &err) != 0) {
|
||||
(void)sp_host_note(h, err.p != NULL ? err.p :
|
||||
"mcp: cannot start the server");
|
||||
sv[i].dead = 1;
|
||||
sp_buf_clear(&err);
|
||||
continue;
|
||||
}
|
||||
if (handshake(i, &err) != 0) {
|
||||
(void)sp_host_note(h, err.p != NULL ? err.p :
|
||||
"mcp: handshake failed");
|
||||
sv[i].dead = 1;
|
||||
sp_buf_clear(&err);
|
||||
continue;
|
||||
}
|
||||
n = register_tools(&sv[i], i, nsv > 1, &err);
|
||||
if (n <= 0) {
|
||||
(void)sp_host_note(h, err.p != NULL ? err.p :
|
||||
"mcp: the server offered no tools");
|
||||
sv[i].dead = 1;
|
||||
sp_buf_clear(&err);
|
||||
continue;
|
||||
}
|
||||
sv[i].ntools = n;
|
||||
total += n;
|
||||
}
|
||||
if (total <= 0) {
|
||||
sp_buf_free(&err);
|
||||
return -1;
|
||||
}
|
||||
(void)sp_host_add_widget(h, &widget);
|
||||
sp_buf_free(&err);
|
||||
for (i = 0; i < nsv; i++) {
|
||||
pthread_t t;
|
||||
|
||||
pthread_mutex_init(&sv[i].lock, NULL);
|
||||
say(sv[i].id, "connecting in the background", NULL);
|
||||
if (pthread_create(&t, NULL, server_thread,
|
||||
(void *)(uintptr_t)i) == 0)
|
||||
pthread_detach(t);
|
||||
else
|
||||
sv[i].dead = 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -916,14 +1064,15 @@ mcp_shutdown(struct sp_host *h)
|
||||
size_t i;
|
||||
|
||||
(void)h;
|
||||
stopping = 1;
|
||||
for (i = 0; i < nsv; i++) {
|
||||
if (!sv[i].http && !sv[i].dead && sv[i].pid > 0) {
|
||||
/* a child is stopped without taking the lock a stuck call may hold */
|
||||
if (!sv[i].http && sv[i].pid > 0) {
|
||||
(void)kill(sv[i].pid, SIGTERM);
|
||||
(void)waitpid(sv[i].pid, NULL, 0);
|
||||
sv[i].pid = 0;
|
||||
}
|
||||
sv[i].dead = 1;
|
||||
if (sv[i].in.p != NULL)
|
||||
sp_buf_free(&sv[i].in);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+4
-1
@@ -128,6 +128,9 @@ tg.cmd.connect = einen Provider hinzufuegen
|
||||
model.choose = Waehle ein Modell. Die Liste kommt aus der Konfiguration; die Wahl gilt fuer diese Sitzung.
|
||||
model.none = Kein Modell konfiguriert. Mit /connect kommt eins dazu.
|
||||
model.unknown = Kein solches Modell: %s
|
||||
model.pool = Pool %s: %s (Anbieter %s, diese Sitzung).
|
||||
model.pools = Pools:
|
||||
ui.cancelling = breche ab ... (Ctrl-C nochmal beendet)
|
||||
model.failed = Umschalten fehlgeschlagen: %s
|
||||
model.switched = Modell: %s (Provider %s, diese Sitzung).
|
||||
model.no_key = " (kein %s gesetzt)"
|
||||
@@ -143,7 +146,7 @@ model.toast = Schalte um
|
||||
connect.start = Neuer Provider. /cancel bricht ab.
|
||||
connect.name = Name? Kleinbuchstaben, Ziffern, - und _ (max 31).
|
||||
connect.name_bad = Das ist kein Name. Nur Kleinbuchstaben, Ziffern, - und _.
|
||||
connect.endpoint = Endpoint? Eine URL wie https://host/v1/chat/completions, oder `ollama` / `opencode` fuer den ueblichen.
|
||||
connect.endpoint = Endpoint? Die API-Basis, etwa https://host/v1, oder `ollama` / `opencode` fuer den ueblichen.
|
||||
connect.endpoint_bad = Ein Endpoint muss mit http:// oder https:// beginnen.
|
||||
connect.model = Welches Modell bedient er?
|
||||
connect.model_bad = Das ist kein Modellname.
|
||||
|
||||
+4
-1
@@ -127,6 +127,9 @@ tg.cmd.connect = add a provider
|
||||
model.choose = Choose a model. The list is the configuration; the choice lasts for this session.
|
||||
model.none = No model is configured. Add one with /connect.
|
||||
model.unknown = No such model: %s
|
||||
model.pool = Pool %s: using %s (provider %s, this session).
|
||||
model.pools = pools:
|
||||
ui.cancelling = cancelling ... (Ctrl-C again quits)
|
||||
model.failed = Could not switch: %s
|
||||
model.switched = Model: %s (provider %s, this session).
|
||||
model.no_key = " (no %s set)"
|
||||
@@ -142,7 +145,7 @@ model.toast = Switching
|
||||
connect.start = New provider. /cancel stops.
|
||||
connect.name = Name? Lower-case letters, digits, - and _ (max 31).
|
||||
connect.name_bad = That is not a name. Lower-case letters, digits, - and _ only.
|
||||
connect.endpoint = Endpoint? A URL like https://host/v1/chat/completions, or `ollama` / `opencode` for the usual one.
|
||||
connect.endpoint = Endpoint? The API base, like https://host/v1, or `ollama` / `opencode` for the usual one.
|
||||
connect.endpoint_bad = An endpoint must start with http:// or https://.
|
||||
connect.model = Which model does it serve?
|
||||
connect.model_bad = That is not a model name.
|
||||
|
||||
@@ -131,6 +131,9 @@ tg.cmd.connect = adicionar um provedor
|
||||
model.choose = Escolha um modelo. A lista e a configuracao; a escolha vale para esta sessao.
|
||||
model.none = Nenhum modelo configurado. Adicione um com /connect.
|
||||
model.unknown = Modelo inexistente: %s
|
||||
model.pool = Pool %s: usando %s (provedor %s, esta sessao).
|
||||
model.pools = Pools:
|
||||
ui.cancelling = cancelando ... (Ctrl-C de novo encerra)
|
||||
model.failed = Nao consegui trocar: %s
|
||||
model.switched = Modelo: %s (provedor %s, esta sessao).
|
||||
model.no_key = " (%s nao definida)"
|
||||
@@ -146,7 +149,7 @@ model.toast = Trocando
|
||||
connect.start = Novo provedor. /cancel cancela.
|
||||
connect.name = Nome? Letras minusculas, digitos, - e _ (max 31).
|
||||
connect.name_bad = Isso nao e um nome. So letras minusculas, digitos, - e _.
|
||||
connect.endpoint = Endpoint? Uma URL como https://host/v1/chat/completions, ou `ollama` / `opencode` para o usual.
|
||||
connect.endpoint = Endpoint? A base da API, como https://host/v1, ou `ollama` / `opencode` para o usual.
|
||||
connect.endpoint_bad = Um endpoint precisa comecar com http:// ou https://.
|
||||
connect.model = Qual modelo ele serve?
|
||||
connect.model_bad = Isso nao e um nome de modelo.
|
||||
|
||||
+888
@@ -0,0 +1,888 @@
|
||||
/*
|
||||
* splinter -- Anthropic Messages API request/reply shaping.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* The second vendor shape, next to openai.c. The seam with the rest of the
|
||||
* harness stays the conversation: the loop knows roles, text and tool calls,
|
||||
* and this file is where those become Anthropic's content blocks and back.
|
||||
*
|
||||
* Three differences are the whole file:
|
||||
*
|
||||
* - the system prompt is a top-level field, not a message;
|
||||
* - a tool call is a `tool_use` block inside the assistant's content, and
|
||||
* its answer is a `tool_result` block inside the next user message;
|
||||
* - messages must alternate, so consecutive observations (one per call of a
|
||||
* parallel round) are merged into one user message.
|
||||
*
|
||||
* A call is stored in the conversation in this file's own neutral shape,
|
||||
*
|
||||
* [{"id":"toolu_01","name":"read","input":{"path":"x"}}]
|
||||
*
|
||||
* because `calls_json` is handed back verbatim on the next request. A
|
||||
* conversation started on an OpenAI endpoint (where the shape is
|
||||
* {"function":{"name":...,"arguments":"..."}}) is still understood: switching
|
||||
* provider in the middle of a session must not turn history into a 400.
|
||||
*
|
||||
* Claude Code's OAuth tokens (sk-ant-oat...) are only accepted for inference
|
||||
* when the request says it is Claude Code, so `oauth` prepends that first
|
||||
* system block. No token is ever put in this file.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "mcp.h"
|
||||
|
||||
#define AS_MAX_CALLS 16
|
||||
#define AS_MAX_BLOCKS 64
|
||||
|
||||
/*
|
||||
* The first system block an OAuth token needs. Measured, not guessed: without
|
||||
* it the API refuses a Claude Code token for every model with a 429 whose
|
||||
* message is just "Error" (haiku-4-5 happens to answer anyway, which is how
|
||||
* this looked like a quota problem at first). The older wording -- "You are
|
||||
* Claude Code, Anthropic's official CLI for Claude." -- is refused today;
|
||||
* this is what claude-cli 2.1.323 sends.
|
||||
*/
|
||||
static const char as_claude_code[] =
|
||||
"You are a Claude agent, built on Anthropic's Claude Agent SDK.";
|
||||
|
||||
/*
|
||||
* A parsed JSON value back to text. Needed because a tool's arguments are sent
|
||||
* as an object, and the conversation stores the provider's own text: turning
|
||||
* it into a string and back would be a second, silently different JSON.
|
||||
*/
|
||||
static int
|
||||
json_emit(struct sp_buf *b, const mcp_json *v)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (v == NULL)
|
||||
return sp_buf_puts(b, "null");
|
||||
switch (v->t) {
|
||||
case MCP_NULL:
|
||||
return sp_buf_puts(b, "null");
|
||||
case MCP_BOOL:
|
||||
return sp_buf_puts(b, v->b ? "true" : "false");
|
||||
case MCP_NUM: {
|
||||
char num[64];
|
||||
|
||||
snprintf(num, sizeof(num), "%.17g", v->n);
|
||||
return sp_buf_puts(b, num);
|
||||
}
|
||||
case MCP_STR:
|
||||
if (sp_buf_puts(b, "\"") != 0 ||
|
||||
sp_json_escape(b, v->s != NULL ? v->s : "") != 0)
|
||||
return -1;
|
||||
return sp_buf_puts(b, "\"");
|
||||
case MCP_ARR:
|
||||
if (sp_buf_puts(b, "[") != 0)
|
||||
return -1;
|
||||
for (i = 0; i < v->count; i++) {
|
||||
if (i > 0 && sp_buf_puts(b, ",") != 0)
|
||||
return -1;
|
||||
if (json_emit(b, v->items[i]) != 0)
|
||||
return -1;
|
||||
}
|
||||
return sp_buf_puts(b, "]");
|
||||
case MCP_OBJ:
|
||||
if (sp_buf_puts(b, "{") != 0)
|
||||
return -1;
|
||||
for (i = 0; i < v->count; i++) {
|
||||
if (i > 0 && sp_buf_puts(b, ",") != 0)
|
||||
return -1;
|
||||
if (sp_buf_puts(b, "\"") != 0 ||
|
||||
sp_json_escape(b, v->keys != NULL &&
|
||||
v->keys[i] != NULL ? v->keys[i] : "") != 0 ||
|
||||
sp_buf_puts(b, "\":") != 0 ||
|
||||
json_emit(b, v->items[i]) != 0)
|
||||
return -1;
|
||||
}
|
||||
return sp_buf_puts(b, "}");
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* the max output of one step; Anthropic requires the field */
|
||||
static int
|
||||
max_tokens(void)
|
||||
{
|
||||
const char *s = getenv("SPLINTER_ANTHROPIC_MAX_TOKENS");
|
||||
long n = s != NULL && *s != '\0' ? strtol(s, NULL, 10) : 0;
|
||||
|
||||
if (n < 256 || n > 128000)
|
||||
n = 16000;
|
||||
return (int)n;
|
||||
}
|
||||
|
||||
/* the members of a parsed object, without the braces */
|
||||
static int
|
||||
json_emit_members(struct sp_buf *b, const mcp_json *v)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < v->count; i++) {
|
||||
if (i > 0 && sp_buf_puts(b, ",") != 0)
|
||||
return -1;
|
||||
if (sp_buf_puts(b, "\"") != 0 ||
|
||||
sp_json_escape(b, v->keys != NULL && v->keys[i] != NULL ?
|
||||
v->keys[i] : "") != 0 ||
|
||||
sp_buf_puts(b, "\":") != 0 ||
|
||||
json_emit(b, v->items[i]) != 0)
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The API rejects the whole request with "input_schema.type: Field required"
|
||||
* when a tool's schema has no type -- and a few here are a bare "{}". The
|
||||
* schema is the tool's own text, so it is completed, never replaced: a
|
||||
* provider that silently dropped a property would leave the model guessing.
|
||||
*/
|
||||
static int
|
||||
schema_emit(struct sp_buf *b, const char *params)
|
||||
{
|
||||
mcp_json *v;
|
||||
int rc;
|
||||
|
||||
if (params == NULL)
|
||||
return sp_buf_puts(b, "{\"type\":\"object\","
|
||||
"\"properties\":{},\"additionalProperties\":true}");
|
||||
v = mcp_parse(params);
|
||||
if (v == NULL || v->t != MCP_OBJ) {
|
||||
mcp_json_free(v);
|
||||
return sp_buf_puts(b, "{\"type\":\"object\","
|
||||
"\"properties\":{},\"additionalProperties\":true}");
|
||||
}
|
||||
if (mcp_arg(v, "type") != NULL) {
|
||||
rc = json_emit(b, v);
|
||||
mcp_json_free(v);
|
||||
return rc;
|
||||
}
|
||||
rc = sp_buf_puts(b, "{\"type\":\"object\"");
|
||||
if (rc == 0 && v->count > 0 && sp_buf_puts(b, ",") != 0)
|
||||
rc = -1;
|
||||
if (rc == 0)
|
||||
rc = json_emit_members(b, v);
|
||||
if (rc == 0)
|
||||
rc = sp_buf_puts(b, "}");
|
||||
mcp_json_free(v);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
text_block(struct sp_buf *b, const char *text, int *first)
|
||||
{
|
||||
if (!*first && sp_buf_puts(b, ",") != 0)
|
||||
return -1;
|
||||
if (sp_buf_puts(b, "{\"type\":\"text\",\"text\":\"") != 0 ||
|
||||
sp_json_escape(b, text != NULL ? text : "") != 0 ||
|
||||
sp_buf_puts(b, "\"}") != 0)
|
||||
return -1;
|
||||
*first = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* One assistant turn: its text, then one tool_use block per call. The stored
|
||||
* shape may be this file's or OpenAI's; both carry a name and arguments.
|
||||
*/
|
||||
static int
|
||||
assistant_blocks(const struct sp_msg *m, struct sp_buf *b, int *first)
|
||||
{
|
||||
mcp_json *v;
|
||||
size_t i;
|
||||
|
||||
if (m->content != NULL && m->content[0] != '\0' &&
|
||||
text_block(b, m->content, first) != 0)
|
||||
return -1;
|
||||
if (m->calls == NULL || m->calls[0] == '\0')
|
||||
return 0;
|
||||
v = mcp_parse(m->calls);
|
||||
if (v == NULL)
|
||||
return 0; /* unusable history is left out, not fatal */
|
||||
if (v->t != MCP_ARR) {
|
||||
mcp_json_free(v);
|
||||
return 0;
|
||||
}
|
||||
for (i = 0; i < v->count; i++) {
|
||||
const mcp_json *c = v->items[i];
|
||||
const mcp_json *fn = mcp_arg(c, "function");
|
||||
const mcp_json *input = mcp_arg(c, "input");
|
||||
const char *id = mcp_arg_string(c, "id");
|
||||
const char *name = fn != NULL ? mcp_arg_string(fn, "name") :
|
||||
mcp_arg_string(c, "name");
|
||||
const char *args = fn != NULL ?
|
||||
mcp_arg_string(fn, "arguments") : NULL;
|
||||
|
||||
if (name == NULL || name[0] == '\0')
|
||||
continue;
|
||||
if (!*first && sp_buf_puts(b, ",") != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
*first = 0;
|
||||
if (sp_buf_puts(b, "{\"type\":\"tool_use\",\"id\":\"") != 0 ||
|
||||
sp_json_escape(b, id != NULL && id[0] != '\0' ? id :
|
||||
"toolu_unknown") != 0 ||
|
||||
sp_buf_puts(b, "\",\"name\":\"") != 0 ||
|
||||
sp_json_escape(b, name) != 0 ||
|
||||
sp_buf_puts(b, "\",\"input\":") != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
if (input != NULL) {
|
||||
if (json_emit(b, input) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
} else if (args != NULL) {
|
||||
mcp_json *a = mcp_parse(args);
|
||||
|
||||
if (a != NULL && a->t == MCP_OBJ) {
|
||||
int rc = json_emit(b, a);
|
||||
|
||||
mcp_json_free(a);
|
||||
if (rc != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
} else {
|
||||
mcp_json_free(a);
|
||||
if (sp_buf_puts(b, "{}") != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
} else if (sp_buf_puts(b, "{}") != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_puts(b, "}") != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
mcp_json_free(v);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* one observation: a tool_result, or plain text when it is not an answer */
|
||||
static int
|
||||
user_blocks(const struct sp_msg *m, struct sp_buf *b, int *first)
|
||||
{
|
||||
int is_err;
|
||||
|
||||
if (m->call_id != NULL && m->call_id[0] != '\0') {
|
||||
is_err = m->content != NULL &&
|
||||
strncmp(m->content, "error", 5) == 0;
|
||||
if (!*first && sp_buf_puts(b, ",") != 0)
|
||||
return -1;
|
||||
*first = 0;
|
||||
if (sp_buf_puts(b, "{\"type\":\"tool_result\","
|
||||
"\"tool_use_id\":\"") != 0 ||
|
||||
sp_json_escape(b, m->call_id) != 0 ||
|
||||
sp_buf_puts(b, "\",\"content\":[{\"type\":\"text\","
|
||||
"\"text\":\"") != 0 ||
|
||||
sp_json_escape(b, m->content != NULL ? m->content : "") != 0 ||
|
||||
sp_buf_puts(b, "\"}]") != 0)
|
||||
return -1;
|
||||
if (is_err && sp_buf_puts(b, ",\"is_error\":true") != 0)
|
||||
return -1;
|
||||
return sp_buf_puts(b, "}");
|
||||
}
|
||||
if (m->content != NULL && m->content[0] != '\0')
|
||||
return text_block(b, m->content, first);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_anthropic_request(const struct sp_conv *conv, const char *model,
|
||||
const struct sp_registry *reg, int streaming, int oauth, struct sp_buf *out)
|
||||
{
|
||||
struct sp_buf sys, blocks;
|
||||
const struct sp_tool *tv;
|
||||
size_t i, ntv, ntv0, k, nmsg = 0;
|
||||
int prev_assistant = -1, rc = -1;
|
||||
|
||||
if (conv == NULL || out == NULL)
|
||||
return -1;
|
||||
if (sp_buf_init(&sys) != 0 || sp_buf_init(&blocks) != 0)
|
||||
return -1;
|
||||
for (i = 0; i < conv->n; i++) {
|
||||
const struct sp_msg *m = &conv->v[i];
|
||||
|
||||
if (m->role == NULL || strcmp(m->role, "system") != 0 ||
|
||||
m->content == NULL || m->content[0] == '\0')
|
||||
continue;
|
||||
if ((sys.len > 0 && sp_buf_puts(&sys, "\n\n") != 0) ||
|
||||
sp_buf_puts(&sys, m->content) != 0) {
|
||||
sp_buf_free(&sys);
|
||||
sp_buf_free(&blocks);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
sp_buf_clear(out);
|
||||
if (sp_buf_puts(out, "{\"model\":\"") != 0 ||
|
||||
sp_json_escape(out, model != NULL ? model : "") != 0 ||
|
||||
sp_buf_printf(out, "\",\"max_tokens\":%d,\"stream\":%s,",
|
||||
max_tokens(), streaming ? "true" : "false") != 0)
|
||||
goto out;
|
||||
if (oauth || sys.len > 0) {
|
||||
int first = 1;
|
||||
|
||||
if (sp_buf_puts(out, "\"system\":[") != 0)
|
||||
goto out;
|
||||
if (oauth) {
|
||||
if (sp_buf_puts(out,
|
||||
"{\"type\":\"text\",\"text\":\"") != 0 ||
|
||||
sp_json_escape(out, as_claude_code) != 0 ||
|
||||
sp_buf_puts(out, "\"}") != 0)
|
||||
goto out;
|
||||
first = 0;
|
||||
}
|
||||
if (sys.len > 0 &&
|
||||
text_block(out, sys.p, &first) != 0)
|
||||
goto out;
|
||||
if (sp_buf_puts(out, "],") != 0)
|
||||
goto out;
|
||||
}
|
||||
|
||||
if (sp_buf_puts(out, "\"messages\":[") != 0)
|
||||
goto out;
|
||||
for (i = 0; i < conv->n; i++) {
|
||||
const struct sp_msg *m = &conv->v[i];
|
||||
int assistant, any = 0;
|
||||
|
||||
if (m->role == NULL || strcmp(m->role, "system") == 0)
|
||||
continue;
|
||||
assistant = strcmp(m->role, "assistant") == 0;
|
||||
sp_buf_clear(&blocks);
|
||||
{
|
||||
int first = 1;
|
||||
|
||||
if ((assistant ? assistant_blocks(m, &blocks, &first) :
|
||||
user_blocks(m, &blocks, &first)) != 0)
|
||||
goto out;
|
||||
any = !first;
|
||||
}
|
||||
if (!any)
|
||||
continue; /* nothing to say: no empty message */
|
||||
if (prev_assistant == assistant) {
|
||||
if (sp_buf_puts(out, ",") != 0 ||
|
||||
(blocks.len > 0 && sp_buf_add(out, blocks.p,
|
||||
blocks.len) != 0))
|
||||
goto out;
|
||||
continue;
|
||||
}
|
||||
if (nmsg++ > 0 && sp_buf_puts(out, ",") != 0)
|
||||
goto out;
|
||||
if (sp_buf_printf(out, "{\"role\":\"%s\",\"content\":[",
|
||||
assistant ? "assistant" : "user") != 0 ||
|
||||
(blocks.len > 0 && sp_buf_add(out, blocks.p,
|
||||
blocks.len) != 0) ||
|
||||
sp_buf_puts(out, "]}") != 0)
|
||||
goto out;
|
||||
prev_assistant = assistant;
|
||||
}
|
||||
if (sp_buf_puts(out, "]") != 0)
|
||||
goto out;
|
||||
|
||||
/* tools: name, description, and the schema as input_schema */
|
||||
tv = sp_registry_tools(reg, &ntv0);
|
||||
for (i = 0, ntv = 0; i < ntv0; i++)
|
||||
if (tv[i].name != NULL && tv[i].name[0] != '\0')
|
||||
ntv++;
|
||||
if (ntv == 0) {
|
||||
if (sp_buf_puts(out, "}") == 0)
|
||||
rc = 0;
|
||||
goto out;
|
||||
}
|
||||
if (sp_buf_puts(out, ",\"tools\":[") != 0)
|
||||
goto out;
|
||||
for (i = 0, k = 0; i < ntv0; i++) {
|
||||
const struct sp_tool *t = &tv[i];
|
||||
|
||||
if (t->name == NULL || t->name[0] == '\0')
|
||||
continue;
|
||||
if (k++ > 0 && sp_buf_puts(out, ",") != 0)
|
||||
goto out;
|
||||
if (sp_buf_puts(out, "{\"name\":\"") != 0 ||
|
||||
sp_json_escape(out, t->name) != 0 ||
|
||||
sp_buf_puts(out, "\",\"description\":\"") != 0 ||
|
||||
sp_json_escape(out, t->description != NULL ?
|
||||
t->description : "") != 0 ||
|
||||
sp_buf_puts(out, "\",\"input_schema\":") != 0)
|
||||
goto out;
|
||||
if (schema_emit(out, t->params) != 0)
|
||||
goto out;
|
||||
if (sp_buf_puts(out, "}") != 0)
|
||||
goto out;
|
||||
}
|
||||
if (sp_buf_puts(out, "]}") == 0)
|
||||
rc = 0;
|
||||
out:
|
||||
sp_buf_free(&sys);
|
||||
sp_buf_free(&blocks);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* the neutral call array this file stores in the conversation */
|
||||
static int
|
||||
calls_json(struct sp_reply *out, const char *const *ids,
|
||||
const char *const *names, const char *const *inputs, size_t n)
|
||||
{
|
||||
struct sp_buf b;
|
||||
size_t i;
|
||||
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return -1;
|
||||
sp_buf_puts(&b, "[");
|
||||
for (i = 0; i < n; i++) {
|
||||
if (i > 0)
|
||||
sp_buf_puts(&b, ",");
|
||||
sp_buf_puts(&b, "{\"id\":\"");
|
||||
sp_json_escape(&b, ids[i] != NULL ? ids[i] : "");
|
||||
sp_buf_puts(&b, "\",\"name\":\"");
|
||||
sp_json_escape(&b, names[i] != NULL ? names[i] : "");
|
||||
sp_buf_puts(&b, "\",\"input\":");
|
||||
sp_buf_puts(&b, inputs[i] != NULL && inputs[i][0] != '\0' ?
|
||||
inputs[i] : "{}");
|
||||
sp_buf_puts(&b, "}");
|
||||
}
|
||||
sp_buf_puts(&b, "]");
|
||||
out->calls_json = strdup(b.p != NULL ? b.p : "[]");
|
||||
sp_buf_free(&b);
|
||||
return out->calls_json != NULL ? 0 : -1;
|
||||
}
|
||||
|
||||
int
|
||||
sp_anthropic_reply(const char *json, struct sp_reply *out, struct sp_buf *err)
|
||||
{
|
||||
mcp_json *v;
|
||||
const mcp_json *content, *usage, *error;
|
||||
struct sp_buf text, input;
|
||||
const char *id[AS_MAX_CALLS], *name[AS_MAX_CALLS];
|
||||
char *inputs[AS_MAX_CALLS];
|
||||
size_t ncalls = 0, i, n;
|
||||
|
||||
memset(out, 0, sizeof(*out));
|
||||
out->status = 200;
|
||||
if (json == NULL || *json == '\0') {
|
||||
sp_buf_puts(err, "anthropic: empty body");
|
||||
return -1;
|
||||
}
|
||||
v = mcp_parse(json);
|
||||
if (v == NULL) {
|
||||
sp_buf_printf(err, "anthropic: reply is not JSON: %.120s", json);
|
||||
return -1;
|
||||
}
|
||||
error = mcp_arg(v, "error");
|
||||
if (error != NULL) {
|
||||
sp_buf_printf(err, "anthropic: provider error: %s",
|
||||
mcp_arg_string(error, "message") != NULL ?
|
||||
mcp_arg_string(error, "message") : "(no message)");
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
content = mcp_arg(v, "content");
|
||||
if (content == NULL || mcp_array_len(content) == 0) {
|
||||
sp_buf_printf(err, "anthropic: no content in reply: %.160s", json);
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_init(&text) != 0 || sp_buf_init(&input) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
for (i = 0; i < mcp_array_len(content); i++) {
|
||||
const mcp_json *block = mcp_array_at(content, i);
|
||||
const char *type = mcp_arg_string(block, "type");
|
||||
|
||||
if (type != NULL && strcmp(type, "text") == 0) {
|
||||
const char *s = mcp_arg_string(block, "text");
|
||||
|
||||
if (s != NULL && sp_buf_puts(&text, s) != 0)
|
||||
goto oom;
|
||||
} else if (type != NULL && strcmp(type, "tool_use") == 0) {
|
||||
const mcp_json *in = mcp_arg(block, "input");
|
||||
|
||||
if (ncalls == AS_MAX_CALLS) {
|
||||
sp_buf_printf(err, "anthropic: more than %d tool "
|
||||
"calls in one reply", AS_MAX_CALLS);
|
||||
goto fail;
|
||||
}
|
||||
sp_buf_clear(&input);
|
||||
if (in != NULL) {
|
||||
if (json_emit(&input, in) != 0)
|
||||
goto oom;
|
||||
} else if (sp_buf_puts(&input, "{}") != 0)
|
||||
goto oom;
|
||||
inputs[ncalls] = strdup(input.p != NULL ? input.p : "{}");
|
||||
if (inputs[ncalls] == NULL)
|
||||
goto oom;
|
||||
id[ncalls] = mcp_arg_string(block, "id");
|
||||
name[ncalls] = mcp_arg_string(block, "name");
|
||||
if (name[ncalls] == NULL || name[ncalls][0] == '\0') {
|
||||
free(inputs[ncalls]);
|
||||
sp_buf_printf(err, "anthropic: tool_use without "
|
||||
"a name");
|
||||
goto fail;
|
||||
}
|
||||
ncalls++;
|
||||
}
|
||||
}
|
||||
out->content = strdup(text.p != NULL ? text.p : "");
|
||||
if (out->content == NULL)
|
||||
goto oom;
|
||||
usage = mcp_arg(v, "usage");
|
||||
if (usage != NULL) {
|
||||
int pin = mcp_arg_int(usage, "input_tokens", -1);
|
||||
int pout = mcp_arg_int(usage, "output_tokens", -1);
|
||||
|
||||
if (pin >= 0)
|
||||
out->tokens_in = pin;
|
||||
if (pout >= 0)
|
||||
out->tokens_out = pout;
|
||||
}
|
||||
if (ncalls > 0) {
|
||||
out->calls = calloc(ncalls, sizeof(*out->calls));
|
||||
if (out->calls == NULL)
|
||||
goto oom;
|
||||
out->ncalls = ncalls;
|
||||
for (i = 0; i < ncalls; i++) {
|
||||
out->calls[i].id = strdup(id[i] != NULL ? id[i] : "");
|
||||
out->calls[i].name = strdup(name[i]);
|
||||
out->calls[i].args = strdup(inputs[i]);
|
||||
if (out->calls[i].id == NULL ||
|
||||
out->calls[i].name == NULL ||
|
||||
out->calls[i].args == NULL)
|
||||
goto oom;
|
||||
}
|
||||
if (calls_json(out, id, name,
|
||||
(const char *const *)inputs, ncalls) != 0)
|
||||
goto oom;
|
||||
}
|
||||
sp_buf_free(&text);
|
||||
sp_buf_free(&input);
|
||||
for (i = 0; i < ncalls; i++)
|
||||
free(inputs[i]);
|
||||
mcp_json_free(v);
|
||||
return 0;
|
||||
oom:
|
||||
sp_buf_puts(err, "anthropic: out of memory");
|
||||
fail:
|
||||
n = ncalls;
|
||||
sp_buf_free(&text);
|
||||
sp_buf_free(&input);
|
||||
for (i = 0; i < n; i++)
|
||||
free(inputs[i]);
|
||||
sp_reply_free(out);
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- stream */
|
||||
|
||||
enum as_btype { AS_NONE, AS_TEXT, AS_THINK, AS_TOOL };
|
||||
|
||||
struct as_call {
|
||||
char *id;
|
||||
char *name;
|
||||
struct sp_buf input; /* the streamed partial_json, joined */
|
||||
int saw;
|
||||
};
|
||||
|
||||
struct sp_as_sse {
|
||||
struct sp_buf content;
|
||||
struct sp_buf think;
|
||||
struct as_call calls[AS_MAX_CALLS];
|
||||
enum as_btype block[AS_MAX_BLOCKS];
|
||||
size_t nblocks;
|
||||
long tokens_in;
|
||||
long tokens_out;
|
||||
int done;
|
||||
};
|
||||
|
||||
struct sp_as_sse *
|
||||
sp_as_sse_new(void)
|
||||
{
|
||||
struct sp_as_sse *s = calloc(1, sizeof(*s));
|
||||
|
||||
if (s == NULL)
|
||||
return NULL;
|
||||
if (sp_buf_init(&s->content) != 0 || sp_buf_init(&s->think) != 0) {
|
||||
free(s);
|
||||
return NULL;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
void
|
||||
sp_as_sse_free(struct sp_as_sse *s)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (s == NULL)
|
||||
return;
|
||||
for (i = 0; i < AS_MAX_CALLS; i++) {
|
||||
free(s->calls[i].id);
|
||||
free(s->calls[i].name);
|
||||
sp_buf_free(&s->calls[i].input);
|
||||
}
|
||||
sp_buf_free(&s->content);
|
||||
sp_buf_free(&s->think);
|
||||
free(s);
|
||||
}
|
||||
|
||||
int
|
||||
sp_as_sse_done(const struct sp_as_sse *s)
|
||||
{
|
||||
return s != NULL ? s->done : 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_as_sse_usage(const struct sp_as_sse *s, long *in, long *out)
|
||||
{
|
||||
if (s == NULL)
|
||||
return 0;
|
||||
if (in != NULL)
|
||||
*in = s->tokens_in;
|
||||
if (out != NULL)
|
||||
*out = s->tokens_out;
|
||||
return (s->tokens_in > 0 || s->tokens_out > 0) ? 1 : 0;
|
||||
}
|
||||
|
||||
static void
|
||||
block_set(struct sp_as_sse *s, int index, enum as_btype t)
|
||||
{
|
||||
if (index < 0 || (size_t)index >= AS_MAX_BLOCKS)
|
||||
return;
|
||||
s->block[index] = t;
|
||||
if ((size_t)index + 1 > s->nblocks)
|
||||
s->nblocks = (size_t)index + 1;
|
||||
}
|
||||
|
||||
static enum as_btype
|
||||
block_get(const struct sp_as_sse *s, int index)
|
||||
{
|
||||
if (index < 0 || (size_t)index >= AS_MAX_BLOCKS ||
|
||||
(size_t)index >= s->nblocks)
|
||||
return AS_NONE;
|
||||
return s->block[index];
|
||||
}
|
||||
|
||||
/*
|
||||
* One SSE line. Returns 0 when the event carries nothing to show, otherwise
|
||||
* the SP_STREAM_* kind of what it produced (in 'out'): text, reasoning, or the
|
||||
* name of a tool call that just began. -1 with the event quoted on a bad one.
|
||||
*/
|
||||
int
|
||||
sp_as_sse_line(struct sp_as_sse *s, const char *line, struct sp_buf *out,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
mcp_json *v;
|
||||
const mcp_json *msg, *usage, *block, *delta, *error;
|
||||
const char *type;
|
||||
int index;
|
||||
|
||||
if (s == NULL)
|
||||
return -1;
|
||||
if (out != NULL)
|
||||
sp_buf_clear(out);
|
||||
while (*line == ' ' || *line == '\t')
|
||||
line++;
|
||||
if (*line == '\0' || *line == ':' || *line == '\n')
|
||||
return 0;
|
||||
if (strncmp(line, "data:", 5) != 0)
|
||||
return 0; /* event:/id:/retry: carry nothing we need */
|
||||
line += 5;
|
||||
while (*line == ' ')
|
||||
line++;
|
||||
if (strncmp(line, "[DONE]", 6) == 0) {
|
||||
s->done = 1;
|
||||
return 0;
|
||||
}
|
||||
v = mcp_parse(line);
|
||||
if (v == NULL) {
|
||||
sp_buf_printf(err, "anthropic sse: unparseable data line: %.200s",
|
||||
line);
|
||||
return -1;
|
||||
}
|
||||
type = mcp_arg_string(v, "type");
|
||||
if (type == NULL) {
|
||||
mcp_json_free(v);
|
||||
return 0;
|
||||
}
|
||||
if (strcmp(type, "error") == 0) {
|
||||
error = mcp_arg(v, "error");
|
||||
sp_buf_printf(err, "anthropic: provider error: %s",
|
||||
error != NULL && mcp_arg_string(error, "message") != NULL ?
|
||||
mcp_arg_string(error, "message") : "(no message)");
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
if (strcmp(type, "message_start") == 0) {
|
||||
msg = mcp_arg(v, "message");
|
||||
usage = msg != NULL ? mcp_arg(msg, "usage") : NULL;
|
||||
if (usage != NULL) {
|
||||
int in = mcp_arg_int(usage, "input_tokens", -1);
|
||||
|
||||
if (in >= 0)
|
||||
s->tokens_in = in;
|
||||
}
|
||||
} else if (strcmp(type, "message_delta") == 0) {
|
||||
usage = mcp_arg(v, "usage");
|
||||
if (usage != NULL) {
|
||||
int outt = mcp_arg_int(usage, "output_tokens", -1);
|
||||
int in = mcp_arg_int(usage, "input_tokens", -1);
|
||||
|
||||
if (outt >= 0)
|
||||
s->tokens_out = outt;
|
||||
if (in >= 0)
|
||||
s->tokens_in = in;
|
||||
}
|
||||
} else if (strcmp(type, "content_block_start") == 0) {
|
||||
const char *bt;
|
||||
|
||||
index = mcp_arg_int(v, "index", -1);
|
||||
block = mcp_arg(v, "content_block");
|
||||
bt = block != NULL ? mcp_arg_string(block, "type") : NULL;
|
||||
if (bt != NULL && strcmp(bt, "tool_use") == 0) {
|
||||
if (index < 0 || index >= AS_MAX_CALLS) {
|
||||
sp_buf_puts(err, "anthropic sse: too many tool "
|
||||
"calls");
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
block_set(s, index, AS_TOOL);
|
||||
if (sp_buf_init(&s->calls[index].input) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
s->calls[index].id = strdup(mcp_arg_string(block, "id") !=
|
||||
NULL ? mcp_arg_string(block, "id") : "");
|
||||
s->calls[index].name = strdup(mcp_arg_string(block,
|
||||
"name") != NULL ? mcp_arg_string(block, "name") : "");
|
||||
s->calls[index].saw = 1;
|
||||
if (s->calls[index].id == NULL ||
|
||||
s->calls[index].name == NULL) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_puts(out, s->calls[index].name) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
mcp_json_free(v);
|
||||
return SP_STREAM_TOOL;
|
||||
}
|
||||
block_set(s, index, bt != NULL && strcmp(bt, "thinking") == 0 ?
|
||||
AS_THINK : AS_TEXT);
|
||||
} else if (strcmp(type, "content_block_delta") == 0) {
|
||||
const char *dt, *txt;
|
||||
enum as_btype kind;
|
||||
|
||||
index = mcp_arg_int(v, "index", -1);
|
||||
delta = mcp_arg(v, "delta");
|
||||
dt = delta != NULL ? mcp_arg_string(delta, "type") : NULL;
|
||||
kind = block_get(s, index);
|
||||
if (dt == NULL) {
|
||||
mcp_json_free(v);
|
||||
return 0;
|
||||
}
|
||||
if (strcmp(dt, "input_json_delta") == 0) {
|
||||
txt = mcp_arg_string(delta, "partial_json");
|
||||
if (txt != NULL && index >= 0 && index < AS_MAX_CALLS &&
|
||||
sp_buf_puts(&s->calls[index].input, txt) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
mcp_json_free(v);
|
||||
return 0;
|
||||
}
|
||||
txt = mcp_arg_string(delta, "text");
|
||||
if (txt == NULL)
|
||||
txt = mcp_arg_string(delta, "thinking");
|
||||
if (txt == NULL) {
|
||||
mcp_json_free(v);
|
||||
return 0;
|
||||
}
|
||||
if (kind == AS_THINK ||
|
||||
strcmp(dt, "thinking_delta") == 0) {
|
||||
if (sp_buf_puts(&s->think, txt) != 0 ||
|
||||
sp_buf_puts(out, txt) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
mcp_json_free(v);
|
||||
return SP_STREAM_THINK;
|
||||
}
|
||||
if (sp_buf_puts(&s->content, txt) != 0 ||
|
||||
sp_buf_puts(out, txt) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
mcp_json_free(v);
|
||||
return SP_STREAM_TEXT;
|
||||
} else if (strcmp(type, "message_stop") == 0) {
|
||||
s->done = 1;
|
||||
}
|
||||
mcp_json_free(v);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_as_sse_finish(struct sp_as_sse *s, struct sp_reply *out, struct sp_buf *err)
|
||||
{
|
||||
const char *id[AS_MAX_CALLS], *name[AS_MAX_CALLS];
|
||||
const char *input[AS_MAX_CALLS];
|
||||
size_t i, n = 0;
|
||||
|
||||
(void)err;
|
||||
if (s == NULL || out == NULL)
|
||||
return -1;
|
||||
out->status = 200;
|
||||
out->tokens_in = s->tokens_in;
|
||||
out->tokens_out = s->tokens_out;
|
||||
out->content = strdup(s->content.p != NULL ? s->content.p : "");
|
||||
if (out->content == NULL)
|
||||
return -1;
|
||||
for (i = 0; i < AS_MAX_CALLS; i++)
|
||||
if (s->calls[i].saw)
|
||||
n++;
|
||||
if (n == 0)
|
||||
return 0;
|
||||
out->calls = calloc(n, sizeof(*out->calls));
|
||||
if (out->calls == NULL)
|
||||
return -1;
|
||||
out->ncalls = 0;
|
||||
for (i = 0; i < AS_MAX_CALLS; i++) {
|
||||
size_t k = out->ncalls;
|
||||
|
||||
if (!s->calls[i].saw)
|
||||
continue;
|
||||
out->calls[k].id = strdup(s->calls[i].id != NULL ?
|
||||
s->calls[i].id : "toolu_unknown");
|
||||
out->calls[k].name = strdup(s->calls[i].name != NULL ?
|
||||
s->calls[i].name : "");
|
||||
out->calls[k].args = strdup(s->calls[i].input.p != NULL ?
|
||||
s->calls[i].input.p : "{}");
|
||||
if (out->calls[k].id == NULL || out->calls[k].name == NULL ||
|
||||
out->calls[k].args == NULL) {
|
||||
out->ncalls = k + 1;
|
||||
sp_reply_free(out);
|
||||
return -1;
|
||||
}
|
||||
id[k] = out->calls[k].id;
|
||||
name[k] = out->calls[k].name;
|
||||
input[k] = out->calls[k].args;
|
||||
out->ncalls++;
|
||||
}
|
||||
return calls_json(out, id, name, input, out->ncalls);
|
||||
}
|
||||
@@ -361,6 +361,21 @@ do_provider(struct cb *c, const char *name, unsigned line, struct ent *e,
|
||||
goto done;
|
||||
if (list[0] != '\0')
|
||||
sp_buf_printf(&l, " | tags=%s", list);
|
||||
} else if (!strcmp(k, "key")) {
|
||||
/* the key itself, in the (0600) file: kept in a private
|
||||
* variable that key_env then names */
|
||||
char var[96];
|
||||
size_t q;
|
||||
|
||||
s = one(c, &e[i]);
|
||||
if (s == NULL || !clean(c, &e[i], s))
|
||||
goto done;
|
||||
snprintf(var, sizeof(var), "SPLINTER_KEY_%s", name);
|
||||
for (q = 0; var[q] != '\0'; q++)
|
||||
var[q] = (char)((var[q] >= 'a' && var[q] <= 'z') ?
|
||||
var[q] - 32 : (var[q] == '-' ? '_' : var[q]));
|
||||
setenv(var, s, 1);
|
||||
sp_buf_printf(&l, " | key_env=%s", var);
|
||||
} else if (!strcmp(k, "env")) {
|
||||
for (j = 0; j < e[i].v.n; j++) {
|
||||
const char *kv = e[i].v.items[j], *eq = strchr(kv, '=');
|
||||
|
||||
+37
-3
@@ -266,8 +266,18 @@ parse_delegate(struct sp_delegate *d, const char *val, struct sp_buf *err,
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else if (!strncmp(s, "kind=", 5))
|
||||
else if (!strncmp(s, "kind=", 5)) {
|
||||
if (strcmp(s + 5, "cli") != 0 &&
|
||||
strcmp(s + 5, "openai") != 0 &&
|
||||
strcmp(s + 5, "anthropic") != 0) {
|
||||
sp_buf_printf(err, "config: %s:%u: kind is "
|
||||
"openai, anthropic or cli, not '%s'",
|
||||
path, lineno, s + 5);
|
||||
free(copy);
|
||||
return -1;
|
||||
}
|
||||
snprintf(d->kind, sizeof(d->kind), "%s", s + 5);
|
||||
}
|
||||
else if (!strncmp(s, "cmd=", 4))
|
||||
snprintf(d->cmd, sizeof(d->cmd), "%s", s + 4);
|
||||
else if (!strncmp(s, "tags=", 5))
|
||||
@@ -628,6 +638,16 @@ load_stream(struct sp_config *c, FILE *f, const char *path,
|
||||
set_str(c->model, sizeof(c->model), val);
|
||||
else if (!strcmp(key, "api_key_env"))
|
||||
set_str(c->key_env, sizeof(c->key_env), val);
|
||||
else if (!strcmp(key, "kind")) {
|
||||
if (strcmp(val, "openai") != 0 &&
|
||||
strcmp(val, "anthropic") != 0) {
|
||||
sp_buf_printf(err, "config: %s:%u: kind is "
|
||||
"openai or anthropic (cli is a provider "
|
||||
"field)", path, lineno);
|
||||
return -1;
|
||||
}
|
||||
set_str(c->kind, sizeof(c->kind), val);
|
||||
}
|
||||
else if (!strcmp(key, "transport"))
|
||||
set_str(c->transport, sizeof(c->transport), val);
|
||||
else if (!strcmp(key, "memory_url"))
|
||||
@@ -803,6 +823,8 @@ sp_config_write_example(const char *path, struct sp_buf *err)
|
||||
sp_buf_printf(err, "config: %s: %s", path, strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
/* the file may end up holding a key: 0600 from the first instant */
|
||||
(void)fchmod(fileno(f), 0600);
|
||||
fprintf(f,
|
||||
"# splinter configuration\n"
|
||||
"#\n"
|
||||
@@ -831,7 +853,7 @@ sp_config_write_example(const char *path, struct sp_buf *err)
|
||||
"\n"
|
||||
"provider local {\n"
|
||||
" about = \"my local model\"\n"
|
||||
" endpoint = http://127.0.0.1:8080/v1/chat/completions\n"
|
||||
" endpoint = http://127.0.0.1:8080/v1 # the API base; routes follow\n"
|
||||
" model = my-model # the name the endpoint serves\n"
|
||||
" tags = [local, code]\n"
|
||||
" #key_env = SPLINTER_API_KEY # name of the variable holding the key\n"
|
||||
@@ -846,6 +868,18 @@ sp_config_write_example(const char *path, struct sp_buf *err)
|
||||
"# env { CLAUDE_CODE_OAUTH_TOKEN = \"${CLAUDE_A_TOKEN}\" }\n"
|
||||
"#}\n"
|
||||
"\n"
|
||||
"# Claude over the API instead of the CLI: the Messages API has its own\n"
|
||||
"# shape, and an sk-ant-oat token (Claude Code) or an sk-ant-api key\n"
|
||||
"# both work. One provider per account, one pool over them.\n"
|
||||
"#provider claude-api {\n"
|
||||
"# kind = anthropic\n"
|
||||
"# endpoint = https://api.anthropic.com/v1\n"
|
||||
"# model = claude-sonnet-5-5\n"
|
||||
"# tags = [analyze, decide, review]\n"
|
||||
"# limit = 40/5h\n"
|
||||
"# key_env = CLAUDE_CODE_OAUTH_TOKEN\n"
|
||||
"#}\n"
|
||||
"\n"
|
||||
"# Providers that stand in for each other:\n"
|
||||
"#pool claude { members = [claude-a, claude-b] strategy = balance }\n");
|
||||
if (ferror(f)) {
|
||||
@@ -896,7 +930,7 @@ scan_family(struct sp_config *c, const char *base, int is_ollama, size_t base_id
|
||||
const char *model = getenv("OLLAMA_MODEL");
|
||||
|
||||
if (host == NULL || *host == '\0')
|
||||
host = "https://ollama.com/v1/chat/completions";
|
||||
host = "https://ollama.com/v1";
|
||||
snprintf(ep, sizeof(ep), "%s", host);
|
||||
|
||||
if (c->ndelegates < SP_CONFIG_MAX_DELEGATES) {
|
||||
|
||||
@@ -117,6 +117,7 @@ struct sp_config {
|
||||
char endpoint[512];
|
||||
char model[256];
|
||||
char key_env[64];
|
||||
char kind[16]; /* of the main provider: "" (openai) or anthropic */
|
||||
unsigned long req_limit, tok_limit; /* of the main provider */
|
||||
long req_window, tok_window;
|
||||
char transport[32];
|
||||
|
||||
+25
-7
@@ -9,7 +9,7 @@
|
||||
* guessing and not by asking a model to pick itself a helper.
|
||||
*
|
||||
* delegate = coder | C99 und POSIX, kennt den Baum | tags=code,c99 |
|
||||
* endpoint=http://kontron.local:8080/v1/chat/completions |
|
||||
* endpoint=http://kontron.local:8080/v1 |
|
||||
* model=Qwen3.6-35B
|
||||
*
|
||||
* The child is splinter itself in one-shot mode: same tools, same rules, own
|
||||
@@ -101,12 +101,7 @@ json_str(const char *args, const char *key, struct sp_buf *keep)
|
||||
static void
|
||||
models_url(const char *endpoint, char *out, size_t len)
|
||||
{
|
||||
const char *cut = strstr(endpoint, "/chat/completions");
|
||||
|
||||
if (cut != NULL)
|
||||
snprintf(out, len, "%.*s/models", (int)(cut - endpoint), endpoint);
|
||||
else
|
||||
snprintf(out, len, "%s/models", endpoint);
|
||||
sp_endpoint_url(endpoint, "models", out, len);
|
||||
}
|
||||
|
||||
static int
|
||||
@@ -648,6 +643,14 @@ exec_delegate(const struct del_ctx *c, const struct sp_delegate *d,
|
||||
argv[n++] = "--plugin";
|
||||
argv[n++] = plug;
|
||||
} else {
|
||||
/*
|
||||
* Anthropic is a built-in vendor shape, not a plugin: the child has
|
||||
* to be told, or it would speak OpenAI at the Messages API.
|
||||
*/
|
||||
if (strcmp(d->kind, "anthropic") == 0) {
|
||||
argv[n++] = "--kind";
|
||||
argv[n++] = (char *)"anthropic";
|
||||
}
|
||||
argv[n++] = "--endpoint";
|
||||
argv[n++] = (char *)d->endpoint;
|
||||
argv[n++] = "--model";
|
||||
@@ -668,6 +671,21 @@ exec_delegate(const struct del_ctx *c, const struct sp_delegate *d,
|
||||
(void)setenv(envname, d->key, 1);
|
||||
argv[n++] = "--api-key-env";
|
||||
argv[n++] = envname;
|
||||
} else if (!cli && d->nenv > 0) {
|
||||
/*
|
||||
* A provider whose token lives in its env block: the child inherits
|
||||
* the variable (applied just below), and has to be told its name or
|
||||
* it would read the default one and send no auth at all.
|
||||
*/
|
||||
const char *eq = strchr(d->env[0], '=');
|
||||
size_t len = eq != NULL ? (size_t)(eq - d->env[0]) : 0;
|
||||
|
||||
if (len > 0 && len < sizeof(envname)) {
|
||||
memcpy(envname, d->env[0], len);
|
||||
envname[len] = '\0';
|
||||
argv[n++] = "--api-key-env";
|
||||
argv[n++] = envname;
|
||||
}
|
||||
}
|
||||
argv[n] = NULL;
|
||||
|
||||
|
||||
+104
-43
@@ -49,8 +49,8 @@ usage(FILE *f)
|
||||
" file in ~/.splinter/agents, .agents/); Tab\n"
|
||||
" switches in the chat\n"
|
||||
" --agent-list list the agent profiles and exit\n"
|
||||
" --doctor check every provider: key, reachability, one\n"
|
||||
" tiny turn (--live: also the cli ones)\n"
|
||||
" --doctor check every provider: key, reachability via\n"
|
||||
" its model list (never spends tokens)\n"
|
||||
" --model-list list what -m accepts (asks each endpoint\n"
|
||||
" which models it serves; --no-probe skips)\n"
|
||||
" --api-key-env VAR read the API key from VAR (default\n"
|
||||
@@ -64,6 +64,8 @@ usage(FILE *f)
|
||||
" --init-config write a commented example config and exit\n"
|
||||
" --plugin PATH load a plugin (.so) before the first turn\n"
|
||||
" --transport NAME use a transport a plugin provides (\"cli\")\n"
|
||||
" --kind NAME vendor shape of --endpoint: openai (default)\n"
|
||||
" or anthropic\n"
|
||||
" --chat interactive curses UI instead of one turn\n"
|
||||
" --theme NAME CDE palette for the UI (default Delphinium)\n"
|
||||
" --list-themes print the palette names and exit\n"
|
||||
@@ -217,6 +219,7 @@ daemon_stream(void *ctx, int kind, const char *text)
|
||||
struct opts {
|
||||
const char *prompt, *endpoint, *script, *model, *key_env;
|
||||
const char *sessdir, *sessid, *theme, *transport, *config_path;
|
||||
const char *kind; /* "anthropic" when -m chose such a provider */
|
||||
const char *choose, *mcp_ip;
|
||||
const char *delegate;
|
||||
const char *plugins[32];
|
||||
@@ -315,6 +318,8 @@ parse_args(int argc, char **argv, struct opts *o, struct sp_agent_config *cfg)
|
||||
VALUE(o->config_path);
|
||||
else if (!strcmp(a, "--transport"))
|
||||
VALUE(o->transport);
|
||||
else if (!strcmp(a, "--kind"))
|
||||
VALUE(o->kind);
|
||||
else if (!strcmp(a, "--script"))
|
||||
VALUE(o->script);
|
||||
else if (!strcmp(a, "--plugin")) {
|
||||
@@ -484,6 +489,26 @@ load_config(struct opts *o, struct sp_config *conf, struct sp_agent_config *cfg,
|
||||
snprintf(cpath, sizeof(cpath), "%s", o->config_path);
|
||||
|
||||
if (o->init_config) {
|
||||
/*
|
||||
* Never over somebody's working config. This wrote over a live
|
||||
* splinter.conf once, with 200 lines of hand-written providers in it:
|
||||
* a starter file that lands in a temp name is still useful, and the
|
||||
* operator decides what replaces what.
|
||||
*/
|
||||
if (access(cpath, F_OK) == 0) {
|
||||
char alt[900];
|
||||
|
||||
snprintf(alt, sizeof(alt), "%s.example", cpath);
|
||||
if (sp_config_write_example(alt, err) != 0) {
|
||||
fprintf(stderr, "splinter: %s\n",
|
||||
err->len > 0 ? err->p :
|
||||
"cannot write the example config");
|
||||
return 3;
|
||||
}
|
||||
printf("splinter: %s exists; wrote %s instead\n",
|
||||
cpath, alt);
|
||||
return 0;
|
||||
}
|
||||
sp_buf_clear(err);
|
||||
if (sp_config_write_example(cpath, err) != 0) {
|
||||
fprintf(stderr, "splinter: %s\n",
|
||||
@@ -815,6 +840,8 @@ run_doctor(const struct sp_config *conf, const struct opts *o)
|
||||
size_t i;
|
||||
int bad = 0;
|
||||
|
||||
(void)o;
|
||||
|
||||
for (i = 0; i < conf->ndelegates; i++) {
|
||||
const struct sp_delegate *d = &conf->delegate[i];
|
||||
struct sp_usage u;
|
||||
@@ -831,57 +858,46 @@ run_doctor(const struct sp_config *conf, const struct opts *o)
|
||||
} else if (d->nenv == 0 && d->key_env[0] != '\0' &&
|
||||
getenv(d->key_env) == NULL) {
|
||||
snprintf(what, sizeof(what), "%s not set", d->key_env);
|
||||
} else if (!o->live) {
|
||||
snprintf(what, sizeof(what), "program found (--live "
|
||||
"asks it a question)");
|
||||
ok = 1;
|
||||
} else {
|
||||
const char *home = getenv("HOME");
|
||||
char cmd[700];
|
||||
FILE *p;
|
||||
char line[200];
|
||||
size_t k;
|
||||
|
||||
(void)home;
|
||||
(void)k;
|
||||
sp_config_apply_env((const char (*)[SP_CONFIG_ENV_LEN])d->env,
|
||||
d->nenv);
|
||||
snprintf(cmd, sizeof(cmd),
|
||||
"%s 'Answer with the single word: pong' 2>&1 </dev/null",
|
||||
d->cmd);
|
||||
p = popen(cmd, "r");
|
||||
if (p != NULL && fgets(line, sizeof(line), p) != NULL) {
|
||||
line[strcspn(line, "\n")] = '\0';
|
||||
snprintf(what, sizeof(what), "answered: %.60s", line);
|
||||
ok = strncasecmp(line, "pong", 4) == 0;
|
||||
} else
|
||||
snprintf(what, sizeof(what), "no answer");
|
||||
if (p != NULL)
|
||||
pclose(p);
|
||||
snprintf(what, sizeof(what), "program found");
|
||||
ok = 1;
|
||||
}
|
||||
} else if (!sp_provider_has_key(d)) {
|
||||
snprintf(what, sizeof(what), "%s is not set", d->key_env);
|
||||
} else {
|
||||
struct sp_provider pv;
|
||||
struct sp_buf ans, perr;
|
||||
time_t t0 = time(NULL);
|
||||
struct sp_buf ids, perr;
|
||||
|
||||
memset(&pv, 0, sizeof(pv));
|
||||
snprintf(pv.id, sizeof(pv.id), "%s", d->id);
|
||||
snprintf(pv.kind, sizeof(pv.kind), "%s", d->kind);
|
||||
snprintf(pv.endpoint, sizeof(pv.endpoint), "%s", d->endpoint);
|
||||
snprintf(pv.model, sizeof(pv.model), "%s", d->model);
|
||||
snprintf(pv.key_env, sizeof(pv.key_env), "%s", d->key_env);
|
||||
if (sp_buf_init(&ans) == 0 && sp_buf_init(&perr) == 0) {
|
||||
ok = sp_provider_test(&pv, &ans, &perr) == 0;
|
||||
if (ok)
|
||||
snprintf(what, sizeof(what), "%lds, %.40s",
|
||||
(long)(time(NULL) - t0), d->model);
|
||||
else
|
||||
/* the model list only: never a completion, never a token spent */
|
||||
if (sp_buf_init(&ids) == 0 && sp_buf_init(&perr) == 0) {
|
||||
char rem[160];
|
||||
int have_use = sp_provider_remote_usage(&pv, rem,
|
||||
sizeof(rem)) == 0;
|
||||
|
||||
if (have_use)
|
||||
snprintf(use, sizeof(use), "%.120s", rem);
|
||||
if (sp_provider_served(&pv, &ids, &perr) == 0) {
|
||||
ok = 1;
|
||||
snprintf(what, sizeof(what), "%.40s%s", d->model,
|
||||
ids.p != NULL && d->model[0] != '\0' &&
|
||||
strstr(ids.p, d->model) == NULL ?
|
||||
" (not in its model list)" : "");
|
||||
} else if (have_use) {
|
||||
/* no model route, but its usage API answered */
|
||||
ok = 1;
|
||||
snprintf(what, sizeof(what), "%.40s (no model list)",
|
||||
d->model);
|
||||
} else
|
||||
snprintf(what, sizeof(what), "%.150s",
|
||||
perr.len > 0 && strstr(perr.p, "transfer failed") == NULL ?
|
||||
perr.p : "no answer within 30 s (down, or busy)");
|
||||
perr.len > 0 ? perr.p : "no answer");
|
||||
}
|
||||
sp_buf_free(&ans);
|
||||
sp_buf_free(&ids);
|
||||
sp_buf_free(&perr);
|
||||
}
|
||||
printf("%-10.10s %-5s %s [%s]\n", d->id, ok ? "ok" : "FAIL", what, use);
|
||||
@@ -964,6 +980,28 @@ apply_selection(struct opts *o, struct sp_config *conf)
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (strcmp(d->kind, "anthropic") == 0) {
|
||||
/*
|
||||
* The token lives in the provider's env block (a Claude Code OAuth
|
||||
* token, one per account). Applying it here means the run reads the
|
||||
* right account's token from the environment it just set, and an
|
||||
* unset key_env can name that block's first variable.
|
||||
*/
|
||||
sp_config_apply_env((const char (*)[SP_CONFIG_ENV_LEN])d->env,
|
||||
d->nenv);
|
||||
o->kind = d->kind;
|
||||
if (d->key_env[0] == '\0' && d->nenv > 0) {
|
||||
static char kenv[SP_CONFIG_ENV_LEN];
|
||||
const char *eq = strchr(d->env[0], '=');
|
||||
size_t n = eq != NULL ? (size_t)(eq - d->env[0]) : 0;
|
||||
|
||||
if (n > 0 && n < sizeof(kenv)) {
|
||||
memcpy(kenv, d->env[0], n);
|
||||
kenv[n] = '\0';
|
||||
o->key_env = kenv;
|
||||
}
|
||||
}
|
||||
}
|
||||
o->endpoint = d->endpoint;
|
||||
o->model = ch.model[0] != '\0' ? ch.model : d->model;
|
||||
if (d->key_env[0] != '\0')
|
||||
@@ -1014,6 +1052,7 @@ run_model_list(const struct sp_config *conf, const struct opts *o)
|
||||
|
||||
memset(&pv, 0, sizeof(pv));
|
||||
snprintf(pv.id, sizeof(pv.id), "%s", d->id);
|
||||
snprintf(pv.kind, sizeof(pv.kind), "%s", d->kind);
|
||||
snprintf(pv.endpoint, sizeof(pv.endpoint), "%s", d->endpoint);
|
||||
snprintf(pv.model, sizeof(pv.model), "%s", d->model);
|
||||
snprintf(pv.key_env, sizeof(pv.key_env), "%s", d->key_env);
|
||||
@@ -1044,7 +1083,28 @@ pick_transport(const struct opts *o, struct sp_agent *ag, struct sp_host *host,
|
||||
const struct sp_registry *reg, struct sp_mock *mock, int *have_mock,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
if (o->transport != NULL) {
|
||||
/* a built-in vendor shape, not a plugin transport */
|
||||
const char *transport = o->transport;
|
||||
|
||||
if (o->kind != NULL && strcmp(o->kind, "anthropic") == 0) {
|
||||
const char *hto = getenv("SPLINTER_HTTP_TIMEOUT");
|
||||
long http_timeout;
|
||||
|
||||
if (o->endpoint == NULL || o->model == NULL) {
|
||||
fprintf(stderr, "splinter: an anthropic provider needs "
|
||||
"an endpoint and a model\n");
|
||||
return 2;
|
||||
}
|
||||
http_timeout = hto != NULL && *hto != '\0' ?
|
||||
strtol(hto, NULL, 10) : 0;
|
||||
if (http_timeout <= 0)
|
||||
http_timeout = 900;
|
||||
ag->tr = sp_anthropic_transport(o->endpoint, o->model,
|
||||
getenv(o->key_env), reg, http_timeout);
|
||||
sp_provider_identify(&ag->tr, o->endpoint, getenv(o->key_env));
|
||||
return 0;
|
||||
}
|
||||
if (transport != NULL) {
|
||||
struct sp_transport *tr;
|
||||
|
||||
if (host == NULL) {
|
||||
@@ -1052,10 +1112,10 @@ pick_transport(const struct opts *o, struct sp_agent *ag, struct sp_host *host,
|
||||
"provides it (--plugin)\n");
|
||||
return 2;
|
||||
}
|
||||
tr = sp_host_transport(host, o->transport);
|
||||
tr = sp_host_transport(host, transport);
|
||||
if (tr == NULL) {
|
||||
fprintf(stderr, "splinter: no plugin provides the '%s' "
|
||||
"transport\n", o->transport);
|
||||
"transport\n", transport);
|
||||
return 2;
|
||||
}
|
||||
ag->tr = *tr;
|
||||
@@ -1420,7 +1480,8 @@ main(int argc, char **argv)
|
||||
if (sp_provider_choose(&conf, al.v[idx].model,
|
||||
&ch) == 0 && ch.d->endpoint[0] != '\0' &&
|
||||
strcmp(ch.d->kind, "cli") != 0) {
|
||||
(void)sp_provider_apply(&ag, ch.d->endpoint,
|
||||
(void)sp_provider_apply(&ag, ch.d->kind,
|
||||
ch.d->endpoint,
|
||||
ch.model[0] != '\0' ? ch.model :
|
||||
ch.d->model, ch.d->key_env, &err);
|
||||
sp_usage_set_active(ch.d->id);
|
||||
|
||||
+5
-3
@@ -135,13 +135,15 @@ static void
|
||||
reply_tools(int fd, int id, const struct sp_registry *reg)
|
||||
{
|
||||
struct sp_buf b;
|
||||
size_t i;
|
||||
size_t i, ntv;
|
||||
const struct sp_tool *tv;
|
||||
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return;
|
||||
sp_buf_puts(&b, "{\"tools\":[");
|
||||
for (i = 0; i < reg->len; i++) {
|
||||
const struct sp_tool *t = ®->tools[i];
|
||||
tv = sp_registry_tools(reg, &ntv);
|
||||
for (i = 0; i < ntv; i++) {
|
||||
const struct sp_tool *t = &tv[i];
|
||||
|
||||
if (i > 0)
|
||||
sp_buf_puts(&b, ",");
|
||||
|
||||
+5
-3
@@ -36,7 +36,8 @@ int
|
||||
sp_openai_request(const struct sp_conv *conv, const char *model,
|
||||
const struct sp_registry *reg, int streaming, struct sp_buf *out)
|
||||
{
|
||||
size_t i;
|
||||
size_t i, ntv;
|
||||
const struct sp_tool *tv;
|
||||
|
||||
sp_buf_clear(out);
|
||||
if (sp_buf_puts(out, "{\"model\":") != 0 || sp_buf_puts(out, "\"") != 0 ||
|
||||
@@ -79,8 +80,9 @@ sp_openai_request(const struct sp_conv *conv, const char *model,
|
||||
/* tools: name, description and an open parameter object */
|
||||
if (sp_buf_puts(out, "],\"tools\":[") != 0)
|
||||
return -1;
|
||||
for (i = 0; i < reg->len; i++) {
|
||||
const struct sp_tool *t = ®->tools[i];
|
||||
tv = sp_registry_tools(reg, &ntv);
|
||||
for (i = 0; i < ntv; i++) {
|
||||
const struct sp_tool *t = &tv[i];
|
||||
|
||||
if (i > 0 && sp_buf_puts(out, ",") != 0)
|
||||
return -1;
|
||||
|
||||
@@ -54,6 +54,8 @@ struct sp_host {
|
||||
struct widget widgets[MAX_WIDGETS];
|
||||
size_t nwidgets;
|
||||
char note[MAX_NOTE];
|
||||
char msgs[16][200]; /* status lines for the chat */
|
||||
size_t msg_head, msg_n;
|
||||
const struct sp_compactor *compact[MAX_COMPACTORS];
|
||||
size_t ncompact;
|
||||
const struct sp_gate *gate[MAX_COMPACTORS];
|
||||
@@ -529,6 +531,42 @@ sp_host_note(struct sp_host *h, const char *text)
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* A status line for the chat, from any thread; the UI takes them one by one. */
|
||||
int
|
||||
sp_host_status_msg(struct sp_host *h, const char *text)
|
||||
{
|
||||
if (h == NULL || text == NULL)
|
||||
return -1;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
if (h->msg_n == 16) { /* the oldest goes */
|
||||
h->msg_head = (h->msg_head + 1) % 16;
|
||||
h->msg_n--;
|
||||
}
|
||||
snprintf(h->msgs[(h->msg_head + h->msg_n) % 16], sizeof(h->msgs[0]),
|
||||
"%s", text);
|
||||
h->msg_n++;
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_status_take(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
int rc = 0;
|
||||
|
||||
if (h == NULL || buf == NULL || len == 0)
|
||||
return 0;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
if (h->msg_n > 0) {
|
||||
snprintf(buf, len, "%s", h->msgs[h->msg_head]);
|
||||
h->msg_head = (h->msg_head + 1) % 16;
|
||||
h->msg_n--;
|
||||
rc = 1;
|
||||
}
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
return rc;
|
||||
}
|
||||
|
||||
size_t
|
||||
sp_host_widget_snapshot(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
|
||||
+215
-26
@@ -73,6 +73,7 @@ sp_provider_at(const struct sp_config *cfg, size_t idx, struct sp_provider *out)
|
||||
if (cfg->endpoint[0] == '\0' && cfg->model[0] == '\0')
|
||||
goto delegates;
|
||||
snprintf(out->id, sizeof(out->id), "main");
|
||||
snprintf(out->kind, sizeof(out->kind), "%s", cfg->kind);
|
||||
snprintf(out->endpoint, sizeof(out->endpoint), "%s",
|
||||
cfg->endpoint);
|
||||
snprintf(out->model, sizeof(out->model), "%s", cfg->model);
|
||||
@@ -90,6 +91,7 @@ delegates:
|
||||
if (idx-- > 0)
|
||||
continue;
|
||||
snprintf(out->id, sizeof(out->id), "%s", d->id);
|
||||
snprintf(out->kind, sizeof(out->kind), "%s", d->kind);
|
||||
snprintf(out->endpoint, sizeof(out->endpoint), "%s", d->endpoint);
|
||||
snprintf(out->model, sizeof(out->model), "%s", d->model);
|
||||
snprintf(out->key_env, sizeof(out->key_env), "%s", d->key_env);
|
||||
@@ -135,6 +137,28 @@ sp_provider_find(const struct sp_config *cfg, const char *id, size_t *idx)
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_provider_select(const struct sp_config *cfg, const char *sel,
|
||||
struct sp_provider *out, char *model, size_t modelcap)
|
||||
{
|
||||
struct sp_choice ch;
|
||||
size_t i, n;
|
||||
|
||||
if (cfg == NULL || sel == NULL || out == NULL ||
|
||||
sp_provider_choose(cfg, sel, &ch) != 0 || ch.d == NULL)
|
||||
return -1;
|
||||
n = sp_provider_count(cfg);
|
||||
for (i = 0; i < n; i++)
|
||||
if (sp_provider_at(cfg, i, out) == 0 &&
|
||||
strcmp(out->id, ch.d->id) == 0) {
|
||||
if (model != NULL && modelcap > 0)
|
||||
snprintf(model, modelcap, "%s",
|
||||
ch.model[0] != '\0' ? ch.model : ch.d->model);
|
||||
return 0;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void
|
||||
sp_provider_identify(struct sp_transport *tr, const char *endpoint,
|
||||
const char *secret)
|
||||
@@ -157,6 +181,8 @@ sp_provider_identify(struct sp_transport *tr, const char *endpoint,
|
||||
else if (endpoint != NULL && (strstr(endpoint, "opencode") != NULL ||
|
||||
strstr(endpoint, "open-code") != NULL))
|
||||
prov = "opencode";
|
||||
else if (endpoint != NULL && strstr(endpoint, "anthropic.com") != NULL)
|
||||
prov = "anthropic";
|
||||
tr->provider = prov;
|
||||
tr->key_id = NULL;
|
||||
if (secret != NULL && *secret != '\0') {
|
||||
@@ -169,8 +195,8 @@ sp_provider_identify(struct sp_transport *tr, const char *endpoint,
|
||||
}
|
||||
|
||||
int
|
||||
sp_provider_apply(struct sp_agent *ag, const char *endpoint, const char *model,
|
||||
const char *key_env, struct sp_buf *err)
|
||||
sp_provider_apply(struct sp_agent *ag, const char *kind, const char *endpoint,
|
||||
const char *model, const char *key_env, struct sp_buf *err)
|
||||
{
|
||||
const char *key = NULL;
|
||||
|
||||
@@ -184,8 +210,12 @@ sp_provider_apply(struct sp_agent *ag, const char *endpoint, const char *model,
|
||||
}
|
||||
if (key_env != NULL && *key_env != '\0')
|
||||
key = getenv(key_env);
|
||||
ag->tr = sp_openai_transport(endpoint, model, key, ag->reg,
|
||||
PROVIDER_TIMEOUT_S);
|
||||
if (kind != NULL && strcmp(kind, "anthropic") == 0)
|
||||
ag->tr = sp_anthropic_transport(endpoint, model, key, ag->reg,
|
||||
PROVIDER_TIMEOUT_S);
|
||||
else
|
||||
ag->tr = sp_openai_transport(endpoint, model, key, ag->reg,
|
||||
PROVIDER_TIMEOUT_S);
|
||||
sp_provider_identify(&ag->tr, endpoint, key);
|
||||
return 0;
|
||||
}
|
||||
@@ -201,7 +231,8 @@ sp_provider_use(struct sp_agent *ag, const struct sp_config *cfg, size_t idx,
|
||||
sp_buf_puts(err, "no such provider");
|
||||
return -1;
|
||||
}
|
||||
if (sp_provider_apply(ag, p.endpoint, p.model, p.key_env, err) != 0)
|
||||
if (sp_provider_apply(ag, p.kind, p.endpoint, p.model, p.key_env,
|
||||
err) != 0)
|
||||
return -1;
|
||||
sp_usage_set_active(p.main ? "main" : p.id);
|
||||
return 0;
|
||||
@@ -267,41 +298,65 @@ http_get(const char *url, const char *const *headers, struct sp_buf *out,
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* /v1/chat/completions -> /v1/models, and anything else gains /models */
|
||||
/* the base (or an old full route) -> base/models, whatever the kind */
|
||||
static void
|
||||
models_url(const char *endpoint, char *buf, size_t len)
|
||||
models_url_kind(const char *endpoint, const char *kind, char *buf, size_t len)
|
||||
{
|
||||
char *cut;
|
||||
(void)kind;
|
||||
sp_endpoint_url(endpoint, "models", buf, len);
|
||||
}
|
||||
|
||||
snprintf(buf, len, "%s", endpoint);
|
||||
cut = strstr(buf, "/chat/completions");
|
||||
if (cut != NULL)
|
||||
snprintf(cut, len - (size_t)(cut - buf), "/models");
|
||||
else if (buf[0] != '\0' && buf[strlen(buf) - 1] == '/')
|
||||
snprintf(buf + strlen(buf), len - strlen(buf), "models");
|
||||
/* the headers one request to this provider carries; 0..3 lines in 'hdrs' */
|
||||
static size_t
|
||||
provider_headers(const struct sp_provider *p, char *hdr, size_t cap,
|
||||
char *hdr2, size_t cap2, const char *hdrs[4])
|
||||
{
|
||||
const char *key;
|
||||
size_t n = 0;
|
||||
|
||||
if (p->key_env[0] != '\0')
|
||||
key = getenv(p->key_env);
|
||||
else
|
||||
snprintf(buf + strlen(buf), len - strlen(buf), "/models");
|
||||
key = NULL;
|
||||
if (p->kind[0] != '\0' && strcmp(p->kind, "anthropic") == 0) {
|
||||
snprintf(hdr2, cap2, "anthropic-version: 2023-06-01");
|
||||
hdrs[n++] = hdr2;
|
||||
if (key != NULL && strncmp(key, "sk-ant-oat", 10) == 0) {
|
||||
snprintf(hdr, cap, "Authorization: Bearer %s", key);
|
||||
hdrs[n++] = hdr;
|
||||
hdrs[n++] = "anthropic-beta: oauth-2025-04-20,"
|
||||
"claude-code-20250219";
|
||||
return n;
|
||||
}
|
||||
if (key != NULL && *key != '\0') {
|
||||
snprintf(hdr, cap, "x-api-key: %s", key);
|
||||
hdrs[n++] = hdr;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
if (key != NULL) {
|
||||
snprintf(hdr, cap, "Authorization: Bearer %s", key);
|
||||
hdrs[n++] = hdr;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
int
|
||||
sp_provider_served(const struct sp_provider *p, struct sp_buf *ids,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
char url[700], hdr[700];
|
||||
const char *hdrs[2] = { NULL, NULL };
|
||||
char url[700], hdr[700], hdr2[200];
|
||||
const char *hdrs[4] = { NULL, NULL, NULL, NULL };
|
||||
struct sp_buf body;
|
||||
mcp_json *v;
|
||||
const mcp_json *data, *item;
|
||||
size_t i;
|
||||
size_t i, nh;
|
||||
|
||||
if (p == NULL || ids == NULL || p->endpoint[0] == '\0')
|
||||
return -1;
|
||||
models_url(p->endpoint, url, sizeof(url));
|
||||
if (p->key_env[0] != '\0' && getenv(p->key_env) != NULL) {
|
||||
snprintf(hdr, sizeof(hdr), "Authorization: Bearer %s",
|
||||
getenv(p->key_env));
|
||||
hdrs[0] = hdr;
|
||||
}
|
||||
models_url_kind(p->endpoint, p->kind, url, sizeof(url));
|
||||
nh = provider_headers(p, hdr, sizeof(hdr), hdr2, sizeof(hdr2), hdrs);
|
||||
hdrs[nh] = NULL;
|
||||
if (sp_buf_init(&body) != 0)
|
||||
return -1;
|
||||
if (http_get(url, hdrs, &body, err) != 0) {
|
||||
@@ -341,6 +396,132 @@ oom:
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* "name N%" for one window object, if it carries a percentage we know */
|
||||
static int
|
||||
window_pct(const mcp_json *v, const char *name, char *out, size_t cap)
|
||||
{
|
||||
static const char *const keys[] = { "usagePercent", "usedPercent",
|
||||
"used_percent", "percent", "percentage", "usage", NULL };
|
||||
const mcp_json *w = mcp_arg(v, name);
|
||||
size_t k;
|
||||
|
||||
if (w == NULL)
|
||||
return 0;
|
||||
for (k = 0; keys[k] != NULL; k++) {
|
||||
double x = mcp_arg_num(w, keys[k], -1.0);
|
||||
|
||||
if (x < 0)
|
||||
continue;
|
||||
if (x <= 1.0 && strcmp(keys[k], "usage") == 0)
|
||||
x *= 100.0;
|
||||
snprintf(out, cap, "%s %.0f%%", name, x);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_provider_remote_usage(const struct sp_provider *p, char *out, size_t cap)
|
||||
{
|
||||
char hdr[700], hdr2[200], line[96], base[600], url[700];
|
||||
const char *hdrs[4] = { NULL, NULL, NULL, NULL };
|
||||
const char *urls[2] = { NULL, NULL };
|
||||
struct sp_buf body, err;
|
||||
mcp_json *v = NULL;
|
||||
size_t u, nh, n = 0;
|
||||
int ollama, ocgo;
|
||||
|
||||
if (out == NULL || cap == 0)
|
||||
return -1;
|
||||
out[0] = '\0';
|
||||
if (p == NULL)
|
||||
return -1;
|
||||
ollama = strstr(p->endpoint, "ollama.com") != NULL;
|
||||
ocgo = strstr(p->endpoint, "opencode.ai/zen/go") != NULL;
|
||||
if (!ollama && !ocgo)
|
||||
return -1;
|
||||
sp_endpoint_url(p->endpoint, NULL, base, sizeof(base));
|
||||
if (ollama) {
|
||||
/* https://ollama.com/v1 -> https://ollama.com/api/balance */
|
||||
size_t bn = strlen(base);
|
||||
|
||||
if (bn >= 3 && strcmp(base + bn - 3, "/v1") == 0)
|
||||
base[bn - 3] = '\0';
|
||||
snprintf(url, sizeof(url), "%s/api/balance", base);
|
||||
} else {
|
||||
/* https://opencode.ai/zen/go/v1 -> .../v1/usage */
|
||||
snprintf(url, sizeof(url), "%s/usage", base);
|
||||
}
|
||||
urls[0] = url;
|
||||
nh = provider_headers(p, hdr, sizeof(hdr), hdr2, sizeof(hdr2), hdrs);
|
||||
hdrs[nh] = NULL;
|
||||
if (sp_buf_init(&body) != 0)
|
||||
return -1;
|
||||
if (sp_buf_init(&err) != 0) {
|
||||
sp_buf_free(&body);
|
||||
return -1;
|
||||
}
|
||||
for (u = 0; urls[u] != NULL && v == NULL; u++) {
|
||||
sp_buf_clear(&body);
|
||||
if (http_get(urls[u], hdrs, &body, &err) != 0 || body.len == 0)
|
||||
continue;
|
||||
v = mcp_parse(body.p);
|
||||
if (v != NULL && mcp_arg(v, "error") != NULL) {
|
||||
mcp_json_free(v);
|
||||
v = NULL;
|
||||
}
|
||||
}
|
||||
sp_buf_free(&body);
|
||||
sp_buf_free(&err);
|
||||
if (v == NULL) {
|
||||
snprintf(out, cap, "no usage answer");
|
||||
return -1;
|
||||
}
|
||||
if (ollama) {
|
||||
const mcp_json *inc = mcp_arg(v, "included");
|
||||
const mcp_json *pur = mcp_arg(v, "purchased");
|
||||
const mcp_json *ses = mcp_arg(inc, "session");
|
||||
const mcp_json *wk = mcp_arg(inc, "weekly");
|
||||
double bal = mcp_arg_num(inc, "balance_usd", -1.0);
|
||||
double all = mcp_arg_num(inc, "allowance_usd", -1.0);
|
||||
double buy = mcp_arg_num(pur, "balance_usd", -1.0);
|
||||
|
||||
if (ses != NULL)
|
||||
n += (size_t)snprintf(out + n, cap - n, "session %.0f%% left",
|
||||
mcp_arg_num(ses, "remaining_percent", 0));
|
||||
if (wk != NULL)
|
||||
n += (size_t)snprintf(out + n, cap - n, "%sweekly %.0f%% left",
|
||||
n ? ", " : "", mcp_arg_num(wk, "remaining_percent", 0));
|
||||
if (bal >= 0)
|
||||
n += (size_t)snprintf(out + n, cap - n, "%s$%.2f%s left",
|
||||
n ? ", " : "", bal, all >= 0 ? "" : "");
|
||||
if (bal >= 0 && all >= 0)
|
||||
n += (size_t)snprintf(out + n, cap - n, " of $%.0f", all);
|
||||
if (buy > 0)
|
||||
n += (size_t)snprintf(out + n, cap - n, "%s$%.2f bought",
|
||||
n ? ", " : "", buy);
|
||||
} else {
|
||||
static const char *const names[] = { "rolling", "weekly",
|
||||
"monthly", NULL };
|
||||
const mcp_json *wrap = mcp_arg(v, "usage");
|
||||
size_t k;
|
||||
|
||||
/* {"usage":{"rolling":{"percent":0,"resetsAt":..},"weekly":..}} */
|
||||
for (k = 0; names[k] != NULL; k++)
|
||||
if (window_pct(wrap != NULL ? wrap : v, names[k], line,
|
||||
sizeof(line)) &&
|
||||
n < cap)
|
||||
n += (size_t)snprintf(out + n, cap - n, "%s%s",
|
||||
n ? ", " : "", line);
|
||||
}
|
||||
mcp_json_free(v);
|
||||
if (n == 0) {
|
||||
snprintf(out, cap, "usage answered, format not recognised");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_provider_test(const struct sp_provider *p, struct sp_buf *answer,
|
||||
struct sp_buf *err)
|
||||
@@ -364,7 +545,11 @@ sp_provider_test(const struct sp_provider *p, struct sp_buf *answer,
|
||||
}
|
||||
if (p->key_env[0] != '\0')
|
||||
key = getenv(p->key_env);
|
||||
tr = sp_openai_transport(p->endpoint, p->model, key, &empty, 30);
|
||||
if (p->kind[0] != '\0' && strcmp(p->kind, "anthropic") == 0)
|
||||
tr = sp_anthropic_transport(p->endpoint, p->model, key, &empty,
|
||||
30);
|
||||
else
|
||||
tr = sp_openai_transport(p->endpoint, p->model, key, &empty, 30);
|
||||
rc = tr.send(tr.ctx, &conv, &reply, err);
|
||||
if (rc == 0) {
|
||||
size_t n = reply.content != NULL ? strlen(reply.content) : 0;
|
||||
@@ -419,6 +604,9 @@ sp_provider_save_choice(const struct sp_config *cfg,
|
||||
(void)fchmod(fileno(f), 0600);
|
||||
fprintf(f, "# written by /model -- delete this file to go back to the "
|
||||
"configuration\n");
|
||||
/* without the kind, the next start would speak OpenAI at the Messages API */
|
||||
if (p->kind[0] != '\0' && strcmp(p->kind, "openai") != 0)
|
||||
fprintf(f, "kind = %s\n", p->kind);
|
||||
fprintf(f, "endpoint = %s\n", p->endpoint);
|
||||
fprintf(f, "model = %s\n", p->model);
|
||||
/* the key variable too: a keyless provider must not inherit one */
|
||||
@@ -914,7 +1102,8 @@ sp_provider_failover(struct sp_agent *ag, const struct sp_config *cfg)
|
||||
return 0;
|
||||
if (sp_buf_init(&err) != 0)
|
||||
return 0;
|
||||
rc = sp_provider_apply(ag, d->endpoint, d->model, d->key_env, &err);
|
||||
rc = sp_provider_apply(ag, d->kind, d->endpoint, d->model,
|
||||
d->key_env, &err);
|
||||
sp_buf_free(&err);
|
||||
if (rc != 0)
|
||||
return 0;
|
||||
|
||||
+24
-3
@@ -18,6 +18,7 @@ struct sp_buf;
|
||||
*/
|
||||
struct sp_provider {
|
||||
char id[64];
|
||||
char kind[16]; /* "openai" (default), "anthropic" or "cli" */
|
||||
char endpoint[512];
|
||||
char model[256];
|
||||
char key_env[64];
|
||||
@@ -30,6 +31,15 @@ size_t sp_provider_count(const struct sp_config *);
|
||||
int sp_provider_at(const struct sp_config *, size_t, struct sp_provider *);
|
||||
int sp_provider_find(const struct sp_config *, const char *id, size_t *idx);
|
||||
|
||||
/*
|
||||
* A selector (-m, /model) as one provider to switch to: a pool, a provider,
|
||||
* "provider/model" or a model name one provider has. Fills 'out' with that
|
||||
* provider and 'model' with the model to ask for. 0, or -1 when nothing
|
||||
* matches.
|
||||
*/
|
||||
int sp_provider_select(const struct sp_config *, const char *sel,
|
||||
struct sp_provider *out, char *model, size_t modelcap);
|
||||
|
||||
/*
|
||||
* Provider identity for the per-key quota/usage plugins: "ollama",
|
||||
* "opencode" or "openai-compat", plus the key fingerprint the bench and the
|
||||
@@ -43,9 +53,11 @@ int sp_provider_use(struct sp_agent *, const struct sp_config *, size_t,
|
||||
struct sp_buf *err);
|
||||
|
||||
/* The same for an endpoint/model the config may not name (one model of a
|
||||
* provider: /model <name>). */
|
||||
int sp_provider_apply(struct sp_agent *, const char *endpoint,
|
||||
const char *model, const char *key_env, struct sp_buf *err);
|
||||
* provider: /model <name>). 'kind' picks the vendor shape: NULL or "" is an
|
||||
* OpenAI-compatible endpoint, "anthropic" the Messages API. */
|
||||
int sp_provider_apply(struct sp_agent *, const char *kind,
|
||||
const char *endpoint, const char *model, const char *key_env,
|
||||
struct sp_buf *err);
|
||||
|
||||
/* The drop-in directory next to the config file (…/splinter.conf.d). */
|
||||
int sp_provider_dir(char *, size_t);
|
||||
@@ -75,6 +87,15 @@ int sp_provider_key_ok(const char *key_env);
|
||||
int sp_provider_served(const struct sp_provider *, struct sp_buf *ids,
|
||||
struct sp_buf *err);
|
||||
|
||||
/*
|
||||
* What the provider itself says about the allowance, from its usage or
|
||||
* balance route (ollama.com /api/balance, opencode go /v1/usage). Reads only;
|
||||
* never a completion. 0 and a short text in 'out', -1 when it has no such
|
||||
* route or did not answer.
|
||||
*/
|
||||
int sp_provider_remote_usage(const struct sp_provider *, char *out,
|
||||
size_t cap);
|
||||
|
||||
/* One tiny turn against the provider: does the endpoint, the model and the key
|
||||
* work? 'answer' gets the first bytes of what came back. */
|
||||
int sp_provider_test(const struct sp_provider *, struct sp_buf *answer,
|
||||
|
||||
+10
-6
@@ -1180,10 +1180,12 @@ tg_model_use(const char *token, long chat_id, struct sp_agent *ag,
|
||||
{
|
||||
struct sp_buf msg, perr;
|
||||
struct sp_provider p;
|
||||
size_t idx;
|
||||
size_t idx = 0;
|
||||
|
||||
memset(&p, 0, sizeof(p));
|
||||
if (conf == NULL || ag == NULL ||
|
||||
!sp_provider_find(conf, id, &idx)) {
|
||||
sp_provider_select(conf, id, &p, NULL, 0) != 0 ||
|
||||
!sp_provider_find(conf, p.id, &idx)) {
|
||||
if (sp_buf_init(&msg) == 0) {
|
||||
sp_buf_printf(&msg, sp_t("model.unknown"), id);
|
||||
(void)send_message(token, chat_id, msg.p, err);
|
||||
@@ -1254,7 +1256,8 @@ tg_model_named(const char *token, long chat_id, struct sp_agent *ag,
|
||||
}
|
||||
if (sp_buf_init(&perr) != 0)
|
||||
return;
|
||||
if (sp_provider_apply(ag, p.endpoint, name, p.key_env, &perr) != 0) {
|
||||
if (sp_provider_apply(ag, p.kind, p.endpoint, name, p.key_env,
|
||||
&perr) != 0) {
|
||||
if (sp_buf_init(&msg) == 0) {
|
||||
sp_buf_printf(&msg, sp_t("model.failed"),
|
||||
perr.p != NULL && perr.len > 0 ? perr.p :
|
||||
@@ -1419,7 +1422,8 @@ tg_model_pick_use(const char *token, long chat_id, struct sp_agent *ag,
|
||||
snprintf(p.model, sizeof(p.model), "%s", tg_picks[idx].model);
|
||||
snprintf(p.key_env, sizeof(p.key_env), "%s", tg_picks[idx].key_env);
|
||||
sp_buf_init(&perr);
|
||||
if (sp_provider_apply(ag, p.endpoint, p.model, p.key_env, &perr) != 0) {
|
||||
if (sp_provider_apply(ag, p.kind, p.endpoint, p.model, p.key_env,
|
||||
&perr) != 0) {
|
||||
if (sp_buf_init(&msg) == 0) {
|
||||
sp_buf_printf(&msg, sp_t("model.failed"),
|
||||
perr.p != NULL ? perr.p : "?");
|
||||
@@ -1642,10 +1646,10 @@ tg_connect_answer(const char *token, long chat_id, const char *text,
|
||||
case TG_CC_ENDPOINT:
|
||||
if (strcmp(text, "ollama") == 0) {
|
||||
snprintf(tg_cc.endpoint, sizeof(tg_cc.endpoint),
|
||||
"http://127.0.0.1:11434/v1/chat/completions");
|
||||
"http://127.0.0.1:11434/v1");
|
||||
} else if (strcmp(text, "opencode") == 0) {
|
||||
snprintf(tg_cc.endpoint, sizeof(tg_cc.endpoint),
|
||||
"https://opencode.ai/zen/go/v1/chat/completions");
|
||||
"https://opencode.ai/zen/go/v1");
|
||||
snprintf(tg_cc.key_env, sizeof(tg_cc.key_env),
|
||||
"OPENCODE_GO_API_KEY");
|
||||
} else if (!sp_provider_endpoint_ok(text)) {
|
||||
|
||||
+35
-9
@@ -17,7 +17,7 @@ int
|
||||
sp_registry_add(struct sp_registry *r, const struct sp_tool *t)
|
||||
{
|
||||
size_t ncap;
|
||||
void *np;
|
||||
void *np, **rt;
|
||||
|
||||
if (r->len == r->cap) {
|
||||
if (r->cap > (size_t)-1 / 2 / sizeof(*r->tools)) {
|
||||
@@ -25,38 +25,64 @@ sp_registry_add(struct sp_registry *r, const struct sp_tool *t)
|
||||
return -1;
|
||||
}
|
||||
ncap = r->cap ? r->cap * 2 : 8;
|
||||
np = realloc(r->tools, ncap * sizeof(*r->tools));
|
||||
np = malloc(ncap * sizeof(*r->tools));
|
||||
if (np == NULL)
|
||||
return -1;
|
||||
r->tools = np;
|
||||
if (r->tools != NULL) {
|
||||
rt = realloc(r->retired, (r->nretired + 1) * sizeof(*rt));
|
||||
if (rt == NULL) {
|
||||
free(np);
|
||||
return -1;
|
||||
}
|
||||
r->retired = rt;
|
||||
memcpy(np, r->tools, r->len * sizeof(*r->tools));
|
||||
r->retired[r->nretired++] = r->tools;
|
||||
}
|
||||
__atomic_store_n(&r->tools, (struct sp_tool *)np,
|
||||
__ATOMIC_RELEASE);
|
||||
r->cap = ncap;
|
||||
}
|
||||
r->tools[r->len++] = *t;
|
||||
r->tools[r->len] = *t;
|
||||
__atomic_store_n(&r->len, r->len + 1, __ATOMIC_RELEASE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const struct sp_tool *
|
||||
sp_registry_tools(const struct sp_registry *r, size_t *n)
|
||||
{
|
||||
*n = __atomic_load_n(&r->len, __ATOMIC_ACQUIRE);
|
||||
return __atomic_load_n(&r->tools, __ATOMIC_ACQUIRE);
|
||||
}
|
||||
|
||||
const struct sp_tool *
|
||||
sp_registry_find(const struct sp_registry *r, const char *name)
|
||||
{
|
||||
size_t i;
|
||||
size_t i, n;
|
||||
const struct sp_tool *tv;
|
||||
|
||||
if (name == NULL)
|
||||
return NULL;
|
||||
for (i = 0; i < r->len; i++)
|
||||
if (strcmp(r->tools[i].name, name) == 0)
|
||||
return &r->tools[i];
|
||||
tv = sp_registry_tools(r, &n);
|
||||
for (i = 0; i < n; i++)
|
||||
if (strcmp(tv[i].name, name) == 0)
|
||||
return &tv[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
size_t
|
||||
sp_registry_count(const struct sp_registry *r)
|
||||
{
|
||||
return r->len;
|
||||
return __atomic_load_n(&r->len, __ATOMIC_ACQUIRE);
|
||||
}
|
||||
|
||||
void
|
||||
sp_registry_free(struct sp_registry *r)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < r->nretired; i++)
|
||||
free(r->retired[i]);
|
||||
free(r->retired);
|
||||
free(r->tools);
|
||||
memset(r, 0, sizeof(*r));
|
||||
}
|
||||
@@ -16,11 +16,46 @@
|
||||
* That form exists for exactly one reason: a test can express a whole turn in
|
||||
* a text file -- no network, no key, no model.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
/*
|
||||
* One route of an endpoint. The config names the API base (https://host/v1);
|
||||
* splinter builds every route from it: chat/completions, messages, models,
|
||||
* usage. An older full route (.../chat/completions, .../messages, .../models)
|
||||
* is cut back to its base first, so both spellings work. 'route' NULL gives
|
||||
* the base itself.
|
||||
*/
|
||||
char *
|
||||
sp_endpoint_url(const char *endpoint, const char *route, char *out,
|
||||
size_t cap)
|
||||
{
|
||||
static const char *const tails[] = { "/chat/completions", "/messages",
|
||||
"/models", NULL };
|
||||
size_t n, k, t;
|
||||
|
||||
if (out == NULL || cap == 0)
|
||||
return out;
|
||||
snprintf(out, cap, "%s", endpoint != NULL ? endpoint : "");
|
||||
n = strlen(out);
|
||||
while (n > 0 && out[n - 1] == '/')
|
||||
out[--n] = '\0';
|
||||
for (k = 0; tails[k] != NULL; k++) {
|
||||
t = strlen(tails[k]);
|
||||
if (n >= t && strcmp(out + n - t, tails[k]) == 0) {
|
||||
n -= t;
|
||||
out[n] = '\0';
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (route != NULL && *route != '\0' && n + 1 < cap)
|
||||
snprintf(out + n, cap - n, "/%s", route);
|
||||
return out;
|
||||
}
|
||||
|
||||
int
|
||||
sp_mock_init(struct sp_mock *m)
|
||||
{
|
||||
@@ -70,6 +105,7 @@ sp_reply_free(struct sp_reply *r)
|
||||
free(r->calls[i].args);
|
||||
}
|
||||
free(r->calls);
|
||||
free(r->calls_json);
|
||||
memset(r, 0, sizeof(*r));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,554 @@
|
||||
/*
|
||||
* splinter -- HTTP transport for the Anthropic Messages API.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Same shape as transport_openai.c, different vendor:
|
||||
*
|
||||
* - curl(1) does the TLS, the JSON body travels through a temp file, and the
|
||||
* token travels as a header built from the environment, never in argv;
|
||||
* - the HTTP status is read from curl's own -D file, streaming or not, so a
|
||||
* 429 keeps being a 429 with the provider's message attached -- a streamed
|
||||
* request used to end as "no answer" and lose the reason;
|
||||
* - the turn's cancellation flag kills curl mid-flight, so Ctrl-C returns
|
||||
* instead of waiting for a model that is talking to nobody.
|
||||
*
|
||||
* Two auth styles, decided by the token itself, because the user has both:
|
||||
*
|
||||
* sk-ant-oat... Claude Code OAuth token -> Authorization: Bearer, plus the
|
||||
* oauth beta and Claude Code's system block (a bare request
|
||||
* with such a token is refused by the API);
|
||||
* sk-ant-api... an ordinary API key -> x-api-key.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#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"
|
||||
#include "mcp.h"
|
||||
|
||||
#define ANTHROPIC_VERSION "2023-06-01"
|
||||
#define ANTHROPIC_OAUTH_BETA "oauth-2025-04-20,claude-code-20250219"
|
||||
|
||||
struct as_ctx {
|
||||
char url[512];
|
||||
char model[128];
|
||||
char key[512];
|
||||
const struct sp_registry *reg;
|
||||
long timeout_s;
|
||||
};
|
||||
|
||||
static int
|
||||
is_oauth(const char *key)
|
||||
{
|
||||
return key != NULL && strncmp(key, "sk-ant-oat", 10) == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Read curl's output, killing it the moment the turn is cancelled.
|
||||
*
|
||||
* poll(), not fread(): a blocking read only notices the flag once the model
|
||||
* starts talking, which is exactly the case the operator is trying to leave.
|
||||
*/
|
||||
static int
|
||||
read_cancel(FILE *f, struct sp_buf *out, const volatile int *cancel,
|
||||
pid_t child)
|
||||
{
|
||||
char chunk[4096];
|
||||
|
||||
for (;;) {
|
||||
struct pollfd pfd;
|
||||
ssize_t got;
|
||||
int pr;
|
||||
|
||||
if (cancel != NULL && *cancel) {
|
||||
(void)kill(child, SIGKILL);
|
||||
return -1;
|
||||
}
|
||||
pfd.fd = fileno(f);
|
||||
pfd.events = POLLIN;
|
||||
pfd.revents = 0;
|
||||
pr = poll(&pfd, 1, 200);
|
||||
if (pr < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
if (pr == 0)
|
||||
continue;
|
||||
got = read(fileno(f), chunk, sizeof(chunk));
|
||||
if (got < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
if (got == 0)
|
||||
break;
|
||||
if (sp_buf_add(out, chunk, (size_t)got) != 0)
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
parse_status_file(const char *path, long *status, long *retry_after)
|
||||
{
|
||||
FILE *f;
|
||||
char line[512];
|
||||
int have = 0;
|
||||
|
||||
*status = 0;
|
||||
*retry_after = 0;
|
||||
if (path == NULL || *path == '\0')
|
||||
return -1;
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
return -1;
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
if (strncmp(line, "HTTP/", 5) == 0) {
|
||||
char *sp = strchr(line + 5, ' ');
|
||||
long st = sp != NULL ? strtol(sp + 1, NULL, 10) : 0;
|
||||
|
||||
if (st > 0) {
|
||||
*status = st;
|
||||
have = 1;
|
||||
}
|
||||
} else if (strncasecmp(line, "Retry-After:", 12) == 0) {
|
||||
*retry_after = strtol(line + 12, NULL, 10);
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
return have ? 0 : -1;
|
||||
}
|
||||
|
||||
/* the provider's own sentence, so a limit shows a reason and not just a code */
|
||||
static void
|
||||
provider_error(const char *body, struct sp_buf *err)
|
||||
{
|
||||
mcp_json *v;
|
||||
const mcp_json *e;
|
||||
|
||||
if (body == NULL || *body == '\0')
|
||||
return;
|
||||
v = mcp_parse(body);
|
||||
if (v == NULL)
|
||||
return;
|
||||
e = mcp_arg(v, "error");
|
||||
if (e != NULL && mcp_arg_string(e, "message") != NULL)
|
||||
sp_buf_printf(err, "anthropic: %s",
|
||||
mcp_arg_string(e, "message"));
|
||||
mcp_json_free(v);
|
||||
}
|
||||
|
||||
static FILE *
|
||||
as_curl(const struct as_ctx *c, const char *body_path, int stream,
|
||||
pid_t *pid, struct sp_buf *err, const char *hdr_path)
|
||||
{
|
||||
char tmo[32], data[600], auth[sizeof(c->key) + 32];
|
||||
const char *args[20];
|
||||
const char *hdrs[6];
|
||||
char sess[200];
|
||||
size_t nh = 0;
|
||||
int n = 0, fd;
|
||||
FILE *f;
|
||||
|
||||
snprintf(tmo, sizeof(tmo), "%ld", c->timeout_s);
|
||||
snprintf(data, sizeof(data), "@%s", body_path);
|
||||
args[n++] = "-sS";
|
||||
args[n++] = "-A";
|
||||
args[n++] = "splinter/" SP_VERSION;
|
||||
if (stream)
|
||||
args[n++] = "-N";
|
||||
args[n++] = "-m";
|
||||
args[n++] = tmo;
|
||||
args[n++] = "-X";
|
||||
args[n++] = "POST";
|
||||
args[n++] = "-H";
|
||||
args[n++] = "Content-Type: application/json";
|
||||
args[n++] = "--data-binary";
|
||||
args[n++] = data;
|
||||
if (hdr_path != NULL && *hdr_path != '\0') {
|
||||
args[n++] = "-D";
|
||||
args[n++] = hdr_path;
|
||||
}
|
||||
if (!stream) {
|
||||
args[n++] = "-w";
|
||||
args[n++] = "\n%{http_code}";
|
||||
}
|
||||
args[n] = NULL;
|
||||
|
||||
hdrs[nh++] = "Accept: application/json, text/event-stream";
|
||||
snprintf(sess, sizeof(sess), "anthropic-version: %s",
|
||||
ANTHROPIC_VERSION);
|
||||
hdrs[nh++] = sess;
|
||||
if (is_oauth(c->key)) {
|
||||
hdrs[nh++] = "anthropic-beta: " ANTHROPIC_OAUTH_BETA;
|
||||
snprintf(auth, sizeof(auth), "Authorization: Bearer %s", c->key);
|
||||
hdrs[nh++] = auth;
|
||||
} else if (c->key[0] != '\0') {
|
||||
snprintf(auth, sizeof(auth), "x-api-key: %s", c->key);
|
||||
hdrs[nh++] = auth;
|
||||
}
|
||||
hdrs[nh] = NULL;
|
||||
fd = sp_curl_start(args, c->url, hdrs, 0, pid, err);
|
||||
memset(auth, 0, sizeof(auth));
|
||||
if (fd < 0)
|
||||
return NULL;
|
||||
f = fdopen(fd, "r");
|
||||
if (f == NULL) {
|
||||
close(fd);
|
||||
(void)kill(*pid, SIGKILL);
|
||||
(void)waitpid(*pid, NULL, 0);
|
||||
sp_buf_printf(err, "anthropic: fdopen: %s", strerror(errno));
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
static void
|
||||
dump_request(const char *body, size_t len)
|
||||
{
|
||||
const char *path = getenv("SPLINTER_DUMP_REQUEST");
|
||||
FILE *f;
|
||||
|
||||
if (path == NULL || *path == '\0')
|
||||
return;
|
||||
f = fopen(path, "w");
|
||||
if (f == NULL)
|
||||
return;
|
||||
if (len > 0)
|
||||
(void)fwrite(body, 1, len, f);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static void
|
||||
temp_template(char *dst, size_t cap, const char *name)
|
||||
{
|
||||
const char *dir = getenv("TMPDIR");
|
||||
|
||||
if (dir == NULL || *dir == '\0')
|
||||
dir = "/var/tmp";
|
||||
snprintf(dst, cap, "%s/splinter-%s-XXXXXX", dir, name);
|
||||
}
|
||||
|
||||
/* write the request body, open curl, and keep the headers in a second file */
|
||||
static FILE *
|
||||
start_request(struct as_ctx *c, struct sp_buf *body, char *path, size_t pcap,
|
||||
char *hdr_path, size_t hcap, int stream, pid_t *child, struct sp_buf *err)
|
||||
{
|
||||
int fd, hfd;
|
||||
ssize_t w;
|
||||
FILE *p;
|
||||
|
||||
temp_template(path, pcap, "as");
|
||||
fd = mkstemp(path);
|
||||
if (fd < 0) {
|
||||
sp_buf_printf(err, "anthropic: mkstemp: %s", strerror(errno));
|
||||
return NULL;
|
||||
}
|
||||
w = write(fd, body->p, body->len);
|
||||
close(fd);
|
||||
if (w < 0 || (size_t)w != body->len) {
|
||||
sp_buf_printf(err, "anthropic: short write: %s", strerror(errno));
|
||||
(void)unlink(path);
|
||||
return NULL;
|
||||
}
|
||||
temp_template(hdr_path, hcap, "ash");
|
||||
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);
|
||||
p = as_curl(c, path, stream, child, err, hdr_path[0] ? hdr_path : NULL);
|
||||
if (p == NULL) {
|
||||
(void)unlink(path);
|
||||
if (hdr_path[0])
|
||||
(void)unlink(hdr_path);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
static void
|
||||
finish_request(const char *path, const char *hdr_path)
|
||||
{
|
||||
(void)unlink(path);
|
||||
if (hdr_path != NULL && hdr_path[0] != '\0')
|
||||
(void)unlink(hdr_path);
|
||||
}
|
||||
|
||||
static int
|
||||
as_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
struct as_ctx *c = ctx;
|
||||
struct sp_buf body, raw;
|
||||
char path[512], hdr_path[540];
|
||||
pid_t child = -1;
|
||||
FILE *p;
|
||||
int rc = -1;
|
||||
long status = 0, retry_after = 0;
|
||||
|
||||
if (c == NULL)
|
||||
return -1;
|
||||
if (sp_buf_init(&body) != 0 || sp_buf_init(&raw) != 0) {
|
||||
sp_buf_puts(err, "anthropic: out of memory");
|
||||
return -1;
|
||||
}
|
||||
if (sp_anthropic_request(conv, c->model, c->reg, 0,
|
||||
is_oauth(c->key), &body) != 0) {
|
||||
sp_buf_puts(err, "anthropic: cannot build the request");
|
||||
goto out;
|
||||
}
|
||||
p = start_request(c, &body, path, sizeof(path), hdr_path,
|
||||
sizeof(hdr_path), 0, &child, err);
|
||||
if (p == NULL)
|
||||
goto out;
|
||||
if (read_cancel(p, &raw, sp_cancel_flag(), child) != 0) {
|
||||
if (sp_cancel_flag() != NULL && *sp_cancel_flag())
|
||||
sp_buf_puts(err, "cancelled");
|
||||
else
|
||||
sp_buf_puts(err, "anthropic: read failed");
|
||||
(void)kill(child, SIGKILL);
|
||||
fclose(p);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
finish_request(path, hdr_path);
|
||||
goto out;
|
||||
}
|
||||
fclose(p);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
(void)parse_status_file(hdr_path, &status, &retry_after);
|
||||
out->retry_after_s = retry_after;
|
||||
sp_log_wire(sp_log_dir(), "response", raw.p != NULL ? raw.p : "",
|
||||
raw.len);
|
||||
if (status == 0) {
|
||||
/* no -w in a streamed request: the code is in the body */
|
||||
sp_buf_puts(err, "anthropic: unparseable response (no status)");
|
||||
finish_request(path, hdr_path);
|
||||
goto out;
|
||||
}
|
||||
out->status = status;
|
||||
if (status < 200 || status > 299) {
|
||||
provider_error(raw.p, err);
|
||||
if (err->len == 0)
|
||||
sp_buf_printf(err, "anthropic: HTTP %ld", status);
|
||||
finish_request(path, hdr_path);
|
||||
goto out;
|
||||
}
|
||||
if (sp_anthropic_reply(raw.p, out, err) != 0) {
|
||||
finish_request(path, hdr_path);
|
||||
goto out;
|
||||
}
|
||||
out->status = status;
|
||||
finish_request(path, hdr_path);
|
||||
rc = 0;
|
||||
out:
|
||||
sp_buf_free(&body);
|
||||
sp_buf_free(&raw);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/*
|
||||
* Streaming: curl stays attached (-N) and its stdout is read line by line;
|
||||
* each line goes through the Anthropic event accumulator. The status file
|
||||
* tells whether the stream was ever a success, so a limit arriving as a JSON
|
||||
* body is reported as a limit and not as "the model said nothing".
|
||||
*/
|
||||
static int
|
||||
as_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
struct sp_buf *err, sp_stream_cb cb, void *cbctx)
|
||||
{
|
||||
struct as_ctx *c = ctx;
|
||||
struct sp_buf body, lbuf, tail, delta;
|
||||
struct sp_as_sse *sse;
|
||||
char path[512], hdr_path[540];
|
||||
FILE *p;
|
||||
pid_t child = -1;
|
||||
int rc = -1, saw_data = 0;
|
||||
long status = 0, retry_after = 0;
|
||||
|
||||
if (c == NULL)
|
||||
return -1;
|
||||
if (sp_buf_init(&body) != 0 || sp_buf_init(&lbuf) != 0 ||
|
||||
sp_buf_init(&tail) != 0 || sp_buf_init(&delta) != 0) {
|
||||
sp_buf_puts(err, "anthropic: out of memory");
|
||||
return -1;
|
||||
}
|
||||
sse = sp_as_sse_new();
|
||||
if (sse == NULL) {
|
||||
sp_buf_puts(err, "anthropic: out of memory");
|
||||
sp_buf_free(&body);
|
||||
sp_buf_free(&lbuf);
|
||||
sp_buf_free(&tail);
|
||||
sp_buf_free(&delta);
|
||||
return -1;
|
||||
}
|
||||
if (sp_anthropic_request(conv, c->model, c->reg, 1,
|
||||
is_oauth(c->key), &body) != 0) {
|
||||
sp_buf_puts(err, "anthropic: cannot build the request");
|
||||
goto out;
|
||||
}
|
||||
p = start_request(c, &body, path, sizeof(path), hdr_path,
|
||||
sizeof(hdr_path), 1, &child, err);
|
||||
if (p == NULL)
|
||||
goto out;
|
||||
for (;;) {
|
||||
struct pollfd pfd;
|
||||
int pr;
|
||||
ssize_t got;
|
||||
size_t i, start;
|
||||
|
||||
if (sp_cancel_flag() != NULL && *sp_cancel_flag()) {
|
||||
(void)kill(child, SIGKILL);
|
||||
sp_buf_puts(err, "cancelled");
|
||||
fclose(p);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
finish_request(path, hdr_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;
|
||||
got = read(fileno(p), lbuf.p + lbuf.len,
|
||||
lbuf.cap - lbuf.len - 1);
|
||||
if (got < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
if (got == 0)
|
||||
break;
|
||||
lbuf.len += (size_t)got;
|
||||
lbuf.p[lbuf.len] = '\0';
|
||||
start = 0;
|
||||
for (i = 0; i < lbuf.len; i++) {
|
||||
int kind;
|
||||
|
||||
if (lbuf.p[i] != '\n')
|
||||
continue;
|
||||
lbuf.p[i] = '\0';
|
||||
if (lbuf.p[start] != '\0' &&
|
||||
strncmp(lbuf.p + start, "data:", 5) != 0 &&
|
||||
tail.len < 4096) {
|
||||
sp_buf_puts(&tail, lbuf.p + start);
|
||||
sp_buf_puts(&tail, "\n");
|
||||
}
|
||||
if (strncmp(lbuf.p + start, "data:", 5) == 0)
|
||||
saw_data = 1;
|
||||
sp_buf_clear(&delta);
|
||||
kind = sp_as_sse_line(sse, lbuf.p + start, &delta, err);
|
||||
if (kind < 0) {
|
||||
(void)kill(child, SIGKILL);
|
||||
fclose(p);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
finish_request(path, hdr_path);
|
||||
goto out;
|
||||
}
|
||||
if (kind > 0 && cb != NULL && delta.len > 0)
|
||||
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';
|
||||
}
|
||||
if (lbuf.len + 1 >= lbuf.cap &&
|
||||
sp_buf_reserve(&lbuf, lbuf.cap * 2) != 0) {
|
||||
sp_buf_puts(err, "anthropic: out of memory");
|
||||
(void)kill(child, SIGKILL);
|
||||
fclose(p);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
finish_request(path, hdr_path);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
if (lbuf.len > 0) {
|
||||
int kind;
|
||||
|
||||
sp_buf_clear(&delta);
|
||||
kind = sp_as_sse_line(sse, lbuf.p, &delta, err);
|
||||
if (kind > 0 && cb != NULL && delta.len > 0)
|
||||
cb(cbctx, kind, delta.p);
|
||||
}
|
||||
fclose(p);
|
||||
{
|
||||
int st;
|
||||
|
||||
(void)waitpid(child, &st, 0);
|
||||
}
|
||||
(void)parse_status_file(hdr_path, &status, &retry_after);
|
||||
out->retry_after_s = retry_after;
|
||||
finish_request(path, hdr_path);
|
||||
if (status != 0 && (status < 200 || status > 299)) {
|
||||
out->status = status;
|
||||
provider_error(tail.p, err);
|
||||
if (err->len == 0)
|
||||
sp_buf_printf(err, "anthropic: HTTP %ld", status);
|
||||
goto out;
|
||||
}
|
||||
if (!saw_data) {
|
||||
sp_buf_printf(err, "anthropic: endpoint sent no SSE data: %.300s",
|
||||
tail.p != NULL ? tail.p : "(empty)");
|
||||
goto out;
|
||||
}
|
||||
if (sp_as_sse_finish(sse, out, err) != 0)
|
||||
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, "anthropic: stream ended with no answer: %.300s",
|
||||
tail.p != NULL ? tail.p : "(empty)");
|
||||
sp_reply_free(out);
|
||||
goto out;
|
||||
}
|
||||
rc = 0;
|
||||
out:
|
||||
sp_as_sse_free(sse);
|
||||
sp_buf_free(&body);
|
||||
sp_buf_free(&lbuf);
|
||||
sp_buf_free(&tail);
|
||||
sp_buf_free(&delta);
|
||||
return rc;
|
||||
}
|
||||
|
||||
struct sp_transport
|
||||
sp_anthropic_transport(const char *url, const char *model, const char *api_key,
|
||||
const struct sp_registry *reg, long timeout_s)
|
||||
{
|
||||
struct as_ctx *ctx;
|
||||
struct sp_transport t;
|
||||
|
||||
memset(&t, 0, sizeof(t));
|
||||
ctx = malloc(sizeof(*ctx));
|
||||
if (ctx == NULL)
|
||||
return t;
|
||||
memset(ctx, 0, sizeof(*ctx));
|
||||
sp_endpoint_url(url, "messages", ctx->url, sizeof(ctx->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 : 900;
|
||||
t.send = as_send;
|
||||
t.send_stream = as_stream;
|
||||
t.ctx = ctx;
|
||||
return t;
|
||||
}
|
||||
+37
-6
@@ -75,26 +75,57 @@ sp_openai_set_cancel(const volatile int *flag)
|
||||
g_cancel = flag;
|
||||
}
|
||||
|
||||
/* Read a child's output, killing it the moment the turn is cancelled. */
|
||||
/* The same flag, for a transport that is not this file: the cli plugin uses it
|
||||
* to kill the program it started. NULL when no turn is running. */
|
||||
const volatile int *
|
||||
sp_cancel_flag(void)
|
||||
{
|
||||
return g_cancel;
|
||||
}
|
||||
|
||||
/*
|
||||
* Read a child's output, killing it the moment the turn is cancelled.
|
||||
* poll(), not fread(): a blocking read only sees the flag once the endpoint
|
||||
* answers, so a --no-stream turn could not be cancelled while it was waiting.
|
||||
*/
|
||||
static int
|
||||
read_all_cancel(FILE *f, struct sp_buf *out, const volatile int *cancel,
|
||||
pid_t child)
|
||||
{
|
||||
char chunk[4096];
|
||||
size_t got;
|
||||
|
||||
for (;;) {
|
||||
struct pollfd pfd;
|
||||
ssize_t got;
|
||||
int pr;
|
||||
|
||||
if (cancel != NULL && *cancel) {
|
||||
(void)kill(child, SIGKILL);
|
||||
return -1;
|
||||
}
|
||||
got = fread(chunk, 1, sizeof(chunk), f);
|
||||
pfd.fd = fileno(f);
|
||||
pfd.events = POLLIN;
|
||||
pfd.revents = 0;
|
||||
pr = poll(&pfd, 1, 200);
|
||||
if (pr < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
if (pr == 0)
|
||||
continue;
|
||||
got = read(fileno(f), chunk, sizeof(chunk));
|
||||
if (got < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
if (got == 0)
|
||||
break;
|
||||
if (sp_buf_add(out, chunk, got) != 0)
|
||||
if (sp_buf_add(out, chunk, (size_t)got) != 0)
|
||||
return -1;
|
||||
}
|
||||
return ferror(f) ? -1 : 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -579,7 +610,7 @@ sp_openai_transport(const char *url, const char *model, const char *api_key,
|
||||
if (ctx == NULL)
|
||||
return t; /* send/provider/key_id all NULL */
|
||||
memset(ctx, 0, sizeof(*ctx));
|
||||
snprintf(ctx->url, sizeof(ctx->url), "%s", url != NULL ? url : "");
|
||||
sp_endpoint_url(url, "chat/completions", ctx->url, sizeof(ctx->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;
|
||||
|
||||
@@ -1722,7 +1722,8 @@ agent_switch(struct ui_state *s, struct sp_agent *ag, int idx, int announce)
|
||||
snprintf(s->home_id, sizeof(s->home_id), "%s",
|
||||
sp_usage_active());
|
||||
if (sp_buf_init(&perr) == 0) {
|
||||
if (sp_provider_apply(ag, ch.d->endpoint,
|
||||
if (sp_provider_apply(ag, ch.d->kind,
|
||||
ch.d->endpoint,
|
||||
ch.model[0] != '\0' ? ch.model : ch.d->model,
|
||||
ch.d->key_env, &perr) == 0) {
|
||||
sp_usage_set_active(ch.d->id);
|
||||
@@ -1948,6 +1949,17 @@ ui_read_line(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
|
||||
}
|
||||
ch = wgetch(ui_input);
|
||||
if (ch == ERR) {
|
||||
{
|
||||
char msg[200];
|
||||
int got = 0;
|
||||
|
||||
while (sp_host_status_take(host, msg, sizeof(msg))) {
|
||||
add_entry(s, "splinter", msg);
|
||||
got = 1;
|
||||
}
|
||||
if (got)
|
||||
draw_history(s, 0);
|
||||
}
|
||||
draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host);
|
||||
draw_status(s, NULL);
|
||||
if (locked) {
|
||||
@@ -2225,10 +2237,10 @@ ui_connect_answer(struct ui_state *s, struct sp_agent *ag, const char *line,
|
||||
case 1:
|
||||
if (strcmp(line, "ollama") == 0) {
|
||||
snprintf(s->cc.endpoint, sizeof(s->cc.endpoint),
|
||||
"http://127.0.0.1:11434/v1/chat/completions");
|
||||
"http://127.0.0.1:11434/v1");
|
||||
} else if (strcmp(line, "opencode") == 0) {
|
||||
snprintf(s->cc.endpoint, sizeof(s->cc.endpoint),
|
||||
"https://opencode.ai/zen/go/v1/chat/completions");
|
||||
"https://opencode.ai/zen/go/v1");
|
||||
snprintf(s->cc.key_env, sizeof(s->cc.key_env),
|
||||
"OPENCODE_GO_API_KEY");
|
||||
} else if (!sp_provider_endpoint_ok(line)) {
|
||||
@@ -2450,6 +2462,25 @@ ui_slash(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
|
||||
struct sp_provider p;
|
||||
struct sp_buf perr, serr;
|
||||
size_t idx = 0, i, n;
|
||||
char poolname[40];
|
||||
int is_pool = 0;
|
||||
|
||||
/*
|
||||
* A pool is a selector too, and so is "pool/model": the run starts
|
||||
* on the member with the most room and moves at a limit, exactly
|
||||
* what naming the pool in -m does.
|
||||
*/
|
||||
snprintf(poolname, sizeof(poolname), "%s", args);
|
||||
is_pool = sp_pool_find(s->conf, args) != NULL;
|
||||
if (!is_pool) {
|
||||
const char *sl = strchr(args, '/');
|
||||
|
||||
if (sl != NULL && (size_t)(sl - args) < sizeof(poolname)) {
|
||||
memcpy(poolname, args, (size_t)(sl - args));
|
||||
poolname[sl - args] = '\0';
|
||||
is_pool = sp_pool_find(s->conf, poolname) != NULL;
|
||||
}
|
||||
}
|
||||
|
||||
if (s->conf == NULL) {
|
||||
sp_buf_puts(&out, sp_t("model.none"));
|
||||
@@ -2462,6 +2493,47 @@ ui_slash(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
|
||||
p.id, p.model,
|
||||
strcmp(p.model, s->model) == 0 ?
|
||||
" *" : "");
|
||||
/* a pool is a selector too: it starts on the member with
|
||||
* the most room and moves at a limit */
|
||||
if (s->conf->npools > 0)
|
||||
sp_buf_printf(&out, "\n%s", sp_t("model.pools"));
|
||||
for (i = 0; i < s->conf->npools; i++) {
|
||||
size_t j;
|
||||
|
||||
sp_buf_printf(&out, "\n %s pool (%s):",
|
||||
s->conf->pool[i].id,
|
||||
s->conf->pool[i].strategy);
|
||||
for (j = 0; j < s->conf->pool[i].nmembers; j++)
|
||||
sp_buf_printf(&out, " %s",
|
||||
s->conf->pool[i].member[j]);
|
||||
}
|
||||
} else if (is_pool) {
|
||||
struct sp_choice ch;
|
||||
|
||||
if (sp_provider_choose(s->conf, args, &ch) != 0) {
|
||||
sp_buf_printf(&out, sp_t("model.unknown"),
|
||||
args);
|
||||
} else {
|
||||
sp_buf_init(&perr);
|
||||
if (sp_provider_apply(ag, ch.d->kind,
|
||||
ch.d->endpoint,
|
||||
ch.model[0] != '\0' ? ch.model : ch.d->model,
|
||||
ch.d->key_env, &perr) != 0) {
|
||||
sp_buf_printf(&out, sp_t("model.failed"),
|
||||
perr.p != NULL ? perr.p : "?");
|
||||
} else {
|
||||
sp_usage_set_active(ch.d->id);
|
||||
snprintf(s->cur_endpoint,
|
||||
sizeof(s->cur_endpoint), "%s",
|
||||
ch.d->endpoint);
|
||||
snprintf(s->cur_model, sizeof(s->cur_model),
|
||||
"%s", ch.model[0] != '\0' ?
|
||||
ch.model : ch.d->model);
|
||||
sp_buf_printf(&out, sp_t("model.pool"),
|
||||
poolname, s->cur_model, ch.d->id);
|
||||
}
|
||||
sp_buf_free(&perr);
|
||||
}
|
||||
} else if (sp_provider_find(s->conf, args, &idx)) {
|
||||
sp_buf_init(&perr);
|
||||
if (sp_provider_use(ag, s->conf, idx, &perr) != 0) {
|
||||
@@ -2489,8 +2561,8 @@ ui_slash(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
|
||||
sp_provider_at(s->conf, idx, &p) != 0)
|
||||
(void)sp_provider_at(s->conf, 0, &p);
|
||||
sp_buf_init(&perr);
|
||||
ok = sp_provider_apply(ag, p.endpoint, args, p.key_env,
|
||||
&perr) == 0;
|
||||
ok = sp_provider_apply(ag, p.kind, p.endpoint, args,
|
||||
p.key_env, &perr) == 0;
|
||||
if (ok) {
|
||||
memset(&chosen, 0, sizeof(chosen));
|
||||
snprintf(chosen.id, sizeof(chosen.id), "%s",
|
||||
@@ -2972,6 +3044,39 @@ ui_turn(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
|
||||
}
|
||||
}
|
||||
wtimeout(ui_input, -1);
|
||||
/*
|
||||
* A cancelled turn: wait for the worker with the screen alive.
|
||||
* Every transport kills its own child or curl when the flag is
|
||||
* set; the cli transport did not, and this join froze the whole
|
||||
* screen until `claude -p` decided to finish. Now the hint is on
|
||||
* screen, the repaint continues, and a second Ctrl-C leaves at
|
||||
* once instead of holding the terminal hostage.
|
||||
*/
|
||||
if (cancelled) {
|
||||
wtimeout(ui_input, 100);
|
||||
for (;;) {
|
||||
int c2, done2;
|
||||
|
||||
pthread_mutex_lock(&tu.lock);
|
||||
done2 = tu.done;
|
||||
pthread_mutex_unlock(&tu.lock);
|
||||
if (done2)
|
||||
break;
|
||||
werase(ui_input);
|
||||
mvwaddstr(ui_input, 0, 0,
|
||||
sp_t("ui.cancelling"));
|
||||
wclrtoeol(ui_input);
|
||||
wrefresh(ui_input);
|
||||
c2 = wgetch(ui_input);
|
||||
if (c2 == 3 || c2 == 4) {
|
||||
endwin();
|
||||
_exit(1);
|
||||
}
|
||||
if (c2 == ERR)
|
||||
turn_paint(s, ag, host, &tu, &v);
|
||||
}
|
||||
wtimeout(ui_input, -1);
|
||||
}
|
||||
pthread_join(th, NULL);
|
||||
if (s->sw) swarm_report_busy(s->sw, 0);
|
||||
rc = tu.rc;
|
||||
|
||||
+46
@@ -11,6 +11,7 @@
|
||||
|
||||
#include "config.h"
|
||||
#include "usage.h"
|
||||
#include "providers.h"
|
||||
#include "i18n.h"
|
||||
|
||||
#define KEEP_SECONDS (32L * 86400) /* the longest window anyone asks for */
|
||||
@@ -309,6 +310,43 @@ bar(double frac, char *b, size_t cap)
|
||||
b[n + 2] = '\0';
|
||||
}
|
||||
|
||||
/* the provider's own usage text, asked at most once a minute per provider */
|
||||
static int
|
||||
remote_cached(const struct sp_delegate *d, char *out, size_t cap)
|
||||
{
|
||||
static struct {
|
||||
char id[32];
|
||||
char text[160];
|
||||
time_t at;
|
||||
int ok;
|
||||
} cache[SP_CONFIG_MAX_DELEGATES];
|
||||
size_t k;
|
||||
time_t now = time(NULL);
|
||||
|
||||
for (k = 0; k < SP_CONFIG_MAX_DELEGATES; k++)
|
||||
if (cache[k].id[0] == '\0' || strcmp(cache[k].id, d->id) == 0)
|
||||
break;
|
||||
if (k == SP_CONFIG_MAX_DELEGATES)
|
||||
return 0;
|
||||
if (cache[k].id[0] == '\0' || now - cache[k].at > 60) {
|
||||
struct sp_provider pv;
|
||||
|
||||
memset(&pv, 0, sizeof(pv));
|
||||
snprintf(cache[k].id, sizeof(cache[k].id), "%s", d->id);
|
||||
snprintf(pv.kind, sizeof(pv.kind), "%s", d->kind);
|
||||
snprintf(pv.endpoint, sizeof(pv.endpoint), "%s", d->endpoint);
|
||||
snprintf(pv.key_env, sizeof(pv.key_env), "%s", d->key_env);
|
||||
cache[k].ok = strcmp(d->kind, "cli") != 0 && d->endpoint[0] != '\0' &&
|
||||
sp_provider_remote_usage(&pv, cache[k].text,
|
||||
sizeof(cache[k].text)) == 0;
|
||||
cache[k].at = now;
|
||||
}
|
||||
if (!cache[k].ok)
|
||||
return 0;
|
||||
snprintf(out, cap, "%s", cache[k].text);
|
||||
return 1;
|
||||
}
|
||||
|
||||
void
|
||||
sp_usage_report(const struct sp_config *cfg, struct sp_buf *out)
|
||||
{
|
||||
@@ -339,6 +377,14 @@ sp_usage_report(const struct sp_config *cfg, struct sp_buf *out)
|
||||
if (u.tok_limit > 0)
|
||||
sp_buf_printf(out, sp_t("usage.of_tokens"), u.tok_used,
|
||||
u.tok_limit);
|
||||
/* what the provider itself says (ollama balance, opencode go usage) */
|
||||
if (i > 0) {
|
||||
const struct sp_delegate *d = &cfg->delegate[i - 1];
|
||||
char rem[160];
|
||||
|
||||
if (remote_cached(d, rem, sizeof(rem)))
|
||||
sp_buf_printf(out, " | %s", rem);
|
||||
}
|
||||
sp_buf_puts(out, "\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
# Fake Anthropic Messages API endpoint.
|
||||
#
|
||||
# argv: port, request log.
|
||||
#
|
||||
# It insists on what the real API insists on, so the transport under test is
|
||||
# checked and not just fed: anthropic-version, an OAuth token as a Bearer
|
||||
# token (and the oauth beta that goes with it), the system prompt as a
|
||||
# top-level field, and tools as input_schema. A request that breaks any of
|
||||
# those gets a 400 that names the field, exactly like the real one would.
|
||||
#
|
||||
# Model "claude-limit" answers 429 with the provider's own message, so the
|
||||
# status/Retry-After path of a streamed request is exercised too.
|
||||
import http.server, json, sys
|
||||
|
||||
|
||||
def ev(d):
|
||||
return ("event: " + d["type"] + "\ndata: " + json.dumps(d) + "\n\n").encode()
|
||||
|
||||
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def bad(self, why):
|
||||
body = json.dumps({"type": "error", "error": {
|
||||
"type": "invalid_request_error", "message": why}}).encode()
|
||||
self.send_response(400)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("Content-Length", 0))
|
||||
raw = self.rfile.read(n)
|
||||
with open(sys.argv[2], "a") as f:
|
||||
f.write(self.path + "\n" + raw.decode("utf-8", "replace") + "\n")
|
||||
try:
|
||||
req = json.loads(raw)
|
||||
except ValueError:
|
||||
return self.bad("Body is not JSON")
|
||||
if self.path != "/v1/messages":
|
||||
return self.bad("wrong path " + self.path)
|
||||
if self.headers.get("anthropic-version") != "2023-06-01":
|
||||
return self.bad("missing anthropic-version")
|
||||
auth = self.headers.get("authorization", "")
|
||||
if not auth.startswith("Bearer sk-ant-oat"):
|
||||
return self.bad("no oauth bearer token")
|
||||
if "oauth-2025-04-20" not in (self.headers.get("anthropic-beta") or ""):
|
||||
return self.bad("missing oauth beta")
|
||||
sysmsg = req.get("system")
|
||||
if not isinstance(sysmsg, list) or not sysmsg or \
|
||||
sysmsg[0].get("text") != \
|
||||
"You are a Claude agent, built on Anthropic's Claude Agent SDK.":
|
||||
return self.bad("system must start with the Claude agent block")
|
||||
if "messages" not in req or not isinstance(req["messages"], list):
|
||||
return self.bad("messages must be an array")
|
||||
for m in req["messages"]:
|
||||
if m.get("role") not in ("user", "assistant"):
|
||||
return self.bad("bad role " + str(m.get("role")))
|
||||
for t in req.get("tools") or []:
|
||||
if "input_schema" not in t:
|
||||
return self.bad("tool without input_schema")
|
||||
|
||||
if req.get("model") == "claude-limit":
|
||||
body = json.dumps({"type": "error", "error": {
|
||||
"type": "rate_limit_error",
|
||||
"message": "This request would exceed your account's rate "
|
||||
"limit. Please try again later."}}).encode()
|
||||
self.send_response(429)
|
||||
self.send_header("Retry-After", "120")
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
|
||||
if req.get("stream"):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.end_headers()
|
||||
w = self.wfile.write
|
||||
w(ev({"type": "message_start", "message": {
|
||||
"id": "msg_1", "type": "message", "role": "assistant",
|
||||
"usage": {"input_tokens": 12}}}))
|
||||
w(ev({"type": "content_block_start", "index": 0,
|
||||
"content_block": {"type": "text", "text": ""}}))
|
||||
for piece in ("weiter ", "gemacht"):
|
||||
w(ev({"type": "content_block_delta", "index": 0,
|
||||
"delta": {"type": "text_delta", "text": piece}}))
|
||||
w(ev({"type": "content_block_stop", "index": 0}))
|
||||
w(ev({"type": "message_delta", "delta": {
|
||||
"stop_reason": "end_turn"}, "usage": {"output_tokens": 5}}))
|
||||
w(ev({"type": "message_stop"}))
|
||||
return
|
||||
|
||||
body = json.dumps({
|
||||
"id": "msg_1", "type": "message", "role": "assistant",
|
||||
"content": [{"type": "text", "text": "weiter gemacht"}],
|
||||
"usage": {"input_tokens": 12, "output_tokens": 5}}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
|
||||
@@ -0,0 +1,248 @@
|
||||
/*
|
||||
* splinter -- Anthropic Messages API shaping, without a network.
|
||||
*
|
||||
* Four things must hold, and each is checked against a body a real endpoint
|
||||
* accepts (the shapes here were verified against api.anthropic.com):
|
||||
*
|
||||
* - the system prompt is the top-level `system` field, not a message;
|
||||
* - a tool call is a `tool_use` block and its answer a `tool_result`;
|
||||
* - observations of one parallel round merge into one user message, because
|
||||
* the Messages API wants alternating roles;
|
||||
* - a stream of events becomes the same reply the non-streaming body does.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
static int failures;
|
||||
|
||||
#define CHECK(cond) do { \
|
||||
if (!(cond)) { \
|
||||
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
|
||||
failures++; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
static int
|
||||
echo_tool(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
(void)ctx;
|
||||
return sp_buf_puts(out, args);
|
||||
}
|
||||
|
||||
int
|
||||
main(void)
|
||||
{
|
||||
struct sp_conv conv;
|
||||
struct sp_registry reg;
|
||||
struct sp_buf req, err, delta;
|
||||
struct sp_reply rep;
|
||||
struct sp_tool t;
|
||||
struct sp_as_sse *sse;
|
||||
|
||||
sp_conv_init(&conv);
|
||||
memset(®, 0, sizeof(reg));
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "read";
|
||||
t.description = "read a file";
|
||||
t.auth = SP_AUTH_READ;
|
||||
t.params = "{\"type\":\"object\",\"properties\":{\"path\":"
|
||||
"{\"type\":\"string\"}},\"required\":[\"path\"]}";
|
||||
t.run = echo_tool;
|
||||
(void)sp_registry_add(®, &t);
|
||||
|
||||
if (sp_buf_init(&req) != 0 || sp_buf_init(&err) != 0 ||
|
||||
sp_buf_init(&delta) != 0)
|
||||
return 1;
|
||||
|
||||
/* ---- request: system is a field, tools use input_schema ---- */
|
||||
CHECK(sp_conv_push(&conv, "system", NULL, "be brief") == 0);
|
||||
CHECK(sp_conv_push(&conv, "user", NULL, "say \"hi\"") == 0);
|
||||
CHECK(sp_anthropic_request(&conv, "claude-x", ®, 0, 0, &req) == 0);
|
||||
CHECK(strstr(req.p, "\"model\":\"claude-x\"") != NULL);
|
||||
CHECK(strstr(req.p, "\"max_tokens\":") != NULL);
|
||||
CHECK(strstr(req.p, "\"system\":[{\"type\":\"text\",\"text\":"
|
||||
"\"be brief\"}]") != NULL);
|
||||
CHECK(strstr(req.p, "\"role\":\"system\"") == NULL);
|
||||
CHECK(strstr(req.p, "\"content\":[{\"type\":\"text\","
|
||||
"\"text\":\"say \\\"hi\\\"\"}]") != NULL);
|
||||
CHECK(strstr(req.p, "\"stream\":false") != NULL);
|
||||
CHECK(strstr(req.p, "\"name\":\"read\"") != NULL);
|
||||
CHECK(strstr(req.p, "\"input_schema\":") != NULL);
|
||||
CHECK(strstr(req.p, "\"parameters\"") == NULL);
|
||||
|
||||
/* streaming flips the flag and nothing else */
|
||||
CHECK(sp_anthropic_request(&conv, "claude-x", ®, 1, 0, &req) == 0);
|
||||
CHECK(strstr(req.p, "\"stream\":true") != NULL);
|
||||
|
||||
/*
|
||||
* An OAuth token needs Claude Code's first system block, because the API
|
||||
* refuses the token otherwise. The operator's own prompt follows it.
|
||||
*/
|
||||
CHECK(sp_anthropic_request(&conv, "claude-x", ®, 0, 1, &req) == 0);
|
||||
CHECK(strstr(req.p, "\"system\":[{\"type\":\"text\",\"text\":"
|
||||
"\"You are a Claude agent, built on Anthropic's Claude Agent SDK.\"},"
|
||||
"{\"type\":\"text\",\"text\":\"be brief\"}]") != NULL);
|
||||
|
||||
/* ---- a tool round: tool_use in, tool_result back ---- */
|
||||
{
|
||||
struct sp_msg am;
|
||||
|
||||
memset(&am, 0, sizeof(am));
|
||||
am.role = "assistant";
|
||||
am.content = "I will read it.";
|
||||
am.calls = "[{\"id\":\"toolu_01\",\"name\":\"read\","
|
||||
"\"input\":{\"path\":\"/etc/hosts\"}}]";
|
||||
CHECK(sp_conv_add(&conv, &am) == 0);
|
||||
}
|
||||
{
|
||||
struct sp_msg tm;
|
||||
|
||||
memset(&tm, 0, sizeof(tm));
|
||||
tm.role = "tool";
|
||||
tm.name = "read";
|
||||
tm.call_id = "toolu_01";
|
||||
tm.content = "127.0.0.1 localhost";
|
||||
CHECK(sp_conv_add(&conv, &tm) == 0);
|
||||
}
|
||||
CHECK(sp_anthropic_request(&conv, "claude-x", ®, 0, 0, &req) == 0);
|
||||
CHECK(strstr(req.p, "\"type\":\"tool_use\"") != NULL);
|
||||
CHECK(strstr(req.p, "\"input\":{\"path\":\"/etc/hosts\"}") != NULL);
|
||||
CHECK(strstr(req.p, "\"type\":\"tool_result\"") != NULL);
|
||||
CHECK(strstr(req.p, "\"tool_use_id\":\"toolu_01\"") != NULL);
|
||||
CHECK(strstr(req.p, "\"content\":[{\"type\":\"text\",\"text\":"
|
||||
"\"127.0.0.1 localhost\"}]") != NULL);
|
||||
|
||||
/* a second observation of the same round merges into that user message */
|
||||
{
|
||||
struct sp_msg am, tm;
|
||||
|
||||
memset(&am, 0, sizeof(am));
|
||||
am.role = "assistant";
|
||||
am.calls = "[{\"id\":\"toolu_02\",\"name\":\"read\","
|
||||
"\"input\":{\"path\":\"/etc/hostname\"}},"
|
||||
"{\"id\":\"toolu_03\",\"name\":\"read\","
|
||||
"\"input\":{\"path\":\"/etc/timezone\"}}]";
|
||||
CHECK(sp_conv_add(&conv, &am) == 0);
|
||||
memset(&tm, 0, sizeof(tm));
|
||||
tm.role = "tool";
|
||||
tm.call_id = "toolu_02";
|
||||
tm.content = "box\n";
|
||||
CHECK(sp_conv_add(&conv, &tm) == 0);
|
||||
memset(&tm, 0, sizeof(tm));
|
||||
tm.role = "tool";
|
||||
tm.call_id = "toolu_03";
|
||||
tm.content = "error: no such file";
|
||||
CHECK(sp_conv_add(&conv, &tm) == 0);
|
||||
}
|
||||
CHECK(sp_anthropic_request(&conv, "claude-x", ®, 0, 0, &req) == 0);
|
||||
CHECK(strstr(req.p, "\"tool_use_id\":\"toolu_02\"") != NULL);
|
||||
CHECK(strstr(req.p, "\"tool_use_id\":\"toolu_03\"") != NULL);
|
||||
CHECK(strstr(req.p, "\"is_error\":true") != NULL);
|
||||
/* one user message carries both results: count the role markers */
|
||||
{
|
||||
const char *p = req.p;
|
||||
int users = 0, assistants = 0;
|
||||
|
||||
while ((p = strstr(p, "\"role\":\"")) != NULL) {
|
||||
if (strncmp(p + 8, "user\"", 5) == 0)
|
||||
users++;
|
||||
else if (strncmp(p + 8, "assistant\"", 10) == 0)
|
||||
assistants++;
|
||||
p += 8;
|
||||
}
|
||||
CHECK(users == 3); /* the question, then one per round */
|
||||
CHECK(assistants == 2);
|
||||
}
|
||||
|
||||
/* ---- reply: blocks become text and calls ---- */
|
||||
CHECK(sp_anthropic_reply("{\"type\":\"message\",\"content\":["
|
||||
"{\"type\":\"text\",\"text\":\"Let me look.\"},"
|
||||
"{\"type\":\"tool_use\",\"id\":\"toolu_9\",\"name\":\"read\","
|
||||
"\"input\":{\"path\":\"/etc/hosts\"}}],"
|
||||
"\"usage\":{\"input_tokens\":11,\"output_tokens\":7}}",
|
||||
&rep, &err) == 0);
|
||||
CHECK(strcmp(rep.content, "Let me look.") == 0);
|
||||
CHECK(rep.ncalls == 1);
|
||||
CHECK(strcmp(rep.calls[0].id, "toolu_9") == 0);
|
||||
CHECK(strcmp(rep.calls[0].name, "read") == 0);
|
||||
CHECK(strcmp(rep.calls[0].args, "{\"path\":\"/etc/hosts\"}") == 0);
|
||||
CHECK(strstr(rep.calls_json, "\"input\":{\"path\":\"/etc/hosts\"}") !=
|
||||
NULL);
|
||||
CHECK(rep.tokens_in == 11 && rep.tokens_out == 7);
|
||||
sp_reply_free(&rep);
|
||||
|
||||
/* a provider error is quoted, not turned into an empty answer */
|
||||
CHECK(sp_anthropic_reply("{\"type\":\"error\",\"error\":"
|
||||
"{\"type\":\"rate_limit_error\",\"message\":\"slow down\"}}",
|
||||
&rep, &err) != 0);
|
||||
CHECK(strstr(err.p, "slow down") != NULL);
|
||||
|
||||
/* ---- stream: the same reply, one event at a time ---- */
|
||||
sse = sp_as_sse_new();
|
||||
CHECK(sse != NULL);
|
||||
CHECK(sp_as_sse_line(sse, "event: message_start", &delta, &err) == 0);
|
||||
CHECK(sp_as_sse_line(sse, "data: {\"type\":\"message_start\","
|
||||
"\"message\":{\"usage\":{\"input_tokens\":21}}}", &delta,
|
||||
&err) == 0);
|
||||
CHECK(sp_as_sse_line(sse, "data: {\"type\":\"content_block_start\","
|
||||
"\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}",
|
||||
&delta, &err) == 0);
|
||||
CHECK(sp_as_sse_line(sse, "data: {\"type\":\"content_block_delta\","
|
||||
"\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"Hel\"}}",
|
||||
&delta, &err) == SP_STREAM_TEXT);
|
||||
CHECK(strcmp(delta.p, "Hel") == 0);
|
||||
CHECK(sp_as_sse_line(sse, "data: {\"type\":\"content_block_delta\","
|
||||
"\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"lo\"}}",
|
||||
&delta, &err) == SP_STREAM_TEXT);
|
||||
CHECK(sp_as_sse_line(sse, "data: {\"type\":\"content_block_start\","
|
||||
"\"index\":1,\"content_block\":{\"type\":\"tool_use\","
|
||||
"\"id\":\"toolu_1\",\"name\":\"read\",\"input\":{}}}",
|
||||
&delta, &err) == SP_STREAM_TOOL);
|
||||
CHECK(strcmp(delta.p, "read") == 0);
|
||||
CHECK(sp_as_sse_line(sse, "data: {\"type\":\"content_block_delta\","
|
||||
"\"index\":1,\"delta\":{\"type\":\"input_json_delta\","
|
||||
"\"partial_json\":\"{\\\"path\\\":\"}}", &delta, &err) == 0);
|
||||
CHECK(sp_as_sse_line(sse, "data: {\"type\":\"content_block_delta\","
|
||||
"\"index\":1,\"delta\":{\"type\":\"input_json_delta\","
|
||||
"\"partial_json\":\"\\\"/tmp\\\"}\"}}", &delta, &err) == 0);
|
||||
CHECK(sp_as_sse_line(sse, "data: {\"type\":\"content_block_stop\","
|
||||
"\"index\":1}", &delta, &err) == 0);
|
||||
CHECK(sp_as_sse_line(sse, "data: {\"type\":\"message_delta\","
|
||||
"\"delta\":{\"stop_reason\":\"tool_use\"},"
|
||||
"\"usage\":{\"output_tokens\":9}}", &delta, &err) == 0);
|
||||
CHECK(sp_as_sse_line(sse, "data: {\"type\":\"message_stop\"}", &delta,
|
||||
&err) == 0);
|
||||
CHECK(sp_as_sse_done(sse));
|
||||
CHECK(sp_as_sse_finish(sse, &rep, &err) == 0);
|
||||
CHECK(strcmp(rep.content, "Hello") == 0);
|
||||
CHECK(rep.ncalls == 1);
|
||||
CHECK(strcmp(rep.calls[0].args, "{\"path\":\"/tmp\"}") == 0);
|
||||
CHECK(rep.tokens_in == 21 && rep.tokens_out == 9);
|
||||
sp_reply_free(&rep);
|
||||
sp_as_sse_free(sse);
|
||||
|
||||
/* reasoning arrives as its own kind: shown, never used as the answer */
|
||||
sse = sp_as_sse_new();
|
||||
CHECK(sp_as_sse_line(sse, "data: {\"type\":\"content_block_start\","
|
||||
"\"index\":0,\"content_block\":{\"type\":\"thinking\"}}", &delta,
|
||||
&err) == 0);
|
||||
CHECK(sp_as_sse_line(sse, "data: {\"type\":\"content_block_delta\","
|
||||
"\"index\":0,\"delta\":{\"type\":\"thinking_delta\","
|
||||
"\"thinking\":\"hmm\"}}", &delta, &err) == SP_STREAM_THINK);
|
||||
CHECK(sp_as_sse_finish(sse, &rep, &err) == 0);
|
||||
CHECK(strcmp(rep.content, "") == 0);
|
||||
sp_reply_free(&rep);
|
||||
sp_as_sse_free(sse);
|
||||
|
||||
sp_buf_free(&req);
|
||||
sp_buf_free(&err);
|
||||
sp_buf_free(&delta);
|
||||
sp_conv_free(&conv);
|
||||
if (failures == 0) {
|
||||
printf("test_anthropic: ok\n");
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# splinter -- the Anthropic transport against a fake Messages API.
|
||||
#
|
||||
# The fake is as strict as the real endpoint: an OAuth token must arrive as a
|
||||
# Bearer token with the oauth beta, the system prompt must be the top-level
|
||||
# `system` field starting with Claude Code's block, and tools must carry
|
||||
# input_schema. So a run that answers here has a request shape the real API
|
||||
# accepts -- not just a socket that says 200.
|
||||
#
|
||||
# Also checked: streaming and non-streaming give the same answer, a 429 keeps
|
||||
# the provider's own message (instead of "no answer"), and -m picks the pool.
|
||||
set -u
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-as-XXXXXX") || exit 1
|
||||
P=$((22000 + $$ % 20000))
|
||||
trap 'kill $FP 2>/dev/null; rm -rf "$D"' EXIT
|
||||
fails=0
|
||||
check() { d=$1; shift; if "$@"; then :; else echo "FAIL $d"; fails=$((fails + 1)); fi; }
|
||||
|
||||
mkdir -p "$D/home"
|
||||
python3 -I tests/fake_anthropic.py "$P" "$D/req.log" &
|
||||
FP=$!
|
||||
for i in $(seq 1 50); do
|
||||
curl -s -o /dev/null "http://127.0.0.1:$P/" && break
|
||||
sleep 0.2
|
||||
done
|
||||
|
||||
cat > "$D/home/splinter.conf" <<CONF
|
||||
core { default = duo }
|
||||
provider api0 {
|
||||
about = "anthropic, Konto 0"
|
||||
kind = anthropic
|
||||
endpoint = http://127.0.0.1:$P/v1/messages
|
||||
model = claude-sonnet-5-5
|
||||
tags = [analyze, decide]
|
||||
key = "sk-ant-oat01-test-token"
|
||||
}
|
||||
provider api1 {
|
||||
about = "anthropic, am Limit"
|
||||
kind = anthropic
|
||||
endpoint = http://127.0.0.1:$P/v1/messages
|
||||
model = claude-limit
|
||||
key_env = SPLINTER_TEST_OAUTH
|
||||
}
|
||||
pool duo { members = [api0] strategy = balance }
|
||||
CONF
|
||||
export HOME="$D/home" SPLINTER_USAGE_DIR="$D/usage"
|
||||
export SPLINTER_COOLDOWN_DIR="$D/cd"
|
||||
export SPLINTER_TEST_OAUTH="sk-ant-oat01-second-token"
|
||||
|
||||
# one answer, streamed (the default for -p) and as one whole reply
|
||||
./splinter --config "$D/home/splinter.conf" -m api0 -p hallo </dev/null \
|
||||
> "$D/o1.txt" 2>&1
|
||||
check "a streamed anthropic answer arrives" grep -q 'weiter gemacht' "$D/o1.txt"
|
||||
./splinter --config "$D/home/splinter.conf" -m api0 --no-stream -p hallo \
|
||||
</dev/null > "$D/o2.txt" 2>&1
|
||||
check "a whole anthropic reply arrives" grep -q 'weiter gemacht' "$D/o2.txt"
|
||||
|
||||
# -m with the pool name reaches the same provider
|
||||
./splinter --config "$D/home/splinter.conf" -m duo --no-stream -p hallo \
|
||||
</dev/null > "$D/o3.txt" 2>&1
|
||||
check "the pool name selects the member" grep -q 'weiter gemacht' "$D/o3.txt"
|
||||
|
||||
# the request says anthropic, not openai
|
||||
check "the endpoint was addressed" grep -q '^/v1/messages' "$D/req.log"
|
||||
check "the system prompt is top level" grep -q '"system":\[{"type":"text"' \
|
||||
"$D/req.log"
|
||||
check "tools carry input_schema" grep -q '"input_schema"' "$D/req.log"
|
||||
check "no chat/completions shape leaked in" \
|
||||
test "$(grep -c 'tool_calls' "$D/req.log")" -eq 0
|
||||
|
||||
# a limit keeps the provider's own sentence and the HTTP status; on_limit=fail
|
||||
# so the run says it now instead of waiting for the window to move
|
||||
cat > "$D/home/limit.conf" <<CONF
|
||||
core { default = solo on_limit = fail }
|
||||
provider solo {
|
||||
kind = anthropic
|
||||
endpoint = http://127.0.0.1:$P/v1/messages
|
||||
model = claude-limit
|
||||
key_env = SPLINTER_TEST_OAUTH
|
||||
}
|
||||
CONF
|
||||
./splinter --config "$D/home/limit.conf" --no-stream -p hallo \
|
||||
</dev/null > "$D/o4.txt" 2>&1
|
||||
rc=$?
|
||||
check "a 429 is not reported as an empty answer" grep -q 'rate limit' \
|
||||
"$D/o4.txt"
|
||||
check "a 429 fails the turn" test "$rc" -ne 0
|
||||
|
||||
if [ "$fails" -eq 0 ]; then echo "test_anthropic: ok"; exit 0; fi
|
||||
cat "$D/o1.txt" "$D/o2.txt" "$D/o3.txt" "$D/o4.txt"
|
||||
exit 1
|
||||
@@ -12,10 +12,12 @@
|
||||
* another splinter session gets another id. A fake opencode shows the same
|
||||
* for --session.
|
||||
*/
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
@@ -33,6 +35,22 @@ static int failures;
|
||||
|
||||
static char tdir[256];
|
||||
|
||||
/* the operator pressing Ctrl-C: set the turn's flag a moment after the start */
|
||||
static volatile int cancel_now;
|
||||
|
||||
static void *
|
||||
set_cancel_soon(void *ctx)
|
||||
{
|
||||
struct timespec ts;
|
||||
|
||||
(void)ctx;
|
||||
ts.tv_sec = 0;
|
||||
ts.tv_nsec = 300000000L;
|
||||
(void)nanosleep(&ts, NULL);
|
||||
cancel_now = 1;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void
|
||||
write_exec(const char *name, const char *body)
|
||||
{
|
||||
@@ -154,6 +172,32 @@ main(void)
|
||||
CHECK(strstr(err.p, "kaputt") != NULL);
|
||||
sp_reply_free(&rep);
|
||||
|
||||
/*
|
||||
* Ctrl-C while the program runs. This is the freeze: the transport used
|
||||
* popen() and read the pipe with no way to stop it, so a `claude -p` turn
|
||||
* held the UI's join for as long as the program kept talking.
|
||||
*/
|
||||
{
|
||||
struct sp_host *hk;
|
||||
pthread_t th;
|
||||
time_t t0;
|
||||
|
||||
hk = host_for(®, &ag, "sleep 60", &err);
|
||||
sp_buf_clear(&err);
|
||||
memset(&rep, 0, sizeof(rep));
|
||||
cancel_now = 0;
|
||||
sp_openai_set_cancel(&cancel_now);
|
||||
CHECK(pthread_create(&th, NULL, set_cancel_soon, NULL) == 0);
|
||||
t0 = time(NULL);
|
||||
CHECK(one_turn(hk, "hallo", &rep, &err) == -1);
|
||||
CHECK(time(NULL) - t0 < 10);
|
||||
CHECK(strstr(err.p, "cancelled") != NULL);
|
||||
CHECK(pthread_join(th, NULL) == 0);
|
||||
sp_openai_set_cancel(NULL);
|
||||
sp_reply_free(&rep);
|
||||
sp_host_free(hk);
|
||||
}
|
||||
|
||||
/* ---- sessions ---- */
|
||||
{
|
||||
struct sp_host *hc, *ho, *hp;
|
||||
|
||||
+1
-1
@@ -185,7 +185,7 @@ main(void)
|
||||
CHECK(c2.delegate[3].prio > 0);
|
||||
}
|
||||
CHECK(strcmp(c.exit[0].endpoint,
|
||||
"https://ollama.com/v1/chat/completions") == 0);
|
||||
"https://ollama.com/v1") == 0);
|
||||
(void)unsetenv("OLLAMA_KEY");
|
||||
(void)unsetenv("OLLAMA_KEY_0");
|
||||
(void)unsetenv("OLLAMA_KEY_1");
|
||||
|
||||
+20
-2
@@ -18,6 +18,7 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
@@ -213,6 +214,23 @@ start_http_server(int *port)
|
||||
}
|
||||
}
|
||||
|
||||
/* the servers connect in the background: wait for a tool to appear */
|
||||
static const struct sp_tool *
|
||||
wait_tool(struct sp_registry *r, const char *name)
|
||||
{
|
||||
int k;
|
||||
|
||||
for (k = 0; k < 100; k++) {
|
||||
const struct sp_tool *t = sp_registry_find(r, name);
|
||||
struct timespec ts = { 0, 100000000L };
|
||||
|
||||
if (t != NULL)
|
||||
return t;
|
||||
nanosleep(&ts, NULL);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int
|
||||
main(void)
|
||||
{
|
||||
@@ -249,7 +267,7 @@ main(void)
|
||||
fprintf(stderr, "load: %s\n", err.p);
|
||||
|
||||
/* a 40 KiB tools/list, behind a notification in the same write */
|
||||
t = sp_registry_find(®, "mcp_big");
|
||||
t = wait_tool(®, "mcp_big");
|
||||
CHECK(t != NULL);
|
||||
if (t != NULL) {
|
||||
CHECK(strlen(t->description) == 40000);
|
||||
@@ -302,7 +320,7 @@ main(void)
|
||||
&err2) == 0);
|
||||
if (err2.len > 0)
|
||||
fprintf(stderr, "http load: %s\n", err2.p);
|
||||
t = sp_registry_find(®2, "mcp_http_tool");
|
||||
t = wait_tool(®2, "mcp_http_tool");
|
||||
CHECK(t != NULL);
|
||||
if (t != NULL) {
|
||||
struct sp_buf out2;
|
||||
|
||||
+114
-20
@@ -94,26 +94,6 @@ main(void)
|
||||
CHECK(sp_provider_find(&cfg, "far", &idx) == 1 && idx == 1);
|
||||
CHECK(sp_provider_find(&cfg, "nope", &idx) == 0);
|
||||
|
||||
/* what /connect must refuse before it becomes a line nobody can read */
|
||||
CHECK(sp_provider_id_ok("ocgo") == 1);
|
||||
CHECK(sp_provider_id_ok("my-prov_2") == 1);
|
||||
CHECK(sp_provider_id_ok("Main") == 0);
|
||||
CHECK(sp_provider_id_ok("main") == 0);
|
||||
CHECK(sp_provider_id_ok("a b") == 0);
|
||||
CHECK(sp_provider_id_ok("") == 0);
|
||||
CHECK(sp_provider_endpoint_ok("http://127.0.0.1:11434/v1/chat/completions") == 1);
|
||||
CHECK(sp_provider_endpoint_ok("https://x/v1") == 1);
|
||||
CHECK(sp_provider_endpoint_ok("x/v1") == 0);
|
||||
CHECK(sp_provider_endpoint_ok("http://x/a b") == 0);
|
||||
CHECK(sp_provider_endpoint_ok("http://x/a|b") == 0);
|
||||
CHECK(sp_provider_model_ok("deepseek-v4.1-flash") == 1);
|
||||
CHECK(sp_provider_model_ok("") == 0);
|
||||
CHECK(sp_provider_model_ok("a|b") == 0);
|
||||
CHECK(sp_provider_key_ok("OPENCODE_GO_API_KEY") == 1);
|
||||
CHECK(sp_provider_key_ok("") == 1);
|
||||
CHECK(sp_provider_key_ok("1BAD") == 0);
|
||||
CHECK(sp_provider_key_ok("has-dash") == 0);
|
||||
|
||||
/* add: one line, and the config remembers it */
|
||||
CHECK(sp_buf_init(&err) == 0);
|
||||
CHECK(sp_provider_add(&cfg, drop, "ocgo",
|
||||
@@ -219,6 +199,120 @@ main(void)
|
||||
CHECK(strstr(line, "key_env=K") != NULL);
|
||||
|
||||
sp_buf_free(&err);
|
||||
/*
|
||||
* A selector as one provider: a pool picks a member, "pool/model" picks
|
||||
* the member and keeps the model, and a bare id is itself. This is what
|
||||
* -m and /model accept, so the kind travels with the choice: a pool of
|
||||
* anthropic members must not be applied as an OpenAI endpoint.
|
||||
*/
|
||||
{
|
||||
struct sp_provider sel;
|
||||
char model[64];
|
||||
|
||||
cfg.ndelegates++;
|
||||
snprintf(cfg.delegate[3].id, 32, "api0");
|
||||
snprintf(cfg.delegate[3].kind, 16, "anthropic");
|
||||
snprintf(cfg.delegate[3].endpoint, 512,
|
||||
"https://api.anthropic.com/v1/messages");
|
||||
snprintf(cfg.delegate[3].model, 256, "claude-sonnet-5-5");
|
||||
cfg.ndelegates++;
|
||||
snprintf(cfg.delegate[4].id, 32, "api1");
|
||||
snprintf(cfg.delegate[4].kind, 16, "anthropic");
|
||||
snprintf(cfg.delegate[4].endpoint, 512,
|
||||
"https://api.anthropic.com/v1/messages");
|
||||
snprintf(cfg.delegate[4].model, 256, "claude-sonnet-5-5");
|
||||
snprintf(cfg.pool[cfg.npools].id, 32, "accounts");
|
||||
snprintf(cfg.pool[cfg.npools].strategy, 16, "balance");
|
||||
snprintf(cfg.pool[cfg.npools].member[0], 32, "api0");
|
||||
snprintf(cfg.pool[cfg.npools].member[1], 32, "api1");
|
||||
cfg.pool[cfg.npools].nmembers = 2;
|
||||
cfg.npools++;
|
||||
|
||||
CHECK(sp_provider_select(&cfg, "accounts", &sel, model,
|
||||
sizeof(model)) == 0);
|
||||
CHECK(strcmp(sel.kind, "anthropic") == 0);
|
||||
CHECK(model[0] != '\0');
|
||||
CHECK(sp_provider_select(&cfg, "accounts/opus-5-5", &sel, model,
|
||||
sizeof(model)) == 0);
|
||||
CHECK(strcmp(model, "opus-5-5") == 0);
|
||||
CHECK(sp_provider_select(&cfg, "api0", &sel, model,
|
||||
sizeof(model)) == 0);
|
||||
CHECK(strcmp(sel.id, "api0") == 0);
|
||||
CHECK(sp_provider_select(&cfg, "nope", &sel, model,
|
||||
sizeof(model)) != 0);
|
||||
}
|
||||
|
||||
/*
|
||||
* A saved anthropic choice keeps its kind: without the line the next
|
||||
* start would speak OpenAI at the Messages API and get a 400.
|
||||
*/
|
||||
{
|
||||
struct sp_provider pick;
|
||||
struct sp_buf merr;
|
||||
char mp[800], mb[1024];
|
||||
FILE *mf;
|
||||
|
||||
memset(&pick, 0, sizeof(pick));
|
||||
snprintf(pick.id, sizeof(pick.id), "api0");
|
||||
snprintf(pick.kind, sizeof(pick.kind), "anthropic");
|
||||
snprintf(pick.endpoint, sizeof(pick.endpoint),
|
||||
"https://api.anthropic.com/v1/messages");
|
||||
snprintf(pick.model, sizeof(pick.model), "claude-sonnet-5-5");
|
||||
snprintf(pick.key_env, sizeof(pick.key_env), "CLAUDE_TOKEN");
|
||||
CHECK(sp_buf_init(&merr) == 0);
|
||||
CHECK(sp_provider_save_choice(&back, &pick, &merr) == 0);
|
||||
snprintf(mp, sizeof(mp), "%s.d/90-model.conf", mainconf);
|
||||
mf = fopen(mp, "r");
|
||||
CHECK(mf != NULL);
|
||||
if (mf != NULL) {
|
||||
CHECK(fgets(mb, sizeof(mb), mf) != NULL);
|
||||
CHECK(fgets(mb, sizeof(mb), mf) != NULL);
|
||||
CHECK(strcmp(mb, "kind = anthropic\n") == 0);
|
||||
fclose(mf);
|
||||
}
|
||||
sp_buf_free(&merr);
|
||||
}
|
||||
|
||||
/* what /connect must refuse before it becomes a line nobody can read */
|
||||
CHECK(sp_provider_id_ok("ocgo") == 1);
|
||||
CHECK(sp_provider_id_ok("my-prov_2") == 1);
|
||||
CHECK(sp_provider_id_ok("Main") == 0);
|
||||
CHECK(sp_provider_id_ok("main") == 0);
|
||||
CHECK(sp_provider_id_ok("a b") == 0);
|
||||
CHECK(sp_provider_id_ok("") == 0);
|
||||
CHECK(sp_provider_endpoint_ok("http://127.0.0.1:11434/v1/chat/completions") == 1);
|
||||
|
||||
/* the config names the base; every route is built from it */
|
||||
{
|
||||
char u[256];
|
||||
|
||||
CHECK(strcmp(sp_endpoint_url("https://h/v1", "chat/completions",
|
||||
u, sizeof(u)), "https://h/v1/chat/completions") == 0);
|
||||
CHECK(strcmp(sp_endpoint_url("https://h/v1/", "models", u,
|
||||
sizeof(u)), "https://h/v1/models") == 0);
|
||||
CHECK(strcmp(sp_endpoint_url("https://h/v1/chat/completions",
|
||||
"models", u, sizeof(u)), "https://h/v1/models") == 0);
|
||||
CHECK(strcmp(sp_endpoint_url("https://h/v1/chat/completions",
|
||||
"chat/completions", u, sizeof(u)),
|
||||
"https://h/v1/chat/completions") == 0);
|
||||
CHECK(strcmp(sp_endpoint_url("https://api.anthropic.com/v1/messages",
|
||||
"models", u, sizeof(u)),
|
||||
"https://api.anthropic.com/v1/models") == 0);
|
||||
CHECK(strcmp(sp_endpoint_url("https://h/v1/messages", NULL, u,
|
||||
sizeof(u)), "https://h/v1") == 0);
|
||||
}
|
||||
CHECK(sp_provider_endpoint_ok("https://x/v1") == 1);
|
||||
CHECK(sp_provider_endpoint_ok("x/v1") == 0);
|
||||
CHECK(sp_provider_endpoint_ok("http://x/a b") == 0);
|
||||
CHECK(sp_provider_endpoint_ok("http://x/a|b") == 0);
|
||||
CHECK(sp_provider_model_ok("deepseek-v4.1-flash") == 1);
|
||||
CHECK(sp_provider_model_ok("") == 0);
|
||||
CHECK(sp_provider_model_ok("a|b") == 0);
|
||||
CHECK(sp_provider_key_ok("OPENCODE_GO_API_KEY") == 1);
|
||||
CHECK(sp_provider_key_ok("") == 1);
|
||||
CHECK(sp_provider_key_ok("1BAD") == 0);
|
||||
CHECK(sp_provider_key_ok("has-dash") == 0);
|
||||
|
||||
printf("%s", failures == 0 ? "test_providers: ok\n" : "");
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -130,5 +130,25 @@ typed '!echo noch-da'; key Enter
|
||||
check shows 'noch-da'
|
||||
check test "$(quit_code)" = 0
|
||||
|
||||
# ---- Ctrl-C during a running request ----
|
||||
# The cli transport had no way to stop its child: Ctrl-C set the flag, the
|
||||
# worker stayed in popen(), and the join froze the screen until the program
|
||||
# finished by itself. The prompt must come back within a couple of seconds.
|
||||
[ -n "$F" ] && kill "$F" 2>/dev/null
|
||||
F=
|
||||
killserver
|
||||
rm -f "$D/rc"
|
||||
tmux new-session -d -s $S -x 110 -y 30 "HOME=$D/home SPLINTER_LOCALE=en \
|
||||
SPLINTER_CLI_CMD='sleep 60' ./splinter --no-config --transport cli \
|
||||
--plugin plugins/cli/cli.so --chat 2>/dev/null; echo \$? > $D/rc"
|
||||
check shows 'Enter sends'
|
||||
typed 'tu was'; key Enter
|
||||
check shows 'working'
|
||||
sleep 0.5
|
||||
key C-c
|
||||
check shows 'cancelled'
|
||||
check shows '^>'
|
||||
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