ext/src/splinter: the old in-tree copy leaves the index
It was committed as ordinary files, so a submodule entry could not be added
("already exists in the index"). The fork is replaced by the submodule of
git.kropa.tech/hiddenbox/splinter.
This commit is contained in:
1 parent
c723c7f277
commit
4c4bc9ade0
984 files changed
-160274
No files matched your search
@@ -1,24 +0,0 @@
|
||||
*.o
|
||||
splinter
|
||||
splinterctl
|
||||
tests/test_buf
|
||||
tests/test_tool
|
||||
tests/test_session
|
||||
tests/test_transport
|
||||
tests/test_agent
|
||||
|
||||
# build artefacts: a .so in git is a .so that conflicts on every build
|
||||
*.so
|
||||
plugins/*/*.so
|
||||
tests/test_*
|
||||
!tests/test_*.c
|
||||
!tests/test_*.sh
|
||||
|
||||
# python bytecode from the test helpers
|
||||
__pycache__/
|
||||
src/backend/catalogs.c
|
||||
src/backend/buildinfo.c
|
||||
|
||||
# Claude Code worktrees and local session state
|
||||
.claude/
|
||||
.splinter-swarm.sock
|
||||
@@ -1,455 +0,0 @@
|
||||
# CHAOS — every idea from the three harness attempts
|
||||
|
||||
**Stand: 2026-11-06.** Collected while planning a new agent harness of our own.
|
||||
Everything below was read out of the existing trees, not invented. Line counts
|
||||
and file references are what the trees actually contain at this date.
|
||||
|
||||
## Provenance — what was read
|
||||
|
||||
| Tree | Location | Size / state |
|
||||
|---|---|---|
|
||||
| MikroAgent | `~/src/MikroAgent` (kitt) | 12,530 lines C99, 17 test binaries, `make check` green, 100,768 B binary, ~4 MB RSS, 0 CPU idle, 2 commits (`e21a11c` Phase 11, `b880a40` Phase 10) |
|
||||
| OpenITT | `~/src/OpenITT` (kontron) | single binary + `libopenitt.a`, 381 tests / 0 failures, docs ≈3,000 lines, **not a git repo** |
|
||||
| agentk | `~/src/agentk` (kitt) | **no code**: 852-line plan `refs/agentk-implementation-plan.md`, 15 skills under `.agents/skills/`, 26 research refs, 5 open tasks in `.tasks/` |
|
||||
|
||||
Read in full: `MikroAgent/docs/{design.md,architecture.md,performance.md}`,
|
||||
`MikroAgent/AGENTS.md`, `OpenITT/OPENITT-OVERVIEW.md`,
|
||||
`OpenITT/specs/{compression-algorithm.md,long-input-design.md,notes-loop-pitch.md}`,
|
||||
`OpenITT/TOOLS.md`, `agentk/refs/agentk-implementation-plan.md` (selected
|
||||
sections), `agentk/.tasks/*.md`.
|
||||
|
||||
---
|
||||
|
||||
# A. MikroAgent — the engine that already runs
|
||||
|
||||
## Transport layer
|
||||
|
||||
1. **Transport vtable**: `send() → {status, body}`, optional `send_stream()`
|
||||
handing **raw bytes** to a callback. The transport never parses JSON or SSE,
|
||||
so a mock, a libcurl adapter and any future provider share one seam.
|
||||
2. **Deterministic mock transport**: replies queued FIFO; `send_stream()`
|
||||
replays a queued body in **caller-chosen chunk sizes**; records the last
|
||||
request body and a request count. This is how fragmented-argument handling
|
||||
is tested with no network and no paid endpoint.
|
||||
3. **SSE framer is the only module that knows `\n\n`**: buffers partial lines
|
||||
across reads, ignores comments and non-`data` fields, strips an optional
|
||||
`\r`, reports an unterminated final event.
|
||||
4. **Wire isolation**: only `model/openai.c` knows the OpenAI shape; tool-call
|
||||
fragments are merged by `index`, and **a fragment never yields a call until
|
||||
the stream finishes**.
|
||||
5. **Raw `arguments` kept as a JSON string**, never parsed into an object at
|
||||
parse time — preserves exactly what the model sent for the audit trail and
|
||||
defers parsing to execution, because the API states arguments may be invalid
|
||||
JSON.
|
||||
|
||||
## Agent loop
|
||||
|
||||
6. Budget checked **before every request**; authorization callback before every
|
||||
non-read tool; **never a call without its result**.
|
||||
7. **Authorization as a callback with fail-closed default**: with no callback,
|
||||
reads run and everything else is denied — the denial is delivered to the
|
||||
model *as the tool's observation*. Enforcement lives in the tool-execution
|
||||
layer, never in the system prompt (the prompt explains, it never decides).
|
||||
8. **Three policies**: read-only, confirm-mutations (default), configured
|
||||
autonomous. The prompt shows tool name, class and the **exact `arguments`
|
||||
JSON**; anything but `y`/`yes` is denial; no stdin (`-p` plus a mutating
|
||||
tool) fails closed.
|
||||
|
||||
## Persistence
|
||||
|
||||
9. **One directory per session**: `meta` as `key = value`, written atomically
|
||||
(`meta.tmp` → `rename()`); `messages.jsonl` opened `O_APPEND`.
|
||||
10. **Crash model**: a crash can only truncate the tail, so recovery replays
|
||||
complete lines and discards one partial line, reporting a `recovered` flag.
|
||||
A **complete** line that is not a valid message object is corruption and
|
||||
fails the load.
|
||||
11. Session ids default to `sess-<time>-<pid>`; an existing session is resumed
|
||||
even without `--resume` (history is never silently dropped), while
|
||||
`--resume` of a missing id is an error.
|
||||
12. **System prompt inserted only into an empty history** — never reordered,
|
||||
never duplicated on resume, and deliberately *not* stored in `meta`, because
|
||||
reconstructing it there would risk drift from what the model actually saw.
|
||||
|
||||
## Tools
|
||||
|
||||
13. `read_file` (offset/limit bytes, `MA_AUTH_READ`, `max_read_bytes`, marks
|
||||
truncation), `write_file` (atomic temp + `rename` in the target directory),
|
||||
`list_dir` (sorted, directories suffixed `/`), `run_command`
|
||||
(`MA_AUTH_DESTRUCTIVE`, `/bin/sh -c` in the workspace root, stdout+stderr
|
||||
merged, output capped, `waitpid` status reported, timeout **kills the child
|
||||
process group** and is reported explicitly).
|
||||
14. **No shell for git**: `git` = closed allowlist
|
||||
(`status|diff|log|show|ls-files|branch`) with fixed flags, `log` bounded to
|
||||
`--oneline -n 50`, `core.pager=cat` so a pager can never swallow output;
|
||||
`git_commit` = `MA_AUTH_MUTATE`, paths validated and passed after `add --`.
|
||||
15. **Option-smuggling defence**: user strings become single argv entries, must
|
||||
not start with `-`, must contain no whitespace or control characters —
|
||||
refused *before* any fork. Rule behind it: the approved action and the
|
||||
executed action must be byte-identical.
|
||||
16. **`subproc` helper** shared by every exec-style tool: pipe+fork, `dup2`
|
||||
merged output, `setpgid` + kill-group on deadline, non-blocking drain into a
|
||||
buffer with byte cap and explicit `truncated` flag, `waitpid` with EINTR
|
||||
retry, structured result (status, signal, timeout). Callers phrase the
|
||||
observation; the helper never annotates.
|
||||
|
||||
## Compaction
|
||||
|
||||
17. **Compaction is a runtime window, never a rewrite**: `view_start` is
|
||||
runtime-only, monotonic, **pair-safe** (a cut never lands on a tool
|
||||
message), bounded (never cuts at the current user turn), and a failed
|
||||
attempt restores the previous window.
|
||||
18. The wire carries **only the count** of omitted messages in a system marker
|
||||
— no model-written summary, because a summary that paraphrases dropped text
|
||||
is fabrication.
|
||||
19. Stored history and the session log stay untouched, so a resume sees
|
||||
everything and compaction is recomputed from scratch.
|
||||
|
||||
## Budget and tokens
|
||||
|
||||
20. 32k default context, `output_reserve` 4096; the budget **refuses rather
|
||||
than letting the endpoint truncate**.
|
||||
21. **Three-tier token counting** as a pluggable vtable: verified tokenizer >
|
||||
calibration from server-reported usage > conservative estimator.
|
||||
22. **Usage-calibrated counter**: the latest `(estimate, prompt_tokens)` pair
|
||||
anchors a linear rescale `ceil(P × E'/E) × (1 + margin)`, pure integer with
|
||||
saturating overflow. A report ≤ 0 never moves the anchor; an absurd report
|
||||
saturates so the budget fails **closed**. Overwritten, never compounded,
|
||||
never persisted.
|
||||
23. **Never requests `stream_options.include_usage`** — it is an extension some
|
||||
compatible backends reject; usage is taken when volunteered.
|
||||
|
||||
## Runaway protection
|
||||
|
||||
24. **Identical-failure limit** (default 3): 64-bit FNV-1a over
|
||||
`(name, arguments, observation)` in a fixed 8-slot recycling window. It
|
||||
counts **only harness-classified failures** — unknown tool, unparseable
|
||||
arguments, policy denial, missing implementation, `run()` failure. A
|
||||
delivered `[exit status 3]` is a *successful* call; grepping output for
|
||||
`error:` would couple the loop to phrasing no contract promises.
|
||||
25. Including the **observation** in the signature means a same-argument retry
|
||||
whose situation changed resets the count: the limit stops *repetition
|
||||
without progress*, not retries.
|
||||
26. **Turn deadline** (`max_turn_ms`, default 600000, `CLOCK_MONOTONIC`)
|
||||
checked **only at safe boundaries**: before building each request and
|
||||
before executing each call of a batch. A mid-batch cut answers every
|
||||
remaining call with `error: turn time limit reached` instead of dropping it,
|
||||
so call/result pairing survives.
|
||||
27. **A failed clock read fails closed** (budget reported spent) rather than
|
||||
running unbounded.
|
||||
|
||||
## Operator control and audit
|
||||
|
||||
28. **Cancel latch**: `volatile sig_atomic_t` polled inside the curl write
|
||||
callbacks. The handler is installed in **every** mode, including replacing
|
||||
an inherited `SIG_IGN` — a backgrounded `-p` run otherwise never sees
|
||||
SIGINT. (This was a real bug caught by an end-to-end test.)
|
||||
29. Distinguishes `cancelled=2` (operator) from `cancelled=1` (consumer parse
|
||||
abort) so error text never misattributes the cause.
|
||||
30. The turn persists its tail **before** printing; Ctrl-C prints
|
||||
`[interrupted -- the session is saved]` and exits 0.
|
||||
31. **Two audit event kinds** in `audit.jsonl`: `decision` (tool, class,
|
||||
approved/denied, reason, args) and `result` (timestamp, tool, call id,
|
||||
observation byte count, UTF-8-safe 200-byte prefix). Read-class results are
|
||||
audited too; full observations stay in `messages.jsonl`.
|
||||
32. **Observation hook** fires once per completed call (executed, denied,
|
||||
unknown, bad arguments) *before* the result is appended — the auditor records
|
||||
exactly what the model will see.
|
||||
|
||||
## Display
|
||||
|
||||
33. Streaming shows only **accepted content deltas**, never tool-argument
|
||||
fragments (partial JSON is not assistant speech), via suffix diffing per SSE
|
||||
event.
|
||||
34. **Display-only authority**: history is appended exactly once from the merged
|
||||
result. If the stream breaks, the user saw text that no history entry
|
||||
received — visible as a turn error, never as a silent lie.
|
||||
35. Harness output (approval prompts, tool events, `[error:]`) always starts on
|
||||
a fresh row; model text and harness text never share a line.
|
||||
|
||||
## Endpoint security
|
||||
|
||||
36. **`endpoint.c` owns the never-downgrade rule** in pure C, testable without
|
||||
libcurl: https for any host; plaintext http **only** for `localhost`,
|
||||
`127.0.0.0/8`, `[::1]`; credentials in the URL (`@`), query, fragment,
|
||||
spaces, control characters and percent-encoded hosts are rejected; the
|
||||
bearer token comes only from a named environment variable.
|
||||
37. libcurl adapter: TLS verification set **explicitly** so a later edit cannot
|
||||
disable it by accident; **`FOLLOWLOCATION = 0`** because a redirect could
|
||||
move the bearer token to another host; `CURLOPT_TIMEOUT_MS`, `NOSIGNAL`; the
|
||||
key is copied at open and never reaches an error string (only
|
||||
`curl_easy_strerror`).
|
||||
38. A non-zero return from the consumer callback aborts the transfer — the agent
|
||||
never sees a partially delivered success.
|
||||
|
||||
## Build and test
|
||||
|
||||
39. `./configure` is POSIX sh, **compiles and links probe programs** instead of
|
||||
checking version strings, preserves `CC/CFLAGS/CPPFLAGS/LDFLAGS/LIBS`, and
|
||||
writes `config.mk`.
|
||||
40. Makefile is **POSIX make + `?=` only** — runs under GNU make *and* bmake; no
|
||||
`$(shell)`, no `ifeq`, no target-specific variables, no `$^`.
|
||||
41. Flags: `-std=c99 -Wall -Wextra -Wpedantic -Werror -D_POSIX_C_SOURCE=200809L`.
|
||||
42. **DEPS hammer**: every object pinned to every internal header, because POSIX
|
||||
suffix rules carry no header dependencies. This bit them for real — a test
|
||||
binary linked against a stale object with the old struct layout and read
|
||||
`cfg.compact` past the field count.
|
||||
43. Test suite: plain C programs with a `failures` counter, no framework. The
|
||||
mock covers normal text, single/multiple tool calls, fragmented arguments,
|
||||
malformed arguments, unknown tools, tool failure, 401/429, context overflow,
|
||||
step and tool-call limits. The curl adapter is tested against a **forked
|
||||
loopback HTTP server**; git tests skip cleanly when git is absent.
|
||||
44. **Performance as a regression contract**: idle REPL 0 CPU ticks, ~4 MB RSS,
|
||||
~5 ms local work per turn, ~2.4 ms startup, ~100 KB binary — with the
|
||||
rejected optimizations documented so nobody optimizes them back in.
|
||||
|
||||
---
|
||||
|
||||
# B. OpenITT — the data model and the low-memory discipline
|
||||
|
||||
## The five core invariants
|
||||
|
||||
45. **External data has no inherent size limit** — model output, reasoning, tool
|
||||
output, stdout, stderr, MCP output, files read, session history. "A 1 KiB
|
||||
result and a 1 GiB result must follow the same architectural path."
|
||||
46. **Disk-backed output, RAM-bounded conversation**: the complete artifact may
|
||||
exist on disk while only a bounded representation is in the model
|
||||
conversation.
|
||||
47. **No silent truncation**: any reduction must be explicit and documented;
|
||||
accidental truncation is a bug. Their own bug history is the argument —
|
||||
255-byte tool-argument truncation, 4096-byte SSE line loss, 512-byte digest
|
||||
truncation.
|
||||
48. **Session data is durable truth, RAM is working state.** Compression changes
|
||||
what is loaded, never what is stored.
|
||||
49. **Reasoning is separate from visible content**: provider-supplied
|
||||
`reasoning_content` is streamed, persisted to `<session>.reasoning`, not
|
||||
printed, and not part of the next request unless exposed through a tool.
|
||||
There is **no NLP thought-detector** — if a provider puts reasoning into
|
||||
`content`, it is content.
|
||||
|
||||
## Data flow
|
||||
|
||||
50. **Streaming rule**: `delta → append to disk + bounded metadata + conversation
|
||||
update`. Never `grow an unbounded RAM buffer → write the file afterwards`.
|
||||
A stream may be arbitrarily large while RAM stays flat.
|
||||
51. **`chat_t` is a working set, not the archive**: role, type, identifier, size,
|
||||
**bounded head**, **bounded tail**, disk reference. It must not silently
|
||||
become an unbounded cache of session contents.
|
||||
52. **Turn as a pipeline**: bounded conversation → provider → stream → content to
|
||||
spool, reasoning to reasoning spool, tool calls to the dispatcher → tool
|
||||
execution → output spool → bounded result back into the conversation → next
|
||||
round. A turn ends when the model answers without another tool call.
|
||||
|
||||
## Compression with retrieval
|
||||
|
||||
53. **Collapse**: older rounds are replaced in the active conversation by a
|
||||
structured digest preserving tool name, call id, **full arguments**, exit
|
||||
status, output size, bounded head, bounded tail and a **retrieval id**.
|
||||
54. **Trim**: if the active round alone exceeds the budget and no older round is
|
||||
left, only the active *representation* is reduced to head/tail. The durable
|
||||
record is untouched.
|
||||
55. **Compression must never make information permanently unreachable**: every
|
||||
compressed artifact keeps a stable id the `history` tool can use to fetch the
|
||||
original or further portions back.
|
||||
56. **Context ordering from measured prompt-cache behaviour**: the digest sits at
|
||||
the *start* of the collapsible region, complete rounds are never split, and
|
||||
the live date block sits at the end. Documented as measured behaviour, not as
|
||||
a universal API assumption.
|
||||
|
||||
## Session format and tooling
|
||||
|
||||
57. Sessions are **human-readable plain text**: `[checkpoint id=… pos=…]`,
|
||||
`[message type=user]`, `[tool id=… command=… output=stdout rc=0]`,
|
||||
`[compress]`. Grep-able, `tail`-able, recoverable without a database, no
|
||||
binary serialization.
|
||||
58. `session_load_chat` reconstructs only the active window; the file remains the
|
||||
complete historical record.
|
||||
59. **Tool set**: `system` (shell), `notes`, `history` (search past sessions
|
||||
**and retrieve archived output**), `skill` (instruction files), `mcp`,
|
||||
`reasoning` (retrieve stored provider reasoning), `output` (control streaming
|
||||
behaviour).
|
||||
60. **Tools are lazy**: nothing enters the conversation merely because it exists
|
||||
on disk; the model requests it when needed.
|
||||
61. Notes under `.openitt/notes/`, skills under `.openitt/skills/` — plain files
|
||||
the model loads explicitly.
|
||||
|
||||
## Providers and diagnostics
|
||||
|
||||
62. Provider abstraction covering **OpenAI-compatible (default), Ollama,
|
||||
Anthropic, xAI/OpenCode**; named model blocks with `api_url` and `model`;
|
||||
environment overrides including `OPENITT_MODEL`, `OPENITT_CTX_LIMIT`,
|
||||
`OPENITT_MCP_URL`, `OPENITT_TRACE`, `OPENITT_MAX_TURNS`, `OPENITT_STREAM_STDOUT`.
|
||||
63. **Seven trace levels**: turn, HTTP, body, wire, state, budget, everything.
|
||||
Diagnostics are a first-class feature, not a debug relic.
|
||||
|
||||
## Memory accounting (designed, not implemented)
|
||||
|
||||
64. Memory is a **first-class observable property**, not a single RSS number:
|
||||
per-module current bytes, per-module peak bytes, allocation and free counts,
|
||||
categories — and **lifecycle snapshots** at startup, configuration loaded,
|
||||
model initialized, session opened, conversation loaded, request started,
|
||||
stream active, tool started, tool output spooling, tool completed,
|
||||
compression, turn completed, shutdown.
|
||||
65. Process RSS measured **separately** from library-level allocation accounting.
|
||||
The accounting must not become a significant part of the footprint it
|
||||
measures. An optional debug mode adds address, size, file, line, lifetime and
|
||||
outstanding allocations.
|
||||
66. Targets: working set **below 1 MiB where practical**; 2–3B CPU models as the
|
||||
primary development target with 4B as the practical ceiling; **8k default
|
||||
context but configurable to 1M** — OpenITT imposes no artificial maximum.
|
||||
|
||||
## Architecture split and housekeeping
|
||||
|
||||
67. **`libopenitt` + thin clients**: the library owns the agent and has zero UI
|
||||
assumptions (no curses, no X11, no terminal drawing). `openitt` is the
|
||||
CLI/curses client with curses **imported from `kibson/curses`** rather than
|
||||
written; `xopenitt` is a later X11/Motif client. Clients must not duplicate
|
||||
agent logic.
|
||||
68. **FD discipline**: spools are `open/write/close`, not a `FILE *` held per
|
||||
spool for a whole round — avoids FD accumulation and stdio buffers. Unlinked
|
||||
temp spools at 0600 where appropriate.
|
||||
69. **Export**: `--export <session> --format=ini|json|raw` operating on the
|
||||
**complete** session rather than the reduced `chat_t`, preserving archived
|
||||
tool output, stderr, compression records and reasoning. Read-only.
|
||||
|
||||
## Explicit non-goals
|
||||
|
||||
70. No automatic model delegation, no orchestrator, no per-task model routing.
|
||||
No reasoning classifier. No artificial 8k maximum. No UI in the core library.
|
||||
No database.
|
||||
|
||||
## Testing and benchmarking philosophy
|
||||
|
||||
71. No test framework; project-local `CHECK_*` macros. Every module tested for
|
||||
normal, empty, large, malformed, partial, allocation failure, EOF, repeated
|
||||
operations, cleanup and boundaries.
|
||||
72. **Content-length scaling test**: same behaviour at 1 KiB, 64 KiB, 1 MiB,
|
||||
16 MiB, 256 MiB — memory must stay approximately constant. An
|
||||
output-size-proportional heap allocation is declared an **architectural
|
||||
failure**.
|
||||
73. `bench.sh` measures wall clock, provider latency, context size, compression
|
||||
behaviour, current and peak memory, tool output size, spool behaviour,
|
||||
allocation count and **open-FD behaviour**; trace level 7 is the diagnosis
|
||||
path.
|
||||
|
||||
## Long input — the idea with the highest value for us
|
||||
|
||||
74. Input is staged into the session file with POSIX `open/write/seek`; the model
|
||||
reads **a 2048-token window at a time**, knows it is only the beginning of a
|
||||
huge input, takes notes to disk **with offsets and checkpoints**, compresses
|
||||
locally after each window, and can **seek back and forth** between
|
||||
checkpoints to re-check things.
|
||||
75. Proposed 8k split: 1k fixed behaviour, 2k compressed memory, 2k next chunk,
|
||||
2k room for the new note, 1k headroom (the author's own words: "i have no
|
||||
idea", i.e. a starting point, not a contract).
|
||||
76. It ends by writing a report into `report/` that fits the output limit —
|
||||
instead of today's behaviour, where a 100k-token input is cut to head+tail
|
||||
and the model answers from roughly 10 KB of it.
|
||||
77. **The hard line: compression is never an LLM call.** A deterministic local
|
||||
algorithm in C, same input → same output, runs on the box forever.
|
||||
78. **The specified algorithm** (deterministic log clustering):
|
||||
- Phase 1 line splitting, every line carrying a byte offset and a line number;
|
||||
- Phase 2 **structural hashing** — numbers → `<NUM>`, `0x…` → `<HEX>`,
|
||||
paths → `<PATH>`, so lines that differ only in variable parts share a
|
||||
template;
|
||||
- Phase 3 class aggregation — count, one sample, first offset, and a **signal
|
||||
flag** (ERROR, WARN, FAIL, denied, blocked, panic, segfault, out of memory,
|
||||
cannot, fatal; case-insensitive);
|
||||
- Phase 4 blob with `[header][signal][noise][head_tail]`;
|
||||
- Phase 5 budget enforcement that drops the **noisiest noise classes first,
|
||||
highest count and lowest uniqueness**, and **never drops signal classes**.
|
||||
- Tuning: `signal_keywords`, `noise_class_min_count`,
|
||||
`head_tail_bytes` (default 500), `max_noise_classes` (default 50).
|
||||
- O(n) single pass, hash table for grouping, seekable, 100k lines → maybe 50
|
||||
classes → a tiny blob.
|
||||
79. **The notes loop**: two phases. Phase 1 is an *investigation loop* with its
|
||||
own budget that reads 100 % of the input in 4 KB windows, writing notes plus a
|
||||
**look-back directive** each turn; Phase 2 is the real conversation, which
|
||||
pays only for the conclusion. The user prompt stays fixed during the
|
||||
investigation; one extra API call per turn to the **same** model; the extra
|
||||
call's tokens are counted in the budget pass so the window cannot blow out
|
||||
silently.
|
||||
80. Why it matters: **the reasoning lives on disk as notes**, so a model *without*
|
||||
a reasoning feature still gets a full investigation — and the reasoning is
|
||||
inspectable, diffable, and independent of the model's own reasoning budget.
|
||||
|
||||
---
|
||||
|
||||
# C. agentk — the compaction theory
|
||||
|
||||
81. **`ContextEngine` vtable as the swappable core**: `on_session_start()` →
|
||||
per call `update_from_response(usage)` → per turn
|
||||
`should_compress()` / `compress(messages, current_tokens, focus_topic, force)`
|
||||
→ `on_session_end()` (real session boundaries only). The usage struct carries
|
||||
prompt/completion/total plus optional input/output/**cache_read/cache_write**/
|
||||
reasoning tokens.
|
||||
82. **LCM-style leaf-compaction pipeline**: structural pre-cleanup → ingest into
|
||||
an append-only store (replay-safe view) → fresh-tail anchoring → loop
|
||||
selecting the **oldest leaf chunk** → dependency-filtered summarizer input →
|
||||
`SummaryNode` into a **DAG** → condense leaves into higher nodes → assemble →
|
||||
bump `compression_count`.
|
||||
83. **`SummaryNode`** carries depth (0 = leaf, 1+ = condensed), summary text,
|
||||
token count, **source token count**, **source ids** (store ids or node ids),
|
||||
source type, created/earliest timestamps — lineage survives at every level.
|
||||
84. **Rescue path on summarizer failure**: deterministic recompile, retry with a
|
||||
**smaller chunk**, then L1/L2/L10 truncation as fallback — never uncontrolled
|
||||
output.
|
||||
85. **Structural pre-cleanup before any LLM compaction** — the highest-ROI step:
|
||||
dedup identical tool results and re-reads (keep the newest), canonicalize
|
||||
whitespace and timestamps, purge resolved error messages, mark repeated
|
||||
intermediate states. **15–30 % cut, lossless, zero model calls.**
|
||||
86. **ObservationPack** (from NVIDIA SoL-Pi): repeated large tool results become a
|
||||
**stable handle with exact paged recall** — `ls` over 100 files collapses to
|
||||
`[ObservationPack: 100 entries, 48k tokens]` plus
|
||||
`agentk_pack_page(handle, offset, limit)`. Paired with an
|
||||
**evidence-preserving reducer**: a long log becomes "receipts" only if every
|
||||
kept quote matches the archived source.
|
||||
87. **Structured summary template** as the core trick: `## Session Intent`,
|
||||
`## Files Modified` (full paths), `## Key Decisions`, `## Active Goals`,
|
||||
`## Next Steps`, fed as `custom_instructions`. Justification: freeform
|
||||
summarization scores 2.19–2.45/5 on artifact tracking (Factory.ai benchmark),
|
||||
while a checklist forces explicit "empty" answers instead of silent omission.
|
||||
88. **Prompt-cache rules**: byte-stable system prefix with the `cache_control`
|
||||
breakpoint at the end; append-only history, never editing earlier turns; a
|
||||
`cache_control` marker **on the compaction block itself**; and **no dynamic
|
||||
content in the prefix** — timestamps, session ids and user metadata belong in
|
||||
the last user message. Compaction events and prefix validation get logged.
|
||||
89. **Files over tools**: filesystem-based context engineering (shell + files) met
|
||||
intent 45 % → 75 % versus tool explosion (Azure SRE). Fewer, more general
|
||||
tools; let the filesystem carry the structure.
|
||||
90. **Threaded reactor** (Konrad's later decision, contradicting OpenITT's "no
|
||||
pthread"): the loop thread is the **sole state writer**, tool threads post
|
||||
results through an **mpsc queue**, pipes are **length-framed**, abort is
|
||||
SIGKILL plus a cooperative two-stage cancel.
|
||||
91. Client protocol layer planned as `agentk` (curses) + `xagentk` (X11), with ACP
|
||||
schemas collected in `refs/research/acp-*`.
|
||||
92. **Working method worth keeping unchanged**: every `.tasks/*.md` card carries
|
||||
`finding`, `evidence` (the actual commands and their output), `goal-ref`,
|
||||
`acceptance`, `owner`. A claim without a command is not a card.
|
||||
|
||||
---
|
||||
|
||||
# D. Where the three disagree — decisions a new harness must settle
|
||||
|
||||
- **Compaction.** MikroAgent keeps originals and shrinks only the wire view with a
|
||||
**count marker**; OpenITT collapses into **retrievable digests**; agentk goes
|
||||
further into an **LLM-summarized DAG**. They can be stacked in that order
|
||||
(window → digest + retrieval → optional LLM summary), but not all at once.
|
||||
- **No LLM in compression** (OpenITT's hard line) versus **DAG summaries by the
|
||||
model** (agentk). Both are defensible for different inputs: log-scale reading
|
||||
wants the deterministic linecomp, conversation history wants structure.
|
||||
- **Threads.** OpenITT forbids them; agentk requires the reactor. A reactor with
|
||||
one state-writing thread and length-framed pipes is the only version that stays
|
||||
portable C99/POSIX and still lets a tool block without freezing the UI.
|
||||
- **Memory accounting.** Only OpenITT takes it seriously, and it is exactly the
|
||||
property that makes a harness trustworthy on an 8 GiB box.
|
||||
- **Tool-call robustness** — the gap that killed Pi on the MacBook today, and that
|
||||
none of the three addresses. Measured there: the model emitted
|
||||
`<tool>{...}</tool>` while the template and the parser expect `<tool_call>`, so
|
||||
`tool_calls` came back `null` even with `tool_choice: "required"`. A new harness
|
||||
can fix that cheaply: accept all three shapes (`<tool>`, `<tool_call>`, native
|
||||
`tool_calls`), retry once on a malformed call with the parse error as the
|
||||
observation, and log which format the model actually used.
|
||||
|
||||
**Summary of the pile:** MikroAgent is the engine that already runs, OpenITT has
|
||||
the data model and the low-memory discipline, agentk has the compaction theory. A
|
||||
new harness that ignores any of the three will rebuild it badly.
|
||||
@@ -1,24 +0,0 @@
|
||||
# IMPORT -- where splinter comes from (root AGENTS.md, "What belongs where")
|
||||
|
||||
upstream splinter, the project's own repository
|
||||
ssh://lotherk@172.25.206.16/home/git/splinter.git (olivia)
|
||||
version 0.1 (no release tag yet; see README.md)
|
||||
archive git archive of the commit below, no tarball upstream
|
||||
commit dc9a1c62eca37972e2ae24492bf7ca2e80b25d7b
|
||||
licence BSD-3-Clause (README.md, "License")
|
||||
imported 2026-11-17, unchanged: the commit that adds this file is the
|
||||
tree of that commit; every later change is a visible diff
|
||||
|
||||
# The tree stays an independent project: it is developed in its own
|
||||
# repository, and Makronix carries a snapshot. An update is a merge, not a
|
||||
# copy (ext/AGENTS.md):
|
||||
#
|
||||
# git remote add splinter ssh://lotherk@172.25.206.16/home/git/splinter.git
|
||||
# git fetch splinter
|
||||
# git merge -X subtree=ext/src/splinter splinter/main
|
||||
# # then renew the recipe's distfile: tools/ext-dist.sh splinter
|
||||
#
|
||||
# A git submodule would not work here: Makronix builds forks from
|
||||
# `git archive' (tools/ext-dist.sh, tools/srctree-stage.sh), and git archive
|
||||
# leaves a submodule as an empty directory -- the package and the source set
|
||||
# would be broken.
|
||||
@@ -1,374 +0,0 @@
|
||||
# splinter -- POSIX make for our own code, GNU make only for the vendored curses.
|
||||
#
|
||||
# make libsplinter.so, the splinter binary, the example plugin
|
||||
# make check builds and runs every test binary
|
||||
# make curses builds the vendored NetBSD curses explicitly
|
||||
# make clean removes generated files only
|
||||
#
|
||||
# The layout is deliberate: the backend lives in libsplinter.so (src/backend,
|
||||
# the engine and everything it owns). The front ends are src/frontend/curses.c
|
||||
# (the screen), src/frontend/protocol.c (the engine on a socket) and
|
||||
# src/frontend/client.c (the reference client); src/main.c launches them.
|
||||
# Every one of them links that single library, so there is exactly one copy of
|
||||
# each symbol in the process. Two copies would mean two registries.
|
||||
|
||||
CC ?= cc
|
||||
CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Werror -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700 -D_NETBSD_SOURCE \
|
||||
-fPIC -Iinclude -Isrc/backend -Isrc/frontend -Ivendor/libmcp -Ivendor/netbsd-curses/libcurses
|
||||
LDFLAGS ?=
|
||||
LIBS ?= -lpthread
|
||||
PREFIX ?= /usr/local
|
||||
|
||||
CURSES_DIR = vendor/netbsd-curses
|
||||
CURSES_A = $(CURSES_DIR)/libcurses/libcurses.a \
|
||||
$(CURSES_DIR)/libterminfo/libterminfo.a
|
||||
# The vendored copy is what a Linux build links (the project's own default).
|
||||
# A build on a system that has curses of its own passes
|
||||
# CURSES_LIB='-lcurses -lterminfo' CURSES_DEP=
|
||||
# and the vendored tree is not built at all (Makronix/NetBSD does this: the
|
||||
# distribution links the base system's curses).
|
||||
CURSES_LIB ?= $(CURSES_A)
|
||||
CURSES_DEP ?= $(CURSES_A)
|
||||
|
||||
LIB = libsplinter.so
|
||||
LIBOBJ = src/backend/buf.o src/backend/tool.o src/backend/session.o src/backend/conv.o src/backend/transport.o \
|
||||
src/backend/json.o src/backend/sse.o src/backend/openai.o src/backend/transport_openai.o \
|
||||
src/backend/anthropic.o src/backend/transport_anthropic.o src/backend/builtin.o \
|
||||
src/backend/agent.o src/backend/theme.o src/backend/palettes.o src/backend/decomp.o src/backend/i18n.o src/backend/delegate.o src/backend/telegram.o src/backend/log.o src/backend/cmdscript.o src/backend/folder.o src/backend/interview.o src/backend/ack.o src/backend/mcpserver.o src/backend/mcpsession.o src/backend/skills.o src/backend/user.o src/backend/prompt.o src/backend/config.o src/backend/plugin.o src/backend/curl.o src/backend/swarm.o src/backend/provstate.o src/backend/md.o src/backend/tgmd.o src/backend/b64.o src/backend/a2aserver.o src/backend/providers.o src/backend/usage.o src/backend/confblock.o src/backend/agents.o src/backend/engine.o src/backend/http.o src/backend/openai_server.o src/backend/catalogs.o
|
||||
# buildinfo.o is separate: buildinfo.c is generated from the objects below.
|
||||
LIBOBJ_ALL = $(LIBOBJ) src/backend/buildinfo.o
|
||||
BIN = splinter
|
||||
BINOBJ = src/main.o src/frontend/curses.o src/frontend/protocol.o \
|
||||
src/frontend/ui_local.o src/frontend/ui_remote.o
|
||||
CLIENT = splinterctl
|
||||
CLIENTOBJ = src/frontend/client.o
|
||||
PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \
|
||||
plugins/cli/cli.so plugins/focus/focus.so plugins/mcp/mcp.so \
|
||||
plugins/ring/ring.so plugins/reminder/reminder.so \
|
||||
plugins/kids/kids.so plugins/status/status.so plugins/processes/processes.so \
|
||||
plugins/provider/provider.so \
|
||||
plugins/scheduler/scheduler.so \
|
||||
plugins/a2a/a2a.so \
|
||||
plugins/junction/junction.so \
|
||||
plugins/self/self.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_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_usage tests/test_agents tests/test_confblock tests/test_jobs tests/test_engine tests/test_self
|
||||
|
||||
RPATH = -Wl,-rpath,'$$ORIGIN'
|
||||
PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..'
|
||||
TEST_RPATH = -Wl,-rpath,'$$ORIGIN/..'
|
||||
|
||||
all: $(LIB) $(BIN) $(CLIENT) $(PLUGIN)
|
||||
|
||||
# The vendored tree ships a GNUmakefile; this is the only place that needs GNU
|
||||
# make, and it is why the comment above says so out loud.
|
||||
$(CURSES_A):
|
||||
cd $(CURSES_DIR) && $(MAKE) -f GNUmakefile libcurses/libcurses.a \
|
||||
libterminfo/libterminfo.a
|
||||
|
||||
curses: $(CURSES_A)
|
||||
|
||||
src/backend/catalogs.c: share/locale/de.msg share/locale/en.msg share/locale/pt_BR.msg tools/embed_catalogs.sh
|
||||
sh tools/embed_catalogs.sh share/locale/*.msg > $@
|
||||
|
||||
# The build stamp --version prints. It is regenerated only when one of the
|
||||
# objects it describes is newer, so a no-op make keeps the old stamp: the
|
||||
# stamp says when this binary was actually built, not when make last ran.
|
||||
# The revision is included because 0.1.0 does not tell two builds apart.
|
||||
src/backend/buildinfo.c: $(LIBOBJ) $(BINOBJ)
|
||||
@{ \
|
||||
rev=`git rev-parse --short HEAD 2>/dev/null` || rev=unknown; \
|
||||
if [ -n "`git status --porcelain --untracked-files=no 2>/dev/null | head -n 1`" ]; then \
|
||||
rev="$$rev-dirty"; \
|
||||
fi; \
|
||||
printf '/* generated by make: the build stamp of this binary */\nconst char *sp_build_time = "%s";\nconst char *sp_build_rev = "%s";\n' \
|
||||
"`date '+%Y-%m-%d %H:%M:%S %Z'`" "$$rev"; \
|
||||
} > $@
|
||||
|
||||
$(LIB): $(LIBOBJ_ALL) $(CURSES_DEP)
|
||||
$(CC) -shared -o $@ $(LIBOBJ_ALL) $(CURSES_LIB) $(LIBS)
|
||||
|
||||
# curses belongs to the front end, not to the library: a plugin that drew into
|
||||
# a WINDOW would be a plugin holding the UI thread's state.
|
||||
# The reference client links the library for the JSON it cannot be bothered to
|
||||
# write twice, but never the curses code and never the engine's internals.
|
||||
$(CLIENT): $(CLIENTOBJ) $(LIB)
|
||||
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(CLIENTOBJ) -L. -lsplinter $(RPATH) \
|
||||
$(LIBS)
|
||||
|
||||
$(BIN): $(BINOBJ) $(LIB)
|
||||
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(BINOBJ) -L. -lsplinter $(RPATH) \
|
||||
$(CURSES_LIB) $(LIBS)
|
||||
|
||||
plugins/clock/clock.so: plugins/clock/clock.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/clock/clock.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/lcm/lcm.so: plugins/lcm/lcm.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/lcm/lcm.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/cli/cli.so: plugins/cli/cli.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/cli/cli.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/ring/ring.so: plugins/ring/ring.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/ring/ring.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/kids/kids.so: plugins/kids/kids.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/kids/kids.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/processes/processes.so: plugins/processes/processes.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/processes/processes.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/status/status.so: plugins/status/status.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/status/status.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/reminder/reminder.so: plugins/reminder/reminder.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/reminder/reminder.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/mcp/mcp.so: plugins/mcp/mcp.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/mcp/mcp.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/focus/focus.so: plugins/focus/focus.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/focus/focus.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/cps/cps.so: plugins/cps/cps.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/cps/cps.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
.c.o:
|
||||
$(CC) $(CFLAGS) -c -o $@ $<
|
||||
|
||||
# A cli delegate's child has to find plugins/cli/cli.so. Beside an installed
|
||||
# binary there is no such file, so the build directory this binary came from is
|
||||
# compiled in as the last resort (sp_delegate_cli_plugin in src/backend/delegate.c).
|
||||
src/backend/delegate.o: src/backend/delegate.c
|
||||
$(CC) $(CFLAGS) -DSPLINTER_PLUGIN_DIR='"$(CURDIR)"' -c -o $@ $<
|
||||
|
||||
# POSIX make has no automatic dependencies. Rather than a list that is wrong
|
||||
# the day somebody adds an #include, every object depends on the headers that
|
||||
# make up the interface: a change there rebuilds everything that could see it.
|
||||
HDRS = include/splinter.h include/splinter_engine.h include/splinter_plugin.h \
|
||||
src/backend/config.h src/backend/ack.h \
|
||||
src/backend/curl.h src/backend/log.h src/backend/i18n.h src/backend/md.h src/backend/b64.h src/backend/a2aserver.h
|
||||
$(LIBOBJ) $(BINOBJ): $(HDRS)
|
||||
$(PLUGIN): $(HDRS)
|
||||
|
||||
src/backend/agent.o: include/splinter.h
|
||||
src/backend/buf.o: include/splinter.h
|
||||
src/backend/tool.o: include/splinter.h
|
||||
src/backend/session.o: include/splinter.h
|
||||
src/backend/transport.o: include/splinter.h
|
||||
src/backend/conv.o: include/splinter.h
|
||||
src/backend/json.o: vendor/libmcp/mcp.h
|
||||
src/backend/sse.o: include/splinter.h vendor/libmcp/mcp.h
|
||||
src/backend/openai.o: include/splinter.h vendor/libmcp/mcp.h
|
||||
src/backend/transport_openai.o: include/splinter.h src/backend/curl.h src/backend/log.h
|
||||
src/backend/anthropic.o: include/splinter.h vendor/libmcp/mcp.h
|
||||
src/backend/transport_anthropic.o: include/splinter.h src/backend/curl.h src/backend/log.h vendor/libmcp/mcp.h
|
||||
src/backend/curl.o: src/backend/curl.h include/splinter.h
|
||||
src/backend/builtin.o: include/splinter.h
|
||||
src/backend/theme.o: src/backend/theme.h src/backend/palettes.h include/splinter.h
|
||||
src/backend/palettes.o: src/backend/palettes.h
|
||||
src/backend/decomp.o: src/backend/decomp.h
|
||||
src/backend/i18n.o: src/backend/i18n.h include/splinter.h
|
||||
src/backend/delegate.o: src/backend/config.h include/splinter.h
|
||||
src/backend/telegram.o: include/splinter.h src/backend/curl.h src/backend/ack.h
|
||||
src/backend/log.o: src/backend/log.h
|
||||
src/backend/cmdscript.o: src/backend/cmdscript.h include/splinter.h
|
||||
src/backend/folder.o: src/backend/folder.h include/splinter.h
|
||||
src/backend/ack.o: src/backend/ack.h include/splinter.h
|
||||
src/backend/interview.o: src/backend/interview.h include/splinter.h
|
||||
src/backend/mcpserver.o: src/backend/mcpserver.h include/splinter.h
|
||||
src/backend/skills.o: src/backend/skills.h src/backend/config.h include/splinter.h
|
||||
src/backend/prompt.o: src/backend/prompt.h include/splinter.h
|
||||
src/backend/config.o: src/backend/config.h include/splinter.h
|
||||
src/backend/plugin.o: include/splinter.h include/splinter_plugin.h
|
||||
src/frontend/curses.o: src/frontend/ui.h src/frontend/ui_backend.h \
|
||||
include/splinter_engine.h src/backend/theme.h src/backend/decomp.h src/backend/i18n.h include/splinter.h include/splinter_plugin.h src/backend/md.h
|
||||
src/backend/md.o: src/backend/md.h include/splinter.h
|
||||
src/backend/b64.o: src/backend/b64.h include/splinter.h
|
||||
src/backend/a2aserver.o: src/backend/a2aserver.h include/splinter.h vendor/libmcp/mcp.h
|
||||
src/frontend/ui_local.o: src/frontend/ui_backend.h include/splinter_engine.h src/frontend/ui.h
|
||||
src/frontend/ui_remote.o: src/frontend/ui_backend.h src/frontend/protocol.h include/splinter_engine.h vendor/libmcp/mcp.h
|
||||
src/frontend/client.o: src/frontend/protocol.h include/splinter.h
|
||||
src/frontend/protocol.o: src/frontend/protocol.h include/splinter_engine.h include/splinter.h src/backend/i18n.h
|
||||
src/backend/http.o: src/backend/http.h include/splinter.h
|
||||
src/backend/openai_server.o: src/backend/openai_server.h src/backend/http.h src/backend/config.h include/splinter.h vendor/libmcp/mcp.h
|
||||
src/backend/engine.o: include/splinter_engine.h src/backend/config.h src/backend/providers.h src/backend/agents.h src/backend/swarm.h src/backend/cmdscript.h src/backend/i18n.h include/splinter_plugin.h
|
||||
src/backend/providers.o: src/backend/providers.h src/backend/config.h include/splinter.h include/splinter_plugin.h
|
||||
src/main.o: include/splinter.h include/splinter_engine.h \
|
||||
src/frontend/ui_backend.h src/backend/config.h src/backend/i18n.h include/splinter_plugin.h src/frontend/ui.h src/backend/theme.h src/backend/a2aserver.h
|
||||
|
||||
tests/test_buf: tests/test_buf.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_buf.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_tool: tests/test_tool.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_tool.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_session: tests/test_session.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_session.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_transport: tests/test_transport.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_transport.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_agent: tests/test_agent.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_agent.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_conv: tests/test_conv.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_conv.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_openai: tests/test_openai.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_openai.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_theme: tests/test_theme.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_theme.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_focus: tests/test_focus.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_focus.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_skills: tests/test_skills.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_skills.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_telegram: tests/test_telegram.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_telegram.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_delegate: tests/test_delegate.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_delegate.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_builtin: tests/test_builtin.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_builtin.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_ack: tests/test_ack.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_ack.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_i18n: tests/test_i18n.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_i18n.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_ascii: tests/test_ascii.c $(LIB) $(BINOBJ)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_ascii.c src/frontend/curses.o -L. -lsplinter \
|
||||
$(TEST_RPATH) $(CURSES_LIB) $(LIBS)
|
||||
tests/test_md: tests/test_md.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_md.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_tgmd: tests/test_tgmd.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_tgmd.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_providers: tests/test_providers.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_providers.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_b64: tests/test_b64.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_b64.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_pause: tests/test_pause.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_pause.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_swarm: tests/test_swarm.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_swarm.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_provstate: tests/test_provstate.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_provstate.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
|
||||
tests/test_agents: tests/test_agents.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_agents.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
|
||||
tests/test_confblock: tests/test_confblock.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_confblock.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
|
||||
tests/test_engine: tests/test_engine.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_engine.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_junction: tests/test_junction.c $(LIB) plugins/junction/junction.so
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_junction.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_self: tests/test_self.c $(LIB) plugins/self/self.so
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_self.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_usage: tests/test_usage.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_usage.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_jobs: tests/test_jobs.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_jobs.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_config: tests/test_config.c $(LIB)
|
||||
$(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)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_cli.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
|
||||
tests/test_compactor: tests/test_compactor.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_compactor.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_secrets: tests/test_secrets.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_secrets.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_mcpclient: tests/test_mcpclient.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_mcpclient.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_kids: tests/test_kids.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_kids.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/plugin_lifecycle.so: tests/plugin_lifecycle.c $(LIB) $(HDRS)
|
||||
$(CC) $(CFLAGS) -shared -o $@ tests/plugin_lifecycle.c -L. -lsplinter \
|
||||
$(TEST_RPATH) $(LIBS)
|
||||
tests/test_lifecycle: tests/test_lifecycle.c $(LIB) tests/plugin_lifecycle.so
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_lifecycle.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_plugin: tests/test_plugin.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_plugin.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
|
||||
check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS) tests/test_junction
|
||||
@set -e; python3 tools/check_i18n.py; \
|
||||
export LD_LIBRARY_PATH=.; \
|
||||
for t in $(TESTS); do echo "== $$t"; ./$$t; done; \
|
||||
echo "== tests/test_delegate_cli.sh"; sh tests/test_delegate_cli.sh; \
|
||||
echo "== tests/test_interview.sh"; sh tests/test_interview.sh; \
|
||||
echo "== tests/test_gateway.sh"; sh tests/test_gateway.sh; \
|
||||
echo "== tests/test_a2a.sh"; sh tests/test_a2a.sh; \
|
||||
echo "== tests/test_a2a_ui.sh"; sh tests/test_a2a_ui.sh; \
|
||||
echo "== tests/test_a2a_server.sh"; sh tests/test_a2a_server.sh; \
|
||||
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; \
|
||||
echo "== tests/test_protocol.sh"; sh tests/test_protocol.sh; \
|
||||
echo "== tests/test_attach.sh"; sh tests/test_attach.sh; \
|
||||
echo "== tests/test_gateway_openai.sh"; sh tests/test_gateway_openai.sh; \
|
||||
echo "== tests/test_reconnect.sh"; sh tests/test_reconnect.sh; \
|
||||
echo "== tests/test_junction.sh"; sh tests/test_junction.sh; \
|
||||
echo "== tests/test_mcpsession.sh"; sh tests/test_mcpsession.sh; \
|
||||
echo "all tests passed"
|
||||
|
||||
# The installed binary finds its own library through an rpath relative to itself
|
||||
# ($ORIGIN), so 'make install PREFIX=$HOME/.local' produces a program that runs
|
||||
# without a wrapper, without LD_LIBRARY_PATH and without an environment file.
|
||||
# Install by rename, never in place. A running splinter has these files
|
||||
# mapped: cp truncates the old inode and writes into pages the process is
|
||||
# executing, which killed a gateway that was up while make install ran
|
||||
# (SIGSEGV at a nonsense address). A rename swaps the directory entry and
|
||||
# leaves the mapped inode alone.
|
||||
install: all
|
||||
mkdir -p $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(PREFIX)/lib \
|
||||
$(DESTDIR)$(PREFIX)/lib/splinter/plugins
|
||||
$(CC) $(CFLAGS) $(LDFLAGS) -Wl,-rpath,'$$ORIGIN/../lib' \
|
||||
-o $(DESTDIR)$(PREFIX)/bin/.splinter.new $(BINOBJ) -L. -lsplinter \
|
||||
$(CURSES_LIB) $(LIBS)
|
||||
mv -f $(DESTDIR)$(PREFIX)/bin/.splinter.new \
|
||||
$(DESTDIR)$(PREFIX)/bin/splinter
|
||||
$(CC) $(CFLAGS) $(LDFLAGS) -Wl,-rpath,'$$ORIGIN/../lib' \
|
||||
-o $(DESTDIR)$(PREFIX)/bin/.$(CLIENT).new $(CLIENTOBJ) -L. -lsplinter \
|
||||
$(LIBS)
|
||||
mv -f $(DESTDIR)$(PREFIX)/bin/.$(CLIENT).new \
|
||||
$(DESTDIR)$(PREFIX)/bin/$(CLIENT)
|
||||
cp $(LIB) $(DESTDIR)$(PREFIX)/lib/.$(LIB).new
|
||||
mv -f $(DESTDIR)$(PREFIX)/lib/.$(LIB).new $(DESTDIR)$(PREFIX)/lib/$(LIB)
|
||||
for p in $(PLUGIN); do \
|
||||
cp "$$p" "$(DESTDIR)$(PREFIX)/lib/splinter/plugins/.new.$$$$" && \
|
||||
mv -f "$(DESTDIR)$(PREFIX)/lib/splinter/plugins/.new.$$$$" \
|
||||
"$(DESTDIR)$(PREFIX)/lib/splinter/plugins/$${p##*/}" || exit 1; \
|
||||
done
|
||||
@echo "installed $(DESTDIR)$(PREFIX)/bin/splinter"
|
||||
|
||||
clean:
|
||||
rm -f src/backend/catalogs.c src/backend/buildinfo.c $(BIN) $(CLIENT) $(LIB) $(LIBOBJ_ALL) $(BINOBJ) \
|
||||
$(CLIENTOBJ) $(PLUGIN) $(TESTS) tests/plugin_lifecycle.so \
|
||||
tests/test_junction
|
||||
|
||||
.PHONY: all check curses install clean
|
||||
|
||||
plugins/provider/provider.so: plugins/provider/provider.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/provider/provider.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/scheduler/scheduler.so: plugins/scheduler/scheduler.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/scheduler/scheduler.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/a2a/a2a.so: plugins/a2a/a2a.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/a2a/a2a.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/junction/junction.so: plugins/junction/junction.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/junction/junction.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/self/self.so: plugins/self/self.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/self/self.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
@@ -1,810 +0,0 @@
|
||||
# splinter
|
||||
|
||||
Named after Master Splinter: the one who knows which tools exist, who may use
|
||||
them, and what happened — and trains the ones that do the fighting.
|
||||
|
||||
A C99/POSIX agent harness with a curses interface: the conversation on three
|
||||
quarters, a sidebar on the last one that says which agent, provider, model and
|
||||
allowance you are on and where the tools will act, a status line above the
|
||||
prompt with the context gauge (`ctx used/max`, cache share, tok/s), and the
|
||||
prompt below it. The conversation starts clear at the top and only ever grows.
|
||||
|
||||
make # libsplinter.so, the binaries, the plugins
|
||||
make check # the tests, no network, no model
|
||||
make install PREFIX=$HOME/.local # binaries, library, plugins
|
||||
|
||||
splinter --init-config # writes ~/.splinter/splinter.conf
|
||||
splinter --doctor # does every provider answer?
|
||||
splinter # the chat; Tab switches build / plan
|
||||
splinter -m claude # a provider, a pool, provider/model
|
||||
splinter --model-list # everything -m takes
|
||||
splinter --serve # the engine on a socket, for a GUI
|
||||
splinter --attach # the same curses UI, as a client of it
|
||||
splinterctl --say "hallo" # the reference client for that socket
|
||||
splinter --openai-listen 127.0.0.1 # /v1 for another harness, gw_ tools
|
||||
|
||||
The working day with several subscriptions (who analyses, who implements, what
|
||||
happens at a limit) is in `docs/WORKFLOW.md`.
|
||||
|
||||
## What it does
|
||||
|
||||
`splinter -p "list the C files" --endpoint http://127.0.0.1:8080/turn` sends a
|
||||
prompt, runs the tools the transport asks for, and prints the answer. Every turn
|
||||
is appended to `~/.splinter/<id>.jsonl` as one JSON object per line.
|
||||
|
||||
## What it refuses to do
|
||||
|
||||
- Send a request that exceeds the configured byte budget (nothing is sent; the
|
||||
turn fails instead of letting an endpoint truncate silently).
|
||||
- Run a tool that is not in the registry (the model is told, not guessed at).
|
||||
- Run a mutating or destructive tool without operator consent, unless
|
||||
`--autonomous` was given.
|
||||
- Skip a denial silently: the denial becomes the observation the model sees.
|
||||
|
||||
## Transport protocol
|
||||
|
||||
The harness speaks a line protocol with its transport, not a vendor API:
|
||||
|
||||
request user <text>
|
||||
request observe <tool> <output>
|
||||
reply answer <text>
|
||||
reply tool <name> <arguments>
|
||||
|
||||
A provider adapter translates an OpenAI-compatible endpoint into this shape and
|
||||
back. That is why `make check` needs no network, no key and no model: the mock
|
||||
transport replays replies.
|
||||
|
||||
## Layout
|
||||
|
||||
The harness is a backend and a set of front ends; `docs/FRONTENDS.md` says
|
||||
where the line runs and how to add another one.
|
||||
|
||||
libsplinter.so every symbol, once; binaries and plugins link to it
|
||||
include/splinter.h the core interface
|
||||
include/splinter_engine.h the engine a front end talks to (events, turns)
|
||||
include/splinter_plugin.h plugin ABI and host API
|
||||
|
||||
src/backend/engine.c session + agent + turn thread + event queue
|
||||
src/backend/agent.c the loop
|
||||
src/backend/conv.c the conversation (owned messages, no sharing)
|
||||
src/backend/openai.c request shaping + reply parsing, pure functions
|
||||
src/backend/transport*.c HTTP, the mock, the vendor shapes
|
||||
src/backend/session.c append-only JSONL session
|
||||
src/backend/builtin.c read/write/edit/search/list/run/web tools
|
||||
src/backend/tool.c the registry
|
||||
src/backend/config.c the config file
|
||||
src/backend/providers.c -m, /model, pools, failover
|
||||
src/backend/plugin.c dlopen loader, widget registry, worker threads
|
||||
src/backend/md.c markdown tables as aligned text
|
||||
src/backend/telegram.c gateway mode
|
||||
src/backend/a2aserver.c the A2A server
|
||||
src/backend/openai_server.c /v1/chat/completions with gw_ tools
|
||||
src/backend/http.c the HTTP helpers the JSON servers share
|
||||
|
||||
src/frontend/curses.c transcript, sidebar, prompt
|
||||
src/frontend/ui_backend.h what the screen needs from a backend
|
||||
src/frontend/ui_local.c that backend as the engine in this process
|
||||
src/frontend/ui_remote.c that backend as a socket client (--attach)
|
||||
src/frontend/protocol.c splinter --serve: JSON lines on a Unix socket
|
||||
src/frontend/client.c splinterctl, the reference protocol client
|
||||
src/frontend/ui.h the curses entry point
|
||||
src/main.c launcher: parse, config, engine, front end
|
||||
|
||||
plugins/clock/ example plugin: a sidebar clock + a tool
|
||||
vendor/netbsd-curses/ NetBSD curses and terminfo, vendored
|
||||
docs/PLUGINS.md the ABI, the threading rules
|
||||
docs/PROTOCOL.md the line protocol a GUI client speaks
|
||||
docs/GATEWAY.md the OpenAI endpoint and its two tool sets
|
||||
tests/ the test binaries, run by `make check`
|
||||
docs/splinter.1 manual page
|
||||
src/www/index*.html the site, written by hand (de, en, pt_BR)
|
||||
|
||||
## Front ends
|
||||
|
||||
The engine is front-end neutral: `sp_engine_submit()` starts a turn on its own
|
||||
thread and everything that happens — streamed text, a step's reasoning, a tool
|
||||
call, its observation, an approval question, the answer — becomes an event the
|
||||
front end drains. The curses interface is one front end; `splinter --serve`
|
||||
is another, and it is what a GUI would use.
|
||||
|
||||
```sh
|
||||
splinter --serve # ~/.splinter/splinter.sock
|
||||
splinter --serve --socket /tmp/s.sock
|
||||
splinter --attach --socket /tmp/s.sock # the curses UI, as a client
|
||||
splinterctl --socket /tmp/s.sock --say "list the C files"
|
||||
python3 docs/proto-example.py /tmp/s.sock "list the C files"
|
||||
```
|
||||
|
||||
The screen itself is a client in `--attach` mode: it speaks the same lines a
|
||||
GUI would, shows the server's session and its transcript so far, runs every
|
||||
turn there and switches the server's profiles. That is the proof that the
|
||||
protocol carries everything the front end needs; if `--attach` works, a GUI
|
||||
has no hidden C dependency.
|
||||
|
||||
The protocol is one JSON object per line (`ready`, `state`, `stream`, `step`,
|
||||
`tool`, `tool_result`, `approval`, `turn`, ...; `input`, `say`, `approve`,
|
||||
`cancel`, `steer`, `state`, `quit`, `sessions`, `open`). `docs/PROTOCOL.md`
|
||||
has the field list and a sequence diagram; `docs/FRONTENDS.md` has the code
|
||||
layout and how to start a GUI on top of it. The socket is `0600` and the server
|
||||
checks the peer's uid.
|
||||
|
||||
The engine keeps more than one session: `sessions` lists the directory, `open`
|
||||
switches to an id (or `new`/`last`) and sends the state and history of that
|
||||
session. The screen offers the same as `/sessions` and `/open ID`, locally and
|
||||
over the socket; a local switch closes the engine and reopens it from the same
|
||||
options, because plugins keep process globals. `/sessions` shows a title - the
|
||||
first user line until `/rename [ID] TITLE` says otherwise - and `/rm ID`
|
||||
removes a session that is not open. One session is active at a time; over the
|
||||
socket, one client at a time.
|
||||
|
||||
`--attach` reconnects: if the server dies, the screen says so, keeps running,
|
||||
and attaches again when a server is back on the socket - asking for the session
|
||||
it was on by id, so the conversation continues where it stopped. If that
|
||||
session is gone, it says which one and stays on the server's current session.
|
||||
|
||||
## Gateway: another harness, splinter's tools
|
||||
|
||||
`splinter --openai-listen 127.0.0.1` serves `/v1/chat/completions` for another
|
||||
harness. The model sees splinter's local tools as `gw_read`, `gw_write`,
|
||||
`gw_run`, ... and the caller's own tools under their own names:
|
||||
|
||||
* a `gw_*` call is executed by splinter, on the host where splinter runs, and
|
||||
the caller only sees the final answer;
|
||||
* any other tool call is returned to the calling harness, which runs it where
|
||||
it runs and sends the results back in the next request.
|
||||
|
||||
That is how one conversation can act in both places, without a name collision
|
||||
between a local `read` and a caller's `read`. Beyond loopback a
|
||||
`SPLINTER_GATEWAY_TOKEN` is required, and local mutating tools need
|
||||
`--autonomous`. `docs/GATEWAY.md` has the details and examples.
|
||||
|
||||
## Plugins and themes
|
||||
|
||||
A plugin is a `.so` against `libsplinter.so`, exporting
|
||||
`sp_plugin_describe()`. It can register tools (with authorization classes the
|
||||
loop enforces) and widgets. A widget's `tick()` runs on its own thread and
|
||||
publishes a line of text, which the sidebar shows; `/widgets` prints the same
|
||||
lines into the transcript. See `docs/PLUGINS.md`.
|
||||
|
||||
The default theme is `Xresources`: it takes `*foreground`, `*background` and
|
||||
`*color0`..`*color15` from `xrdb -query` (or `~/.Xresources` without X) and
|
||||
paints the UI with them, so the harness looks like the terminal it runs in.
|
||||
Without any of those resources it keeps the terminal's own colour indices.
|
||||
|
||||
Two flat themes are the readable ones: `light` is a white page with black text,
|
||||
`dark` the same inverted. The chat, the sidebar and the input line share the
|
||||
page colour; only the status line above the prompt is a separate surface (light
|
||||
grey on `light`, dark grey on `dark`). That is the shape to reach for when a
|
||||
palette leaves the conversation unreadable: `theme = light` in the config or
|
||||
`--theme light`.
|
||||
|
||||
Every CDE palette from the desktop's `.dp` files is a theme as well, 42 of them
|
||||
including `Default` and `MakroSlate`. A palette is used the way the desktop
|
||||
uses it: set 5 is the chat background, set 4 the input area, set 1 the user's
|
||||
lines, set 7 the model's answer, set 3 its reasoning, set 6 tool calls, set 8
|
||||
status and session notes, and set 2 observations, with black or white text by
|
||||
CDE's own rule. Role colours keep their hue and are moved away from the
|
||||
background only when they would disappear into it. `--list-themes` prints the
|
||||
names, `--theme NAME` picks one, and `theme = NAME` in the config makes it the
|
||||
default.
|
||||
|
||||
## Talking to a model
|
||||
|
||||
```sh
|
||||
./splinter -p "say hi" --endpoint http://127.0.0.1:8080/v1 \
|
||||
--model qwen2.5-coder-7b --api-key-env SPLINTER_API_KEY
|
||||
```
|
||||
|
||||
The adapter shapes the whole conversation into one `chat/completions` request,
|
||||
including the tool table, and parses `content` and `tool_calls` back. The
|
||||
provider's raw `tool_calls` array is stored verbatim in the conversation and
|
||||
sent back unchanged on the next round: re-encoding it would be a silently
|
||||
different JSON. `content: null` is an empty answer, not an error; a reply
|
||||
without choices, or a provider `error` object, is an error that quotes the
|
||||
provider's own message.
|
||||
|
||||
## Any program as the model
|
||||
|
||||
```sh
|
||||
SPLINTER_CLI_CMD="claude -p" ./splinter -p "hi" --plugin plugins/cli/cli.so --transport cli
|
||||
```
|
||||
|
||||
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
|
||||
SPLINTER_A2A_URL=https://agent.example/rpc \
|
||||
SPLINTER_A2A_TOKEN=... \
|
||||
./splinter -p "hi" --plugin plugins/a2a/a2a.so --transport a2a
|
||||
```
|
||||
|
||||
The client half of Agent2Agent: one `SendMessage` over JSON-RPC 2.0 with a text
|
||||
part, blocking, and a direct `Message` or a completed `Task` as the answer. In
|
||||
the UI the turn streams: `SendStreamingMessage`, artifact text appearing as it
|
||||
arrives. The task and context ids are kept for the session, so the next turn
|
||||
continues the same A2A context. `SPLINTER_A2A_CARD` discovers the JSON-RPC
|
||||
endpoint from an agent card; `SPLINTER_A2A_URL` sets it directly. One-shot mode
|
||||
streams by default; `--no-stream` asks for the blocking send.
|
||||
|
||||
The transport sends text. A file goes with `a2a_send` — a message plus a `file`
|
||||
part (base64, 8 MiB cap, media type guessed from the name) — and a file the
|
||||
other side sends back is saved (`SPLINTER_A2A_INBOX`, default
|
||||
`$TMPDIR/splinter-a2a-inbox`) and named by path in the answer. `a2a_get_task`,
|
||||
`a2a_cancel_task` and `a2a_subscribe` (the SSE events of a task, as one text)
|
||||
use the same endpoint. Push notifications are not sent by the client.
|
||||
|
||||
## The other direction: splinter as an A2A server
|
||||
|
||||
```sh
|
||||
SPLINTER_A2A_SERVER_TOKEN=... \
|
||||
./splinter --a2a-server-listen 127.0.0.1 --a2a-listen-port 8099
|
||||
```
|
||||
|
||||
Another agent can send `SendMessage` to `POST /a2a` and read `GetTask` or
|
||||
`ListTasks`; the
|
||||
agent card is served at `/.well-known/agent-card.json`. `SendStreamingMessage`
|
||||
streams the answer as SSE artifact updates, then a completed status. A
|
||||
`contextId` is a conversation: the next message with it continues. Without one
|
||||
the server creates a context and returns it in the task. A
|
||||
`taskPushNotificationConfig` in the request posts the completed task to a
|
||||
webhook: loopback is always allowed, other hosts need
|
||||
`SPLINTER_A2A_PUSH_ALLOW`; the config's token travels as
|
||||
`X-A2A-Notification-Token`, its authentication as `Authorization`. Binary
|
||||
`file`/`raw` parts are written into the session's `inbox/` and described to the
|
||||
model by path (a text model cannot read a PNG, the agent around it can); URL
|
||||
parts are fetched from loopback or a host in `SPLINTER_A2A_URL_ALLOW`.
|
||||
`SubscribeToTask` replays the stored task state once and ends the stream — the
|
||||
server answers one request at a time, so there is no progress to watch. Beyond loopback the bearer token is required;
|
||||
there is no TLS, so put it behind ssh or a tunnel.
|
||||
|
||||
## Configuration
|
||||
|
||||
`splinter` alone starts the chat: endpoint, model, plugins, theme and session
|
||||
directory come from `~/.splinter/splinter.conf` (or `$SPLINTER_CONFIG`), written
|
||||
in blocks: `core { }`, `provider NAME { }`, `pool NAME { }`. Command line wins
|
||||
over the file, the file wins over the built-in default, and an unknown key is
|
||||
an error with the line you wrote. Providers (several accounts, usage limits per
|
||||
window, pools that balance or fail over) and agent profiles are in
|
||||
`docs/CONFIG.md`; `splinter --init-config` writes a commented starter.
|
||||
|
||||
## Streaming
|
||||
|
||||
Answers arrive as they are produced, not as one block: the adapter reads SSE,
|
||||
appends text deltas to the transcript as they arrive and a tool call as its own
|
||||
line, and a reasoning model's own `reasoning_content` is shown dimmed, in
|
||||
sequence, instead of being hidden. In one-shot mode the text goes straight to
|
||||
stdout as it comes.
|
||||
|
||||
A data object split across SSE events, a blank line between its lines and a
|
||||
truncated trailing fragment are all tolerated: the parser buffers until the
|
||||
object is complete and drops a fragment that never is, instead of failing a
|
||||
turn that already has its answer. `test_sse` feeds recorded lines: plain text,
|
||||
a tool call split across three chunks, two calls in one turn, a pretty-printed
|
||||
object across events, a truncated tail, and the keepalive lines that carry
|
||||
nothing.
|
||||
|
||||
A request that fails before anything was streamed is tried again three times,
|
||||
five seconds apart; a broken connection, a missing status, a 5xx and a stream
|
||||
that carried no answer qualify, a 401 or 404 does not. After the first streamed
|
||||
chunk the retry stops, because printing the same answer twice is worse than
|
||||
reporting the provider's error. The wait is visible: the prompt line says
|
||||
`retrying in 5 s: ...` until the next attempt answers, so a pause does not look
|
||||
like a hang. Ctrl-C during a wait ends it at once.
|
||||
|
||||
A stream is never cut for being slow: a router may wait minutes for an upstream
|
||||
without sending anything but keepalive lines, and a byte-per-second guard cut
|
||||
exactly those with "Less than 1 bytes/sec". The overall HTTP timeout is the
|
||||
only limit.
|
||||
|
||||
## Colour, measured
|
||||
|
||||
A CDE palette is eight mid-tones; painted literally, a role can sit a few
|
||||
percent away from the background, and nothing is readable. Two safeguards live
|
||||
in `theme.c`: text on a surface follows CDE's rule (black on light, white on
|
||||
dark), and a role that is too close to the background is pushed away from it
|
||||
until it is legible. The push keeps the hue, and each role gets a slightly
|
||||
different minimum, so even a monochrome palette yields distinguishable steps.
|
||||
The 256-colour path picks the nearest cube or grey-ramp entry instead of
|
||||
rounding channels down, which used to turn a dark orange into grey 240.
|
||||
`Xresources` themes follow the same rules with colour0..15.
|
||||
|
||||
The other half was a real bug: `COLORS` was read before `start_color()`, so it
|
||||
was 0, the code took the eight-basic-colour path, and the whole palette
|
||||
collapsed to white on black.
|
||||
|
||||
## Screen encoding, measured
|
||||
|
||||
The vendored NetBSD curses emits Latin-1 bytes for wide characters (`ü` becomes
|
||||
`0xFC`); ncurses passes UTF-8 through. So the UI transliterates for display
|
||||
(`gruen`), while the conversation and the session log keep the exact UTF-8.
|
||||
That is a defect in the ported library, recorded here instead of being papered
|
||||
over with a claim that it works.
|
||||
|
||||
## What you see, and what is on disk
|
||||
|
||||
The chat draws a transcript: `[time] <you>`, `[time] ~ denkt:` for the model's
|
||||
reasoning, `[time] >> Run du -sh ../xsrc` for a tool call, `[time] | output`
|
||||
for what the tool returned, `[time] <model>` for the answer. A turn that calls
|
||||
tools therefore reads in order: reasoning, text before the call, the call, the
|
||||
output, text after it.
|
||||
|
||||
A call is one row and it says what happened in the words a person would use:
|
||||
the tool as a capitalized verb, then its one interesting argument - the command
|
||||
of a `run`, the path of a `read`, the pattern of a `search`. No JSON, no
|
||||
`command:` in front of the value, and no second copy of the arguments in the
|
||||
prompt: the model's encoding is not the reader's business. Call rows are painted
|
||||
in the accent colour, their output dim underneath, so a run of shell calls is a
|
||||
list of calls and not a grey column of the same word.
|
||||
|
||||
The same records go to `<session_dir>/logs/<session-id>/session.log`, in the
|
||||
order they happened: the user's words, the model's answer, its reasoning, every
|
||||
call with its arguments, every observation, failures and token counts.
|
||||
`wire.jsonl` next to it keeps the request bodies and replies, raw. The log is
|
||||
the complete record - the screen keeps sixteen rows and 4 KiB of a long
|
||||
observation, whichever comes first, and says how many lines are left out, so an
|
||||
`ls -la` or a 300 KB JSON dump does not bury the conversation; the log has all
|
||||
of it.
|
||||
|
||||
## Input history
|
||||
|
||||
Up and Down walk through what was typed before, like a shell. The list is kept
|
||||
in `<session_dir>/history`, so the next session starts with it.
|
||||
|
||||
## Steering while a turn runs
|
||||
|
||||
The turn runs on its own thread, so the keyboard stays live. Every tool call is
|
||||
one row in the transcript, in the words of the call itself - `>> Run echo a` -
|
||||
because "it did something" is not information. The reasoning is inserted before
|
||||
those rows: it came first, and the log should read in the order things
|
||||
happened. While it runs, the input line is only `12s steer> ` and what is
|
||||
typed, and the status line above it stays visible: the call belongs in the
|
||||
transcript, and in the prompt it was a second copy that pushed the steer hint
|
||||
off the right edge. A steer is picked up at the
|
||||
next step boundary; in a single-step turn it becomes the next message instead of
|
||||
being dropped. Curses is only ever touched by the UI thread.
|
||||
|
||||
A name is not text: `SP_STREAM_TOOL` carries the name of a call that has begun,
|
||||
and the answer text is built from `SP_STREAM_TEXT` alone. The stream used to be
|
||||
classified by looking for `tool_calls` in the raw line, which broke as soon as
|
||||
the provider sent `"content":null` beside the call - the name landed in the
|
||||
answer and two `read` calls were printed as `<model> readread`. The kind now
|
||||
comes from the parser (`sp_sse_kind`).
|
||||
|
||||
## Compaction
|
||||
|
||||
`focus` keeps a short recap of the session's goal in front of the model every
|
||||
seven turns — one inserted system message, never twice in a turn, nothing until
|
||||
a goal is set. `/goal <text>` sets the goal and starts that recap turn; the
|
||||
model's answer is remembered and injected later. The goal is stored in the
|
||||
session's `.meta`, so a resumed session finds it; `/continue` starts the next
|
||||
turn from it. `/goal` alone shows it. There is no separate `/recap`: recapping
|
||||
is what a goal does. Both work in the TUI and with `-p`.
|
||||
|
||||
## Languages
|
||||
|
||||
UI strings live in `share/locale/<lang>.msg`, plain `key = text` files read at
|
||||
startup — no gettext, no `.mo`, nothing to build. The language comes from
|
||||
`locale` in the config, else `SPLINTER_LOCALE`, `LC_ALL`, `LC_MESSAGES`, `LANG`.
|
||||
A missing translation falls back to English; a key that exists nowhere is shown
|
||||
as itself, so nothing is silently empty. `test_i18n` fails if `de.msg` misses a
|
||||
key that `en.msg` has.
|
||||
|
||||
Ships with `en` and `de`. Plugins translate their own strings with `sp_t()`.
|
||||
|
||||
## Hosts: one fleet
|
||||
|
||||
A delegate may name a host. The whole invocation then goes through ssh, so
|
||||
claude, opencode or another splinter run where the model or the network is:
|
||||
|
||||
provider remote {
|
||||
about = "on a remote host"
|
||||
tags = [remote]
|
||||
host = build.example.org
|
||||
endpoint = http://10.0.0.2:8080/v1
|
||||
model = ...
|
||||
}
|
||||
|
||||
delegate and delegate_parallel both honour it, and the report names the host like
|
||||
any other model. The remote needs splinter at the same path and its own keys -
|
||||
nothing crosses the jump except the task.
|
||||
|
||||
Proven: a delegate with host=build.example.org ran on the remote host and answered from a
|
||||
provider reachable only over the wireguard link.
|
||||
|
||||
A failing delegate can be run without a model, which is how the child's own
|
||||
error text and exit status are inspected:
|
||||
|
||||
./splinter --delegate claude0 -p "sage nur: beta"
|
||||
|
||||
The observation carries the delegate line, the child's exit status and the task
|
||||
or job state; no model turn, no transport.
|
||||
|
||||
## A fleet in one directory
|
||||
|
||||
`src/swarm.c` is the local variant. The first splinter started in a directory
|
||||
binds `.splinter-swarm.sock` and becomes the master; later ones join as slaves.
|
||||
`/swarm <text>` sends a line to the least busy peer, `/swarm <id> <text>` picks
|
||||
one, `/swarm ls` lists them, and a routed command runs there. It is IPC between
|
||||
processes that share a working directory — not A2A, and not a network protocol.
|
||||
|
||||
## First run: the interview
|
||||
|
||||
splinter --interview
|
||||
|
||||
No questionnaire: the model talks to you. Its system prompt says to get to know
|
||||
you - what you work on, the tools you reach for, how you want to be spoken to,
|
||||
what you never want - one question at a time, and to end with a compact summary
|
||||
followed by the single line `INTERVIEW_COMPLETE`.
|
||||
|
||||
That summary is written to `~/.splinter/USER.txt` (0600) and put into the system
|
||||
prompt of every later session, so the harness starts out knowing who it is
|
||||
working with. The marker itself never reaches the file or the transcript. The
|
||||
interview needs a provider like any chat; Telegram has the same `/interview`,
|
||||
with the conversation in the chat.
|
||||
|
||||
An installation from before `USER.txt` still has `~/.splinter/profile/<user>.md`;
|
||||
it is read as the fallback until the first new interview. Starting the chat
|
||||
without either prints a hint, once.
|
||||
|
||||
## Piped input
|
||||
|
||||
cat /etc/passwd | splinter "explain the file"
|
||||
|
||||
Anything on standard input becomes context, framed and labelled with its size:
|
||||
|
||||
[stdin: 12 bytes]
|
||||
...
|
||||
[/stdin]
|
||||
|
||||
The question and the bytes are kept apart, so the model knows which is which. A
|
||||
binary input is reported as binary instead of being sprayed into the request, the
|
||||
size is capped at 192 KiB (with `[truncated]`), and `--no-stdin` ignores the pipe
|
||||
entirely. With no prompt at all, the input becomes the prompt.
|
||||
|
||||
## Gateway mode
|
||||
|
||||
`--daemon` turns splinter into a Telegram bot: long-poll `getUpdates`, one turn
|
||||
per message, reply. No curses, no terminal.
|
||||
|
||||
~/.splinter/telegram.token the token, mode 0600 (or SPLINTER_TELEGRAM_TOKEN)
|
||||
telegram_allow = 8300935 who is answered, comma separated; nobody by default
|
||||
|
||||
The token is read from a file or the environment and never from an argument, and
|
||||
the message loop keeps no state on disk beyond the session: a restart re-delivers
|
||||
the last update, which costs one duplicated answer and never a lost message.
|
||||
Signature handling is the session's business, not the gateway's.
|
||||
|
||||
A bot cannot start a conversation - the user has to write first, otherwise the
|
||||
API answers `chat not found`. That is Telegram, not the harness.
|
||||
|
||||
The bot registers the commands that actually exist with `setMyCommands`:
|
||||
`/start`, `/help`, `/interview`, `/new`, `/model`, `/connect`, every command a
|
||||
loaded plugin registers
|
||||
(`/goal`, `/quota`, ...) and every program in
|
||||
`~/.splinter/commands/` whose name is a valid Telegram command (lower-case,
|
||||
digits, underscore, at most 32). `/start` and `/help` answer with the short
|
||||
text plus that live list. An approval arrives as a message with **Yes/No
|
||||
buttons**; the callback answers the button, removes the buttons and writes the
|
||||
ack file. The text form `ok <id>` / `no <id>` still works.
|
||||
|
||||
The model's markdown is rendered as Telegram HTML: bold, italic, strike,
|
||||
inline code, fenced blocks, links (also `<https://…>`) and quotes become tags,
|
||||
everything else is escaped. An image is sent as a photo with the alt text as
|
||||
caption: `` is fetched by Telegram, `` (or
|
||||
`file:///…`) is uploaded from this machine. A local file that is not an image
|
||||
goes out as a document (`sendDocument`, at most 50 MiB). The photo guard still
|
||||
checks the bytes — PNG/JPEG/GIF/WebP up to 10 MiB — so a text file cannot ride
|
||||
in as a photo; a missing or unreadable file stays a reference in the chat.
|
||||
Images inside code or a table stay text. Tables are laid out as columns inside a `<pre>` block. A long answer
|
||||
is split at tag boundaries, with the open tags closed and reopened per
|
||||
message, and a piece Telegram refuses to parse is sent as plain text instead.
|
||||
`SPLINTER_TG_MARKDOWN=0` turns the rendering off.
|
||||
|
||||
`/compact [tokens]` runs the compactors now (default target: `compact_target`,
|
||||
else 8000 tokens) and reports messages/bytes before and after. With
|
||||
`compact_threshold` set, the harness compacts automatically once the last
|
||||
request was larger than that: the conversation is cut to `compact_target`
|
||||
before the next turn, so the context never grows without bound. Compaction
|
||||
rewrites the prompt prefix, which invalidates the provider's prompt cache - the
|
||||
threshold is the knob that trades cache hits for a smaller context. What was
|
||||
dropped stays in the session log, and the `recall` tool searches it: the model
|
||||
can look an earlier turn up instead of guessing.
|
||||
|
||||
`/new` (or `/reset`) starts a fresh conversation and a fresh session file; the
|
||||
old one stays on disk, and the system prompt is put back.
|
||||
|
||||
`/model` lists the models the config names (the main endpoint, every delegate
|
||||
with a model, every exit) as buttons and points the running transport at the
|
||||
one you press. The choice is written to `<config>.d/90-model.conf` as
|
||||
`default = PROVIDER[/MODEL]`, so the next start uses it too; picking `main`
|
||||
deletes that file. `/model <name>` keeps the endpoint and takes another model
|
||||
from it. `/model probe` asks every endpoint
|
||||
`/v1/models` and offers what it really serves.
|
||||
|
||||
In the curses chat, `/model` alone opens a picker: Up/Down move, typing filters
|
||||
by provider or model, Enter takes the highlighted selector, Esc cancels. It is
|
||||
the same list the clients get from the `models` protocol command, so `--attach`
|
||||
has it too, and the actual switch is still the ordinary `/model <selector>`
|
||||
command.
|
||||
|
||||
`/connect` works the same in the TUI, one answer per line. It adds a provider
|
||||
in four answers — name, endpoint, model, key
|
||||
variable (or `-` for none); `ollama` and `opencode` stand for their usual
|
||||
endpoint. It writes the line to `<config>.d/20-connect.conf`, so the next start
|
||||
has the provider too, runs one tiny turn against it to prove endpoint, model
|
||||
and key work, and offers to use it right away.
|
||||
|
||||
`/interview` starts the same model-driven interview as `splinter --interview`
|
||||
in the chat; `/new` leaves it. A program in
|
||||
`commands/` answers in the chat: its output is the reply. In the
|
||||
TUI the same program's output becomes context for the model instead. A typo
|
||||
such as `/nosuch` is answered with the command list, not sent to the model.
|
||||
|
||||
`docs/splinter-gateway.service` is a systemd user unit if it should survive a
|
||||
logout.
|
||||
|
||||
## The exit ring
|
||||
|
||||
`plugins/ring/ring.so` holds several ways to reach a model and walks them in
|
||||
order when one is rate limited:
|
||||
|
||||
exit = go | OpenCode Go | endpoint=... | model=...
|
||||
exit = groq | Groq free tier | endpoint=... | model=... | key_env=GROQ_KEY
|
||||
exit = local | local | endpoint=... | model=...
|
||||
|
||||
Run it with `--transport ring`. Only pressure moves the ring: 429, 5xx, "rate
|
||||
limit", "quota". A dead host or a bad key stops the turn where it is - a ring
|
||||
that treats every failure as "try the next" hides real breakage behind a random
|
||||
provider. Proven against two fake providers: the first answered 429, the ring
|
||||
moved on and the second answered; a dead port did not move it.
|
||||
|
||||
## Providers from the environment
|
||||
|
||||
Nothing to configure if the keys are already there:
|
||||
|
||||
OLLAMA_KEY OLLAMA_KEY_0 .. OLLAMA_KEY_N
|
||||
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`) 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.
|
||||
|
||||
The keys are copied into memory and passed to children through the environment -
|
||||
never on a command line, never into a log.
|
||||
|
||||
$ OLLAMA_KEY=... CLAUDE_CODE_OAUTH_TOKEN=... splinter --choose "plane die arbeit"
|
||||
claude-3 score=4 prio=10 task mentions 'plan'
|
||||
$ OLLAMA_KEY=... splinter --choose "implementier das"
|
||||
ollama-2 score=3 prio=0 task mentions 'implement'
|
||||
|
||||
Parallel handover uses `delegate_parallel` with a list of tasks - each picks its
|
||||
own model, up to eight run at once, and the answers come back labelled:
|
||||
|
||||
[parallel: 2 task(s), 12018 ms wall]
|
||||
|
||||
## task 1 | model slow | score 5 | 12018 ms | exit 0 | 75 B | requested tag 'slow'
|
||||
> sag A
|
||||
...
|
||||
|
||||
## task 2 | model fast | score 5 | 16 ms | exit 0 | 74 B | requested tag 'fast'
|
||||
...
|
||||
|
||||
## summary
|
||||
- slow: 1 task(s), 12018 ms total
|
||||
- fast: 1 task(s), 16 ms total
|
||||
|
||||
The summary gets who did what, how long it took and whether it worked - not a wall
|
||||
of answers. A delegate that is slow or failing is visible in the header before
|
||||
anybody reads its prose.
|
||||
|
||||
`max_parallel` still applies: a delegate that is full skips the task with a note
|
||||
instead of queueing it.
|
||||
|
||||
That is the workflow the tool is built for: a strong model plans and defines the
|
||||
work, the local models implement it, and `delegate` is the handover.
|
||||
|
||||
## Delegation
|
||||
|
||||
Work can be handed to another model. A delegate is a `provider` block in the
|
||||
config - no profiles, no directories, nothing to keep in sync:
|
||||
|
||||
provider coder {
|
||||
about = "C99, POSIX, knows the source tree"
|
||||
tags = [code, c99, review]
|
||||
prio = 5
|
||||
max_parallel = 2
|
||||
endpoint = http://127.0.0.1:8080/v1
|
||||
model = Qwen3.6-35B
|
||||
}
|
||||
provider quick { about = "short answers" tags = [chat, cheap] endpoint = ... model = ... }
|
||||
|
||||
Which provider takes a task is decided by words, with synonyms (docs/CONFIG.md,
|
||||
"How a task finds its provider"); a private task only goes to a provider tagged
|
||||
`private`.
|
||||
|
||||
`prio` breaks ties (higher wins), `max_parallel` caps how many calls may run on
|
||||
one delegate at once - a busy delegate answers "busy", it does not queue
|
||||
silently. `kind=cli` and `cmd=claude -p` turn a delegate into a program instead
|
||||
of an endpoint.
|
||||
|
||||
The `delegate` tool takes a task and, optionally, tags. splinter picks the model
|
||||
itself: a requested tag counts 5, a tag found in the task 3, a word of the
|
||||
description 1. The observation starts with the choice and the reason, so a wrong
|
||||
pick is visible instead of mysterious:
|
||||
|
||||
[delegate coder, score 7: task mentions 'code']
|
||||
|
||||
`--choose "text"` prints that decision without running anything:
|
||||
`coder 7 task mentions 'code'`. The child is splinter in one-shot mode with its
|
||||
own context; the tool is classed destructive, so the operator approves the
|
||||
delegation once.
|
||||
|
||||
## Resuming
|
||||
|
||||
`--resume` loads the newest session in the session directory back into the
|
||||
conversation and puts it on screen. It continues that session id rather than
|
||||
opening a fresh one beside it - the first version did the latter, which looked
|
||||
like a resume and was none. The agent profile comes back too: the engine keeps
|
||||
the session's profile in `<session>.agent`, so a session left in plan resumes
|
||||
in plan.
|
||||
|
||||
## MCP
|
||||
|
||||
`plugins/mcp/mcp.so` speaks MCP to a server and registers its tools. The config
|
||||
names the servers; two transports, one block each:
|
||||
|
||||
mcp junction {
|
||||
url = http://172.25.206.16:8090/mcp
|
||||
header = "Authorization: Bearer ${JUNCTION_TOKEN}"
|
||||
}
|
||||
mcp files {
|
||||
cmd = "npx -y @modelcontextprotocol/server-filesystem /home"
|
||||
}
|
||||
|
||||
`url` is the streamable-HTTP transport: one POST per JSON-RPC message, answered
|
||||
with one JSON object or with an SSE stream of `data:` lines - both are read, and
|
||||
the `Mcp-Session-Id` a server hands out is echoed back. `cmd` starts a program
|
||||
whose stdin/stdout carry the same messages. A header travels to curl through its
|
||||
stdin config, so the token is never in `ps`.
|
||||
|
||||
Each tool keeps the schema the server published, so the model sees its
|
||||
parameters; the class is `mutate`, because a server can do anything and the
|
||||
harness does not pretend to know better. With one server the tools are
|
||||
`mcp_<tool>`; with several, `mcp_<server>_<tool>`. Proven against both: a stdio
|
||||
test server (the model called `mcp_add(17, 25)` and answered 42) and a socket
|
||||
server that speaks HTTP and SSE.
|
||||
|
||||
The one-server form from before still works:
|
||||
|
||||
SPLINTER_MCP_CMD="npx -y @modelcontextprotocol/server-filesystem /home" \
|
||||
splinter --plugin plugins/mcp/mcp.so
|
||||
|
||||
The other direction, splinter as the server, is `--mcp-server-listen IP`:
|
||||
newline-delimited JSON-RPC over TCP, read tools only unless `--autonomous`.
|
||||
On 127.x it needs nothing; on any other address it refuses to start without
|
||||
`SPLINTER_MCP_TOKEN`, and every connection must begin with the line
|
||||
`AUTH <token>`. There is no TLS: across a network you do not own, tunnel it.
|
||||
|
||||
SPLINTER_MCP_TOKEN=$(cat ~/.splinter/mcp.token) \
|
||||
splinter --mcp-server-listen 0.0.0.0
|
||||
(echo "AUTH $(cat ~/.splinter/mcp.token)"; cat requests.jsonl) | nc host 8098
|
||||
|
||||
Beside the file tools the server offers the session tools, so another agent can
|
||||
work with splinter itself:
|
||||
|
||||
splinter_sessions list the sessions (current marked)
|
||||
splinter_state model, endpoint, profile, session, busy, tokens
|
||||
splinter_models the selectors /model takes
|
||||
splinter_agents the profiles
|
||||
splinter_history the open session's user and assistant messages
|
||||
splinter_say send a prompt, wait, return the answer
|
||||
splinter_open switch to a session (id, new, last)
|
||||
splinter_model switch the model (any /model selector)
|
||||
splinter_agent switch the profile by name
|
||||
splinter_steer type into the running turn
|
||||
splinter_cancel cancel the running turn
|
||||
splinter_approve answer a pending approval (allow true|false)
|
||||
|
||||
`say` starts a real turn, so the server needs a provider: give it `-m` (or run
|
||||
`--daemon --mcp-server-listen`, where the Telegram daemon and the MCP server
|
||||
share one engine). A turn that parks on an approval is returned as the
|
||||
question, not as a failure; `splinter_approve` answers it. The first line of
|
||||
`splinter_say` is the answer, then the step and tool-call counts.
|
||||
|
||||
## Tools
|
||||
|
||||
Every tool declares its class, and the loop enforces it - never the model, never
|
||||
the prompt.
|
||||
|
||||
- `read` (read): numbered lines, offset and limit, refuses binary files, says
|
||||
where it stopped.
|
||||
- `search` (read): literal string over a directory tree, capped at 100 hits.
|
||||
- `list` (read): a directory.
|
||||
- `write` (mutate): writes a file, up to 4 MiB.
|
||||
- `edit` (mutate): replaces exactly one occurrence; a non-unique `old` is an
|
||||
error, because an ambiguous edit is a wrong edit waiting to happen.
|
||||
- `run` (destructive): a shell command; the exit status is an observation.
|
||||
Its own process group, stdin `/dev/null`, killed after `SPLINTER_RUN_TIMEOUT`
|
||||
seconds (default 600) or `run_timeout` in the config, and an environment without
|
||||
splinter's API keys and tokens, so `run env` cannot hand them to the model.
|
||||
- `webfetch` (mutate): http(s) only, curl started without a shell. Not read:
|
||||
a URL the model picks is a message out of the machine.
|
||||
- `echo` (read), `clock` (read).
|
||||
|
||||
Mutate and destructive tools ask first, unless `--autonomous` is set. In the
|
||||
chat the question sits where the prompt is, worded like the transcript row -
|
||||
`Run touch x (destructive)? y/N` - and the turn waits on it; `n` or Esc
|
||||
denies, and the model is told
|
||||
`error: denied by operator`. This used to be dead code in the TUI: the prompt
|
||||
read stdin behind curses' back, so with `--autonomous` off every such tool was
|
||||
silently denied.
|
||||
|
||||
## Shell escape
|
||||
|
||||
`!command` runs it here and puts the output into the conversation, so the model
|
||||
sees what the operator saw. Capped at 4 KiB: a runaway command must not eat the
|
||||
budget in one keystroke.
|
||||
|
||||
## Slash commands
|
||||
|
||||
A leading `/` never reaches the model: the UI asks the host, the host asks the
|
||||
plugins. A plugin registers what it handles (`/goal` today); an
|
||||
unknown command lists what exists instead of being sent as a prompt.
|
||||
|
||||
Compaction is a plugin, not a switch in the loop. Two ship here: `lcm`
|
||||
(deterministic front-trim with an in-band system message saying what went) and
|
||||
`cps` (continuous parallel compression: plans are prepared on a worker thread
|
||||
from an index of the conversation, then spliced in instantly). Details and the
|
||||
ABI in `docs/PLUGINS.md`.
|
||||
|
||||
## Limits, stated
|
||||
|
||||
- Tool arguments reach the tool as one string; each tool validates its own.
|
||||
- MCP tools are all `mutate`, so they ask before they run.
|
||||
- The ring only retries on rate limits; a 500 from a broken endpoint also counts
|
||||
as pressure, so a provider that fails hard gets skipped rather than fixed.
|
||||
- No retrieval tiers over old sessions. Compaction is a plugin (lcm); it cuts the
|
||||
conversation, it does not remember what it cut.
|
||||
- A `tick()` that never returns hangs the exit: the host can stop a thread only
|
||||
between ticks, not inside one.
|
||||
- Plugins are not sandboxed. They run in the process with full rights; the
|
||||
authorization classes protect the harness from the *model*, not from code you
|
||||
chose to load.
|
||||
|
||||
## License
|
||||
|
||||
BSD-3-Clause.
|
||||
@@ -1,95 +0,0 @@
|
||||
# Offene Punkte
|
||||
|
||||
Stand: 2026-11-10. Jeder Punkt nennt den Beleg und den naechsten Schritt.
|
||||
Erledigtes steht unten, damit die Liste nicht wieder behauptet, etwas sei offen.
|
||||
|
||||
## Offen
|
||||
|
||||
|
||||
Nichts aus der alten Liste. A2A nimmt binaere `file`/`raw`-Teile an und legt
|
||||
sie in `inbox/` ab, der Prompt nennt den Pfad; URL-Teile werden nur von
|
||||
erlaubten Hosts geholt. `SubscribeToTask` schickt den aktuellen Zustand einmal
|
||||
und beendet den Stream (ein Request zur Zeit: es gibt keinen Fortschritt zu
|
||||
beobachten).
|
||||
|
||||
## Erledigt
|
||||
|
||||
- **`~/.local/lib` entwirrt**: `~/.local/lib` ist jetzt ein echtes Verzeichnis
|
||||
mit `libsplinter.so` und einem `node_modules`-Symlink auf
|
||||
`../npm/node_modules`. Der npm-Baum ist keine Fremdlast: er enthaelt
|
||||
`mcp-local-memory` (der MCP, auf den `~/.local/bin/mcp-local-memory` zeigt)
|
||||
und die Python-User-Verzeichnisse. `npm root -g`, das Modul und
|
||||
`~/.local/bin/splinter --version` sind geprueft; nichts geloescht.
|
||||
- **Kids-Zustimmung ueber echtes Telegram**: Am 2026-11-10 wurde Anfrage
|
||||
`548769685` an `@hbx_splinter_bot` geschickt; die Antwort `ok 548769685` kam
|
||||
im Chat, das Gateway loeste sie auf, der `write` lief und schrieb
|
||||
`/tmp/opencode/ack-proof.txt`. Das installierte `~/.splinter/bin/tg-ask` war
|
||||
eine alte Kopie ohne Tokenpfad und wurde durch `tools/tg-ask.sh` ersetzt.
|
||||
- **Telegram-Menue und Knoepfe**: `setMyCommands` registriert dynamisch
|
||||
`/start`, `/help`, `/interview`, alle Befehle der geladenen Plugins und alle
|
||||
Programme in `~/.splinter/commands/` mit gueltigem Telegram-Namen; `/start`
|
||||
und `/help` listen sie im Chat. `/interview` stellt die sechs Fragen im Chat
|
||||
und schreibt das Profil; `/skip` und `/cancel` gehoeren dazu. Zustimmungen kommen mit Ja/Nein-Knoepfen; `callback_query`
|
||||
prueft denselben Allow-List-Eintrag, antwortet, entfernt die Knoepfe und legt
|
||||
die Antwortdatei ab. Der Textweg `ok <id>` bleibt. Programme in
|
||||
`commands/` antworten im Telegram-Chat direkt (im TUI gehen sie ans Modell);
|
||||
ein unbekannter `/Befehl` antwortet mit der Liste. `test_gateway.sh` prueft
|
||||
Menue, Markup, den Fremden-Callback, den echten Callback, das Skript und den
|
||||
unbekannten Befehl.
|
||||
- **Delegate-Diagnose**: `--delegate ID -p TEXT` fuehrt einen benannten Delegate
|
||||
ohne Modell und ohne Transport aus und druckt die Beobachtung (Exit-Status des
|
||||
Kindes, dessen Fehlertext, Job-Zeile). Am 2026-11-10 liefert
|
||||
`--delegate claude0 -p "sage nur: beta"` die Antwort `beta`; der alte Exit 2
|
||||
ist damit nicht reproduzierbar. `tests/test_delegate_cli.sh` prueft den Pfad,
|
||||
den unbekannten Namen und die fehlende Aufgabe.
|
||||
- **Planner-Race**: Der Widget-Tick rief alle fuenf Sekunden `load_tasks()` und
|
||||
setzte das Array unter einem laufenden Tool zurueck; `test_planner` fiel etwa
|
||||
in jedem sechsten Lauf. Ein rekursiver Mutex deckt jetzt Tools, `/tasks` und
|
||||
den Tick. 20 Laeufe in Folge gruen (`ef3c4d0`).
|
||||
- **A2A-Client und -Server**: `plugins/a2a/a2a.c` sendet `SendMessage`
|
||||
(JSON-RPC 2.0, Text, blockierend), in der UI `SendStreamingMessage` (SSE,
|
||||
Artefakt-Text live) und findet den Endpunkt ueber `SPLINTER_A2A_CARD`;
|
||||
`src/a2aserver.c` serviert `SendMessage`, `SendStreamingMessage` (SSE),
|
||||
`GetTask`, `ListTasks`, Multiturn ueber `contextId`, text/plain-`raw`-,
|
||||
URL- und String-`data`-Teile, Webhook-Push samt Push-Config-CRUD,
|
||||
`a2a_get_task`/`a2a_cancel_task` als Client-Werkzeuge und die Agent Card mit
|
||||
Bearer-Token; die Karte meldet `streaming:true` und
|
||||
`pushNotifications:true`. `GetTask` liefert das Task-Objekt, nicht
|
||||
`{"task":...}`. Ein mutierendes Werkzeug pausiert als
|
||||
`INPUT_REQUIRED`; `SendMessage` mit `taskId` und `yes`/`no` setzt fort,
|
||||
`CancelTask` bricht ab (`test_pause`, `test_a2a_input.sh`). `tests/test_a2a.sh` prueft Task, Message, Token, Fehler,
|
||||
Streaming und Discovery, `tests/test_a2a_ui.sh` den Streaming-Pfad,
|
||||
`tests/test_a2a_server.sh` den Server und den Client gegen den Server
|
||||
(Discovery, blockierend und streamend), `tests/test_a2a_context.sh` die
|
||||
Konversation ueber `contextId`.
|
||||
- **Markdown-Tabellen**: `src/md.c` erkennt Kopf + Trenner, rechnet die Breite
|
||||
je Spalte und gibt ausgerichteten Text aus; Text davor/danach bleibt.
|
||||
`tests/test_md.c` (Kopf, Trenner, ungleich lange Zeilen, UTF-8, zwei Bloecke)
|
||||
und ein Fall in `tests/test_ui.sh`, der die Spalten auf dem Schirm prueft.
|
||||
- **Website von Hand**: `tools/gen_www.py` ist weg; die drei Seiten in `src/www/`
|
||||
werden von Hand geschrieben. Zahlen darin sind Stand 2026-11-11, nicht
|
||||
generiert, und muessen bei Aenderungen von Hand nachgezogen werden.
|
||||
- **Delegate im Task-Panel**: `tests/test_delegate.c` uebergibt einen Host mit
|
||||
geladenem `tasks`-Plugin, laesst einen Delegate laufen und prueft
|
||||
`delegate:panel exit 0` im Widget sowie `tasks_running == 0`.
|
||||
- **8k-Kontext gemessen**: `tests/test_compactor.c` faehrt den echten Turn-Loop
|
||||
mit `lcm` bei 8192 und 32768 Bytes Budget und zaehlt die Kompressionen. Der
|
||||
alte Vorschlag `SPLINTER_CTX_MAX=8192` war falsch: das speist nur die Anzeige
|
||||
(`src/ui.c:1045`), komprimiert wird nach `max_bytes` (`src/agent.c:327`).
|
||||
- **Doku-Drift**: `docs/PLUGINS.md` hat Abschnitte fuer planner, provider,
|
||||
scheduler, tmux und a2a; `README.md` nennt `swarm` und die aktuelle Testzahl;
|
||||
`docs/ROADMAP.md` fuehrt Remote/Jumphost und die 8k-Messung als erledigt.
|
||||
- **Neue Tests**: `test_swarm` (master/slave, route, busy, standalone),
|
||||
`test_provstate` (429/503, getrennte Keys, Dateimodus, Fingerprint),
|
||||
`test_planner` (add/list/update, `/tasks`, Datei, Widget) und `test_jobs`
|
||||
(submit/jobs/result, force-Retry, faelliger Job im Scheduler-Tick,
|
||||
Scheduler-Widget).
|
||||
- **Fehler dabei gefunden und behoben**: `delegate_retry` las `id` und `force`
|
||||
in denselben Puffer; `json_str` haengt an, also wurde aus `job-1` mit
|
||||
`force=1` die Id `job-11` (`src/delegate.c`, `tool_delegate_retry`).
|
||||
- **Skills und Memory**: `src/skills.c`, `src/memory.c`, registriert in
|
||||
`src/main.c:908-909` und `test_skills` laufen gruen.
|
||||
- **Kompression verdrahtet**: `ag->host` wird gesetzt (`src/main.c:635`).
|
||||
- **Turn-Loop-Schrittlimit**: `8` war der alte Default, kein Zaehlfehler;
|
||||
`75d8bee` setzt 150 (`src/main.c:873`, `src/config.c:573`).
|
||||
- **Delegate-Limit und Fallback**: `tests/test_delegate.c`.
|
||||
@@ -1,548 +0,0 @@
|
||||
# Configuration
|
||||
|
||||
Splinter reads one file, so that `splinter` alone is enough to start working.
|
||||
|
||||
```
|
||||
~/.splinter/splinter.conf
|
||||
```
|
||||
|
||||
next to the sessions. If that file does not exist, an older install's
|
||||
`$XDG_CONFIG_HOME/splinter/config` (or `~/.config/splinter/config`) is read
|
||||
instead.
|
||||
|
||||
`SPLINTER_CONFIG=/path` overrides the location, `--config PATH` does the same
|
||||
for one run, `--no-config` ignores the file entirely, and `--init-config`
|
||||
writes a commented example.
|
||||
|
||||
## Format
|
||||
|
||||
Blocks with `{ }`, settings as `name = value`, lists in `[ ]`, `#` starts a
|
||||
comment, `"${NAME}"` inserts an environment variable. Not JSON, on purpose —
|
||||
this file gets edited by hand, and a missing comma must not be the reason the
|
||||
harness will not start. An error names the line you wrote.
|
||||
|
||||
```
|
||||
core {
|
||||
default = main # a provider or a pool, below
|
||||
theme = Xresources
|
||||
autonomous = true
|
||||
steps = 60
|
||||
on_limit = wait # a usage limit is waited out (or: fail)
|
||||
max_wait = 2d
|
||||
}
|
||||
|
||||
plugin lcm { } # one block per plugin, see "Plugins"
|
||||
plugin cli { }
|
||||
|
||||
telegram { allow = [123456789] }
|
||||
|
||||
provider ocgo {
|
||||
about = "fast and cheap, good at planning"
|
||||
tags = [cloud, code, fast]
|
||||
endpoint = https://api.example.org/v1
|
||||
model = some-model
|
||||
key_env = EXAMPLE_API_KEY
|
||||
prio = 10
|
||||
limit = 100/5h
|
||||
}
|
||||
provider claude-a {
|
||||
kind = cli
|
||||
cmd = "claude -p"
|
||||
tags = [cli, big]
|
||||
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, 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 `cli` provider can take its model from `-m` like any other:
|
||||
|
||||
```
|
||||
provider occli {
|
||||
kind = cli
|
||||
cmd = "opencode run" # {model} marks where the model goes
|
||||
provider = opencode # prefix for a bare model name
|
||||
model = big-pickle # the default
|
||||
}
|
||||
```
|
||||
|
||||
`-m occli` runs `opencode run --model opencode/big-pickle`,
|
||||
`-m occli/deepseek-v4.1-flash-free` runs `... --model
|
||||
opencode/deepseek-v4.1-flash-free`, and a model that already has a `/`
|
||||
(`-m occli/opencode-go/kimi-k2`) is passed as it is. Without `{model}` in
|
||||
`cmd` the model is appended as `--model`; without any model the command runs
|
||||
unchanged. A model name may hold only letters, digits and `._:/@+-`, since the
|
||||
command goes through `/bin/sh`.
|
||||
|
||||
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
|
||||
fields are the ones of `delegate =` below, plus `delegate = false` to keep it
|
||||
out of delegation. Several files work: every `splinter.conf.d/*.conf` is read
|
||||
too, each in either format.
|
||||
|
||||
The older flat form (`key = value` per line, `delegate = id | text | k=v`)
|
||||
still loads, and is what the tables below describe key by key.
|
||||
|
||||
## Choosing a model: `-m` and `--model-list`
|
||||
|
||||
```
|
||||
splinter --model-list # everything -m takes; asks each endpoint what it serves
|
||||
splinter -m claude # a pool (the member with the most left)
|
||||
splinter -m ocgo # a provider
|
||||
splinter -m ocgo/other-model # a provider with another of its models
|
||||
splinter -m some-model-name # a model that one provider has
|
||||
```
|
||||
|
||||
Without `-m`, `default` in `core` decides. The order is: `-m` on the command
|
||||
line, then the last `default` from the config and its drop-ins (a `/model`
|
||||
choice writes one), then the `endpoint`/`model` of the `core` block (the main
|
||||
endpoint). An explicit `default` is never shadowed by a main endpoint.
|
||||
|
||||
## Agent profiles: build, plan and your own
|
||||
|
||||
Tab in the chat (Shift-Tab back) switches the agent profile, like opencode.
|
||||
The prompt carries the name (`plan> `), the transcript notes the switch,
|
||||
`/agent` lists them, `/agent NAME` picks one, `splinter --agent NAME` starts in
|
||||
one and `--agent-list` prints them.
|
||||
|
||||
- `build` is the default: every tool.
|
||||
- `plan` reads, searches and analyses, changes nothing (tools of the class
|
||||
read only, plus `delegate*` and `plan_task_*`), and ends with a plan.
|
||||
|
||||
Your own are markdown files, `NAME.md`, with front matter like opencode's:
|
||||
|
||||
```
|
||||
---
|
||||
description: Reviews code without touching it
|
||||
model: analyst # what -m takes: provider, pool, provider/model
|
||||
tools: read # all (default) | mutate | read
|
||||
allow: [delegate*] # names (or prefix*) allowed beyond that
|
||||
deny: [run] # never allowed, wins over everything
|
||||
autonomous: false # run mutating tools without asking, or not
|
||||
---
|
||||
The prompt. It is added to the system prompt while this profile is active.
|
||||
```
|
||||
|
||||
Where they are read, later ones replacing earlier ones of the same name:
|
||||
`~/.splinter/agents/`, then `.agents/` and `.splinter/agents/` from the
|
||||
working directory's parents down to the working directory itself. A file named
|
||||
`build.md` or `plan.md` replaces the built-in profile. `mode: subagent` in the
|
||||
front matter marks a file as not for the chat; other keys (temperature ...)
|
||||
are ignored.
|
||||
|
||||
The switch applies from the next turn. A refused tool says so in its result
|
||||
and tells the model to ask for a switch. `model:` moves the chat to that
|
||||
provider (an HTTP one; a cli provider such as `claude -p` cannot be switched
|
||||
to mid-chat, use `delegate` for it) and the next profile without a `model`
|
||||
moves it back.
|
||||
|
||||
## Pools
|
||||
|
||||
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.
|
||||
|
||||
For the conversation: when the provider it is on hits a limit, splinter moves
|
||||
to the next member with room and repeats the request. For delegation: a task
|
||||
that fits a member goes to whichever member the pool picks, as long as that
|
||||
member has every tag of the one that matched (a private task never leaves
|
||||
the `private` provider). A cli member's pool mates become its fallback.
|
||||
|
||||
## How a task finds its provider
|
||||
|
||||
`delegate` (and `--choose TEXT`, which shows the verdict) scores every
|
||||
provider that is not benched or used up:
|
||||
|
||||
| | points |
|
||||
|---|---|
|
||||
| the model asked for the tag (`tags` argument) | +6 |
|
||||
| a word of the task is the tag | +3 |
|
||||
| a word of the task starts with the tag, or is a synonym of it | +2 |
|
||||
| a word of the provider's `about` is in the task (max +2) | +1 |
|
||||
|
||||
Words, not substrings: `client` is not `cli`. Synonyms are built in, German
|
||||
and English: `big` is also gross, large, komplex, migration; `review` is
|
||||
pruef, audit; `plan` is entwurf, architektur; `private` is privat, geheim,
|
||||
secret; and so on for `code`, `small`, `fast`, `cheap`, `local`, `chat`,
|
||||
`summary`, `research`, `test`, `doc`. A tag counts once.
|
||||
|
||||
Two things are rules, not scores. A task that is private (tag `private` or its
|
||||
synonyms) only goes to a provider tagged `private`; with none available it
|
||||
fails rather than leaving the house. And when no tag fits at all, `default`
|
||||
takes the task (unless it is private) instead of an error.
|
||||
|
||||
Equal scores go to the provider with the most left of its allowance, then to
|
||||
the higher `prio`. A pool then picks its member (see above).
|
||||
|
||||
## When everything is at its limit
|
||||
|
||||
splinter finds out when the limit lifts (from `Retry-After`, from the reset a
|
||||
provider names in its message, or from its own count), says so, waits and
|
||||
repeats the request: `on_limit = wait`, the default. `max_wait` bounds it
|
||||
(default 12h). In the chat the screen stays alive; Ctrl-C stops the wait and
|
||||
`/resume` goes on. `on_limit = fail` reports the limit instead.
|
||||
|
||||
## Not in the file: the goal
|
||||
|
||||
The session goal is set at runtime with `/goal <text>` — in the TUI, or in a
|
||||
one-shot run (`splinter -p "/goal ship the config"`). It sets the goal and
|
||||
starts a turn that writes a short recap; the recap is injected every seventh
|
||||
turn. The goal itself is stored in the session's `.meta`, so `/continue` and a
|
||||
resumed session find it. It belongs to the conversation in front of you.
|
||||
|
||||
## Precedence
|
||||
|
||||
Command line, then the file, then the built-in default. An unknown key is an
|
||||
error with its line number: a typo that is silently ignored is a config that
|
||||
lies about what it does.
|
||||
|
||||
## Keys
|
||||
|
||||
| key | meaning |
|
||||
|-----|---------|
|
||||
| `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 |
|
||||
| `ctx` | context window in tokens, optional; the curses status bar uses it for the `ctx used/max` gauge. `SPLINTER_CTX_MAX` overrides it for one run |
|
||||
| `api_key_env` | name of the env var holding the key (default `SPLINTER_API_KEY`) |
|
||||
| `transport` | a transport a plugin provides, e.g. `cli` |
|
||||
| `cli_cmd` | command for the `cli` transport, e.g. `claude -p` |
|
||||
| `plugin` | a plugin to load, one line each: a shipped plugin's name (`lcm`) or a path; in the block form `plugin NAME { }`, see "Plugins" |
|
||||
| `theme` | `Xresources` (the default: `*foreground`, `*background`, `*color0..15` from `xrdb`), `light`/`dark` (white or black page, black or white text), or a CDE palette name (`splinter --list-themes`) |
|
||||
| `locale` | language code (`de`, `en`); catalogues live in `share/locale` |
|
||||
| `autonomous` | `1` runs mutating/destructive tools without asking |
|
||||
| `steps` | tool rounds per turn (default 150) |
|
||||
| `max_bytes` | conversation budget in bytes, `0` = no limit |
|
||||
| `compact_threshold` | context tokens past which the next request is compacted (`0` = off) |
|
||||
| `compact_target` | the size compaction aims for, in tokens; `/compact [tokens]` forces it now |
|
||||
| `session_dir` | where session logs go (default `~/.splinter`) |
|
||||
| `system_prompt` | sent once at the start of a conversation |
|
||||
| `telegram_allow` | user ids the gateway answers, comma-separated; empty means nobody |
|
||||
| `skills_dir` | a directory of skills, one line each |
|
||||
| `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 |
|
||||
| `exit` | one way to reach a model for the exit ring, see below |
|
||||
| `delegate` | another model the `delegate` tool can hand work to, see below |
|
||||
| `mcp` | an MCP server whose tools become splinter's tools, see below |
|
||||
|
||||
Secrets never go into the file: every `*key_env` names a variable, and the
|
||||
variable holds the key. Those variables are hidden from the `run` tool's shell.
|
||||
|
||||
## Exits and delegates
|
||||
|
||||
Both are one line each, `|`-separated, every field but the first named:
|
||||
|
||||
```
|
||||
exit = groq | Groq free tier | endpoint=https://api.groq.com/openai/v1/chat/completions | model=llama-3.3-70b | key_env=GROQ_KEY
|
||||
|
||||
delegate = coder | C99, POSIX, kennt den Quellbaum | endpoint=http://127.0.0.1:8080/v1/chat/completions | model=qwen | tags=code,review | prio=5 | max_parallel=2
|
||||
delegate = far | the same, on another machine | host=buildbox | endpoint=... | model=...
|
||||
delegate = claude-cli | Claude Code | kind=cli | cmd=claude -p | tags=plan
|
||||
delegate = claude-b | Claude Code, second account | kind=cli | cmd=claude -p | env=CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-...
|
||||
```
|
||||
|
||||
`exit` fields: `endpoint`, `model`, `key_env`; the second field is the label.
|
||||
`delegate` fields: `endpoint`, `model`, `key_env`, `tags`, `prio`,
|
||||
`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
|
||||
|
||||
Subscriptions (Claude Pro, ollama.com, opencode-go ...) give an allowance per
|
||||
window and mostly no API that says how much is left. splinter counts its own
|
||||
calls: one line per call in `~/.splinter/usage/<id>.log`, shared by every
|
||||
splinter on the machine. You declare the allowance:
|
||||
|
||||
```
|
||||
limit = 45/5h # the main provider: 45 calls per 5 hours
|
||||
tokens = 2000000/7d # and/or tokens per window (5m, 5h, 7d, 2w)
|
||||
delegate = claude-a | Claude Pro A | kind=cli | cmd=claude -p | tags=plan | limit=45/5h
|
||||
delegate = claude-b | Claude Pro B | kind=cli | cmd=claude -p | tags=plan | limit=45/5h | env=CLAUDE_CODE_OAUTH_TOKEN=...
|
||||
delegate = cloud | ollama.com | endpoint=... | model=... | tags=code | tokens=5000000/7d
|
||||
```
|
||||
|
||||
What it does with that:
|
||||
|
||||
- `/usage` shows how full each allowance is (`claude-a 5h 62%`), a benched
|
||||
one shows when it is back;
|
||||
- delegation skips a provider whose allowance is used up, and among providers
|
||||
that fit the task equally well (same tags: a pool of accounts) it takes the
|
||||
one with the most left;
|
||||
- a refused call (HTTP 429/402/529, or "you've hit your limit - resets 3am")
|
||||
benches the provider until the reset it names.
|
||||
|
||||
The counts are splinter's own: use the same account elsewhere and the real
|
||||
usage is higher than shown. Set the limit a little below the real one.
|
||||
|
||||
`env=NAME=VALUE` (repeatable, up to 8) sets a variable for the delegate's
|
||||
child right before it starts, overwriting whatever the parent exported - so two
|
||||
delegates can run the same CLI with two different accounts. With `host=` it is
|
||||
sent in front of the remote command as `env 'NAME=VALUE'`. A value cannot
|
||||
contain `|`. A literal token in the file is a secret in the file: `chmod 600`.
|
||||
|
||||
### Limits: bench and fall back
|
||||
|
||||
A delegate whose answer says it is at its limit - a 429, "rate limit", "usage
|
||||
limit", claude's "You've hit your weekly limit · resets 3am (Europe/Lisbon)" -
|
||||
is benched until that reset, and the same task goes to the next delegate that
|
||||
fits (the request's tags plus the benched one's). The bench is a file,
|
||||
`~/.splinter/cooldown/<id>` holding the epoch, so every splinter on the machine
|
||||
skips it, even when it is asked for by name; delete the file to unbench early.
|
||||
A reset that cannot be read benches for an hour. In `delegate_parallel` the
|
||||
task moves to the next delegate in its own slot while the others keep running,
|
||||
unless that one is already at its `max_parallel`. Only when nothing else fits
|
||||
does the job wait (`waiting_quota`) for the reset.
|
||||
|
||||
## Plugins
|
||||
|
||||
Every plugin has its own block. The block loads it, and everything in it
|
||||
apart from `path` and `enabled` is that plugin's own configuration:
|
||||
|
||||
```
|
||||
plugin lcm {
|
||||
keep = 6 # messages kept verbatim
|
||||
tool_trim = 8192 # older tool outputs are cut to this
|
||||
}
|
||||
plugin junction { } # url/header from the mcp junction server
|
||||
plugin mine {
|
||||
path = ~/my/plugin.so # not shipped: say where it is
|
||||
foo = bar
|
||||
}
|
||||
plugin status { enabled = false } # kept in the file, not loaded
|
||||
```
|
||||
|
||||
| field | meaning |
|
||||
|-------|---------|
|
||||
| `path` | the `.so` to load; without it the shipped plugin of that name |
|
||||
| `enabled` | `false` keeps the block but does not load the plugin (default on) |
|
||||
| anything else | the plugin's own setting, read with `sp_host_plugin_config()` |
|
||||
|
||||
Without `path`, `plugin NAME { }` finds the shipped plugin next to the
|
||||
binary: `plugins/NAME/NAME.so` in the build tree, then the installed
|
||||
`$(PREFIX)/lib/splinter/plugins/NAME.so`, then the build directory the binary
|
||||
was compiled in. A nested block gives dotted names: `server a { url = x }`
|
||||
inside `plugin foo` is `server.a.url`; a list `[a, b]` arrives as `a,b`.
|
||||
`docs/PLUGINS.md` has the API.
|
||||
|
||||
The old forms still load, so an existing file keeps working:
|
||||
`plugins = [plugins/lcm/lcm.so, ...]` in `core` (one path each) and the flat
|
||||
`plugin = /path/to/x.so`. They carry no plugin settings.
|
||||
|
||||
`plugin junction { }` reads the address and the key from the `mcp junction`
|
||||
server it already uses; its own block may override them:
|
||||
|
||||
```
|
||||
plugin junction {
|
||||
url = http://127.0.0.1:8090/mcp
|
||||
header = "Authorization: Bearer ${JUNCTION_TOKEN}"
|
||||
interval = 5000 # ms between /mcp and status checks
|
||||
models_interval = 60000 # ms between /v1/models probes
|
||||
status_path = /status # first alias; /v1/status, /queue, /v1/queue follow
|
||||
}
|
||||
```
|
||||
|
||||
It evaluates the `X-Junction-Mcp` response header (that is how junction
|
||||
identifies itself; a 200 without it is reported as "not junction") and reads
|
||||
uptime, MCP-server health, queue and request counts from `/status`. The sidebar
|
||||
widget, the `junction` status segment, `junction_status` and `/junction` all
|
||||
show that snapshot. Without either block, `SPLINTER_JUNCTION_URL` and
|
||||
`SPLINTER_JUNCTION_TOKEN` are read.
|
||||
|
||||
## MCP servers
|
||||
|
||||
An MCP server contributes tools. The servers are the configuration of the
|
||||
`mcp` plugin, one `server` block each:
|
||||
|
||||
```
|
||||
plugin mcp {
|
||||
# streamable HTTP: one POST per message
|
||||
server junction {
|
||||
url = http://172.25.206.16:8090/mcp
|
||||
header = "Authorization: Bearer ${JUNCTION_TOKEN}"
|
||||
}
|
||||
|
||||
# or a program that speaks MCP on its stdin/stdout
|
||||
server files {
|
||||
cmd = "npx -y @modelcontextprotocol/server-filesystem /home"
|
||||
}
|
||||
|
||||
# a server that exists but should not be asked
|
||||
server old { url = http://127.0.0.1:9000/mcp enabled = false }
|
||||
}
|
||||
```
|
||||
|
||||
The top-level `mcp NAME { ... }` block and the flat `mcp = ...` line from
|
||||
before still work (they need the plugin loaded as well).
|
||||
|
||||
| field | meaning |
|
||||
|-------|---------|
|
||||
| `url` | the endpoint, streamable-HTTP transport (`.../mcp`) |
|
||||
| `cmd` | a program started with `/bin/sh -c`, spoken to over stdin/stdout |
|
||||
| `header` | one header line, usually the token: `Authorization: Bearer ...` |
|
||||
| `enabled` | `0`/`false` keeps the entry but does not load it (default on) |
|
||||
|
||||
The token belongs in the environment: `"${JUNCTION_TOKEN}"` is expanded when
|
||||
the file is read, and the header travels to curl through its stdin config, so
|
||||
it is never in `ps`. A literal token in the file is a secret in the file:
|
||||
`chmod 600`.
|
||||
|
||||
Tool names: with one server they are `mcp_<tool>`; with several they are
|
||||
`mcp_<server>_<tool>`, so two servers that both offer `search` stay apart. They
|
||||
are all in the `mutate` class - a server can do anything, and the harness does
|
||||
not pretend to know better. The sidebar widget shows how many tools came back
|
||||
and says so when a server stops answering.
|
||||
|
||||
The handshake is `initialize` + `notifications/initialized` + `tools/list`; a
|
||||
server that fails it is reported and skipped, and the others still load. The
|
||||
single-server environment variable from before still works:
|
||||
`SPLINTER_MCP_CMD="npx -y ..."` is one stdio server.
|
||||
|
||||
## Example: local model
|
||||
|
||||
```
|
||||
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 = Xresources
|
||||
autonomous = 1
|
||||
plugin = lcm
|
||||
plugin = cps
|
||||
plugin = clock
|
||||
session_dir = /home/lotherk/.splinter
|
||||
```
|
||||
|
||||
## Example: Claude Code as the model
|
||||
|
||||
```
|
||||
transport = cli
|
||||
cli_cmd = claude -p
|
||||
cli_timeout = 1800
|
||||
plugin = cli
|
||||
theme = Xresources
|
||||
```
|
||||
|
||||
`cli_env = NAME=VALUE` (repeatable, up to 8) sets a variable for the cli
|
||||
program, e.g. `cli_env = CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-...`. It
|
||||
overwrites an exported variable of the same name.
|
||||
|
||||
### Sessions
|
||||
|
||||
A cli program keeps its own conversation across calls. splinter exports its
|
||||
session id as `SPLINTER_CLI_SESSION`; a cli delegate extends it with its name
|
||||
(`sess-...:claude0`), so every delegate has its own conversation per splinter
|
||||
session, and `claude0` and `claude1` never share one. From that key:
|
||||
|
||||
- `claude`: a UUID derived from the key, `--session-id` on the first call,
|
||||
`--resume` after that (remembered in `~/.splinter/cli/`, or
|
||||
`$SPLINTER_CLI_STATE`). If claude disagrees - session moved or deleted - the
|
||||
other form is tried once, which costs no model call.
|
||||
- `opencode`: `--session ses_<derived>`, created by opencode if missing.
|
||||
- anything else: `{session}` and `{uuid}` in the command expand to the key and
|
||||
the UUID.
|
||||
|
||||
Consecutive calls stay in one conversation, so the provider's prompt cache
|
||||
covers the history: measured with claude, the second call read 17.6k tokens
|
||||
from cache and wrote 80. A command that already says `--session`, `--resume`
|
||||
or `--continue` is left alone; an exported empty `SPLINTER_CLI_SESSION` turns
|
||||
sessions off. Only the newest user message is sent - the program has the rest.
|
||||
|
||||
`cli_fallback = claude1, claude0` names cli delegates to use, in order, when
|
||||
`cli_cmd` is at its limit: their `cmd` and `env=` replace the main ones for
|
||||
that call. The main command is benched as `cli`, a fallback under its own id -
|
||||
the same bench delegation uses, so an account at its limit is skipped
|
||||
everywhere. The session key stays, so claude resumes the same conversation
|
||||
under the next account. A fallback's `env=` reaches the program through a
|
||||
0600 file the shell sources, never through a command line `ps` would show.
|
||||
When every account is benched, the turn fails with the first reset time.
|
||||
|
||||
`cli_cmd` may contain `{file}` (the prompt temp-file path) or `{prompt}` (a
|
||||
shell-quoted prompt). Without a placeholder the prompt is fed on stdin, which
|
||||
works for `claude -p`, `ollama run`, and similar tools. For CLIs that take the
|
||||
message as an argument, use e.g. `cli_cmd = opencode run --format default {file}`
|
||||
or pass the prompt via a flag your CLI supports.
|
||||
|
||||
With both `endpoint` and `transport` set, `transport` wins — it is the more
|
||||
specific instruction.
|
||||
|
||||
## Adding a provider from the chat
|
||||
|
||||
`/connect` — in the Telegram gateway and in the TUI (one answer per line) —
|
||||
asks for a name, an endpoint, a model and the
|
||||
variable that holds the key, then writes one `delegate` line to
|
||||
`<config>.d/20-connect.conf` — the drop-in next to the file that is in use, so
|
||||
`--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` 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
|
||||
choice is written to `<config>.d/90-model.conf` as
|
||||
`default = PROVIDER[/MODEL]`, so the next start has it. The provider block
|
||||
supplies kind, endpoint and key variable; the drop-in only names the choice.
|
||||
Picking `main` deletes that file and the configuration speaks again.
|
||||
`/model probe` asks each endpoint `/v1/models` and lists what it really serves;
|
||||
`/model <name>` takes another model from the current endpoint. With a plugin
|
||||
`transport` nothing is written — that program picks the model.
|
||||
|
||||
## Drop-ins
|
||||
|
||||
Next to the config file, a directory with the same name plus `.d` is read after
|
||||
it, every `*.conf` in name order:
|
||||
|
||||
```
|
||||
~/.splinter/splinter.conf
|
||||
~/.splinter/splinter.conf.d/10-local.conf
|
||||
~/.splinter/splinter.conf.d/20-delegates.conf
|
||||
```
|
||||
|
||||
A later file overrides an earlier one, and an unknown key is still an error -
|
||||
now with the file it came from. Proven in `test_config`.
|
||||
|
||||
## Installieren ohne root
|
||||
|
||||
make install PREFIX=$HOME/.local
|
||||
|
||||
Das installierte Binary traegt einen RPATH auf `$ORIGIN/../lib`, findet seine
|
||||
`libsplinter.so` also neben sich. Kein Wrapper, kein `LD_LIBRARY_PATH`, keine
|
||||
Umgebungsdatei: `~/.local/bin/splinter` ist das Programm.
|
||||
|
||||
Keys kommen aus der Umgebung, die du selbst exportierst — splinter liest keine
|
||||
fremde Konfigurationsdatei mit. Ein Delegate nennt nur den Namen der Variablen
|
||||
(`key_env=OPENCODE_GO_API_KEY`).
|
||||
@@ -1,119 +0,0 @@
|
||||
# Backend and front ends
|
||||
|
||||
`splinter` is split in two so that the screen is not the harness.
|
||||
|
||||
```
|
||||
+-----------------------+
|
||||
a keyboard ---> | front end (curses) | ---\
|
||||
+-----------------------+ \
|
||||
\ +----------------+
|
||||
a socket ---> | front end (protocol) | --------> | the engine |
|
||||
+-----------------------+ / +----------------+
|
||||
/ agent, tools,
|
||||
-p / --daemon --> | direct library use | ---/ transports,
|
||||
+-----------------------+ session, config,
|
||||
plugins
|
||||
```
|
||||
|
||||
## The backend
|
||||
|
||||
`libsplinter.so` is the whole harness minus the screen:
|
||||
|
||||
| file | what it owns |
|
||||
| --- | --- |
|
||||
| `src/backend/engine.c` | `struct sp_engine`: session, conversation, registry, plugins, transport, agent, turn thread, event queue, slash commands |
|
||||
| `src/backend/agent.c` | the loop: request, tool calls, observations, answer |
|
||||
| `src/backend/transport*.c`, `openai.c`, `anthropic.c`, `sse.c` | a conversation in, a reply out |
|
||||
| `src/backend/builtin.c`, `tool.c` | the tools and the registry |
|
||||
| `src/backend/session.c`, `conv.c` | append-only JSONL, owned messages |
|
||||
| `src/backend/config.c`, `providers.c`, `usage.c` | configuration and providers |
|
||||
| `src/backend/plugin.c` | `dlopen`, widgets, commands, gates, compactors |
|
||||
| `src/backend/telegram.c`, `a2aserver.c`, `mcpserver.c` | outbound protocol adapters |
|
||||
|
||||
The engine never calls into a front end. A turn runs on a thread of the
|
||||
engine's making and appends `struct sp_event` records to a queue; the front end
|
||||
drains it whenever it draws. That is the whole threading rule, and it is why a
|
||||
slow terminal cannot stall a model, and why a GUI cannot corrupt a turn.
|
||||
|
||||
`include/splinter_engine.h` is the C boundary. Its event kinds map one to one
|
||||
onto the JSON `ev` names in `docs/PROTOCOL.md`.
|
||||
|
||||
## The front ends
|
||||
|
||||
| file | kind |
|
||||
| --- | --- |
|
||||
| `src/frontend/curses.c` | the screen: transcript, sidebar, prompt, keys |
|
||||
| `src/frontend/ui_backend.h` | what the screen needs from a backend |
|
||||
| `src/frontend/ui_local.c` | that backend as the engine in this process |
|
||||
| `src/frontend/ui_remote.c` | that backend as a protocol client (`--attach`) |
|
||||
| `src/frontend/protocol.c` | `splinter --serve`: JSON lines, sessions, open |
|
||||
| `src/frontend/client.c` | `splinterctl`, the reference protocol client |
|
||||
| `src/main.c` | the launcher: parse, config, engine, pick a front end |
|
||||
|
||||
`curses.c` owns the screen, the themes, the markdown-to-ASCII pass, the input
|
||||
history and the key bindings. It does not know how a provider is switched, how
|
||||
a session is created or how an approval is waited for — those are
|
||||
`/model`, `/new` and the engine's condition variable. It talks to one of two
|
||||
backends through `ui_backend.h`: the engine linked into the process
|
||||
(`--chat`), or a served engine over the socket (`--attach`). The screen cannot
|
||||
tell them apart, which is the test the protocol has to pass.
|
||||
|
||||
```
|
||||
splinter --serve --socket /tmp/s.sock # one process: engine + protocol
|
||||
splinter --attach --socket /tmp/s.sock # another: the screen as a client
|
||||
```
|
||||
|
||||
The server owns the engine: `sessions` lists the session directory and `open`
|
||||
switches to another id (or `new`/`last`), sending the state and history of that
|
||||
session. The curses screen exposes that as `/sessions` and `/open ID`, in both
|
||||
modes: `--serve` switches its engine, and the in-process `--chat` closes its
|
||||
engine and opens the next one from the same options (plugins keep process
|
||||
globals, so the old one goes first). One session is active at a time; two
|
||||
clients still take turns.
|
||||
|
||||
`--attach` keeps running when the backend disappears: it says so, retries every
|
||||
second, and on the next server asks for the session it was on by id. The history
|
||||
it already had is shown again, and turns continue; if that session is gone, the
|
||||
screen says which one and stays on the session the server has. A GUI gets the
|
||||
same with `sessions`, `open` and its own retry loop.
|
||||
|
||||
## Writing a GUI client
|
||||
|
||||
Two ways, and the second one is the interesting one.
|
||||
|
||||
1. **Link the library.** Include `splinter_engine.h`, call `sp_engine_open()`,
|
||||
then `sp_engine_input()` / `sp_engine_submit()` / `sp_engine_poll()` as
|
||||
`src/frontend/curses.c` does. This only works from C or a C-binding
|
||||
language.
|
||||
|
||||
2. **Speak the socket.** Run `splinter --serve` and connect to the Unix socket
|
||||
from anything that can open one and write JSON: Python/Tk, Qt, GTK, a web
|
||||
front end through a small bridge. `docs/PROTOCOL.md` is the contract;
|
||||
`docs/proto-example.py` is a complete 60-line client, and
|
||||
`splinter --attach` is the full curses front end running this way. Use
|
||||
`sessions`/`open` for tabs and retry the connect for a server restart.
|
||||
|
||||
3. **Let another harness use splinter as a model.** `splinter --openai-listen`
|
||||
serves `/v1/chat/completions`: the caller's tools stay with the caller,
|
||||
splinter's own run locally under `gw_*`. See `docs/GATEWAY.md`.
|
||||
|
||||
The recommended shape for a GUI:
|
||||
|
||||
* one window per connection; the `state` event fills the sidebar (session,
|
||||
model, agent, tokens);
|
||||
* on connect, send `history` once and draw the returned items - a GUI that
|
||||
joins a session should not look like it invented it;
|
||||
* append `stream` deltas to the open bubble; close it on `step` or `turn`;
|
||||
* draw `tool` as a call row and `tool_result` under it (or on the same row
|
||||
when `join` is true);
|
||||
* when `approval` arrives, show the question and send `approve`;
|
||||
* `busy` drives the spinner; `cancel` and `steer` are the two buttons that
|
||||
must remain live during a turn;
|
||||
* nothing in the client has to know a provider, a session file or a tool's
|
||||
authorization class — the engine already decided.
|
||||
|
||||
There is one conversation and one client at a time; a second connection waits
|
||||
until the first is gone. An attaching client asks for `history` (the last 100
|
||||
messages, up to 256 KiB) and shows the session it joins; live events continue
|
||||
from that point. If a client disconnects, the server cancels a running turn,
|
||||
because an approval that nobody can answer would park the engine forever.
|
||||
@@ -1,120 +0,0 @@
|
||||
# The OpenAI gateway
|
||||
|
||||
`splinter --openai-listen IP [--openai-listen-port N]` is a small
|
||||
OpenAI-compatible endpoint. Another harness points its OpenAI client at it and
|
||||
gets an answer from splinter's configured provider, with **tools on both
|
||||
sides**: splinter executes its own tools where splinter runs, the caller
|
||||
executes its tools where the caller runs.
|
||||
|
||||
```sh
|
||||
# the side with the files and the shell
|
||||
splinter -m myprovider --openai-listen 127.0.0.1 --openai-listen-port 8097
|
||||
|
||||
# the other harness
|
||||
export OPENAI_BASE_URL=http://127.0.0.1:8097/v1
|
||||
export OPENAI_API_KEY=unused # unless SPLINTER_GATEWAY_TOKEN is set
|
||||
```
|
||||
|
||||
`GET /v1/models` answers with the run's model, so a client that probes first is
|
||||
happy. `POST /v1/chat/completions` accepts the usual `messages`, `tools` and
|
||||
`stream` fields.
|
||||
|
||||
## Two tool namespaces
|
||||
|
||||
The model sees two kinds of tools in one request:
|
||||
|
||||
| name | who runs it | where |
|
||||
| --- | --- | --- |
|
||||
| `gw_read`, `gw_write`, `gw_edit`, `gw_run`, … | splinter | on the host where splinter runs |
|
||||
| everything in the caller's `tools` array | the calling harness | where the harness runs |
|
||||
|
||||
`gw_` is reserved: a caller tool with that prefix is refused with HTTP 400,
|
||||
because that is how a local `read` and a caller's `read` stay apart.
|
||||
|
||||
The loop, inside one HTTP request:
|
||||
|
||||
1. splinter asks its provider with the caller's conversation, the caller's
|
||||
tools **and** its own tools renamed `gw_*`.
|
||||
2. If the model calls `gw_*`, splinter runs it here (read tools always;
|
||||
mutating and destructive ones only with `--autonomous`), appends the
|
||||
observation and asks the provider again. The caller never sees these calls.
|
||||
3. If the model calls a caller tool, splinter returns a normal
|
||||
`chat.completion` with `tool_calls` and `finish_reason: "tool_calls"`. The
|
||||
harness runs them, sends the results as `tool` messages in the next request,
|
||||
and the gateway continues.
|
||||
4. If a reply mixes both, the local calls run here and the caller's calls are
|
||||
returned in the same `tool_calls` answer. Since the caller cannot answer a
|
||||
`gw_` call, the local observations travel in the message `content` (under
|
||||
"local gateway tools ran on the splinter host:"); the caller sends them back
|
||||
with the assistant message as usual, and the model sees both sides.
|
||||
|
||||
Every request is stateless, as the OpenAI protocol says: the conversation
|
||||
travels with it. The loop is capped at 16 local tool rounds and each
|
||||
observation at 32 KiB.
|
||||
|
||||
## Request shaping
|
||||
|
||||
The caller's `temperature`, `top_p` and `max_tokens` (or
|
||||
`max_completion_tokens`) are forwarded to the provider; absent values stay the
|
||||
provider's default. The response echoes the request's `model` name, and every
|
||||
message, including the mixed-reply case, stays within the OpenAI chat shape.
|
||||
|
||||
Bodies may arrive with `Content-Length` or `Transfer-Encoding: chunked`; only
|
||||
one request per connection is read, then the connection closes.
|
||||
|
||||
## Streaming
|
||||
|
||||
With `"stream": true` the gateway uses the provider's streaming transport and
|
||||
forwards each text delta as a `chat.completion.chunk` event while it arrives -
|
||||
the caller sees the answer grow instead of waiting for the last token. The
|
||||
caller's tool calls are sent as one `tool_calls` delta at the end of the step,
|
||||
because a name is only complete when the provider has finished it; local
|
||||
`gw_*` calls stay invisible. `"stream_options":{"include_usage":true}` adds a
|
||||
final usage chunk before `[DONE]`, with the token counts summed over every
|
||||
upstream round of the request.
|
||||
|
||||
If the provider fails after the stream has started, the stream carries an
|
||||
`{"error":...}` object and `[DONE]`; a request that was invalid before the
|
||||
first byte is still an ordinary HTTP 400. The gateway ignores SIGPIPE, so a
|
||||
caller that closes its stream early cannot kill the server.
|
||||
|
||||
## Examples
|
||||
|
||||
A local tool, executed by splinter, from the caller's point of view an ordinary
|
||||
completion:
|
||||
|
||||
```sh
|
||||
curl -s http://127.0.0.1:8097/v1/chat/completions \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"model":"x","messages":[{"role":"user","content":"read Cargo.toml"}]}'
|
||||
```
|
||||
|
||||
A caller tool comes back instead:
|
||||
|
||||
```json
|
||||
{"choices":[{"index":0,"message":{"role":"assistant","content":"",
|
||||
"tool_calls":[{"id":"c1","type":"function",
|
||||
"function":{"name":"browser_open","arguments":"{\"url\":\"...\"}"}}]},
|
||||
"finish_reason":"tool_calls"}]}
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
- Beyond loopback the server refuses to start without
|
||||
`SPLINTER_GATEWAY_TOKEN`; with a token set, every request needs
|
||||
`Authorization: Bearer <token>`.
|
||||
- `--autonomous` is the switch that lets the model use `gw_write`, `gw_edit`
|
||||
and `gw_run`. Without it those calls are denied with an observation the model
|
||||
reads, so it can still answer.
|
||||
- There is no TLS. Expose it through ssh, WireGuard or a TLS proxy when the
|
||||
network is not yours.
|
||||
- One request is served at a time; the endpoint is a gateway, not a load
|
||||
balanced service.
|
||||
|
||||
## Where the tools come from
|
||||
|
||||
`gw_*` is the engine's registry: the builtins (`read`, `write`, `edit`,
|
||||
`search`, `list`, `run`, `websearch`, `webfetch`), `folder_history`,
|
||||
`delegate`, and the skills tools. Plugins loaded with `--plugin` add
|
||||
theirs. The caller's tools are passed through to the provider untouched, except
|
||||
for the `gw_` reservation.
|
||||
@@ -1,499 +0,0 @@
|
||||
# Plugins
|
||||
|
||||
A splinter plugin is a shared object that links against `libsplinter.so` and
|
||||
exports one symbol:
|
||||
|
||||
```c
|
||||
const struct sp_plugin *sp_plugin_describe(void);
|
||||
```
|
||||
|
||||
The struct, the ABI number and the host functions are in
|
||||
`include/splinter_plugin.h`. Nothing else is stable. `SP_PLUGIN_ABI` changes
|
||||
whenever that header changes in a way that breaks an old plugin, and a plugin
|
||||
with the wrong number is refused at load time with the two numbers in the
|
||||
message.
|
||||
|
||||
## Build
|
||||
|
||||
```sh
|
||||
cc -std=c99 -shared -fPIC -o myplugin.so myplugin.c -L. -lsplinter \
|
||||
-Wl,-rpath,'$ORIGIN'
|
||||
```
|
||||
|
||||
`splinter --plugin ./myplugin.so --chat` loads it before the first turn. A
|
||||
plugin that fails to load is reported on stderr and skipped; the harness keeps
|
||||
working.
|
||||
|
||||
## Configuration
|
||||
|
||||
In the config file every plugin has its own block (`docs/CONFIG.md`,
|
||||
"Plugins"):
|
||||
|
||||
```
|
||||
plugin mine {
|
||||
path = ~/my/myplugin.so # omitted: the shipped plugin "mine"
|
||||
depth = 3
|
||||
hosts = [a, b]
|
||||
server a { url = http://a/mcp }
|
||||
}
|
||||
```
|
||||
|
||||
Everything but `path` and `enabled` is the plugin's own, and it reads it
|
||||
through the host by the block's name:
|
||||
|
||||
```c
|
||||
const char *d = sp_host_plugin_config(host, "mine", "depth"); /* "3" */
|
||||
const char *h = sp_host_plugin_config(host, "mine", "hosts"); /* "a,b" */
|
||||
const char *u = sp_host_plugin_config(host, "mine", "server.a.url");
|
||||
```
|
||||
|
||||
A missing key is NULL; the value is a string, parsing is the plugin's job.
|
||||
To see every setting (the servers it was given, say), walk them in file order:
|
||||
|
||||
```c
|
||||
const char *key, *val;
|
||||
size_t i;
|
||||
|
||||
for (i = 0; (val = sp_host_plugin_config_at(host, "mine", i, &key)) != NULL; i++)
|
||||
/* key = "depth", "hosts", "server.a.url", ... */;
|
||||
```
|
||||
|
||||
Both work from `init()` on. The config is read once at start; a value does
|
||||
not change while the plugin runs. The `mcp` plugin is the one exception to
|
||||
the dotted names: its `server NAME { }` blocks become the MCP server list it
|
||||
always read (`sp_host_config()`), so `plugin mcp { server ... }` and the old
|
||||
`mcp NAME { }` block mean the same.
|
||||
|
||||
## What a plugin may do
|
||||
|
||||
| hook | thread | may block | may touch curses |
|
||||
|------------|---------------|-----------|------------------|
|
||||
| `init()` | main | no | no |
|
||||
| `run()` | main | yes | no |
|
||||
| `tick()` | its own | yes | no |
|
||||
| `draw()` | main (UI) | no | no |
|
||||
|
||||
Streaming is a transport concern, not a plugin one: `sp_transport.send_stream`
|
||||
is optional, and a transport that cannot stream leaves it NULL — the loop then
|
||||
falls back to the one-shot call.
|
||||
|
||||
`tick()` runs on a thread the host creates and can stop. It may read files,
|
||||
wait on sockets, sleep. It must not assume it is the only thread.
|
||||
|
||||
What the plugin wants to say is published as a widget line:
|
||||
|
||||
```c
|
||||
sp_host_widget_text(host, "mywidget", "42 items");
|
||||
```
|
||||
|
||||
The host copies the string under a mutex, so a stack buffer is fine and the
|
||||
worker never hands the UI a pointer it could free.
|
||||
|
||||
## Widgets
|
||||
|
||||
```c
|
||||
static const struct sp_widget w = {
|
||||
.name = "clock",
|
||||
.tick = clock_tick, /* worker thread, publishes text */
|
||||
.draw = NULL, /* NULL: render the published text */
|
||||
.ctx = NULL,
|
||||
.interval_ms = 1000, /* 0: tick once */
|
||||
};
|
||||
sp_host_add_widget(host, &w);
|
||||
```
|
||||
|
||||
The sidebar lists one line per widget, `name: text`; `/widgets` prints the same
|
||||
lines into the transcript. `draw()` exists for widgets that need more than one
|
||||
line; it runs on the UI thread and must be fast, because it holds up the rest of
|
||||
the screen while it runs.
|
||||
|
||||
## Threads, honestly
|
||||
|
||||
- One thread per widget with a `tick`. A widget without `tick` gets no thread.
|
||||
- The host joins every thread in `sp_host_free()`, setting a stop flag first.
|
||||
A `tick` that never returns therefore hangs the exit; that is a bug in the
|
||||
plugin, not something the host can fix from outside.
|
||||
- No plugin is `dlclose()`d. Unmapping code that a thread might still be
|
||||
inside is how a harness dies in a way nobody can debug.
|
||||
- The host pointer is thread-safe only for `sp_host_widget_text()` and
|
||||
`sp_host_note()`. Everything else belongs to the main thread. That is a
|
||||
rule, not an accident.
|
||||
|
||||
## Tools
|
||||
|
||||
A plugin registers tools with the same authorization classes the builtins use:
|
||||
|
||||
```c
|
||||
struct sp_tool t = { 0 };
|
||||
t.name = "clock";
|
||||
t.description = "Report the local date and time.";
|
||||
t.auth = SP_AUTH_READ;
|
||||
t.run = clock_tool;
|
||||
sp_host_add_tool(host, &t);
|
||||
```
|
||||
|
||||
`SP_AUTH_READ` runs. `SP_AUTH_MUTATE` and `SP_AUTH_DESTRUCTIVE` ask the
|
||||
operator unless the harness was started with `--autonomous`. The loop decides
|
||||
this, not the plugin.
|
||||
|
||||
## Compaction
|
||||
|
||||
A compactor runs on the main thread before every request, with the whole
|
||||
conversation in hand, and may rewrite it:
|
||||
|
||||
```c
|
||||
struct sp_compactor {
|
||||
.const char *name;
|
||||
int (*compact)(struct sp_host *, struct sp_conv *, size_t budget_bytes,
|
||||
unsigned turn);
|
||||
};
|
||||
```
|
||||
|
||||
Return 1 when it changed something, 0 when there was nothing to do, -1 on
|
||||
failure. A failure is counted and the turn continues: a broken compactor must
|
||||
not take the conversation with it.
|
||||
|
||||
Two come with the tree.
|
||||
|
||||
**lcm** — deterministic, lossy, honest. If the conversation does not fit the
|
||||
budget, it first cuts **old tool outputs** to a head and a tail with a marker
|
||||
in between (their middle stays in the session log, where the `recall` tool
|
||||
finds it); only when that is not enough does it keep the leading system message
|
||||
and the last six messages and put one system message in between that says how
|
||||
many messages went, of which roles, and quotes the head of the oldest dropped
|
||||
turn. No second model is called, so a run stays reproducible and costs nothing
|
||||
extra. `plugin lcm { keep = 6; tool_trim = 8192 }` sets the verbatim tail and
|
||||
the byte cap per old observation; `tool_trim = 0` turns the trim off.
|
||||
|
||||
**cps** — continuous parallel compression. The expensive part (deciding what
|
||||
would go) is computed on the widget's worker thread from an *index* of the
|
||||
conversation — role, size, and 64 bytes of head per message, copied under a
|
||||
mutex. The worker never touches the conversation itself. When the budget is
|
||||
hit, the main thread splices an already-prepared plan in one pass. Its widget
|
||||
line shows `idle (applied N, prepared M)` or `plan ready: cut X/Y, A -> B B`,
|
||||
so "continuous" is visible rather than claimed.
|
||||
|
||||
The limit is stated in both files: they can decide *which* messages go, not
|
||||
summarise their text, because summarising needs the text and the text is not
|
||||
the worker's to read.
|
||||
|
||||
## Transports
|
||||
|
||||
A transport turns a conversation into an answer. The built-in one speaks
|
||||
OpenAI's `chat/completions`; a plugin can provide others:
|
||||
|
||||
```c
|
||||
struct sp_transport tr = { my_send, my_ctx };
|
||||
sp_host_add_transport(host, "cli", tr);
|
||||
```
|
||||
|
||||
then `splinter --plugin ... --transport cli`.
|
||||
|
||||
**cli** ships with the tree and makes *any program* the model — `claude -p`,
|
||||
`opencode run`, `ollama run`, a shell script. Each brings its own keys, its own
|
||||
quota, its own free tier:
|
||||
|
||||
```sh
|
||||
SPLINTER_CLI_CMD="claude -p" ./splinter -p "hi" --plugin plugins/cli/cli.so --transport cli
|
||||
SPLINTER_CLI_CMD="opencode run" ./splinter -p "hi" --plugin plugins/cli/cli.so --transport cli
|
||||
```
|
||||
|
||||
- `SPLINTER_CLI_CMD` — the program, default `claude -p`
|
||||
- `SPLINTER_CLI_FULL=1` — send the whole transcript instead of the last user
|
||||
message (for programs that keep no history of their own)
|
||||
- `SPLINTER_CLI_TIMEOUT` — seconds, default 1800 (or `cli_timeout` in the config)
|
||||
- `SPLINTER_CLI_CMD` may include `{file}` (prompt file path) or `{prompt}` (shell-quoted prompt); without a placeholder the prompt is passed on stdin
|
||||
|
||||
The command comes from the operator's environment and runs through `/bin/sh -c`;
|
||||
it is never built from model output. Output is capped at 4 MiB, a non-zero exit
|
||||
returns the program's own stderr, and a program that prints nothing is an error
|
||||
— an empty answer must never look like a real one.
|
||||
|
||||
## focus
|
||||
|
||||
Long conversations drift: ten turns in, the model is deep in a detail and the
|
||||
reason the session exists is somewhere behind it. `focus` puts the goal back on
|
||||
the table.
|
||||
|
||||
```
|
||||
/goal splinter zu einem agent-harness machen, das hermes ersetzt
|
||||
```
|
||||
|
||||
`/goal <text>` sets it and starts a turn: the prompt asks the model for a short
|
||||
recap (3-5 bullets, what must be true at the end, the first steps, open
|
||||
questions). The plugin remembers that answer and injects it every seventh turn
|
||||
— never twice in one turn, nothing at all when no goal is set. `/goal` alone
|
||||
shows the goal. There is no `/recap`: recapping is what a goal does. The goal is
|
||||
stored in the session's `.meta`, so a resume, `/open` or `/continue` finds it
|
||||
again. `/continue` starts a turn that picks the goal up where the session
|
||||
stopped. That works in the TUI and in a one-shot run
|
||||
(`splinter -p "/goal ..."`); it is not a config key, because a goal belongs to
|
||||
the conversation in front of you. `SPLINTER_FOCUS_EVERY` sets the interval
|
||||
(default 7 turns).
|
||||
|
||||
The goal is in the prompt from the first request, not from the seventh turn:
|
||||
when a goal exists and has not been announced in this session yet (config,
|
||||
resume, planner), the compactor inserts it once, before the newest user
|
||||
message.
|
||||
|
||||
A goal ends. Every text that carries the goal — the first announcement, the
|
||||
recap prompt, `/continue`, the periodic reminder — tells the model to end its
|
||||
final answer with the single line `GOAL_COMPLETE` when the goal is fully
|
||||
achieved. The plugin then records `goal_state=succeeded` beside the goal in the
|
||||
session `.meta` (it also watches the session log from its tick, so the state
|
||||
changes without waiting for the next turn), stops reminding, writes one
|
||||
`goal succeeded: …` note into the transcript, and shows `[done]` in the sidebar.
|
||||
Only an answer written after the goal went into a prompt can close it, so an
|
||||
old `GOAL_COMPLETE` cannot mark a goal that was set later. `/goal` reports the
|
||||
state; a new goal opens a new one.
|
||||
|
||||
It registers as a compactor and inserts one system message — *before* the newest
|
||||
user message, so the model reads recap then request and answers the request. If
|
||||
the model has not answered the recap prompt yet, the goal text stands in. Its
|
||||
widget line shows the goal, `[done]` when it is reached, and the warning is
|
||||
never printed twice in one turn.
|
||||
|
||||
It is a reminder, not an instruction: the user can change direction at any
|
||||
time, and the message says so on its face.
|
||||
|
||||
## junction
|
||||
|
||||
The fleet router, evaluated from the outside. junction answers `/mcp` with
|
||||
|
||||
```
|
||||
X-Junction-Mcp: 1
|
||||
```
|
||||
|
||||
and that header is the identity: a 200 with the header is junction, a 200
|
||||
without it is "not junction, or a proxy in front of it" — a health check that
|
||||
trusts any answer is wrong exactly when it matters.
|
||||
|
||||
The widget is only what belongs to the model this run is on: its name (from
|
||||
the engine, not from the provider's configured default — `/model` can switch
|
||||
the model without touching the config) and the targets the matching
|
||||
`/status` rule sends it to. Nothing else: a `!` marks a target whose own
|
||||
health probe is failing.
|
||||
|
||||
```
|
||||
junction
|
||||
deepseek-v4.1-flash
|
||||
serving opencode-go1
|
||||
route opencode-go0
|
||||
opencode-go1
|
||||
opencode-go2
|
||||
ollama0-splinter
|
||||
4/4 up
|
||||
```
|
||||
|
||||
`serving` is the `X-Junction-Endpoint` of the **last real answer** - the
|
||||
provider says which upstream actually served it, and the transport publishes
|
||||
it (`sp_host_served_by`). That is not the route: junction may pick another
|
||||
target per request, and a fallback can differ from every rule. `(no request
|
||||
yet)` until the first answer. The route below is what the matching rule would
|
||||
use; the rule is chosen by exact model match, then glob (`*`, `?`), then
|
||||
catch-all, and rules with a `path` describe another route (`/v1/models`). A
|
||||
target whose probe is down gets the `!`.
|
||||
|
||||
Everything else is `/junction`, not the sidebar: uptime, MCP servers, queue,
|
||||
requests, endpoints with p95 and exhausted counts, the model count from
|
||||
`/v1/models`, and **every response header** of every probe grouped by source.
|
||||
That includes `X-Junction-Ms`/`X-Junction-Cache` and the probe's own
|
||||
`X-Junction-Endpoint` (which is `/v1/models` -> `opencode-go`, not the
|
||||
conversation's route). junction accepts `/status`, `/v1/status`, `/queue` and
|
||||
`/v1/queue` as the same route; the plugin remembers which one answered and
|
||||
only tries the whole list when it stops. It does not count a second time.
|
||||
|
||||
That is a widget, a status segment (`junction 20m up`), the tool
|
||||
`junction_status` and `/junction`. The address and the key come from the
|
||||
plugin's own block, else from the `mcp junction` server, else from
|
||||
`SPLINTER_JUNCTION_URL` / `SPLINTER_JUNCTION_TOKEN`. The header is never
|
||||
printed: it carries the key. `interval` (milliseconds, default 5000) sets how
|
||||
often the tick asks; `models_interval` (default 60000) how often the model
|
||||
route is probed, because that one goes upstream and the other two do not.
|
||||
|
||||
## self
|
||||
|
||||
What the session costs the machine, and what its children cost:
|
||||
|
||||
```
|
||||
self
|
||||
84M rss 3.2% cpu
|
||||
18 thr 41 fd
|
||||
kids 3 120M 1.4% cpu
|
||||
io 12M r 300k w
|
||||
```
|
||||
|
||||
The process itself from `/proc/self/status` (VmRSS, Threads), `/proc/self/fd`
|
||||
(count) and `/proc/self/io` (bytes); the children from one pass over
|
||||
`/proc/<pid>/stat`, following the parent chain: `run` calls, MCP server
|
||||
children, delegates, a CLI transport. CPU is the delta between two samples
|
||||
(2 s by default, `interval` in ms), so it says what is happening now; IO is
|
||||
cumulative for the session. `/self` and the `session_usage` tool print the
|
||||
same numbers with the pid and the child count.
|
||||
|
||||
## Zustimmung (ack)
|
||||
|
||||
Ein Werkzeug, das etwas aendert, braucht ein Ja von einem Menschen. Der Mensch
|
||||
kann am Terminal sitzen, am Telefon, oder hinter einem Skript - es koennen
|
||||
mehrere Kanaele sein, und die erste Antwort gewinnt.
|
||||
|
||||
Der Mechanismus ist zwei Dateien, damit nicht zwei Prozesse um dieselben
|
||||
Telegram-Updates streiten:
|
||||
|
||||
~/.splinter/ack/pending/<id> die Anfrage (0600)
|
||||
~/.splinter/ack/pending/<id>.answer die Antwort (0600)
|
||||
|
||||
Der blockierte Prozess wartet nur auf die Datei. Kanaele sind Melder: sie stossen
|
||||
die Anfrage nach draussen (ein Kommando pro Kanal), und wer die Antwort liest -
|
||||
das Gateway, ein Telefon, ein Skript - legt die Antwortdatei ab.
|
||||
|
||||
SPLINTER_ACK_CHANNELS="telegram-ask,mastodon-ask" # Kommandos, Komma-getrennt
|
||||
SPLINTER_ACK_TTL=120 # Sekunden, Default 120
|
||||
SPLINTER_ACK_DIR=~/.splinter/ack # optional
|
||||
SPLINTER_ACK_BY=konrad # wer antwortet (beim --ack)
|
||||
|
||||
Im Telegram-Chat antwortet ein Programm aus <code>commands/</code> direkt; im
|
||||
TUI geht seine Ausgabe als Kontext ans Modell. Ein unbekannter Slash-Befehl
|
||||
antwortet mit der Liste, statt an das Modell zu gehen.
|
||||
|
||||
Antworten, aus jedem Prozess:
|
||||
|
||||
splinter --ack 482915307 yes # yes, y, ok, ja
|
||||
splinter --ack 482915307 no # no, n, nein - jedes andere Wort ist ein Fehler
|
||||
splinter --ack-list
|
||||
|
||||
Ein Timeout ist ein Nein. Stille ist keine Zustimmung.
|
||||
|
||||
Das Telegram-Gateway registriert seine Befehle beim Start: die der geladenen
|
||||
Plugins, die Programme in `~/.splinter/commands/` mit gueltigem Telegram-Namen
|
||||
und `/start`, `/help`, `/interview`; `/help` listet sie im Chat. `/interview`
|
||||
startet dasselbe modellgetriebene Interview wie `splinter --interview` im Chat;
|
||||
die Zusammenfassung landet in `~/.splinter/USER.txt`, `/new` beendet es. Die Anfrage selbst legt es als
|
||||
Nachricht mit **Ja/Nein-Knoepfen** vor.
|
||||
Der Knopf ist ein `callback_query`, kein Text: das Gateway prueft denselben
|
||||
Allow-List-Eintrag, antwortet dem Knopf, entfernt die Knoepfe und legt die
|
||||
Antwortdatei ab. Die Textform `ok <id>` / `no <id>` bleibt als Rueckfall.
|
||||
|
||||
Regeln, die der Code durchsetzt:
|
||||
|
||||
- Die Id ist zufaellig (6-9 Ziffern) und wird nie wiederverwendet; sie ist nicht
|
||||
die pid. Eine Antwort gilt genau einer Anfrage.
|
||||
- Nur die erste Antwort zaehlt; eine zweite wird abgewiesen.
|
||||
- Ist die Anfrage beantwortet oder abgelaufen, wird sie geloescht. Eine spaete
|
||||
Antwort scheitert mit "no open request", statt auf die naechste Anfrage zu
|
||||
warten.
|
||||
- Ein ack-Verzeichnis, das nicht dem Benutzer gehoert oder fuer andere
|
||||
schreibbar ist, wird abgelehnt: dort koennte jeder ein Ja hinlegen.
|
||||
- Grenze: Jeder Prozess unter derselben uid kann antworten. Wer das Kind am
|
||||
selben Konto vom Zustimmen abhalten will, braucht eine eigene uid fuer splinter
|
||||
(oder einen Kanal, dessen Antwort der lokale Benutzer nicht schreiben kann).
|
||||
|
||||
## provider
|
||||
|
||||
Per-`(provider, key)` quota and usage, shared by every splinter that uses the
|
||||
same key: state is written under `~/.splinter/providers/` with `flock` and an
|
||||
atomic rename. `preflight` can delay or refuse a request before it is sent;
|
||||
`account` records the status and token counts afterwards. A 429, 402 or 529
|
||||
becomes a quota wait, 503 and 408 a short backoff. Ollama is treated as local
|
||||
(backoff only, no quota) unless a quota is configured. `SPLINTER_PROVIDER_PROBE`
|
||||
and `SPLINTER_QUOTA_PROBE_URL` enable an optional probe.
|
||||
|
||||
## scheduler
|
||||
|
||||
The other half of a quota wait: once a minute it looks for one durable
|
||||
delegation job that is due (`waiting_quota`, `waiting_poll` or `queued` with
|
||||
`run_after`/`next_poll_at` reached) and retries it. With `provider` and the
|
||||
delegate job tools, "quota is back in three days" becomes a scheduled retry
|
||||
instead of a lost task.
|
||||
|
||||
## a2a
|
||||
|
||||
Another agent as the backend, over the Agent2Agent protocol. The transport is
|
||||
selected like any other:
|
||||
|
||||
SPLINTER_A2A_URL=https://agent.example/rpc \
|
||||
SPLINTER_A2A_TOKEN=... \
|
||||
splinter --plugin plugins/a2a/a2a.so --transport a2a -p "..."
|
||||
|
||||
It sends `SendMessage` as JSON-RPC 2.0 with one text part, blocking, and reads
|
||||
either a direct `Message` or a `Task` in `TASK_STATE_COMPLETED`; text parts,
|
||||
text/plain `raw` parts (base64) and string `data` parts from the status message
|
||||
and the artifacts are joined. A binary `file` or `raw` part is saved
|
||||
(`SPLINTER_A2A_INBOX`, default `$TMPDIR/splinter-a2a-inbox`) and named in the
|
||||
answer by path, so the agent can open it; a `url` part is ignored on the client. `SPLINTER_A2A_FULL=1` sends the
|
||||
whole transcript instead of the last user turn, and `SPLINTER_A2A_TIMEOUT` sets
|
||||
the curl timeout (default 300 seconds). The task id and context id are remembered
|
||||
for the session, so the next turn stays in the same A2A context; a terminal task
|
||||
loses its id, a context keeps it.
|
||||
|
||||
When the UI is driving the turn (`sp_agent_config.stream` is set), the transport
|
||||
uses `SendStreamingMessage` instead and hands artifact/message text to the screen
|
||||
as it arrives. Intermediate status notes are progress and are not appended; a
|
||||
completed status message is the answer only when no artifact or direct message
|
||||
text came. One-shot mode streams too unless `--no-stream` asks for the blocking
|
||||
`SendMessage` path.
|
||||
|
||||
The endpoint can be configured directly (`SPLINTER_A2A_URL`) or discovered:
|
||||
`SPLINTER_A2A_CARD` names the agent card, and the first call picks the
|
||||
`JSONRPC` entry from `supportedInterfaces` (or the older single `url` field).
|
||||
The discovered URL is kept for the session.
|
||||
|
||||
The transport sends text; `a2a_send` (destructive) sends a message with an
|
||||
optional `file` part — base64, 8 MiB cap, `mimeType` guessed from the name when
|
||||
not given — and returns the other side's answer, saving a file it sends back.
|
||||
The client does not send push notifications. With a local transport, the plugin
|
||||
also registers `a2a_get_task`, `a2a_cancel_task` and `a2a_subscribe`
|
||||
(read/destructive/read); they use the same endpoint or card.
|
||||
The first two return the raw task/error JSON; the subscription reads the SSE
|
||||
events (`statusUpdate`, `artifactUpdate`, a whole task) into one text: the
|
||||
state, the message and the artifact text, in the order the server sent them.
|
||||
`tests/fake_a2a.py` and `tests/test_a2a.sh` pin the blocking wire shape, both
|
||||
result forms, the bearer token, a JSON-RPC error, streaming and discovery;
|
||||
`tests/test_a2a_ui.sh` drives the streaming path through tmux.
|
||||
|
||||
## a2a server
|
||||
|
||||
The reverse direction is not a plugin: `src/a2aserver.c` is built in, because it
|
||||
needs the agent and its authorization model, not only a transport.
|
||||
|
||||
SPLINTER_A2A_SERVER_TOKEN=... \
|
||||
splinter --a2a-server-listen 127.0.0.1 --a2a-listen-port 8099
|
||||
|
||||
`POST /a2a` speaks JSON-RPC: `SendMessage` runs one turn in the conversation
|
||||
named by `contextId` (or a fresh one, whose id comes back in the task), stores
|
||||
the completed Task and returns it;
|
||||
`SendStreamingMessage` runs the same turn and writes SSE `artifactUpdate` events
|
||||
as the transport produces text (a non-streaming transport sends its whole answer
|
||||
as one artifact), followed by a completed `statusUpdate`; `GetTask` returns the
|
||||
stored Task itself and `ListTasks` lists them (optionally by `contextId`); `GET /.well-known/agent-card.json` serves a card with the `JSONRPC`
|
||||
interface. One request at a time, one connection at a time.
|
||||
|
||||
A `taskPushNotificationConfig` in the `SendMessage`/`SendStreamingMessage`
|
||||
configuration posts the completed task to that webhook (payload: one
|
||||
`StreamResponse` with `task`). Loopback is allowed by default; any other host
|
||||
needs `SPLINTER_A2A_PUSH_ALLOW` (comma separated, `*` for all), which keeps a
|
||||
client from turning the server into an SSRF probe. The config token travels as
|
||||
`X-A2A-Notification-Token`, the authentication as `Authorization`. The four
|
||||
push-config methods (`CreateTaskPushNotificationConfig`, `Get...`, `List...`,
|
||||
`Delete...`) manage the same configs in memory.
|
||||
|
||||
A text/plain `url` part is fetched from loopback or a host in
|
||||
`SPLINTER_A2A_URL_ALLOW` (same syntax, 1 MiB cap, no redirects). A binary part
|
||||
arrives as `file { name, mimeType, bytes }` or `raw` + `mediaType`; it is
|
||||
written to the session's `inbox/` (0600, 8 MiB cap) and the prompt says
|
||||
`[file <name> at <path> (mime, n bytes)]`, because a text model cannot read a
|
||||
PNG but the agent around it can. The same is true for a binary `url` part.
|
||||
|
||||
A mutating tool that needs approval pauses the task in
|
||||
`TASK_STATE_INPUT_REQUIRED`; the assistant call is already in the context, the
|
||||
tool has not run. Another `SendMessage` with the same `taskId` and a
|
||||
`yes`/`no` answer resumes it (`sp_agent_resume`); `CancelTask` cancels it.
|
||||
`SendStreamingMessage` has nowhere to resume, so it denies mutating tools
|
||||
instead of pausing.
|
||||
|
||||
`SubscribeToTask` sends the state the task has now (status update with its
|
||||
message) and ends the stream: one request at a time means a task cannot make
|
||||
progress while a subscription is open, so a live feed would be a promise the
|
||||
server cannot keep. Beyond loopback
|
||||
`SPLINTER_A2A_SERVER_TOKEN` is required and checked as
|
||||
`Authorization: Bearer ...`; there is no TLS.
|
||||
@@ -1,264 +0,0 @@
|
||||
# The front-end protocol
|
||||
|
||||
`splinter --serve` runs the engine on a Unix socket. Everything a front end
|
||||
needs — the transcript, the reasoning as it streams, tool calls, approval
|
||||
questions, slash commands, model and profile switches — arrives as one JSON
|
||||
object per line. The curses interface uses the same engine in-process through
|
||||
`include/splinter_engine.h`; this socket is the same boundary for programs that
|
||||
are not C.
|
||||
|
||||
```
|
||||
splinter --serve [--socket PATH]
|
||||
```
|
||||
|
||||
The default socket is `$SPLINTER_SOCKET`, else `~/.splinter/splinter.sock`.
|
||||
The file is created mode `0600` and the server refuses a peer whose uid is not
|
||||
the owner's: this conversation may run `run` with the owner's rights.
|
||||
|
||||
The reference client is `splinterctl`; `docs/proto-example.py` is a 60-line
|
||||
Python client that shows the whole loop. `splinter --attach` is the complete
|
||||
curses front end speaking this protocol, so anything the screen can do is
|
||||
reachable over the socket by design. If its connection drops, `--attach`
|
||||
reconnects and asks for the session it was on with `open`; a GUI can do the
|
||||
same.
|
||||
|
||||
## Framing
|
||||
|
||||
* One JSON object per line, UTF-8, `\n` terminated. No arrays, no envelope.
|
||||
* Server → client objects have `"ev"`; client → server objects have `"cmd"`.
|
||||
* Unknown fields are ignored. Unknown `cmd` answers with an `error` event.
|
||||
* `"protocol": 2` in the greeting is the format version. It changes only when
|
||||
a field changes meaning; new fields are added without a bump.
|
||||
|
||||
One client at a time. The server holds one active engine, so one conversation
|
||||
runs; `open` switches it, it does not run two. A second writer on the same
|
||||
engine would be a second history. When a client disconnects in the middle of a turn, the server
|
||||
cancels the turn (an approval nobody can answer would otherwise park the
|
||||
engine forever) and accepts the next client.
|
||||
|
||||
## Sequence
|
||||
|
||||
```
|
||||
client server
|
||||
| connect |
|
||||
|<-- {"ev":"ready","protocol":2,...} |
|
||||
| {"cmd":"commands"} / {"cmd":"history"} |
|
||||
|<-- {"ev":"state",...} |
|
||||
|<-- {"ev":"commands","names":[...]} |
|
||||
|<-- {"ev":"history","items":[...]} |
|
||||
| {"cmd":"input","line":"hallo"} |
|
||||
|<-- {"ev":"submitted","text":"hallo"}|
|
||||
|<-- {"ev":"busy","on":true} |
|
||||
|<-- {"ev":"stream","kind":"think",..}| (only with a reasoning model)
|
||||
|<-- {"ev":"stream","kind":"text",..} |
|
||||
|<-- {"ev":"step","think":..,"text":..}
|
||||
|<-- {"ev":"tool","name":"run",...} |
|
||||
|<-- {"ev":"approval","name":"run",..}| (a mutating tool)
|
||||
| {"cmd":"approve","allow":true} |
|
||||
|<-- {"ev":"tool_result",...} |
|
||||
|<-- {"ev":"stream","kind":"text",..} |
|
||||
|<-- {"ev":"turn","ok":true,...} |
|
||||
|<-- {"ev":"state",...} |
|
||||
|<-- {"ev":"busy","on":false} |
|
||||
```
|
||||
|
||||
`stream` chunks are deltas: append them. `step` marks the end of one model step
|
||||
at a tool call; it carries the step's whole reasoning and answer, so a client
|
||||
that lost a chunk can repair from it. The final answer of the turn is in
|
||||
`turn.answer` (the last step's text, which is also the last `stream` text).
|
||||
|
||||
A `turn` event does not by itself mean the engine is idle. A steer that was
|
||||
typed too late for a step boundary becomes a second turn in the same busy
|
||||
period: another `entry` (`you`), more `stream`/`turn` events, and only then
|
||||
`busy:false`. A client finishes its work when `busy.on` is `false`, not at the
|
||||
first `turn`; each `turn` is one answer to show.
|
||||
|
||||
## Client → server
|
||||
|
||||
### `{"cmd":"input","line":"..."}`
|
||||
|
||||
The universal entry point: exactly what the operator typed.
|
||||
|
||||
* A slash command (`/model`, `/status`, `/agent plan`, …) answers with a
|
||||
`reply` event and does not start a turn.
|
||||
* A prompt starts a turn: `submitted`, then the turn events.
|
||||
* `!command` runs a shell; its output arrives as an `entry` with
|
||||
`"role":"shell"`.
|
||||
* A program in `~/.splinter/commands/` replaces the line with its output and
|
||||
starts a turn with it (`submitted` carries the text).
|
||||
|
||||
The server refuses this command with an `error` while a turn is running; the
|
||||
transcript is the engine's, not a client's scratchpad.
|
||||
|
||||
### `{"cmd":"say","text":"..."}`
|
||||
|
||||
Start a turn directly, without command interpretation. The client has already
|
||||
decided this is a prompt (for example from its own input field).
|
||||
|
||||
### `{"cmd":"command","line":"/..."}`
|
||||
|
||||
Alias of `input`; kept because a client that has a command palette knows what
|
||||
it is sending.
|
||||
|
||||
### `{"cmd":"approve","allow":true}`
|
||||
|
||||
Answer the open approval question. `false` denies; the denial becomes the
|
||||
observation the model sees (it is not silent).
|
||||
|
||||
### `{"cmd":"cancel"}`
|
||||
|
||||
Cancel the running turn. The engine sets its flag; every transport kills the
|
||||
child process or the `curl` it started. The turn then ends with
|
||||
`"ev":"turn","ok":false`.
|
||||
|
||||
### `{"cmd":"steer","text":"..."}`
|
||||
|
||||
Text typed while the turn runs. The loop picks it up at the next step boundary
|
||||
and puts it into the conversation; a step that has already ended cannot be
|
||||
interrupted. If no turn runs, the answer is an `error`.
|
||||
|
||||
### `{"cmd":"state"}`
|
||||
|
||||
Ask for a `state` event. Useful after a reconnect.
|
||||
|
||||
### `{"cmd":"history"}`
|
||||
|
||||
Ask for the transcript so far: `"ev":"history"`, `"truncated":bool`,
|
||||
`"items":[{"role":"user","text":"..."}, {"role":"assistant",...}]`. The last
|
||||
100 messages and 256 KiB are sent; a client that attaches shows the session it
|
||||
joins instead of an empty pane. The system prompt and tool observations stay
|
||||
out — this is what the person and the model said.
|
||||
|
||||
### `{"cmd":"sessions"}`
|
||||
|
||||
List the sessions in the server's session directory, newest first:
|
||||
`"ev":"sessions"`, `"items":[{"id","title","mtime","bytes","current"}]`.
|
||||
`title` is the first user line or what `/rename` set (empty when there is no
|
||||
message yet), `current` marks the session the connection is on.
|
||||
|
||||
### `{"cmd":"open","session":"ID"}`
|
||||
|
||||
Switch this connection to another session. `"new"` starts a fresh one,
|
||||
`"last"` the newest, an id continues that file. The server sends `ready`,
|
||||
`state`, `commands`, `history` and finally `"ev":"opened"` with the new
|
||||
`session` and `dir`; the old engine is closed first, so plugins are not doubled.
|
||||
While a turn runs the command is refused. An unknown id is an error and the
|
||||
connection stays on its session.
|
||||
|
||||
`{"cmd":"input","line":"/rename [ID] TITLE"}` names the current session (or the
|
||||
one named by ID), and `{"cmd":"input","line":"/rm ID"}` removes a session that is
|
||||
not the open one: its JSONL, sidecars and `<dir>/logs/<id>` directory. Both
|
||||
answer with a `reply` event.
|
||||
|
||||
### `{"cmd":"commands"}`
|
||||
|
||||
Ask what a command palette may offer: `"ev":"commands"`,
|
||||
`"names":["agent","connect","model",...]` — the same list Tab completes in the
|
||||
curses front end, plugin commands and `commands/` programs included.
|
||||
|
||||
### `{"cmd":"models"}`
|
||||
|
||||
The list `/model` takes, for a picker: `"ev":"models"` with
|
||||
`"items":[{"sel":"junction","label":"junction qwen3.6-35b","current":true},...]`.
|
||||
`sel` is what goes after `/model `, `label` is what the picker shows, and
|
||||
`current` marks the model the run is on. It is the configuration (providers,
|
||||
then pools), not a network probe, so it answers at once; `/model <selector>`
|
||||
through `input` does the switch.
|
||||
|
||||
### `{"cmd":"ping"}` / `{"cmd":"quit"}`
|
||||
|
||||
`pong`; and a clean shutdown: `quit` event, server closes the socket and exits
|
||||
with 0.
|
||||
|
||||
## Server → client
|
||||
|
||||
| `ev` | fields | meaning |
|
||||
| --- | --- | --- |
|
||||
| `ready` | `protocol`, `version` | the greeting, always first |
|
||||
| `state` | `session`, `dir`, `model`, `endpoint`, `agent`, `agents[]`, `agent_cur`, `tokens_in`, `tokens_out`, `ctx_used`, `ctx_max`, `cached`, `turn_tokens_out`, `steps`, `calls`, `compactions`, `last_ms`, `last_steps`, `last_calls`, `busy`, `waiting`, `quit` | everything a sidebar or the status bar shows |
|
||||
| `submitted` | `text` | the prompt actually run (a command may have rewritten it) |
|
||||
| `busy` | `on` | a turn started or ended |
|
||||
| `stream` | `kind` (`text` or `think`), `text` | a delta of the answer or the reasoning |
|
||||
| `step` | `think`, `text` | one model step ended at a tool call |
|
||||
| `tool` | `name`, `args`, `call` | a tool call; `call` is the readable line (`Run ls -l`) |
|
||||
| `tool_result` | `name`, `text`, `join` | what the tool returned; `join` true means "append to the call row" |
|
||||
| `entry` | `role`, `text` | a finished transcript entry |
|
||||
| `note` | `text` | a one-line prompt note, e.g. a usage-limit wait; `""` clears it |
|
||||
| `approval` | `name`, `args`, `call`, `auth`, `class` | a tool needs consent; answer with `approve` |
|
||||
| `turn` | `ok`, `rc`, `answer`, `error` | one turn ended; `busy:false` ends the work |
|
||||
| `clear` | — | `/new`: drop the transcript pane (the session is new) |
|
||||
| `reply` | `text` | the answer to a command; may be empty |
|
||||
| `error` | `text` | the command was refused |
|
||||
| `commands` | `names[]` | the slash commands, for a palette |
|
||||
| `sessions` | `items[]` | the sessions, with id/title/mtime/bytes/current |
|
||||
| `opened` | `session`, `dir` | the switch is complete |
|
||||
| `history` | `truncated`, `items[]` | the transcript so far (role/text) |
|
||||
| `pong` | — | answer to `ping` |
|
||||
| `quit` | — | the engine is shutting down |
|
||||
|
||||
`entry.role` is one of `you`, `agent`, `thinking`, `tool`, `observation`,
|
||||
`splinter`, `shell`, `error`. A client renders them in its own way; the
|
||||
sidecar values (`state`, `tool.call`, `tool_result.join`) exist so it does not
|
||||
have to re-implement the harness' own arithmetic.
|
||||
|
||||
## A minimal client
|
||||
|
||||
```python
|
||||
import json, socket, sys
|
||||
|
||||
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
s.connect(sys.argv[1])
|
||||
f = s.makefile("rw", encoding="utf-8")
|
||||
|
||||
def send(obj):
|
||||
f.write(json.dumps(obj) + "\n")
|
||||
f.flush()
|
||||
|
||||
send({"cmd": "input", "line": "list the C files"})
|
||||
for line in f:
|
||||
ev = json.loads(line)
|
||||
if ev["ev"] == "stream" and ev["kind"] == "text":
|
||||
print(ev["text"], end="", flush=True)
|
||||
elif ev["ev"] == "tool":
|
||||
print("\n>>", ev["call"])
|
||||
elif ev["ev"] == "approval":
|
||||
send({"cmd": "approve", "allow": True})
|
||||
elif ev["ev"] == "turn":
|
||||
print()
|
||||
break
|
||||
```
|
||||
|
||||
Run it against `splinter --serve --socket /tmp/s.sock` with the socket path as
|
||||
the argument; `docs/proto-example.py` is the same program with argument
|
||||
handling.
|
||||
|
||||
## The same boundary in C
|
||||
|
||||
`include/splinter_engine.h` is what `src/frontend/curses.c` and
|
||||
`src/frontend/protocol.c` use:
|
||||
|
||||
```c
|
||||
struct sp_engine *eng;
|
||||
struct sp_engine_opts o = { .conf = &conf, .base = &cfg, .endpoint = url,
|
||||
.model = name, .key_env = "SPLINTER_API_KEY" };
|
||||
sp_engine_open(&eng, &o, &err);
|
||||
sp_engine_input(eng, "/status", &reply); /* or a prompt ... */
|
||||
sp_engine_submit(eng, prompt); /* ... then a turn */
|
||||
while (sp_engine_poll(eng, &ev)) /* the same events as above */
|
||||
handle(ev);
|
||||
sp_engine_approve(eng, 1);
|
||||
sp_engine_close(eng);
|
||||
```
|
||||
|
||||
The event kinds map one to one onto the JSON `ev` names (`SP_EV_TOOL` ↔
|
||||
`tool`, `SP_EV_TURN_END` ↔ `turn`). A front end cannot drift from the socket
|
||||
protocol without drifting from the curses one, because both read the same
|
||||
queue.
|
||||
|
||||
## Versioning
|
||||
|
||||
`"protocol": 2` is the current version. Additive fields keep the number;
|
||||
removing a field or changing its meaning bumps it, and the curses front end
|
||||
moves in the same commit. Version 2 added the `history` command, which
|
||||
`--attach` uses during its greeting: a client that needs it refuses a version
|
||||
1 server instead of waiting for an answer that never comes.
|
||||
@@ -1,109 +0,0 @@
|
||||
# Offene Punkte
|
||||
|
||||
Stand: 2026-11-10. Die geprüfte, ausführliche Liste mit Belegen steht in
|
||||
`TODO.md`.
|
||||
|
||||
## Offen
|
||||
|
||||
Nichts aus der alten A2A-Liste. Binaere A2A-Teile landen in `inbox/` und
|
||||
werden dem Modell als Pfad genannt; URL-Teile nur von erlaubten Hosts.
|
||||
`SubscribeToTask` wiederholt den gespeicherten Zustand einmal und schliesst den
|
||||
Stream.
|
||||
|
||||
## Erledigt
|
||||
|
||||
- **Echtes Gateway-Streaming 2026-11-16**: `stream:true` nutzt den
|
||||
Streaming-Transport des Providers und schickt Text-Deltas sofort als
|
||||
`chat.completion.chunk`; Caller-Tool-Calls kommen als ein Delta am Ende des
|
||||
Schritts, `stream_options.include_usage` liefert die summierten Token-Zahlen
|
||||
vor `[DONE]`. Fehler nach dem ersten Byte kommen als SSE-`error`; SIGPIPE ist
|
||||
ignoriert. Test: `tests/stream_probe.py` prueft, dass die Chunks waehrend des
|
||||
Upstream-Streams ankommen (nicht als ein Block am Ende).
|
||||
- **Session-Titel 2026-11-16**: `.meta` traegt `title` (erste User-Zeile,
|
||||
ueberschreibbar per `/rename [ID] TITEL`); `sessions` liefert ihn als
|
||||
`title`, `/sessions` zeigt ihn. `/rm ID` entfernt JSONL, Sidecars und
|
||||
`logs/<id>` und verweigert die offene Session. Tests: `test_session`,
|
||||
`test_protocol.sh`, `test_ui.sh`.
|
||||
- **Nachtrag 2026-11-16**: Session-Wechsel auch im lokalen UI
|
||||
(`sp_engine_switch`, `/sessions` + `/open` ohne `--attach`), Gateway reicht
|
||||
`temperature`/`top_p`/`max_tokens` durch, liest chunked Bodies und gibt bei
|
||||
gemischten Antworten die Caller-Calls zurueck (lokale Beobachtungen im
|
||||
Content, auch im SSE-Delta); ein beim Reconnect verschwundener Session-Name
|
||||
wird gemeldet statt still ersetzt; Ring-Transports werden disposed;
|
||||
`/status` ist uebersetzt; `docs/splinter.1` ist mandoc-sauber.
|
||||
- **Gateway, Sessions, Reconnect**: `splinter --openai-listen` ist ein
|
||||
OpenAI-kompatibler Endpunkt; lokale Tools heissen `gw_*` und laufen auf dem
|
||||
Splinter-Host, die Tools des aufrufenden Harness werden als tool_calls
|
||||
zurueckgegeben und dort ausgefuehrt (`docs/GATEWAY.md`,
|
||||
`tests/test_gateway_openai.sh`). `--serve` haelt mehrere Sessions
|
||||
(`sessions`/`open`, `/sessions`/`/open` im UI), `--attach` verbindet sich
|
||||
nach einem Serverausfall selbst neu und holt die alte Session per id
|
||||
(`tests/test_protocol.sh`, `tests/test_reconnect.sh`).
|
||||
- **Review-Nachlauf 2026-11-16**: 8-KiB-Zeilen in Server/Client/attach durch
|
||||
dynamische Puffer ersetzt (9-KB-Prompt, 8-KB-Shell-Eintrag), `turn` beendet
|
||||
nicht mehr das busy-Fenster (Steer-Rest), Curses finalisiert jeden Turn
|
||||
einzeln, Engine-Steer-Rest wird per `sp_engine_take_steer` uebernommen,
|
||||
Engine-Statistik als Lock-Snapshot (kein Datenrace), Profil wird in
|
||||
`<session>.agent` gemerkt (--resume startet wieder in plan), `/new` oeffnet
|
||||
das Log neu und vergibt eindeutige Ids, Shell-Ausgabe 64 KiB mit Marker,
|
||||
Socket-Probe/Inode/CLOEXEC/SO_SNDTIMEO, Protokoll v2 mit `history` (attach
|
||||
zeigt das bisherige Transkript), `same_user` auch fuer BSD, Exit 2 fuer
|
||||
Konfigurationsfehler, `agent_switch` meldet Aktivierungsfehler, i18n-Checker
|
||||
scannt src/backend+frontend. `tests/test_protocol.sh` und
|
||||
`tests/test_attach.sh` decken die neuen Pfade ab; `make check` gruen.
|
||||
- **Backend und Frontends getrennt**: `src/backend/` traegt Engine, Loop,
|
||||
Tools, Session, Config und Plugins; `src/frontend/curses.c` zeichnet nur
|
||||
noch und liest Tasten, `src/frontend/protocol.c` gibt dieselben Events als
|
||||
JSON-Zeilen auf einem Unix-Socket aus, `src/frontend/client.c` ist der
|
||||
Referenz-Client (`splinterctl`). Die C-Grenze ist
|
||||
`include/splinter_engine.h`; das Format steht in `docs/PROTOCOL.md`, die
|
||||
Aufteilung in `docs/FRONTENDS.md`. Ein GUI-Client kann damit in jeder
|
||||
Sprache gegen `splinter --serve` gebaut werden. Belege:
|
||||
`tests/test_engine` (Event-Reihenfolge eines Turns) und
|
||||
`tests/test_protocol.sh` (Socket, Freigabe, Kommandos, quit).
|
||||
- Werkzeuge: read, write, edit, search, list, run, websearch, webfetch,
|
||||
folder_history, delegate (plus parallel/list/submit/jobs/result/due/retry),
|
||||
skill_search/skill_load, echo, clock
|
||||
- Freigabe im TUI (Condition Variable), Diff-Anzeige, Ctrl-C killt curl
|
||||
- Session-Resume, MCP-Client und -Server, Exit-Ring, Delegation mit Modellwahl
|
||||
- Gateway (Telegram) mit Typing-Indicator und Slash-Commands
|
||||
- Session-Logs: `~/.splinter/logs/<id>/{session.log,wire.jsonl}`
|
||||
- Slash-Programme: `~/.splinter/commands/<name>`, Ausgabe geht ans Modell
|
||||
- **Skills**: `~/.splinter/skills/` + `skills_dir`, `skill_search`/`skill_load`,
|
||||
kein Vorladen (`test_skills`)
|
||||
- **Streaming im Gateway**: eigener Callback, damit auch SSE-only-Provider gehen
|
||||
- **Remote/Jumphost**: `host=` schickt den ganzen Aufruf über ssh; belegt in
|
||||
`README.md` (olivia, Provider nur über WireGuard erreichbar)
|
||||
- **Kompression im echten Loop**: `ag->host` ist gesetzt; `test_compactor` fährt
|
||||
den Turn mit lcm bei 8 KiB und 32 KiB Budget und zählt die Kompressionen
|
||||
- **Tabellen im Chat**: `src/md.c` erkennt Kopf + Trenner, rechnet Spaltenbreiten
|
||||
und zeichnet ausgerichteten Text (`test_md`, `test_ui.sh`)
|
||||
- **Neue Konversation**: `/new` bzw. `/reset` im Gateway und im TUI; neue
|
||||
Sitzungsdatei, Konversation auf den System-Prompt zurueck
|
||||
(`test_gateway.sh`, `test_ui.sh`); `/connect` auch im TUI
|
||||
- **Modelle wechseln und Provider anlegen**: `/model` liest die konfigurierten
|
||||
Modelle (Haupt-Endpoint, Delegates, Exits), haengt den Transport um, merkt
|
||||
die Wahl in `90-model.conf` und fragt per `/model probe` die Endpoints nach
|
||||
`/v1/models`; das TUI kann dasselbe. `/connect` schreibt eine validierte
|
||||
`delegate`-Zeile in den Drop-in neben der benutzten Konfiguration, prueft sie
|
||||
mit einem Test-Turn und registriert sie im laufenden Prozess
|
||||
(`test_providers`, `test_gateway.sh`, `test_ui.sh`)
|
||||
- **A2A-Client mit Dateien**: `a2a_send` schickt eine Nachricht mit `file`-Teil
|
||||
(base64, 8 MiB), empfangene Dateien landen im Inbox-Pfad (`test_a2a.sh`)
|
||||
- **A2A-Client-Abo**: `a2a_subscribe` liest die Ereignisse eines fremden Tasks
|
||||
als Text (Zustand, Nachricht, Artefakte) (`test_a2a.sh`)
|
||||
- **Bilder als Foto**: Markdown-Bilder gehen als `sendPhoto` raus (Alt als
|
||||
Caption, Fallback Text), in der Reihenfolge des Textes; lokale Dateien per
|
||||
Multipart als Foto (10 MiB) oder Dokument (50 MiB) (`test_gateway.sh`)
|
||||
- **Markdown als Telegram-HTML**: `src/tgmd.c` rendert fett/kursiv/Code/Links/
|
||||
Zitate/Tabellen in die Tags von `parse_mode=HTML`, escapt alles andere und
|
||||
teilt lange Antworten an Tag-Grenzen, mit offenen Tags pro Stueck
|
||||
(`test_tgmd`, `test_gateway.sh`)
|
||||
- **Website von Hand**: die drei Seiten in `src/www/` sind handgeschrieben,
|
||||
ohne Generator; Zahlen darin sind Stand 2026-11-11
|
||||
- **Letzter Delegate-Fehler**: die letzten 400 Bytes des Kindes stehen im Fehler,
|
||||
ein Limit bencht den Delegate und der nächste übernimmt (`test_delegate`)
|
||||
- **A2A INPUT_REQUIRED**: ein mutierendes Werkzeug pausiert (`sp_agent_run`
|
||||
liefert 2), `SendMessage` mit `taskId` und `yes`/`no` setzt per
|
||||
`sp_agent_resume` fort; `CancelTask` bricht ab (`test_pause`,
|
||||
`test_a2a_input.sh`)
|
||||
@@ -1,112 +0,0 @@
|
||||
# Workflow: Claude analysiert und entscheidet, die Flash-Modelle setzen um
|
||||
|
||||
Das Setup, das diese Datei beschreibt, ist eine Aufteilung nach Rolle, nicht
|
||||
nach Modellgröße:
|
||||
|
||||
| Rolle | wer | Tags | Pool |
|
||||
|-------|-----|------|------|
|
||||
| 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` | – |
|
||||
|
||||
Das Gespräch selbst läuft auf `work` (`default = work`): der günstige Pool
|
||||
führt, liest und ändert Dateien. Sobald eine Frage Analyse oder Entscheidung
|
||||
ist, gibt er sie mit dem `delegate`-Tool an Claude ab. Dafür sorgt
|
||||
`system_prompt` in `core`; die Auswahl macht splinter nach Tags.
|
||||
|
||||
## 1. Einmalig
|
||||
|
||||
```
|
||||
cd ~/src/splinter && make && make install PREFIX=$HOME/.local
|
||||
splinter --model-list # Pools und Provider; --no-probe ohne Netz
|
||||
```
|
||||
|
||||
In `~/.splinter/splinter.conf` die echten Grenzen eintragen (sonst zählt
|
||||
splinter nur mit und reagiert erst auf einen Fehler):
|
||||
|
||||
```
|
||||
provider ocgo { ... limit = 100/5h } # was dein Tarif hergibt
|
||||
provider ollama { ... tokens = 5000000/7d }
|
||||
```
|
||||
|
||||
Zahlen etwas unter das echte Limit setzen: splinter zählt nur, was es selbst
|
||||
sendet.
|
||||
|
||||
## 2. Eine Sitzung
|
||||
|
||||
```
|
||||
cd ~/src/projekt
|
||||
splinter # Chat auf "work"
|
||||
```
|
||||
|
||||
1. **Ziel setzen**: `/goal <was am Ende stimmen muss>`. Das setzt das Ziel und
|
||||
startet einen Turn, der einen kurzen Recap schreibt; `focus` injiziert ihn
|
||||
alle sieben Turns, auch nach Kontext-Verdichtung.
|
||||
2. **Projektregeln mitgeben**: splinter liest `AGENTS.md`/`GOAL.md` nicht von
|
||||
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 `claudeapi`.
|
||||
4. **Hintergrundarbeit**: `process_start` startet lange Kommandos,
|
||||
`process_list`/`process_result` holen Stand und Ausgabe; `delegate` gibt
|
||||
eine Aufgabe an ein anderes Modell, der `scheduler` wiederholt wartende
|
||||
Jobs nach Quota/`run_after`.
|
||||
5. **Verbrauch sehen**: Statusleiste und `/usage` (Balken je Provider).
|
||||
6. **Beenden/Fortsetzen**: Ctrl-D beendet, `splinter -c` setzt die letzte
|
||||
Sitzung in diesem Verzeichnis fort.
|
||||
|
||||
Direkt mit Claude arbeiten, wenn das Gespräch selbst Analyse ist:
|
||||
|
||||
```
|
||||
splinter -m claudeapi
|
||||
```
|
||||
|
||||
Ohne Chat: `splinter -p "..."` (mit `-m claudeapi` für eine einzelne Analyse).
|
||||
|
||||
## 3. Wer bekommt was
|
||||
|
||||
`splinter --choose "<Aufgabe>"` zeigt die Entscheidung, ohne etwas zu starten.
|
||||
|
||||
- Tags passen nach Wort, mit Synonymen (*gross* = `big`, *entscheide* =
|
||||
`decide`, *prüfe* = `review`). Analyse-, Entscheidungs-, Review- und
|
||||
Planwörter zählen so viel wie der Tag selbst.
|
||||
- Gleicher Treffer: wer im Kontingent mehr übrig hat, dann `prio`.
|
||||
- Innerhalb eines Pools entscheidet die Strategie: `balance` nimmt den mit der
|
||||
geringsten Auslastung. Ohne eingetragenes Limit ist die Last das, was
|
||||
splinter in der letzten Stunde dorthin geschickt hat (50 Aufrufe = voll),
|
||||
sodass `ocgo` und `ollama` sich abwechseln.
|
||||
- Eine private Aufgabe (*privat, geheim, secret*) geht nur an einen Provider
|
||||
mit Tag `private`, sonst Fehler, nie in die Cloud.
|
||||
- Passt kein Tag, nimmt `default`.
|
||||
|
||||
## 4. Wenn ein Limit erreicht wird
|
||||
|
||||
1. Das Mitglied wird bis zum Reset gesperrt (aus `Retry-After`, aus der
|
||||
Meldung des Anbieters, oder aus der eigenen Zählung).
|
||||
2. Der Pool nimmt das nächste Mitglied mit Platz und wiederholt die Anfrage.
|
||||
3. Sind alle am Limit: splinter nennt die Uhrzeit, wartet (der Bildschirm
|
||||
bleibt lebendig) und macht von allein weiter. `max_wait` begrenzt das
|
||||
(Default 12 h, in der Beispiel-Config 2 d).
|
||||
4. **Stoppen**: Ctrl-C bricht das Warten ab. **Fortsetzen**: `/resume`.
|
||||
5. `on_limit = fail` schaltet das Warten ab.
|
||||
|
||||
## 5. Kostenstufen (gratis, dann bezahlt)
|
||||
|
||||
Ein Provider ist so viel wert wie sein Limit. Trägst du das Gratis-Kontingent
|
||||
von opencode-go als `limit` ein, wird `ocgo` bei 100 % übersprungen und
|
||||
`ollama` nimmt die Last. Weiter bezahlt: einen zweiten Provider mit derselben
|
||||
URL anlegen (`ocgo-paid`, ohne Limit) und bewusst wählen
|
||||
(`splinter -m ocgo-paid`) oder erst dem Limit-Warten zuvorkommen. Ein
|
||||
bezahltes Mitglied in einen `balance`-Pool zu legen ist keine gute Idee: ohne
|
||||
Limit hat es immer die geringste Last und bekäme alles.
|
||||
|
||||
## 6. Grenzen, die du kennen musst
|
||||
|
||||
- Die Zählung ist splinters eigene; wird derselbe Account anderswo benutzt,
|
||||
ist die echte Auslastung höher.
|
||||
- Ein Wechsel mitten im Gespräch ist für HTTP-Provider getestet. Für Claude
|
||||
über die CLI übernimmt deren eigenes Fallback (die anderen Mitglieder des
|
||||
Pools).
|
||||
- `AGENTS.md` wird nicht automatisch gelesen.
|
||||
- Mit `autonomous = true` läuft splinter ohne Rückfrage: vorher committen oder
|
||||
stashen.
|
||||
@@ -1,73 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A minimal splinter GUI-backend client.
|
||||
|
||||
It speaks the line protocol from docs/PROTOCOL.md and prints the transcript as
|
||||
text -- the same events a Tk/Qt/Electron window would draw. Start a server
|
||||
first:
|
||||
|
||||
splinter --serve --socket /tmp/splinter.sock
|
||||
python3 docs/proto-example.py /tmp/splinter.sock "list the C files"
|
||||
|
||||
Approve is answered with `y` on stdin; everything else is printed as it
|
||||
arrives.
|
||||
"""
|
||||
import json
|
||||
import socket
|
||||
import sys
|
||||
|
||||
|
||||
class Splinter:
|
||||
def __init__(self, path):
|
||||
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.sock.connect(path)
|
||||
self.f = self.sock.makefile("rw", encoding="utf-8")
|
||||
|
||||
def send(self, **obj):
|
||||
self.f.write(json.dumps(obj) + "\n")
|
||||
self.f.flush()
|
||||
|
||||
def events(self):
|
||||
for line in self.f:
|
||||
line = line.strip()
|
||||
if line:
|
||||
yield json.loads(line)
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 3:
|
||||
print(__doc__)
|
||||
return 2
|
||||
cli = Splinter(sys.argv[1])
|
||||
cli.send(cmd="input", line=" ".join(sys.argv[2:]))
|
||||
for ev in cli.events():
|
||||
kind = ev.get("ev")
|
||||
if kind == "stream" and ev.get("kind") == "text":
|
||||
print(ev.get("text", ""), end="", flush=True)
|
||||
elif kind == "stream" and ev.get("kind") == "think":
|
||||
pass # a GUI would show this dimmed
|
||||
elif kind == "tool":
|
||||
print("\n>> " + ev.get("call", "?"))
|
||||
elif kind == "tool_result" and not ev.get("join"):
|
||||
print(ev.get("text", ""))
|
||||
elif kind in ("entry", "reply", "error"):
|
||||
print("[%s] %s" % (ev.get("role", kind), ev.get("text", "")))
|
||||
elif kind == "approval":
|
||||
print("[approval] %s (%s) [y/N] " % (ev.get("call", "?"),
|
||||
ev.get("class", "?")),
|
||||
end="", flush=True)
|
||||
answer = sys.stdin.readline().strip().lower()
|
||||
cli.send(cmd="approve", allow=answer.startswith("y"))
|
||||
elif kind == "state" and ev.get("busy"):
|
||||
print("[%s/%s]" % (ev.get("agent"), ev.get("model")),
|
||||
file=sys.stderr)
|
||||
elif kind == "turn":
|
||||
print()
|
||||
if not ev.get("ok"):
|
||||
print("turn failed: " + ev.get("error", ""), file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,22 +0,0 @@
|
||||
# systemd --user unit for splinter's gateway mode.
|
||||
#
|
||||
# cp docs/splinter-gateway.service ~/.config/systemd/user/
|
||||
# systemctl --user daemon-reload
|
||||
# systemctl --user enable --now splinter-gateway
|
||||
#
|
||||
# The token lives in ~/.splinter/telegram.token (0600) and is never passed as an
|
||||
# argument: arguments show up in ps.
|
||||
[Unit]
|
||||
Description=splinter gateway (Telegram)
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=%h/src/splinter/splinter --daemon
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
# a gateway that answers the world is not a gateway, it is a leak
|
||||
Environment=SPLINTER_CONFIG=%h/.splinter/splinter.conf
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -1,227 +0,0 @@
|
||||
.Dd November 7, 2026
|
||||
.Dt SPLINTER 1
|
||||
.Os
|
||||
.Sh NAME
|
||||
.Nm splinter
|
||||
.Nd a small C99/POSIX agent harness
|
||||
.Sh SYNOPSIS
|
||||
.Nm
|
||||
.Fl p Ar prompt
|
||||
.Fl -endpoint Ar url
|
||||
.Op Fl -autonomous
|
||||
.Op Fl -steps Ar n
|
||||
.Op Fl -session Ar dir
|
||||
.Op Fl -session-id Ar id
|
||||
.Nm
|
||||
.Fl p Ar prompt
|
||||
.Fl -script Ar file
|
||||
.Op Ar options
|
||||
.Nm
|
||||
.Fl V
|
||||
.Sh DESCRIPTION
|
||||
.Nm
|
||||
runs one turn of an agent loop against a transport.
|
||||
It sends a prompt, executes the tools the transport asks for, and prints the
|
||||
final answer.
|
||||
Every turn is appended to a session log as JSON Lines.
|
||||
.Pp
|
||||
The loop enforces, in this order, before any tool runs:
|
||||
.Bl -enum -compact
|
||||
.It
|
||||
the request fits the configured byte budget; otherwise nothing is sent;
|
||||
.It
|
||||
the tool exists in the registry; otherwise the model is told it does not;
|
||||
.It
|
||||
the tool's authorization class allows the call; a mutating or destructive
|
||||
tool asks the operator unless
|
||||
.Fl -autonomous
|
||||
was given.
|
||||
.El
|
||||
.Pp
|
||||
A denied tool is not skipped silently: the denial is the observation the model
|
||||
receives.
|
||||
.Sh OPTIONS
|
||||
.Bl -tag -width Ds
|
||||
.It Fl p , -prompt Ar TEXT
|
||||
The user message for this turn.
|
||||
Required.
|
||||
.It Fl -endpoint Ar URL
|
||||
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 ,
|
||||
print its observation and exit.
|
||||
No model and no transport are involved; this is the diagnostic path for a
|
||||
delegate that fails.
|
||||
.It Fl -script Ar FILE
|
||||
Transport: replay one reply per line from
|
||||
.Ar FILE .
|
||||
This needs no network and is how the test suite drives the loop.
|
||||
.It Fl -no-stream
|
||||
One-shot mode: wait for the whole reply instead of printing it as it arrives.
|
||||
A transport that can stream uses its streaming method by default; this asks for
|
||||
its plain send method.
|
||||
.It Fl -autonomous
|
||||
Run mutating tools without asking.
|
||||
Read-only tools never ask.
|
||||
.It Fl -steps Ar N
|
||||
Maximum tool rounds per turn (default 150).
|
||||
.It Fl -max-bytes Ar N
|
||||
Request budget in bytes; 0 means no limit.
|
||||
.It Fl -a2a-server-listen Ar IP
|
||||
Serve the A2A agent (JSON-RPC, agent card) on
|
||||
.Ar IP .
|
||||
Beyond 127.x it needs
|
||||
.Ev SPLINTER_A2A_SERVER_TOKEN .
|
||||
.It Fl -a2a-listen-port Ar N
|
||||
A2A port (default 8099).
|
||||
.It Fl -openai-listen Ar IP
|
||||
Serve an OpenAI-compatible endpoint
|
||||
.Pq Pa /v1/chat/completions , /v1/models
|
||||
for another harness.
|
||||
The model sees splinter's local tools as
|
||||
.Pa gw_ Ns Ar name
|
||||
and runs them here; tools the caller sends are returned to the caller as
|
||||
ordinary tool calls and run there.
|
||||
Beyond loopback it needs
|
||||
.Ev SPLINTER_GATEWAY_TOKEN . See
|
||||
.Pa docs/GATEWAY.md .
|
||||
.It Fl -openai-listen-port Ar N
|
||||
Gateway port (default 8097).
|
||||
.It Fl -serve
|
||||
Serve the engine on a Unix socket instead of drawing a screen.
|
||||
Each request and event is one JSON object per line; see
|
||||
.Pa docs/PROTOCOL.md .
|
||||
Any program that can open a Unix socket can be a front end, which is what a
|
||||
GUI client connects to.
|
||||
.It Fl -attach
|
||||
Run the curses interface as a client of a served engine
|
||||
.Pq Fl -serve .
|
||||
The screen shows the server's session and its transcript so far (asked for
|
||||
with the protocol's history command) and runs every turn there; the socket
|
||||
protocol is the same one a GUI client uses.
|
||||
The commands
|
||||
.Pa /sessions
|
||||
and
|
||||
.Pa /open Ar ID
|
||||
switch the session.
|
||||
.Pa /sessions
|
||||
shows each session with its title: the first user line, or what
|
||||
.Pa /rename
|
||||
.Pq Op Ar ID
|
||||
.Ar TITLE
|
||||
set.
|
||||
.Pa /rm Ar ID
|
||||
removes a session that is not open.
|
||||
If the server goes away, the screen keeps running, reconnects and asks for the
|
||||
session it was on.
|
||||
.It Fl -socket Ar PATH
|
||||
Socket for
|
||||
.Fl -serve
|
||||
and
|
||||
.Fl -attach ,
|
||||
default
|
||||
.Ev SPLINTER_SOCKET
|
||||
or
|
||||
.Pa ~/.splinter/splinter.sock .
|
||||
The file is mode 0600 and the server refuses a peer of another uid.
|
||||
.It Fl -session Ar DIR
|
||||
Session directory (default
|
||||
.Pa ~/.splinter ) .
|
||||
.It Fl -session-id Ar ID
|
||||
Session id (default
|
||||
.Pa sess-<time>-<pid> ) .
|
||||
.It Fl V , -version
|
||||
Print the version, the build time and the git revision, then exit.
|
||||
The release number stays
|
||||
.Ql 0.1.0 ;
|
||||
the build stamp is what tells two builds apart.
|
||||
.El
|
||||
.Sh PROTOCOL
|
||||
.Nm
|
||||
is a backend with front ends.
|
||||
The curses interface links the engine in process;
|
||||
.Fl -serve
|
||||
exposes the same engine as JSON lines on a Unix socket, where
|
||||
.Pa splinterctl
|
||||
is the reference client and the place to start a GUI from.
|
||||
The engine reports a turn as events \(em streamed text, a step, a tool call, its
|
||||
observation, an approval question, the answer \(em and never calls into a front
|
||||
end.
|
||||
.Pp
|
||||
Between the harness and its transport the protocol is simpler, and not a
|
||||
vendor API:
|
||||
.Bd -literal -offset indent
|
||||
request user <text>
|
||||
request observe <tool> <output>
|
||||
reply answer <text>
|
||||
reply tool <name> <arguments>
|
||||
.Ed
|
||||
.Pp
|
||||
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 FILES
|
||||
.Bl -tag -width Ds
|
||||
.It Pa ~/.splinter/<id>.jsonl
|
||||
Append-only session log, one JSON object per line.
|
||||
A crash can only truncate the tail.
|
||||
.El
|
||||
.Sh EXIT STATUS
|
||||
.Bl -tag -width Ds -compact
|
||||
.It 0
|
||||
The turn produced an answer.
|
||||
.It 1
|
||||
The turn failed.
|
||||
The reason is printed on standard error.
|
||||
.It 2
|
||||
Usage or configuration error.
|
||||
.It 3
|
||||
The environment could not be set up, for example the session directory.
|
||||
.El
|
||||
.Sh EXAMPLES
|
||||
Run a scripted turn with no network:
|
||||
.Bd -literal -offset indent
|
||||
$ printf 'answer hello\\n' > /tmp/r.txt
|
||||
$ splinter -p "say hello" --script /tmp/r.txt
|
||||
hello
|
||||
.Ed
|
||||
.Pp
|
||||
Talk to an adapter:
|
||||
.Bd -literal -offset indent
|
||||
$ splinter -p "list the C files" --endpoint http://127.0.0.1:8080/turn
|
||||
.Ed
|
||||
.Sh SEE ALSO
|
||||
.Xr curl 1
|
||||
.Sh AUTHORS
|
||||
.An Konrad Lother
|
||||
.Sh CAVEATS
|
||||
The transport is responsible for anything the model says; the harness trusts
|
||||
only the registry and the authorization classes.
|
||||
Tool arguments are passed as a single string and are not validated beyond the
|
||||
tool's own checks.
|
||||
@@ -1,579 +0,0 @@
|
||||
/*
|
||||
* splinter -- a small C99/POSIX agent harness.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Design rules this header encodes:
|
||||
* - no fixed-size buffers anywhere; every growing thing is a struct sp_buf
|
||||
* with geometric growth and overflow checks;
|
||||
* - a tool declares its authorization class; the harness decides whether it
|
||||
* may run, never the model and never a prompt;
|
||||
* - a session is append-only JSONL, so a crash can only truncate its tail;
|
||||
* - the transport is a vtable, so the whole loop is testable with no network.
|
||||
*/
|
||||
#ifndef SPLINTER_H
|
||||
#define SPLINTER_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#define SP_VERSION "0.1.0"
|
||||
|
||||
/*
|
||||
* The build stamp of the binary. Generated by make into
|
||||
* src/backend/buildinfo.c, so --version says which build is running even
|
||||
* though the release number stays the same.
|
||||
*/
|
||||
extern const char *sp_build_time;
|
||||
extern const char *sp_build_rev;
|
||||
|
||||
/* ------------------------------------------------------------------ buffer */
|
||||
|
||||
struct sp_buf {
|
||||
char *p;
|
||||
size_t len; /* bytes used, excluding the NUL we keep at p[len] */
|
||||
size_t cap; /* allocated bytes, always > len */
|
||||
};
|
||||
|
||||
int sp_buf_init(struct sp_buf *);
|
||||
int sp_buf_add(struct sp_buf *, const char *, size_t);
|
||||
int sp_buf_puts(struct sp_buf *, const char *);
|
||||
int sp_buf_printf(struct sp_buf *, const char *, ...);
|
||||
int sp_buf_reserve(struct sp_buf *, size_t);
|
||||
void sp_buf_clear(struct sp_buf *);
|
||||
void sp_buf_free(struct sp_buf *);
|
||||
|
||||
/* --------------------------------------------------------------- escaping */
|
||||
|
||||
/* Append s as a JSON string body (no surrounding quotes). */
|
||||
int sp_json_escape(struct sp_buf *, const char *);
|
||||
|
||||
/* --------------------------------------------------------------- tools */
|
||||
|
||||
enum sp_auth {
|
||||
SP_AUTH_READ = 0, /* may run without asking */
|
||||
SP_AUTH_MUTATE, /* changes files or sends data out: consent */
|
||||
SP_AUTH_DESTRUCTIVE /* runs commands: needs operator consent */
|
||||
};
|
||||
|
||||
struct sp_tool;
|
||||
|
||||
/*
|
||||
* One choice /model takes, for a picker: the selector to type after /model,
|
||||
* a label to show, and whether it is the current one. SP_MODEL_CHOICES is the
|
||||
* most a caller's array has to hold (main + delegates + exits + pools).
|
||||
*/
|
||||
#define SP_MODEL_CHOICES 96
|
||||
struct sp_model_choice {
|
||||
char sel[320];
|
||||
char label[512];
|
||||
int current;
|
||||
};
|
||||
|
||||
/* Return 0 on success. The observation is written into out. */
|
||||
typedef int (*sp_tool_run)(const char *args_json, struct sp_buf *out,
|
||||
void *ctx);
|
||||
|
||||
struct sp_tool {
|
||||
const char *name;
|
||||
const char *description;
|
||||
const char *params; /* JSON schema of the arguments, may be NULL */
|
||||
enum sp_auth auth;
|
||||
sp_tool_run run;
|
||||
void *ctx;
|
||||
};
|
||||
|
||||
struct sp_registry {
|
||||
struct sp_tool *tools;
|
||||
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 */
|
||||
|
||||
struct sp_msg {
|
||||
char *role; /* system | user | assistant | tool */
|
||||
char *name; /* tool name when role is "tool" */
|
||||
char *call_id; /* tool_call id, when role is "tool" */
|
||||
char *content;
|
||||
char *calls; /* raw tool_calls JSON of an assistant turn */
|
||||
};
|
||||
|
||||
struct sp_conv {
|
||||
struct sp_msg *v;
|
||||
size_t n;
|
||||
size_t cap;
|
||||
};
|
||||
|
||||
void sp_conv_init(struct sp_conv *);
|
||||
void sp_conv_free(struct sp_conv *);
|
||||
int sp_conv_add(struct sp_conv *, const struct sp_msg *);
|
||||
int sp_conv_insert(struct sp_conv *, size_t at, const struct sp_msg *);
|
||||
int sp_conv_push(struct sp_conv *, const char *role, const char *name,
|
||||
const char *content);
|
||||
/*
|
||||
* Start over: drop every message and keep only the system prompt (may be
|
||||
* NULL). The session file stays; it is the record of what was said, and a
|
||||
* fresh session is a new file next to it.
|
||||
*/
|
||||
int sp_conv_reset(struct sp_conv *, const char *system_prompt);
|
||||
size_t sp_conv_bytes(const struct sp_conv *);
|
||||
int sp_conv_trim(struct sp_conv *, size_t keep_last);
|
||||
|
||||
/* ------------------------------------------------------------- transport */
|
||||
|
||||
struct sp_toolcall {
|
||||
char *id;
|
||||
char *name;
|
||||
char *args; /* the arguments as a JSON text */
|
||||
};
|
||||
|
||||
struct sp_reply {
|
||||
long status;
|
||||
long tokens_in; /* provider-reported, 0 when unknown */
|
||||
long tokens_out;
|
||||
long tokens_cached; /* prompt tokens the provider served
|
||||
* from its cache, 0 unknown */
|
||||
long retry_after_s; /* parsed Retry-After header, 0 unknown */
|
||||
/*
|
||||
* A router may say which upstream answered (junction sends
|
||||
* X-Junction-Endpoint): the model a run is on is not always the
|
||||
* endpoint that serves it. "" when the provider does not say.
|
||||
*/
|
||||
char served_by[128];
|
||||
char *content; /* assistant text, may be "" */
|
||||
struct sp_toolcall *calls;
|
||||
char *calls_json; /* the provider's own tool_calls array */
|
||||
size_t ncalls;
|
||||
};
|
||||
|
||||
/*
|
||||
* A transport turns a whole conversation into one request and one reply. The
|
||||
* seam is the conversation, not a raw string: a provider adapter cannot invent
|
||||
* history, and the loop cannot depend on a vendor's JSON.
|
||||
*/
|
||||
/*
|
||||
* Streaming: a transport that can deliver a turn incrementally reports text
|
||||
* deltas and tool-call starts through this callback while it reads. A transport
|
||||
* that cannot simply leaves send_stream NULL and the loop uses send().
|
||||
*/
|
||||
enum {
|
||||
SP_STREAM_TEXT = 1, /* a chunk of the assistant's answer */
|
||||
SP_STREAM_TOOL, /* a tool call has begun: text is its name */
|
||||
SP_STREAM_THINK /* the model is reasoning: show it, do not use it */
|
||||
};
|
||||
|
||||
typedef void (*sp_stream_cb)(void *ctx, int kind, const char *text);
|
||||
|
||||
/*
|
||||
* Request shaping a front end may pass through to a provider. The gateway
|
||||
* forwards what the calling harness asked for instead of dropping it; zero
|
||||
* flags mean "not given" and leave the provider default.
|
||||
*/
|
||||
struct sp_gen_opts {
|
||||
int have_temperature;
|
||||
double temperature;
|
||||
int have_top_p;
|
||||
double top_p;
|
||||
int have_max_tokens;
|
||||
long max_tokens;
|
||||
/* streaming: ask the provider for a final usage chunk */
|
||||
int include_usage;
|
||||
};
|
||||
|
||||
struct sp_transport {
|
||||
int (*send)(void *ctx, const struct sp_conv *, struct sp_reply *out,
|
||||
struct sp_buf *err);
|
||||
int (*send_stream)(void *ctx, const struct sp_conv *,
|
||||
struct sp_reply *out, struct sp_buf *err,
|
||||
sp_stream_cb, void *cbctx);
|
||||
void *ctx;
|
||||
/* optional: provider/key identity for quota/usage tracking (plugins) */
|
||||
const char *provider; /* e.g. "openai-compat", "ollama", "opencode" */
|
||||
const char *key_id; /* stable key fingerprint/id, never the secret */
|
||||
/*
|
||||
* Optional: free the context a constructor allocated. A transport a
|
||||
* caller builds per request (the OpenAI gateway) uses this; the agent's
|
||||
* own transport lives as long as the agent. Zero for plugin transports,
|
||||
* whose context belongs to the plugin.
|
||||
*/
|
||||
void (*free)(void *ctx);
|
||||
};
|
||||
|
||||
void sp_reply_free(struct sp_reply *);
|
||||
/* free a transport's context (if it owns one) and zero the struct */
|
||||
void sp_transport_dispose(struct sp_transport *);
|
||||
|
||||
/* A deterministic in-process transport: replies are queued FIFO. */
|
||||
struct sp_mock {
|
||||
struct sp_reply *queue;
|
||||
size_t head;
|
||||
size_t len;
|
||||
size_t cap;
|
||||
struct sp_buf last_request;
|
||||
size_t requests;
|
||||
};
|
||||
|
||||
int sp_mock_init(struct sp_mock *);
|
||||
int sp_mock_push(struct sp_mock *, long status, const char *body);
|
||||
void sp_mock_free(struct sp_mock *);
|
||||
struct sp_transport sp_mock_transport(struct sp_mock *);
|
||||
|
||||
/* --------------------------------------------------------------- session */
|
||||
|
||||
struct sp_session_info {
|
||||
char id[64];
|
||||
char dir[512];
|
||||
};
|
||||
|
||||
int sp_session_open(struct sp_session_info *, const char *dir,
|
||||
const char *id, struct sp_buf *err);
|
||||
int sp_session_append(const struct sp_session_info *, const char *role,
|
||||
const char *text, struct sp_buf *err);
|
||||
int sp_session_count(const struct sp_session_info *, size_t *n,
|
||||
struct sp_buf *err);
|
||||
int sp_session_latest(const char *dir, char *id, size_t cap);
|
||||
/* The newest session started in this directory - what '-c' means. */
|
||||
int sp_session_last_for(const char *dir, const char *cwd, char *id,
|
||||
size_t cap);
|
||||
/* What happened in a directory: sessions, turns, last question. */
|
||||
int sp_session_folder_history(const char *dir, const char *cwd,
|
||||
unsigned limit, struct sp_buf *out);
|
||||
int sp_session_load(const struct sp_session_info *, struct sp_conv *conv,
|
||||
size_t *loaded, struct sp_buf *err);
|
||||
|
||||
/* one line of a session listing: id, title, mtime, bytes; newest first */
|
||||
struct sp_session_brief {
|
||||
char id[64];
|
||||
char title[96]; /* set title, or the first user line */
|
||||
long mtime;
|
||||
size_t bytes;
|
||||
};
|
||||
/* up to max entries from dir; returns the count (0..max), or -1 */
|
||||
int sp_session_list(const char *dir, struct sp_session_brief *v,
|
||||
size_t max);
|
||||
/* give a session a title (one line, at most 95 bytes) */
|
||||
int sp_session_set_title(const char *dir, const char *id,
|
||||
const char *title, struct sp_buf *err);
|
||||
/* the session's /goal, stored in its meta sidecar so a resume finds it */
|
||||
int sp_session_set_goal(const char *dir, const char *id,
|
||||
const char *goal, struct sp_buf *err);
|
||||
int sp_session_get_goal(const char *dir, const char *id,
|
||||
char *buf, size_t cap);
|
||||
/*
|
||||
* "open" or "succeeded". A model that reached the goal answers GOAL_COMPLETE;
|
||||
* the state is what the sidebar and the status line show afterwards. Setting a
|
||||
* new goal resets it to open.
|
||||
*/
|
||||
int sp_session_set_goal_state(const char *dir, const char *id,
|
||||
const char *state, struct sp_buf *err);
|
||||
int sp_session_get_goal_state(const char *dir, const char *id,
|
||||
char *buf, size_t cap);
|
||||
/*
|
||||
* Remove a session: its log, meta, saved profile and the logs/<id> directory.
|
||||
* The caller must not delete the session its engine has open.
|
||||
*/
|
||||
int sp_session_delete(const char *dir, const char *id, struct sp_buf *err);
|
||||
|
||||
/* ----------------------------------------------------------------- agent */
|
||||
|
||||
struct sp_agent_config {
|
||||
size_t max_steps; /* tool rounds per turn */
|
||||
size_t max_bytes; /* request budget */
|
||||
/*
|
||||
* Compaction by tokens: past `compact_threshold` the next request is
|
||||
* compacted to `compact_target` (both in tokens, 0 = off). The byte
|
||||
* budget stays the hard ceiling.
|
||||
*/
|
||||
size_t compact_threshold;
|
||||
size_t compact_target;
|
||||
const char *system_prompt;
|
||||
int autonomous; /* 1: run mutate tools without asking */
|
||||
FILE *approval_in; /* NULL with !autonomous means deny */
|
||||
FILE *approval_out;
|
||||
/*
|
||||
* UI path for approval: when set, it is asked instead of the streams, so a
|
||||
* curses program can put the question on the screen instead of reading
|
||||
* stdin behind its own back. Returns 1 to allow, 0 to deny.
|
||||
*/
|
||||
int (*approve)(void *ctx, const char *name, int auth,
|
||||
const char *args);
|
||||
void *approve_ctx;
|
||||
/*
|
||||
* Nonzero: 'approve' is itself the channel (the Telegram gateway asks in
|
||||
* its own chat) and is asked directly. Otherwise the ack mechanism goes
|
||||
* first when SPLINTER_ACK_CHANNELS is set - which in the gateway meant
|
||||
* waiting for an answer that only the blocked gateway could read.
|
||||
*/
|
||||
int approve_is_channel;
|
||||
|
||||
/*
|
||||
* Steering: while a turn runs, the operator may type. The UI cannot
|
||||
* interrupt a request that is already on the wire, so the text is picked
|
||||
* up at the next step boundary -- stated here, not discovered later.
|
||||
* `cancel` is read before every request; `steer` is asked for text.
|
||||
*/
|
||||
volatile int *cancel;
|
||||
int (*steer)(void *ctx, struct sp_buf *out);
|
||||
void *steer_ctx;
|
||||
|
||||
/* Called before a tool runs, with its name and its arguments as sent. */
|
||||
void (*tool_begin)(void *ctx, const char *name,
|
||||
const char *args);
|
||||
void *tool_begin_ctx;
|
||||
/* Called after a tool ran, with its observation. */
|
||||
void (*tool_end)(void *ctx, const char *name,
|
||||
const char *observation);
|
||||
void *tool_end_ctx;
|
||||
|
||||
/*
|
||||
* A status line the operator should see while a request waits or is
|
||||
* retried; "" clears it. The engine turns it into SP_EV_NOTE, so the
|
||||
* screen can say "retrying in 5 s" instead of looking hung.
|
||||
*/
|
||||
void (*note)(void *ctx, const char *text);
|
||||
void *note_ctx;
|
||||
|
||||
/* Called when the conversation was compacted to fit the budget. */
|
||||
void (*on_compact)(void *ctx, size_t before, size_t after,
|
||||
size_t msgs_before, size_t msgs_after);
|
||||
void *on_compact_ctx;
|
||||
|
||||
/*
|
||||
* Called when a request hit a usage limit that lifts at 'until' (epoch).
|
||||
* The callback waits (it may take hours) and returns 1 to ask again, or
|
||||
* 0 to give up and let the turn fail with the error. NULL: fail at once.
|
||||
*/
|
||||
int (*limit_wait)(void *ctx, long until, const char *why);
|
||||
void *limit_ctx;
|
||||
/* tried before waiting: move to another provider; 1 if it did */
|
||||
int (*limit_switch)(void *ctx);
|
||||
void *switch_ctx;
|
||||
|
||||
/* incremental output, if the transport and the caller both support it */
|
||||
sp_stream_cb stream;
|
||||
void *stream_ctx;
|
||||
};
|
||||
|
||||
struct sp_agent_stats {
|
||||
size_t steps;
|
||||
size_t tokens_in;
|
||||
size_t tokens_out;
|
||||
size_t last_in; /* the last request's prompt, for the meter */
|
||||
size_t last_cached; /* of which the provider had cached */
|
||||
size_t compactions;
|
||||
size_t tool_calls;
|
||||
size_t denied;
|
||||
size_t bytes_sent;
|
||||
};
|
||||
|
||||
/* waits for a usage limit without a screen; ctx: const long *max_wait_secs */
|
||||
int sp_limit_wait_default(void *ctx, long until, const char *why);
|
||||
|
||||
struct sp_host; /* plugin host, see splinter_plugin.h */
|
||||
|
||||
/*
|
||||
* Which tools an agent profile (build, plan ...) may use. max_auth is the
|
||||
* highest authorization class that runs without question (-1: any); allow and
|
||||
* deny are comma lists of tool names, a trailing '*' is a prefix, and deny wins.
|
||||
*/
|
||||
struct sp_tool_policy {
|
||||
char name[48]; /* the profile, for the refusal's wording */
|
||||
int max_auth;
|
||||
char allow[512];
|
||||
char deny[512];
|
||||
};
|
||||
|
||||
struct sp_agent {
|
||||
const struct sp_tool_policy *policy; /* NULL: no restriction */
|
||||
struct sp_registry *reg;
|
||||
struct sp_host *host; /* optional: compactors live there */
|
||||
struct sp_transport tr;
|
||||
const struct sp_agent_config *cfg;
|
||||
struct sp_session_info *sess;
|
||||
struct sp_conv *conv; /* optional: history lives here */
|
||||
struct sp_agent_stats stats;
|
||||
/*
|
||||
* A turn that stopped before a tool ran because a person has to decide.
|
||||
* The assistant message with the calls is already in the conversation;
|
||||
* the calls from pending_from on are still unobserved.
|
||||
*/
|
||||
struct sp_reply pending;
|
||||
size_t pending_from;
|
||||
int has_pending;
|
||||
};
|
||||
|
||||
#define SP_AGENT_INPUT_REQUIRED 2
|
||||
|
||||
int sp_agent_run(struct sp_agent *, const char *user_text,
|
||||
struct sp_buf *answer, struct sp_buf *err);
|
||||
/* Resume a paused turn: decision 1 allows the pending calls, 0 denies. */
|
||||
int sp_agent_resume(struct sp_agent *, int decision, struct sp_buf *answer,
|
||||
struct sp_buf *err);
|
||||
|
||||
/* builtin.c */
|
||||
int sp_builtin_register(struct sp_registry *);
|
||||
/*
|
||||
* Environment names the 'run' tool's shell does not inherit (API keys,
|
||||
* tokens). A trailing '*' makes a prefix. sp_secret_env_is takes "NAME=value".
|
||||
*/
|
||||
int sp_secret_env_add(const char *name);
|
||||
int sp_secret_env_is(const char *entry);
|
||||
struct sp_config;
|
||||
int sp_delegate_register(struct sp_registry *, const struct sp_config *,
|
||||
struct sp_host *);
|
||||
/* Gateway mode: answers on Telegram until SIGINT/SIGTERM. */
|
||||
struct sp_host;
|
||||
int sp_telegram_run(struct sp_agent *, struct sp_host *host,
|
||||
const char *token, const char *allow, struct sp_config *conf,
|
||||
struct sp_buf *err);
|
||||
int sp_telegram_token(char *buf, size_t len, const char *path);
|
||||
const char *sp_user_name(void);
|
||||
/*
|
||||
* Slash commands that are programs: <session dir>/commands/<name>. The program
|
||||
* gets the rest of the line, and its output becomes context for the model.
|
||||
*/
|
||||
int sp_slash_script(const char *dir, const char *name, const char *args,
|
||||
struct sp_buf *out, struct sp_buf *err);
|
||||
int sp_delegate_prio(const struct sp_config *, const char *id);
|
||||
/*
|
||||
* Where the child of a cli delegate finds the cli transport: the plugin path
|
||||
* for a binary at 'self'. $SPLINTER_CLI_PLUGIN wins outright; otherwise the
|
||||
* build tree next to the binary, the installed layout, then the build
|
||||
* directory compiled in. When none of them exists the first candidate is
|
||||
* returned, so the child's own error names the place that was expected.
|
||||
*/
|
||||
void sp_delegate_cli_plugin(const char *self, char *out, size_t len);
|
||||
|
||||
/*
|
||||
* A shipped plugin by name ("lcm", "mcp"): the build tree next to the binary
|
||||
* at 'self', the installed layout ($(PREFIX)/lib/splinter/plugins), then the
|
||||
* build directory compiled in. None found: the first candidate.
|
||||
*/
|
||||
void sp_plugin_path(const char *self, const char *name, char *out,
|
||||
size_t len);
|
||||
|
||||
/*
|
||||
* Limits. sp_limit_parse: is this error text a rate/usage limit (429, "weekly
|
||||
* limit", "quota", ...) and until when - the reset it names, else an hour.
|
||||
* The bench is ~/.splinter/cooldown/<id> ($SPLINTER_COOLDOWN_DIR), shared by
|
||||
* every splinter on the machine: sp_cooldown_until is 0 when <id> is free.
|
||||
*/
|
||||
int sp_limit_parse(const char *err, long *until);
|
||||
long sp_cooldown_until(const char *id);
|
||||
void sp_cooldown_set(const char *id, long until, const char *why);
|
||||
int sp_delegate_choose(const struct sp_config *, const char *task,
|
||||
const char *tags, char *id, size_t cap, char *why, size_t whylen,
|
||||
int *score);
|
||||
|
||||
/* 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.
|
||||
*/
|
||||
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);
|
||||
/* the same, with request shaping the caller wants forwarded */
|
||||
struct sp_transport sp_openai_transport_gen(const char *url, const char *model,
|
||||
const char *api_key, const struct sp_registry *, long timeout_s,
|
||||
const struct sp_gen_opts *);
|
||||
|
||||
/* openai.c -- pure JSON shaping, testable without a network */
|
||||
int sp_openai_request(const struct sp_conv *, const char *model,
|
||||
const struct sp_registry *, int streaming, struct sp_buf *out);
|
||||
int sp_openai_request_opts(const struct sp_conv *, const char *model,
|
||||
const struct sp_registry *, int streaming,
|
||||
const struct sp_gen_opts *, struct sp_buf *out);
|
||||
int sp_openai_reply(const char *json, struct sp_reply *out,
|
||||
struct sp_buf *err);
|
||||
|
||||
/* SSE accumulation, one line at a time, so it can be tested without a socket */
|
||||
struct sp_sse;
|
||||
struct sp_sse *sp_sse_new(void);
|
||||
void sp_sse_free(struct sp_sse *);
|
||||
/* Feed one line (with or without its newline). Returns 1 when a delta was
|
||||
* produced (written to out, may be empty), 0 for lines that carry nothing,
|
||||
* -1 on a parse error with the line quoted. */
|
||||
int sp_sse_line(struct sp_sse *, const char *line, struct sp_buf *out,
|
||||
struct sp_buf *err);
|
||||
/* Turn the accumulated state into a reply. Returns 0 or -1. */
|
||||
int sp_sse_finish(struct sp_sse *, struct sp_reply *out, struct sp_buf *err);
|
||||
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);
|
||||
/* What the last line carried: SP_STREAM_THINK, SP_STREAM_TEXT, SP_STREAM_TOOL,
|
||||
* or -1 for nothing. Transports classify by this, not by sniffing the line:
|
||||
* OpenAI sends `"content":null` next to `tool_calls`, and a substring test made
|
||||
* the tool's name part of the answer ("<model> readread"). */
|
||||
int sp_sse_kind(const struct sp_sse *);
|
||||
|
||||
/*
|
||||
* 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);
|
||||
struct sp_transport sp_anthropic_transport_gen(const char *url,
|
||||
const char *model, const char *api_key, const struct sp_registry *,
|
||||
long timeout_s, const struct sp_gen_opts *);
|
||||
|
||||
/* 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_request_opts(const struct sp_conv *, const char *model,
|
||||
const struct sp_registry *, int streaming, int oauth,
|
||||
const struct sp_gen_opts *, 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 */
|
||||
@@ -1,258 +0,0 @@
|
||||
/*
|
||||
* splinter -- the engine every front end talks to.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* The engine is the whole harness minus the screen: it owns the session, the
|
||||
* conversation, the tool registry, the plugins, the transport and the agent,
|
||||
* runs one turn at a time on its own thread, and reports what happened as a
|
||||
* queue of events.
|
||||
*
|
||||
* Why a queue and not callbacks: a turn runs on a thread of the engine's
|
||||
* making, and a front end (curses, a socket, a GUI) must not be called from
|
||||
* it -- it would have to be thread-safe in every drawing routine, and a slow
|
||||
* front end would stall the model. The engine only appends to a queue under a
|
||||
* mutex; the front end drains it whenever it is ready. Nothing here ever calls
|
||||
* into a front end.
|
||||
*
|
||||
* The contract, in one paragraph: sp_engine_open() builds the engine from the
|
||||
* command line and the config; sp_engine_input() turns a typed line into
|
||||
* either a command reply or a prompt; sp_engine_submit() starts the turn;
|
||||
* sp_engine_poll() delivers its events; sp_engine_approve(), sp_engine_steer()
|
||||
* and sp_engine_cancel() are what a front end may do while it runs.
|
||||
*
|
||||
* This is the C boundary. The same engine is served over a line-oriented JSON
|
||||
* socket by `splinter --serve`, so a GUI may be written in any language; see
|
||||
* docs/PROTOCOL.md. The two front ends use exactly the calls below, which is
|
||||
* what keeps them from drifting apart.
|
||||
*/
|
||||
#ifndef SPLINTER_ENGINE_H
|
||||
#define SPLINTER_ENGINE_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
struct sp_config;
|
||||
struct sp_host;
|
||||
struct sp_agent;
|
||||
struct sp_conv;
|
||||
struct sp_engine;
|
||||
struct swarm;
|
||||
|
||||
#define SP_ENGINE_PLUGINS 32
|
||||
|
||||
/* ---------------------------------------------------------------- options */
|
||||
|
||||
/*
|
||||
* What sp_engine_open() needs. Strings are copied; `conf` and `base` are read
|
||||
* and not owned (main keeps them alive for the whole run), but the engine does
|
||||
* change conf the way the old binary did: /model writes a drop-in, /connect
|
||||
* adds a provider, a pool failover marks one benched.
|
||||
*/
|
||||
struct sp_engine_opts {
|
||||
struct sp_config *conf;
|
||||
const struct sp_agent_config *base; /* steps, byte budget, prompt */
|
||||
const char *endpoint;
|
||||
const char *model;
|
||||
const char *key_env; /* variable holding the API key */
|
||||
const char *transport; /* plugin transport ("cli"), or NULL */
|
||||
const char *kind; /* "anthropic", or NULL */
|
||||
const char *script; /* mock replies, one per line */
|
||||
const char *agent; /* profile to start in */
|
||||
const char *session_dir;
|
||||
const char *session_id;
|
||||
const char *plugins[SP_ENGINE_PLUGINS];
|
||||
size_t nplugins;
|
||||
int resume; /* load the session's history */
|
||||
int continue_last; /* -c: newest session in this cwd */
|
||||
int no_transport; /* tools only (MCP server, delegate) */
|
||||
int interview; /* the model interviews the user */
|
||||
int swarm; /* join the local fleet */
|
||||
};
|
||||
|
||||
/* ----------------------------------------------------------------- events */
|
||||
|
||||
enum sp_ev_kind {
|
||||
SP_EV_NONE = 0,
|
||||
SP_EV_BUSY, /* n: 1 the turn started, 0 it ended */
|
||||
SP_EV_STREAM, /* n: SP_STREAM_TEXT|SP_STREAM_THINK, a: chunk */
|
||||
SP_EV_STEP, /* a: the step's reasoning, b: its answer */
|
||||
SP_EV_TOOL, /* a: name, b: arguments as sent */
|
||||
SP_EV_TOOL_RESULT, /* a: name, b: observation, n: 1 joins the call */
|
||||
SP_EV_NOTE, /* a: the prompt's one line, "" clears it */
|
||||
SP_EV_ENTRY, /* a: role, b: text */
|
||||
SP_EV_APPROVAL, /* a: name, b: args, n: authorization class */
|
||||
SP_EV_TURN_END, /* n: rc, a: answer, b: error */
|
||||
SP_EV_STATE, /* the model, tokens or profile changed */
|
||||
SP_EV_CLEAR, /* /new: the transcript is the old conversation */
|
||||
SP_EV_QUIT /* /quit was typed; the front end may close */
|
||||
};
|
||||
|
||||
struct sp_event {
|
||||
int kind;
|
||||
long n;
|
||||
char *a;
|
||||
char *b;
|
||||
};
|
||||
|
||||
/* 1 when an event was taken, 0 when the queue is empty. Free with
|
||||
* sp_engine_event_free(). */
|
||||
int sp_engine_poll(struct sp_engine *, struct sp_event *);
|
||||
void sp_engine_event_free(struct sp_event *);
|
||||
|
||||
/* --------------------------------------------------------------- snapshot */
|
||||
|
||||
struct sp_engine_state {
|
||||
char model[256];
|
||||
char endpoint[512];
|
||||
char agent[48];
|
||||
char session[64];
|
||||
char dir[512];
|
||||
char theme[48]; /* set by the front end, for /status */
|
||||
size_t tokens_in, tokens_out;
|
||||
size_t ctx_used; /* prompt tokens of the last request */
|
||||
size_t ctx_max; /* context window, 0 = unknown */
|
||||
size_t cached; /* of ctx_used, served from the provider cache */
|
||||
size_t turn_tokens_out; /* output tokens of this/last turn */
|
||||
size_t steps, calls, compactions; /* the session's counters */
|
||||
size_t last_ms, last_steps, last_calls; /* the last turn */
|
||||
int busy;
|
||||
int quit; /* /quit was typed */
|
||||
int waiting; /* the turn waits for an approval */
|
||||
int agents_n;
|
||||
int agent_cur;
|
||||
};
|
||||
|
||||
int sp_engine_state(struct sp_engine *, struct sp_engine_state *);
|
||||
|
||||
/*
|
||||
* The choices /model takes - every provider, then every pool - with the model
|
||||
* as the label and the current one marked. Configuration, not a network probe:
|
||||
* a picker must open at once. Returns how many were written.
|
||||
*/
|
||||
size_t sp_engine_models(struct sp_engine *, struct sp_model_choice *,
|
||||
size_t max);
|
||||
|
||||
/* -------------------------------------------------------------- lifecycle */
|
||||
|
||||
int sp_engine_open(struct sp_engine **, const struct sp_engine_opts *,
|
||||
struct sp_buf *err);
|
||||
void sp_engine_close(struct sp_engine *);
|
||||
/*
|
||||
* Move an engine to another session: close the old engine, open the new one
|
||||
* from the same options, replace *ep. `id` is a session id, "new" for a fresh
|
||||
* one, or NULL/"last" for the newest. The old engine is closed first because
|
||||
* plugins keep process globals; a failed open reopens the session the engine
|
||||
* was on, so the pointer is only NULL when even that fails. Returns 0 or -1
|
||||
* with `err` set.
|
||||
*/
|
||||
int sp_engine_switch(struct sp_engine **ep, const struct sp_engine_opts *,
|
||||
const char *id, struct sp_buf *err);
|
||||
|
||||
/* The pieces a front end may look at. The pointers stay valid until close. */
|
||||
struct sp_agent *sp_engine_agent(struct sp_engine *);
|
||||
struct sp_host *sp_engine_host(struct sp_engine *);
|
||||
struct sp_config *sp_engine_config(struct sp_engine *);
|
||||
struct sp_registry *sp_engine_registry(struct sp_engine *);
|
||||
struct swarm *sp_engine_swarm(struct sp_engine *);
|
||||
const struct sp_conv *sp_engine_conv(struct sp_engine *);
|
||||
void sp_engine_set_theme(struct sp_engine *, const char *);
|
||||
/* The default stream callback for async turns (the gateway has nobody to
|
||||
* stream to and installs a sink; -p passes its own to sp_engine_prompt). */
|
||||
void sp_engine_set_stream(struct sp_engine *, sp_stream_cb, void *ctx);
|
||||
const char *sp_engine_state_dir(struct sp_engine *);
|
||||
const char *sp_engine_session_id(struct sp_engine *);
|
||||
|
||||
/* ------------------------------------------------------------------ turns */
|
||||
|
||||
/*
|
||||
* Start a turn. Returns 0, or -1 when one is already running: the engine runs
|
||||
* exactly one turn at a time, because there is one conversation and one model.
|
||||
*/
|
||||
int sp_engine_submit(struct sp_engine *, const char *text);
|
||||
int sp_engine_busy(struct sp_engine *);
|
||||
int sp_engine_quit(struct sp_engine *);
|
||||
/* Join the finished turn. Call it once sp_engine_busy() said 0, before the
|
||||
* next submit; closing does it too. */
|
||||
int sp_engine_wait(struct sp_engine *);
|
||||
|
||||
/* Ask the model once without the queue: what -p and the slash prompt use. */
|
||||
int sp_engine_prompt(struct sp_engine *, const char *text, sp_stream_cb,
|
||||
void *stream_ctx, struct sp_buf *answer, struct sp_buf *err);
|
||||
|
||||
/* ------------------------------------------------------- during one turn */
|
||||
|
||||
int sp_engine_cancel(struct sp_engine *);
|
||||
/* Text typed while the turn runs: the loop picks it up at a step boundary.
|
||||
* -1 when no turn is running. */
|
||||
int sp_engine_steer(struct sp_engine *, const char *text);
|
||||
/*
|
||||
* A steer that arrived after the turn's last step boundary: the worker has
|
||||
* finished, the text is still pending. A front end takes it and runs it as the
|
||||
* next prompt, so typing into the last second is not lost. 0 while a turn is
|
||||
* still running (the loop will take it) or when nothing is pending.
|
||||
*/
|
||||
int sp_engine_take_steer(struct sp_engine *, struct sp_buf *out);
|
||||
/* 1 while a tool waits for the operator, with the call in the buffers. */
|
||||
int sp_engine_approval(struct sp_engine *, char *name, size_t namelen,
|
||||
int *auth, char *args, size_t argslen);
|
||||
/* Answer it. 0 when nothing was pending. */
|
||||
int sp_engine_approve(struct sp_engine *, int allow);
|
||||
|
||||
/* ------------------------------------------------------------------ input */
|
||||
|
||||
/*
|
||||
* One line from the operator. Returns
|
||||
*
|
||||
* SP_INPUT_PROMPT a prompt for the model; start the turn with it
|
||||
* SP_INPUT_HANDLED a command; `out` is the reply to show
|
||||
* SP_INPUT_SUBMIT a command that replaced the line; `out` is the prompt
|
||||
* to start a turn with (a program in commands/)
|
||||
*
|
||||
* The engine owns /model, /agent, /new, /connect, /usage, /status, /widgets,
|
||||
* /swarm, /resume, /quit, !shell and every command a plugin registered, so a
|
||||
* GUI gets the same set as the curses front end without re-implementing one.
|
||||
*
|
||||
* Call it while the engine is idle. A command changes the conversation, the
|
||||
* transport and the session; doing that under a running turn is a front-end
|
||||
* bug. sp_engine_conv() is a read-only view for the same reason: the messages
|
||||
* are the worker's while a turn runs.
|
||||
*/
|
||||
#define SP_INPUT_PROMPT 0
|
||||
#define SP_INPUT_HANDLED 1
|
||||
#define SP_INPUT_SUBMIT 2
|
||||
|
||||
int sp_engine_input(struct sp_engine *, const char *line, struct sp_buf *out);
|
||||
/* The names Tab completes, without the slash, sorted. Returns the count. */
|
||||
int sp_engine_command_names(struct sp_engine *, char (*names)[64], int max);
|
||||
|
||||
/* Agent profiles: Tab's three calls. */
|
||||
int sp_engine_agents(struct sp_engine *);
|
||||
const char *sp_engine_agent_name(struct sp_engine *, int idx);
|
||||
int sp_engine_agent_cur(struct sp_engine *);
|
||||
int sp_engine_agent_switch(struct sp_engine *, int idx);
|
||||
|
||||
/* ------------------------------------------------------------- formatting */
|
||||
|
||||
/*
|
||||
* How a tool call and its observation read, shared by every front end:
|
||||
*
|
||||
* Run du -sh ../xsrc
|
||||
* Read src/frontend/curses.c
|
||||
*
|
||||
* Arguments are unescaped, the one that matters (command, path, ...) is
|
||||
* picked, and the rest is left out. SP_OBS_JOIN says the observation is only
|
||||
* " [exit status 0]" and belongs on the call's row; SP_OBS_NONE says there is
|
||||
* nothing to show; SP_OBS_SHOWN means `out` is a block for the transcript.
|
||||
*/
|
||||
#define SP_OBS_NONE 0
|
||||
#define SP_OBS_SHOWN 1
|
||||
#define SP_OBS_JOIN 2
|
||||
|
||||
void sp_call_summary(const char *name, const char *args, char *out,
|
||||
size_t cap);
|
||||
int sp_obs_short(const char *obs, struct sp_buf *out);
|
||||
|
||||
#endif /* SPLINTER_ENGINE_H */
|
||||
@@ -1,280 +0,0 @@
|
||||
/*
|
||||
* splinter -- plugin ABI.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* A plugin is a shared object loaded with dlopen(). It links against
|
||||
* libsplinter.so, never against the binary, so there is exactly one copy of
|
||||
* every symbol in the process.
|
||||
*
|
||||
* What a plugin may do, and where:
|
||||
*
|
||||
* init() called once, on the main thread, before any turn. Register
|
||||
* tools and widgets here. May fail; a failed plugin is unloaded
|
||||
* from the set and reported, never half-used.
|
||||
* run() called on the main thread while a turn is being handled.
|
||||
* tick() called on the widget's own thread, so it may block, read
|
||||
* files, wait on sockets. It must NOT touch curses and must NOT
|
||||
* assume it is the only thread.
|
||||
* draw() called on the UI thread only, must be fast and non-blocking.
|
||||
* A widget without draw() is rendered from its published text.
|
||||
*
|
||||
* Text that should appear in the sidebar is published with
|
||||
* sp_host_widget_text(); the host copies it under a mutex, so the string does
|
||||
* not have to outlive the call.
|
||||
*/
|
||||
#ifndef SPLINTER_PLUGIN_H
|
||||
#define SPLINTER_PLUGIN_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
/*
|
||||
* Raise this whenever a struct a plugin hands to the host changes shape. It
|
||||
* stayed 1 while struct sp_gate gained block_turn: a gate built against the old
|
||||
* header would have had the host read past its struct and call what it found.
|
||||
* 2: sp_gate.block_turn, sp_task_ops, sp_status, commands and transports.
|
||||
*/
|
||||
#define SP_PLUGIN_ABI 2u
|
||||
|
||||
struct sp_host;
|
||||
|
||||
struct sp_widget {
|
||||
const char *name; /* unique in the sidebar */
|
||||
int (*tick)(struct sp_host *, const char *name, void *ctx);
|
||||
void (*draw)(struct sp_host *, const char *name, void *ctx);
|
||||
void *ctx;
|
||||
unsigned interval_ms; /* 0: tick once, then stop */
|
||||
};
|
||||
|
||||
/*
|
||||
* A compactor runs on the main thread before every request, with the whole
|
||||
* conversation in hand. It may rewrite it. Returning 1 means "changed", 0
|
||||
* "nothing to do", -1 "failed" - and a failure is reported, never ignored.
|
||||
*/
|
||||
struct sp_compactor {
|
||||
const char *name;
|
||||
int (*compact)(struct sp_host *, struct sp_conv *,
|
||||
size_t budget_bytes, unsigned turn);
|
||||
};
|
||||
|
||||
/*
|
||||
* A command is what the operator types with a leading slash: /goal <text>.
|
||||
* The UI does not know any command by name; it asks the host, and the host asks
|
||||
* the plugins. A plugin that wants one registers it here.
|
||||
*
|
||||
* Return 0 and put the reply in `out`; return -1 to say "not mine".
|
||||
*/
|
||||
typedef int (*sp_cmd_fn)(struct sp_host *, const char *args, struct sp_buf *out,
|
||||
void *ctx);
|
||||
|
||||
/*
|
||||
* A gate decides whether a tool may run, before the operator is asked and before
|
||||
* the authorization class is applied. It exists so a plugin can hold a policy the
|
||||
* core does not know: kid mode, a sandbox, a host-level allow list.
|
||||
*
|
||||
* Return 1 to allow (skips the operator prompt), 0 to deny, -1 to say "no
|
||||
* opinion" - then the normal rules apply.
|
||||
*/
|
||||
struct sp_gate {
|
||||
const char *name;
|
||||
int (*check)(struct sp_host *, const char *tool,
|
||||
int auth, const char *args, char *reason,
|
||||
size_t reason_len);
|
||||
/*
|
||||
* Optional: refuse the whole turn before the model is called. Used by kid
|
||||
* mode when the day's minutes are gone - a message the child reads, not a
|
||||
* hang, and not a model that has to be trusted to obey.
|
||||
*/
|
||||
int (*block_turn)(struct sp_host *, char *msg, size_t len);
|
||||
};
|
||||
|
||||
/*
|
||||
* What the status line is allowed to know. The harness owns the numbers - a
|
||||
* plugin must not count tokens twice or guess a price.
|
||||
*/
|
||||
struct sp_meter {
|
||||
size_t ctx_used; /* tokens the last request carried */
|
||||
size_t ctx_max; /* the window, 0 = unknown */
|
||||
size_t tok_in; /* this session */
|
||||
size_t tok_out;
|
||||
size_t cached; /* tokens the provider served from cache */
|
||||
long tps; /* output tokens per second, last turn */
|
||||
double cost; /* session cost, filled from the price config */
|
||||
unsigned tasks_running;
|
||||
unsigned tasks_max;
|
||||
};
|
||||
|
||||
/* A status segment: a name and a renderer, drawn in the order registered. */
|
||||
struct sp_status {
|
||||
const char *name;
|
||||
void (*render)(struct sp_host *, char *buf, size_t len);
|
||||
};
|
||||
|
||||
/*
|
||||
* Tasks owned by someone else. The delegate runs a model on another host and the
|
||||
* tasks plugin shows it; neither knows the other, so the harness passes an entry
|
||||
* through this little interface: begin gives an id, end closes it with a status
|
||||
* and whatever was spent.
|
||||
*/
|
||||
struct sp_task_ops {
|
||||
int (*begin)(struct sp_host *, const char *label, const char *detail);
|
||||
void (*end)(struct sp_host *, int id, int status, size_t tokens);
|
||||
};
|
||||
|
||||
struct sp_plugin {
|
||||
uint32_t abi; /* must equal SP_PLUGIN_ABI */
|
||||
const char *name;
|
||||
const char *version;
|
||||
int (*init)(struct sp_host *);
|
||||
int (*run)(struct sp_host *, const char *input,
|
||||
struct sp_buf *out);
|
||||
void (*shutdown)(struct sp_host *);
|
||||
};
|
||||
|
||||
/* Every plugin exports exactly this. */
|
||||
const struct sp_plugin *sp_plugin_describe(void);
|
||||
|
||||
/* ---- host API, implemented by splinter, called by plugins ---- */
|
||||
|
||||
uint32_t sp_host_abi(struct sp_host *);
|
||||
int sp_host_add_tool(struct sp_host *, const struct sp_tool *);
|
||||
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 *);
|
||||
const struct sp_meter *sp_host_meter(struct sp_host *);
|
||||
/*
|
||||
* The model the engine is on right now. The config says what a provider was
|
||||
* configured with; /model can change the model without touching it, and a
|
||||
* plugin that shows routing must not guess (it did, and named the wrong
|
||||
* route). Empty until the engine sets it.
|
||||
*/
|
||||
const char *sp_host_model(struct sp_host *h);
|
||||
void sp_host_set_model(struct sp_host *h, const char *model);
|
||||
/*
|
||||
* The upstream that served the last model request, when the provider says
|
||||
* (junction: X-Junction-Endpoint). The model is what was asked for; this is
|
||||
* who answered, and a router may pick a different one per request.
|
||||
*/
|
||||
const char *sp_host_served_by(struct sp_host *h);
|
||||
void sp_host_set_served_by(struct sp_host *h, const char *endpoint);
|
||||
void sp_host_set_meter(struct sp_host *, const struct sp_meter *);
|
||||
/*
|
||||
* Thread-safe: a copy under the host lock, and a change of only the caller's
|
||||
* fields under the lock. Use these from any thread but the UI's; the two above
|
||||
* remain for the UI thread and for reading a single field.
|
||||
*/
|
||||
void sp_host_meter_get(struct sp_host *, struct sp_meter *out);
|
||||
void sp_host_meter_update(struct sp_host *,
|
||||
void (*fn)(struct sp_meter *, void *), void *ctx);
|
||||
size_t sp_host_status_text(struct sp_host *, char *buf, size_t len);
|
||||
void sp_host_set_task_ops(struct sp_host *, const struct sp_task_ops *);
|
||||
int sp_host_task_begin(struct sp_host *, const char *label, const char *detail);
|
||||
void sp_host_task_end(struct sp_host *, int id, int status, size_t tokens);
|
||||
/* Ask every gate. Returns 1 allowed, 0 denied (reason filled), -1 no opinion. */
|
||||
int sp_host_gate(struct sp_host *, const char *tool, int auth,
|
||||
const char *args, char *reason, size_t reason_len);
|
||||
int sp_host_turn_blocked(struct sp_host *, char *msg, size_t len);
|
||||
int sp_host_add_command(struct sp_host *, const char *name, sp_cmd_fn,
|
||||
void *ctx);
|
||||
int sp_host_command(struct sp_host *, const char *name, const char *args,
|
||||
struct sp_buf *out);
|
||||
size_t sp_host_command_help(struct sp_host *, struct sp_buf *out);
|
||||
int sp_host_add_transport(struct sp_host *, const char *name,
|
||||
struct sp_transport);
|
||||
struct sp_transport *sp_host_transport(struct sp_host *, const char *name);
|
||||
|
||||
/* ---- provider: quota/usage/burst policy, pluggable (per key, shared state) ---- */
|
||||
enum sp_prov_decision { SP_PROV_ADMIT = 0, SP_PROV_DELAY, SP_PROV_WAIT_QUOTA, SP_PROV_DENY };
|
||||
struct sp_prov_result {
|
||||
enum sp_prov_decision decision;
|
||||
long retry_after_s; /* seconds to wait (DELAY) */
|
||||
long ready_at; /* unix timestamp when quota/backoff ends (WAIT_QUOTA) */
|
||||
char reason[256];
|
||||
};
|
||||
struct sp_provider_ops {
|
||||
void *ctx;
|
||||
int (*preflight)(void *ctx, const char *provider, const char *key_id,
|
||||
struct sp_prov_result *out);
|
||||
void (*account)(void *ctx, const char *provider, const char *key_id,
|
||||
long http_status, size_t tokens_in, size_t tokens_out);
|
||||
};
|
||||
void sp_host_set_provider(struct sp_host *, const struct sp_provider_ops *);
|
||||
enum sp_prov_decision sp_host_provider_preflight(struct sp_host *, const char *provider,
|
||||
const char *key_id, struct sp_prov_result *out);
|
||||
void sp_host_provider_account(struct sp_host *, const char *provider, const char *key_id,
|
||||
long http_status, size_t tokens_in, size_t tokens_out);
|
||||
|
||||
/* shared per-(provider,key_id) usage/quota state (~/.splinter/providers/...), flock+atomic.
|
||||
* Provider plugins use this for cross-instance, per-key tracking. */
|
||||
struct sp_prov_state {
|
||||
long quota_ready_at; long backoff_until;
|
||||
unsigned req_count; unsigned long tok_in, tok_out;
|
||||
long last_status, last_update, last_429_at;
|
||||
char note[128];
|
||||
};
|
||||
int sp_provstate_load(const char *provider, const char *key_id, struct sp_prov_state *out);
|
||||
int sp_provstate_update(const char *provider, const char *key_id,
|
||||
void (*fn)(struct sp_prov_state *s, void *ctx), void *ctx);
|
||||
void sp_provstate_account(const char *provider, const char *key_id,
|
||||
long http_status, size_t tok_in, size_t tok_out, long retry_after_s);
|
||||
int sp_provstate_preflight(const char *provider, const char *key_id,
|
||||
long now, long *ready_at, char *reason, size_t reason_cap);
|
||||
/* Stable fingerprint of a secret key (never stores/returns the secret). */
|
||||
char *sp_key_fingerprint(const char *secret, char *buf, size_t cap);
|
||||
|
||||
int sp_host_compact(struct sp_host *, struct sp_conv *, size_t budget);
|
||||
size_t sp_host_compaction_stats(struct sp_host *, size_t *compactions,
|
||||
size_t *failed, unsigned *turns);
|
||||
void sp_host_turn(struct sp_host *);
|
||||
/* The loaded configuration, so plugins (the exit ring) can read it. */
|
||||
const void *sp_host_config(struct sp_host *);
|
||||
void sp_host_set_config(struct sp_host *, const void *);
|
||||
|
||||
/*
|
||||
* A plugin's own configuration, from its block in the config file:
|
||||
*
|
||||
* plugin lcm {
|
||||
* keep = 40
|
||||
* server junction { url = http://... }
|
||||
* }
|
||||
*
|
||||
* sp_host_plugin_config(h, "lcm", "keep") is "40", a nested block gives
|
||||
* dotted keys ("server.junction.url"), a list "a,b,c". NULL when the key is
|
||||
* not set (or no config is loaded). 'plugin' is the block's name.
|
||||
*
|
||||
* sp_host_plugin_config_at() walks every setting of 'plugin' in file order:
|
||||
* index 0, 1, ... until it returns NULL; *key gets the setting's name.
|
||||
*/
|
||||
const char *sp_host_plugin_config(struct sp_host *, const char *plugin,
|
||||
const char *key);
|
||||
const char *sp_host_plugin_config_at(struct sp_host *, const char *plugin,
|
||||
size_t i, const char **key);
|
||||
struct sp_registry *sp_host_registry(struct sp_host *);
|
||||
|
||||
/* ---- host side, implemented by splinter, called by the harness ---- */
|
||||
|
||||
struct sp_host *sp_host_new(struct sp_registry *, struct sp_agent *,
|
||||
struct sp_session_info *);
|
||||
void sp_host_free(struct sp_host *);
|
||||
const char *sp_host_session_dir(struct sp_host *);
|
||||
const char *sp_host_session_id(struct sp_host *);
|
||||
/* Retry a durable delegation job (scheduler/worker). 0 on handled (see out). */
|
||||
int sp_delegate_retry_job(const char *id, int force, struct sp_buf *out);
|
||||
/* Scheduler tick: retry one due waiting_quota/waiting_poll job if any. */
|
||||
int sp_delegate_tick(struct sp_buf *out);
|
||||
int sp_plugin_load(struct sp_host *, const char *path,
|
||||
struct sp_buf *err);
|
||||
size_t sp_host_widget_snapshot(struct sp_host *, char *buf, size_t len);
|
||||
size_t sp_host_widget_count(struct sp_host *);
|
||||
|
||||
#endif /* SPLINTER_PLUGIN_H */
|
||||
@@ -1,14 +0,0 @@
|
||||
splinter is a C99/POSIX agent harness with a curses interface: the
|
||||
conversation on three quarters of the screen, a sidebar with the agent,
|
||||
provider, model and allowance in use, a status line with the context gauge,
|
||||
and the prompt below it.
|
||||
|
||||
It speaks to providers over their HTTP APIs, runs the tools it is asked to
|
||||
run (only those in its registry, and a mutating one only with consent), keeps
|
||||
every turn as JSON Lines under ~/.splinter, and can put its engine on a
|
||||
socket (splinter --serve) for another front end, or present an OpenAI-
|
||||
compatible endpoint of its own (splinter --openai-listen).
|
||||
|
||||
The library (libsplinter.so) is the backend; splinter and splinterctl are the
|
||||
front ends; the plugins under lib/splinter/plugins are the tools (a clock,
|
||||
the MCP client, provider pools, process control and others).
|
||||
@@ -1,52 +0,0 @@
|
||||
# $NetBSD$
|
||||
#
|
||||
# Makronix: splinter is the project's own C99/POSIX agent harness
|
||||
# (ext/src/splinter, IMPORT). It is built from the archive tools/ext-dist.sh
|
||||
# makes out of ext/src/splinter, so there is no MASTER_SITES.
|
||||
|
||||
DISTNAME= splinter-0.1
|
||||
CATEGORIES= misc
|
||||
DISTFILES= ${DISTNAME}${EXTRACT_SUFX}
|
||||
|
||||
MAINTAINER= lotherk@lother.io
|
||||
COMMENT= C99/POSIX agent harness with a curses interface
|
||||
LICENSE= modified-bsd
|
||||
|
||||
# The top Makefile is POSIX make; it runs the vendored NetBSD curses through
|
||||
# $(MAKE) -f GNUmakefile, which is GNU make. The build host's GNU make is
|
||||
# what USE_TOOLS brings; the target compiler comes from pkgsrc's wrappers.
|
||||
USE_TOOLS+= gmake
|
||||
MAKE_PROGRAM= ${GMAKE}
|
||||
|
||||
NO_CONFIGURE= yes
|
||||
NO_BUILDLINK= yes
|
||||
BUILD_TARGET= all
|
||||
INSTALL_TARGET= install
|
||||
|
||||
MAKE_FLAGS+= PREFIX=${PREFIX}
|
||||
MAKE_FLAGS+= DESTDIR=${DESTDIR}
|
||||
|
||||
# splinter's Makefile has its own CFLAGS default: the dialect, the include
|
||||
# paths of the source tree and -fPIC. A CFLAGS on the command line replaces
|
||||
# that default, so the package's flags are appended here. No -Werror: a
|
||||
# warning in the distribution is not a reason to stop the build. One line
|
||||
# and escaped spaces: a continuation ate the space before -fPIC (measured
|
||||
# 2026-11-17: "make: PIC -Iinclude ... No such file or directory").
|
||||
SPL_CFLAGS= -std=c99\ -D_POSIX_C_SOURCE=200809L\ -D_XOPEN_SOURCE=700\ -D_NETBSD_SOURCE\ -fPIC\ -Iinclude\ -Isrc/backend\ -Isrc/frontend\ -Ivendor/libmcp\ -Ivendor/netbsd-curses/libcurses
|
||||
MAKE_FLAGS+= CFLAGS=${CFLAGS:Q}\ ${SPL_CFLAGS}
|
||||
|
||||
# libsplinter.so is what the binaries and the plugins link against
|
||||
LDFLAGS+= ${COMPILER_RPATH_FLAG}${PREFIX}/lib
|
||||
MAKE_FLAGS+= LDFLAGS=${LDFLAGS:Q}
|
||||
MAKE_FLAGS+= LIBS=-lpthread
|
||||
|
||||
# NetBSD's own curses, not the vendored copy: the base system has libcurses
|
||||
# and libterminfo, and linking them keeps the package small and the build
|
||||
# free of tools that must run while it builds (the vendored tree's nbperf is
|
||||
# a target binary in a cross build). The project's Linux build keeps the
|
||||
# vendored default (Konrad, 2026-11-17: "nur auf linux eigenes curses").
|
||||
MAKE_FLAGS+= CURSES_LIB=-lcurses\ -lterminfo
|
||||
MAKE_FLAGS+= CURSES_DEP=
|
||||
|
||||
.include "../../mk/pthread.buildlink3.mk"
|
||||
.include "../../mk/bsd.pkg.mk"
|
||||
@@ -1,19 +0,0 @@
|
||||
bin/splinter
|
||||
bin/splinterctl
|
||||
lib/libsplinter.so
|
||||
lib/splinter/plugins/a2a.so
|
||||
lib/splinter/plugins/cli.so
|
||||
lib/splinter/plugins/clock.so
|
||||
lib/splinter/plugins/cps.so
|
||||
lib/splinter/plugins/focus.so
|
||||
lib/splinter/plugins/junction.so
|
||||
lib/splinter/plugins/kids.so
|
||||
lib/splinter/plugins/lcm.so
|
||||
lib/splinter/plugins/mcp.so
|
||||
lib/splinter/plugins/processes.so
|
||||
lib/splinter/plugins/provider.so
|
||||
lib/splinter/plugins/reminder.so
|
||||
lib/splinter/plugins/ring.so
|
||||
lib/splinter/plugins/scheduler.so
|
||||
lib/splinter/plugins/self.so
|
||||
lib/splinter/plugins/status.so
|
||||
@@ -1,5 +0,0 @@
|
||||
$NetBSD$
|
||||
|
||||
BLAKE2s (splinter-0.1.tar.gz) = 3656546bdeb6e52ac0e65a56da7b3f6d0935f6e0e67617b1661ad452e9ed79a0
|
||||
SHA512 (splinter-0.1.tar.gz) = b0fbf0dfe818de321f5f30f7bf8bbc3fafc73df23f790644fa1de86ab98b3eabba84409dbbe3001e0557621c58eb3239e575e3cf07f2594f726c37b1afffbba8
|
||||
Size (splinter-0.1.tar.gz) = 1274702 bytes
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,725 +0,0 @@
|
||||
/*
|
||||
* splinter -- cli: any command-line agent as the model.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Splinter does not need an HTTP endpoint. It needs something that answers.
|
||||
* This transport runs a program and takes its stdout as the answer, so
|
||||
* `claude -p`, `opencode run`, `ollama run`, `llm` or a shell script can all be
|
||||
* the brains -- and each of them brings its own keys, its own quota, its own
|
||||
* free tier.
|
||||
*
|
||||
* Configuration is by environment, deliberately: no config file to drift.
|
||||
*
|
||||
* SPLINTER_CLI_CMD the program, default "claude -p". If it contains
|
||||
* {file}, the prompt file path is substituted there;
|
||||
* {prompt} substitutes a shell-quoted prompt. Without
|
||||
* a placeholder the prompt is fed on stdin.
|
||||
* SPLINTER_CLI_FULL=1 send the whole transcript instead of the last user
|
||||
* message (the program keeps no history of its own)
|
||||
* SPLINTER_CLI_TIMEOUT seconds, default 1800
|
||||
* SPLINTER_CLI_SESSION the session key (set by splinter); empty: no sessions
|
||||
* SPLINTER_CLI_ID the name this command is benched under at its
|
||||
* limit; "cli" for the main one, the delegate's id
|
||||
* in a delegate's child
|
||||
* SPLINTER_CLI_STATE where the claude resume markers live,
|
||||
* default ~/.splinter/cli
|
||||
*
|
||||
* Trust note, because it matters: the command runs through /bin/sh -c, so the
|
||||
* string comes from the operator's environment, never from the model. Output
|
||||
* grows dynamically (capped at 64 MiB) and a non-zero exit is an error with the
|
||||
* program's own stderr attached -- a silent empty answer is the one thing this
|
||||
* must not do.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <time.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "i18n.h"
|
||||
#include "config.h"
|
||||
|
||||
#define OUT_CAP (64u << 20)
|
||||
|
||||
struct cli_cfg {
|
||||
char cmd[512];
|
||||
char timeout[16];
|
||||
int full;
|
||||
struct sp_host *host;
|
||||
/* for a fallback: the delegate's env=, sourced from a 0600 file */
|
||||
const char (*env)[SP_CONFIG_ENV_LEN];
|
||||
size_t nenv;
|
||||
};
|
||||
|
||||
static void
|
||||
render(const struct sp_conv *conv, int full, struct sp_buf *out)
|
||||
{
|
||||
size_t i, from = 0;
|
||||
|
||||
sp_buf_clear(out);
|
||||
if (!full) {
|
||||
for (i = conv->n; i > 0; i--) {
|
||||
if (conv->v[i - 1].role != NULL &&
|
||||
strcmp(conv->v[i - 1].role, "user") == 0) {
|
||||
from = i - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i = from; i < conv->n; i++) {
|
||||
const struct sp_msg *m = &conv->v[i];
|
||||
|
||||
if (m->content == NULL || m->content[0] == '\0')
|
||||
continue;
|
||||
if (full)
|
||||
sp_buf_printf(out, "%s: ", m->role != NULL ? m->role :
|
||||
"?");
|
||||
if (sp_buf_puts(out, m->content) != 0 ||
|
||||
sp_buf_puts(out, "\n") != 0)
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/* 's' as one single-quoted shell word */
|
||||
static int
|
||||
sh_word(struct sp_buf *b, const char *s)
|
||||
{
|
||||
if (sp_buf_puts(b, "'") != 0)
|
||||
return -1;
|
||||
for (; *s != '\0'; s++)
|
||||
if (*s == '\'' ? sp_buf_puts(b, "'\\''") != 0 :
|
||||
sp_buf_add(b, s, 1) != 0)
|
||||
return -1;
|
||||
return sp_buf_puts(b, "'");
|
||||
}
|
||||
|
||||
/*
|
||||
* Sessions. Every call used to start the program cold: a fresh claude or
|
||||
* opencode session per turn, no history over there, no warm cache. Now the
|
||||
* caller's session key ($SPLINTER_CLI_SESSION: the splinter session id, and
|
||||
* for a delegate that id plus ':' and the delegate's name) maps to one stable
|
||||
* session id per program, so consecutive calls land in the same conversation.
|
||||
*
|
||||
* claude a UUID derived from the key: --session-id the first time,
|
||||
* --resume after that. Which one is remembered in a marker file;
|
||||
* if the program disagrees (moved directory, deleted session) the
|
||||
* other one is tried once.
|
||||
* opencode --session ses_<derived>, which opencode creates if missing.
|
||||
* other {session} and {uuid} in the command expand to the key and the
|
||||
* derived UUID, for programs splinter does not know.
|
||||
*
|
||||
* A command that already names a session (--session, --resume, --continue)
|
||||
* is left alone. SPLINTER_CLI_SESSION set but empty turns all of this off.
|
||||
*/
|
||||
enum cli_prog { PROG_OTHER, PROG_CLAUDE, PROG_OPENCODE };
|
||||
|
||||
static enum cli_prog
|
||||
prog_of(const char *cmd)
|
||||
{
|
||||
const char *p = cmd, *w, *e, *base;
|
||||
size_t len;
|
||||
|
||||
for (;;) {
|
||||
while (*p == ' ' || *p == '\t')
|
||||
p++;
|
||||
w = p;
|
||||
while (*p != '\0' && *p != ' ' && *p != '\t')
|
||||
p++;
|
||||
e = p;
|
||||
if (e == w)
|
||||
return PROG_OTHER;
|
||||
/* skip NAME=value words in front of the program */
|
||||
if (memchr(w, '=', (size_t)(e - w)) == NULL)
|
||||
break;
|
||||
}
|
||||
for (base = e; base > w && base[-1] != '/'; base--)
|
||||
;
|
||||
len = (size_t)(e - base);
|
||||
if (len == 6 && strncmp(base, "claude", 6) == 0)
|
||||
return PROG_CLAUDE;
|
||||
if (len == 8 && strncmp(base, "opencode", 8) == 0)
|
||||
return PROG_OPENCODE;
|
||||
return PROG_OTHER;
|
||||
}
|
||||
|
||||
static uint64_t
|
||||
fnv64(const char *s, uint64_t h)
|
||||
{
|
||||
for (; *s != '\0'; s++) {
|
||||
h ^= (unsigned char)*s;
|
||||
h *= 0x100000001b3ULL;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/* the same key gives the same UUID, every time, on every machine */
|
||||
static void
|
||||
key_uuid(const char *key, char out[37])
|
||||
{
|
||||
unsigned char b[16];
|
||||
uint64_t h1 = fnv64(key, 0xcbf29ce484222325ULL);
|
||||
uint64_t h2 = fnv64(key, h1 ^ 0x9e3779b97f4a7c15ULL);
|
||||
int i;
|
||||
|
||||
for (i = 0; i < 8; i++) {
|
||||
b[i] = (unsigned char)(h1 >> (8 * i));
|
||||
b[8 + i] = (unsigned char)(h2 >> (8 * i));
|
||||
}
|
||||
b[6] = (unsigned char)((b[6] & 0x0f) | 0x40); /* version 4 */
|
||||
b[8] = (unsigned char)((b[8] & 0x3f) | 0x80); /* RFC 4122 variant */
|
||||
snprintf(out, 37, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
|
||||
"%02x%02x%02x%02x%02x%02x", b[0], b[1], b[2], b[3], b[4], b[5],
|
||||
b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]);
|
||||
}
|
||||
|
||||
/* opencode's shape: ses_ and 26 letters and digits */
|
||||
static void
|
||||
key_ses(const char *key, char out[31])
|
||||
{
|
||||
static const char abc[] =
|
||||
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
uint64_t h = fnv64(key, 0xcbf29ce484222325ULL);
|
||||
int i;
|
||||
|
||||
memcpy(out, "ses_", 4);
|
||||
for (i = 0; i < 26; i++) {
|
||||
if (i % 10 == 0)
|
||||
h = fnv64(key, h + (uint64_t)i);
|
||||
out[4 + i] = abc[h % 62];
|
||||
h /= 62;
|
||||
}
|
||||
out[30] = '\0';
|
||||
}
|
||||
|
||||
static void
|
||||
marker_path(const char *uuid, char *buf, size_t len)
|
||||
{
|
||||
const char *st = getenv("SPLINTER_CLI_STATE");
|
||||
const char *home = getenv("HOME");
|
||||
|
||||
if (st != NULL && *st != '\0')
|
||||
snprintf(buf, len, "%s/%s", st, uuid);
|
||||
else
|
||||
snprintf(buf, len, "%s/.splinter/cli/%s",
|
||||
home != NULL ? home : "/tmp", uuid);
|
||||
}
|
||||
|
||||
static int
|
||||
marker_exists(const char *uuid)
|
||||
{
|
||||
char path[600];
|
||||
|
||||
marker_path(uuid, path, sizeof(path));
|
||||
return access(path, F_OK) == 0;
|
||||
}
|
||||
|
||||
static void
|
||||
marker_set(const char *uuid)
|
||||
{
|
||||
char path[600], *slash;
|
||||
FILE *f;
|
||||
|
||||
marker_path(uuid, path, sizeof(path));
|
||||
slash = strrchr(path, '/');
|
||||
if (slash != NULL) {
|
||||
*slash = '\0';
|
||||
(void)mkdir(path, 0700);
|
||||
*slash = '/';
|
||||
}
|
||||
f = fopen(path, "w");
|
||||
if (f != NULL)
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static int
|
||||
ci_contains(const char *hay, const char *needle)
|
||||
{
|
||||
size_t n = strlen(needle);
|
||||
|
||||
for (; *hay != '\0'; hay++)
|
||||
if (strncasecmp(hay, needle, n) == 0)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Build the shell line: timeout, the command with placeholders expanded, the
|
||||
* session arguments, stdin and stderr redirection.
|
||||
*/
|
||||
static int
|
||||
build_cmd(const struct cli_cfg *c, const char *path, const char *prompt,
|
||||
const char *key, const char *uuid, const char *extra, const char *errpath,
|
||||
const char *envfile, struct sp_buf *cmd)
|
||||
{
|
||||
int placeholder;
|
||||
const char *p = c->cmd;
|
||||
|
||||
sp_buf_clear(cmd);
|
||||
placeholder = strstr(c->cmd, "{file}") != NULL ||
|
||||
strstr(c->cmd, "{prompt}") != NULL;
|
||||
if (envfile != NULL && envfile[0] != '\0' &&
|
||||
(sp_buf_puts(cmd, ". ") != 0 || sh_word(cmd, envfile) != 0 ||
|
||||
sp_buf_puts(cmd, " && ") != 0))
|
||||
return -1;
|
||||
if (sp_buf_printf(cmd, "timeout %s ", c->timeout) != 0)
|
||||
return -1;
|
||||
while (*p != '\0') {
|
||||
if (strncmp(p, "{file}", 6) == 0) {
|
||||
if (sh_word(cmd, path) != 0)
|
||||
return -1;
|
||||
p += 6;
|
||||
} else if (strncmp(p, "{prompt}", 8) == 0) {
|
||||
if (sh_word(cmd, prompt) != 0)
|
||||
return -1;
|
||||
p += 8;
|
||||
} else if (strncmp(p, "{session}", 9) == 0) {
|
||||
if (sh_word(cmd, key) != 0)
|
||||
return -1;
|
||||
p += 9;
|
||||
} else if (strncmp(p, "{uuid}", 6) == 0) {
|
||||
if (sh_word(cmd, uuid) != 0)
|
||||
return -1;
|
||||
p += 6;
|
||||
} else if (sp_buf_add(cmd, p, 1) != 0) {
|
||||
return -1;
|
||||
} else
|
||||
p++;
|
||||
}
|
||||
if (extra != NULL && extra[0] != '\0' &&
|
||||
(sp_buf_puts(cmd, " ") != 0 || sp_buf_puts(cmd, extra) != 0))
|
||||
return -1;
|
||||
if (!placeholder &&
|
||||
(sp_buf_puts(cmd, " < ") != 0 || sh_word(cmd, path) != 0))
|
||||
return -1;
|
||||
if (sp_buf_puts(cmd, " 2> ") != 0 || sh_word(cmd, errpath) != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* 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)
|
||||
{
|
||||
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);
|
||||
*status = 0;
|
||||
if (pipe(fds) != 0) {
|
||||
sp_buf_printf(err, "cli: pipe: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
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;
|
||||
}
|
||||
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");
|
||||
rc = -1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
close(fds[0]);
|
||||
(void)waitpid(child, &st, 0);
|
||||
*status = st;
|
||||
ef = fopen(errpath, "r");
|
||||
if (ef != NULL) {
|
||||
en = fread(errtext, 1, errcap - 1, ef);
|
||||
fclose(ef);
|
||||
}
|
||||
errtext[en] = '\0';
|
||||
(void)unlink(errpath);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
ok_status(int status)
|
||||
{
|
||||
return WIFEXITED(status) && WEXITSTATUS(status) == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The delegate's env= for a fallback, as `export NAME='value'` lines in a file
|
||||
* only this user can read, sourced by the shell. Not `env NAME=value cmd`: a
|
||||
* command line is visible to every user on the machine through ps.
|
||||
*/
|
||||
static int
|
||||
write_envfile(const struct cli_cfg *c, const char *path)
|
||||
{
|
||||
struct sp_buf b;
|
||||
size_t i;
|
||||
int fd, rc = -1;
|
||||
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return -1;
|
||||
for (i = 0; i < c->nenv; i++) {
|
||||
const char *eq = strchr(c->env[i], '=');
|
||||
|
||||
if (eq == NULL)
|
||||
continue;
|
||||
if (sp_buf_puts(&b, "export ") != 0 ||
|
||||
sp_buf_add(&b, c->env[i], (size_t)(eq - c->env[i]) + 1) != 0 ||
|
||||
sh_word(&b, eq + 1) != 0 || sp_buf_puts(&b, "\n") != 0)
|
||||
goto out;
|
||||
}
|
||||
fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
|
||||
if (fd < 0)
|
||||
goto out;
|
||||
if (b.len == 0 || write(fd, b.p, b.len) == (ssize_t)b.len)
|
||||
rc = 0;
|
||||
close(fd);
|
||||
out:
|
||||
sp_buf_free(&b);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
cli_send_one(struct cli_cfg *c, const struct sp_conv *conv,
|
||||
struct sp_reply *out, struct sp_buf *err)
|
||||
{
|
||||
struct sp_buf body, cmd, raw;
|
||||
char path[512], errpath[540] = "", errtext[512];
|
||||
char envfile[540] = "";
|
||||
char uuid[37] = "", ses[31] = "", extra[96] = "";
|
||||
const char *tmpdir = getenv("TMPDIR");
|
||||
const char *key = getenv("SPLINTER_CLI_SESSION");
|
||||
enum cli_prog prog = prog_of(c != NULL ? c->cmd : "");
|
||||
int fd, status = 0, resume = 0, sessions;
|
||||
ssize_t w;
|
||||
size_t n;
|
||||
|
||||
if (c == NULL)
|
||||
return -1;
|
||||
if (sp_buf_init(&body) != 0 || sp_buf_init(&cmd) != 0 ||
|
||||
sp_buf_init(&raw) != 0) {
|
||||
sp_buf_puts(err, "cli: out of memory");
|
||||
return -1;
|
||||
}
|
||||
render(conv, c->full, &body);
|
||||
|
||||
sessions = key != NULL && *key != '\0' &&
|
||||
strstr(c->cmd, "--session") == NULL &&
|
||||
strstr(c->cmd, "--resume") == NULL &&
|
||||
strstr(c->cmd, "--continue") == NULL;
|
||||
if (key == NULL)
|
||||
key = "";
|
||||
key_uuid(key, uuid);
|
||||
if (sessions && prog == PROG_CLAUDE) {
|
||||
resume = marker_exists(uuid);
|
||||
snprintf(extra, sizeof(extra), "%s %s",
|
||||
resume ? "--resume" : "--session-id", uuid);
|
||||
} else if (sessions && prog == PROG_OPENCODE) {
|
||||
key_ses(key, ses);
|
||||
snprintf(extra, sizeof(extra), "--session %s", ses);
|
||||
}
|
||||
|
||||
if (tmpdir == NULL || *tmpdir == '\0')
|
||||
tmpdir = "/var/tmp";
|
||||
snprintf(path, sizeof(path), "%s/splinter-cli-XXXXXX", tmpdir);
|
||||
fd = mkstemp(path);
|
||||
if (fd < 0) {
|
||||
sp_buf_printf(err, "cli: mkstemp: %s", strerror(errno));
|
||||
goto fail;
|
||||
}
|
||||
n = body.len;
|
||||
w = write(fd, body.p, n);
|
||||
close(fd);
|
||||
if (w < 0 || (size_t)w != n) {
|
||||
sp_buf_printf(err, "cli: short write: %s", strerror(errno));
|
||||
unlink(path);
|
||||
goto fail;
|
||||
}
|
||||
|
||||
/*
|
||||
* The program reads the prompt on stdin unless the command names where it
|
||||
* goes: {file} becomes the prompt file path, {prompt} becomes the prompt
|
||||
* as a shell word. timeout guards a hang. stderr goes to a file next to
|
||||
* the prompt so it never lands in the middle of a curses screen.
|
||||
*/
|
||||
snprintf(errpath, sizeof(errpath), "%s.err", path);
|
||||
if (c->nenv > 0) {
|
||||
snprintf(envfile, sizeof(envfile), "%s.env", path);
|
||||
if (write_envfile(c, envfile) != 0) {
|
||||
sp_buf_printf(err, "cli: env file: %s", strerror(errno));
|
||||
envfile[0] = '\0';
|
||||
unlink(path);
|
||||
goto fail;
|
||||
}
|
||||
}
|
||||
if (build_cmd(c, path, body.p != NULL ? body.p : "", key, uuid, extra,
|
||||
errpath, envfile, &cmd) != 0 ||
|
||||
run_cmd(cmd.p, errpath, &raw, errtext, sizeof(errtext), &status,
|
||||
err) != 0) {
|
||||
unlink(path);
|
||||
goto fail;
|
||||
}
|
||||
/*
|
||||
* claude refuses --session-id for a session it already has and --resume
|
||||
* for one it cannot find (another directory, a deleted file). Either way
|
||||
* the other form is right; try it once, it costs no model call.
|
||||
*/
|
||||
if (prog == PROG_CLAUDE && extra[0] != '\0' && !ok_status(status) &&
|
||||
(ci_contains(errtext, "session") ||
|
||||
ci_contains(errtext, "conversation"))) {
|
||||
resume = !resume;
|
||||
snprintf(extra, sizeof(extra), "%s %s",
|
||||
resume ? "--resume" : "--session-id", uuid);
|
||||
if (build_cmd(c, path, body.p != NULL ? body.p : "", key, uuid,
|
||||
extra, errpath, envfile, &cmd) != 0 ||
|
||||
run_cmd(cmd.p, errpath, &raw, errtext, sizeof(errtext),
|
||||
&status, err) != 0) {
|
||||
unlink(path);
|
||||
goto fail;
|
||||
}
|
||||
}
|
||||
unlink(path);
|
||||
if (prog == PROG_CLAUDE && extra[0] != '\0' && ok_status(status))
|
||||
marker_set(uuid);
|
||||
|
||||
if (WIFEXITED(status) && WEXITSTATUS(status) == 124) {
|
||||
sp_buf_printf(err, sp_td("cli.timeout", "cli: '%s' timed out after %s s"), c->cmd,
|
||||
c->timeout);
|
||||
goto fail;
|
||||
}
|
||||
if (!ok_status(status)) {
|
||||
sp_buf_printf(err, sp_td("cli.failed", "cli: '%s' failed (exit %d): %.400s"), c->cmd,
|
||||
WIFEXITED(status) ? WEXITSTATUS(status) : -1,
|
||||
errtext[0] != '\0' ? errtext : raw.p != NULL ? raw.p : "");
|
||||
goto fail;
|
||||
}
|
||||
if (raw.len == 0) {
|
||||
sp_buf_printf(err, sp_td("cli.no_output", "cli: '%s' produced no output"), c->cmd);
|
||||
goto fail;
|
||||
}
|
||||
if (envfile[0] != '\0') {
|
||||
(void)unlink(envfile);
|
||||
envfile[0] = '\0';
|
||||
}
|
||||
out->status = 200;
|
||||
out->content = strdup(raw.p);
|
||||
if (out->content == NULL)
|
||||
goto fail;
|
||||
sp_buf_free(&body);
|
||||
sp_buf_free(&cmd);
|
||||
sp_buf_free(&raw);
|
||||
return 0;
|
||||
|
||||
fail:
|
||||
if (errpath[0] != '\0')
|
||||
(void)unlink(errpath);
|
||||
if (envfile[0] != '\0')
|
||||
(void)unlink(envfile);
|
||||
sp_buf_free(&body);
|
||||
sp_buf_free(&cmd);
|
||||
sp_buf_free(&raw);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/*
|
||||
* The main cli at its limit. cli_cmd is tried first, benched as "cli"; then
|
||||
* the cli delegates named in cli_fallback, in order, each with its own cmd and
|
||||
* env=, benched under its own id - the same bench the delegation uses, so an
|
||||
* account at its limit is skipped everywhere. The session key stays the same,
|
||||
* so claude resumes the same conversation under the next account.
|
||||
*/
|
||||
static int
|
||||
cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
struct cli_cfg *c = ctx;
|
||||
const struct sp_config *cfg;
|
||||
char list[300], *id, *save = NULL;
|
||||
long until, soonest = 0;
|
||||
int first = 1, tried = 0, rc = -1;
|
||||
|
||||
if (c == NULL)
|
||||
return -1;
|
||||
cfg = c->host != NULL ? sp_host_config(c->host) : NULL;
|
||||
/*
|
||||
* In a delegate's child the command is that delegate's, and so is the
|
||||
* bench: SPLINTER_CLI_ID names it. Benching "cli" from there would bench
|
||||
* the main program for an account it may not even use.
|
||||
*/
|
||||
{
|
||||
const char *self = getenv("SPLINTER_CLI_ID");
|
||||
|
||||
snprintf(list, sizeof(list), "%s,%s",
|
||||
self != NULL && *self != '\0' ? self : "cli",
|
||||
cfg != NULL ? cfg->cli_fallback : "");
|
||||
}
|
||||
for (id = strtok_r(list, ", ", &save); id != NULL;
|
||||
id = strtok_r(NULL, ", ", &save), first = 0) {
|
||||
struct cli_cfg alt = *c;
|
||||
const struct sp_delegate *d = NULL;
|
||||
size_t k;
|
||||
|
||||
if (!first) {
|
||||
for (k = 0; cfg != NULL && k < cfg->ndelegates; k++)
|
||||
if (strcmp(cfg->delegate[k].id, id) == 0)
|
||||
d = &cfg->delegate[k];
|
||||
if (d == NULL || strcmp(d->kind, "cli") != 0) {
|
||||
if (c->host != NULL)
|
||||
(void)sp_host_note(c->host, "cli: "
|
||||
"cli_fallback names no cli delegate");
|
||||
continue;
|
||||
}
|
||||
if (sp_cli_command(d, NULL, alt.cmd,
|
||||
sizeof(alt.cmd)) != 0)
|
||||
snprintf(alt.cmd, sizeof(alt.cmd), "%s",
|
||||
d->cmd[0] != '\0' ? d->cmd : "claude -p");
|
||||
alt.env = (const char (*)[SP_CONFIG_ENV_LEN])d->env;
|
||||
alt.nenv = d->nenv;
|
||||
}
|
||||
if ((until = sp_cooldown_until(id)) != 0) {
|
||||
if (soonest == 0 || until < soonest)
|
||||
soonest = until;
|
||||
continue;
|
||||
}
|
||||
if (tried > 0 && c->host != NULL) {
|
||||
char note[96];
|
||||
|
||||
snprintf(note, sizeof(note), "cli: falling back to %s",
|
||||
id);
|
||||
(void)sp_host_note(c->host, note);
|
||||
}
|
||||
tried++;
|
||||
sp_buf_clear(err);
|
||||
rc = cli_send_one(&alt, conv, out, err);
|
||||
if (rc == 0 || !sp_limit_parse(err->p, &until))
|
||||
return rc;
|
||||
sp_cooldown_set(id, until, err->p);
|
||||
if (soonest == 0 || until < soonest)
|
||||
soonest = until;
|
||||
}
|
||||
if (tried == 0 || rc != 0) {
|
||||
char when[32] = "?";
|
||||
time_t tt = (time_t)soonest;
|
||||
struct tm tm;
|
||||
|
||||
if (soonest > 0)
|
||||
strftime(when, sizeof(when), "%Y-%m-%d %H:%M",
|
||||
localtime_r(&tt, &tm));
|
||||
if (tried == 0)
|
||||
sp_buf_clear(err);
|
||||
sp_buf_printf(err, "%scli: every account at its usage limit, "
|
||||
"first back %s (WAIT_QUOTA ready_at=%ld)",
|
||||
err->len > 0 ? " -- " : "", when, soonest);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int
|
||||
cli_init(struct sp_host *h)
|
||||
{
|
||||
static struct cli_cfg cfg;
|
||||
static struct sp_transport tr;
|
||||
const char *cmd = getenv("SPLINTER_CLI_CMD");
|
||||
const char *to = getenv("SPLINTER_CLI_TIMEOUT");
|
||||
const char *full = getenv("SPLINTER_CLI_FULL");
|
||||
|
||||
memset(&cfg, 0, sizeof(cfg));
|
||||
snprintf(cfg.cmd, sizeof(cfg.cmd), "%s",
|
||||
cmd != NULL && *cmd != '\0' ? cmd : "claude -p");
|
||||
snprintf(cfg.timeout, sizeof(cfg.timeout), "%s",
|
||||
to != NULL && *to != '\0' ? to : "1800");
|
||||
cfg.full = full != NULL && strcmp(full, "0") != 0;
|
||||
|
||||
cfg.host = h;
|
||||
tr.send = cli_send;
|
||||
tr.ctx = &cfg;
|
||||
return sp_host_add_transport(h, "cli", tr);
|
||||
}
|
||||
|
||||
static const struct sp_plugin cli_plugin = {
|
||||
SP_PLUGIN_ABI, "cli", "1.0.0", cli_init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &cli_plugin;
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* splinter -- example plugin: a clock widget in the sidebar.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Shows the three parts of the ABI that matter:
|
||||
* - init() registers a widget,
|
||||
* - tick() runs on the host's worker thread and only publishes text,
|
||||
* - run() adds a turn-level tool the harness can call.
|
||||
*
|
||||
* Build: cc -std=c99 -shared -fPIC -o clock.so clock.c -lsplinter
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
static int
|
||||
clock_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
char out[128];
|
||||
time_t now = time(NULL);
|
||||
struct tm tm;
|
||||
|
||||
(void)ctx;
|
||||
localtime_r(&now, &tm);
|
||||
snprintf(out, sizeof(out), "%02d:%02d:%02d", tm.tm_hour, tm.tm_min,
|
||||
tm.tm_sec);
|
||||
return sp_host_widget_text(h, name, out);
|
||||
}
|
||||
|
||||
static int
|
||||
clock_tool(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char line[64];
|
||||
time_t now = time(NULL);
|
||||
struct tm tm;
|
||||
|
||||
(void)args;
|
||||
(void)ctx;
|
||||
localtime_r(&now, &tm);
|
||||
snprintf(line, sizeof(line), "%04d-%02d-%02d %02d:%02d:%02d",
|
||||
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min,
|
||||
tm.tm_sec);
|
||||
return sp_buf_puts(out, line);
|
||||
}
|
||||
|
||||
static int
|
||||
clock_init(struct sp_host *h)
|
||||
{
|
||||
static const struct sp_widget w = {
|
||||
"clock", clock_tick, NULL, NULL, 1000
|
||||
};
|
||||
struct sp_tool t;
|
||||
|
||||
if (sp_host_add_widget(h, &w) != 0)
|
||||
return -1;
|
||||
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "clock";
|
||||
t.description = "Report the local date and time.";
|
||||
t.params = "{\"type\":\"object\",\"properties\":{}}";
|
||||
t.auth = SP_AUTH_READ;
|
||||
t.run = clock_tool;
|
||||
return sp_host_add_tool(h, &t);
|
||||
}
|
||||
|
||||
static const struct sp_plugin clock_plugin = {
|
||||
SP_PLUGIN_ABI,
|
||||
"clock",
|
||||
"1.0.0",
|
||||
clock_init,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &clock_plugin;
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
/*
|
||||
* splinter -- cps: continuous parallel compression.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* The idea: the expensive part of compaction is deciding what to cut. That can
|
||||
* be done while nothing else happens, on a thread of its own, so the moment the
|
||||
* budget is hit the main thread only has to splice an already-computed plan.
|
||||
*
|
||||
* The worker never sees the conversation. It sees an index: the role and the
|
||||
* size of each message, copied under a mutex by the main thread. That is why
|
||||
* this is safe without a lock around the conversation itself, and it is also
|
||||
* its limit: it can decide *which* messages go, not summarise their text.
|
||||
*
|
||||
* The widget in the sidebar shows how often a plan was prepared and what the
|
||||
* last one would cut - so "continuous" is visible, not claimed.
|
||||
*/
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "i18n.h"
|
||||
|
||||
#define SNAP_MAX 256
|
||||
#define KEEP_TAIL 6
|
||||
#define SUMMARY_MAX 512
|
||||
|
||||
struct snap_msg {
|
||||
char role[16];
|
||||
size_t len;
|
||||
char head[64];
|
||||
};
|
||||
|
||||
static struct {
|
||||
pthread_mutex_t lock;
|
||||
size_t n; /* messages in the snapshot, <= SNAP_MAX */
|
||||
size_t total; /* messages in the conversation then */
|
||||
size_t bytes; /* and its size: a stale plan is refused */
|
||||
struct snap_msg m[SNAP_MAX];
|
||||
int requested;
|
||||
int ready;
|
||||
size_t cut; /* drop [1, cut) */
|
||||
char summary[SUMMARY_MAX];
|
||||
size_t before;
|
||||
size_t after;
|
||||
unsigned long prepared;
|
||||
unsigned long applied;
|
||||
unsigned long idle;
|
||||
char widget[256];
|
||||
} cps;
|
||||
|
||||
static void
|
||||
copy_snapshot(const struct sp_conv *conv)
|
||||
{
|
||||
size_t i, n = conv->n > SNAP_MAX ? SNAP_MAX : conv->n;
|
||||
|
||||
pthread_mutex_lock(&cps.lock);
|
||||
cps.n = n;
|
||||
cps.total = conv->n;
|
||||
cps.bytes = sp_conv_bytes(conv);
|
||||
for (i = 0; i < n; i++) {
|
||||
const struct sp_msg *m = &conv->v[i];
|
||||
|
||||
snprintf(cps.m[i].role, sizeof(cps.m[i].role), "%s",
|
||||
m->role != NULL ? m->role : "?");
|
||||
cps.m[i].len = m->content != NULL ? strlen(m->content) : 0;
|
||||
snprintf(cps.m[i].head, sizeof(cps.m[i].head), "%s",
|
||||
m->content != NULL ? m->content : "");
|
||||
}
|
||||
cps.requested = 1;
|
||||
cps.ready = 0;
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
}
|
||||
|
||||
static int
|
||||
cps_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
unsigned turn)
|
||||
{
|
||||
size_t i, at;
|
||||
int apply = 0;
|
||||
|
||||
(void)turn;
|
||||
if (conv == NULL || conv->n <= KEEP_TAIL + 1)
|
||||
return 0;
|
||||
|
||||
pthread_mutex_lock(&cps.lock);
|
||||
/*
|
||||
* The plan fits this conversation only if it is the one it was made for.
|
||||
* Comparing against cps.n, which stops at SNAP_MAX, meant that past 256
|
||||
* messages no plan ever applied - compaction just stopped.
|
||||
*/
|
||||
if (budget == 0) {
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
return 0; /* no byte budget: nothing to do */
|
||||
}
|
||||
if (cps.ready && cps.total == conv->n &&
|
||||
cps.bytes == sp_conv_bytes(conv) &&
|
||||
sp_conv_bytes(conv) > budget) {
|
||||
apply = 1;
|
||||
} else {
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
copy_snapshot(conv);
|
||||
return 0; /* plan is being prepared */
|
||||
}
|
||||
|
||||
if (apply) {
|
||||
size_t cut = cps.cut;
|
||||
char summary[SUMMARY_MAX];
|
||||
struct sp_msg msg;
|
||||
size_t inserted;
|
||||
|
||||
snprintf(summary, sizeof(summary), "%s", cps.summary);
|
||||
cps.ready = 0;
|
||||
cps.applied++;
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
|
||||
/* a tool result goes with the call it answers, never alone */
|
||||
while (cut < conv->n && conv->v[cut].role != NULL &&
|
||||
strcmp(conv->v[cut].role, "tool") == 0)
|
||||
cut++;
|
||||
if (cut <= 1 || cut >= conv->n)
|
||||
return 0;
|
||||
for (i = 1; i < cut; i++) {
|
||||
free(conv->v[i].role);
|
||||
free(conv->v[i].name);
|
||||
free(conv->v[i].call_id);
|
||||
free(conv->v[i].content);
|
||||
free(conv->v[i].calls);
|
||||
}
|
||||
memmove(&conv->v[1], &conv->v[cut],
|
||||
(conv->n - cut) * sizeof(*conv->v));
|
||||
conv->n = 1 + (conv->n - cut);
|
||||
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.role = "system";
|
||||
msg.content = summary;
|
||||
at = (conv->n > 0 && strcmp(conv->v[0].role, "system") == 0) ?
|
||||
1 : 0;
|
||||
if (sp_conv_insert(conv, at, &msg) != 0)
|
||||
return -1;
|
||||
inserted = at;
|
||||
(void)inserted;
|
||||
return 1;
|
||||
}
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
(void)h;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* the worker side: called from the widget's own thread, never from the loop */
|
||||
static int
|
||||
cps_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
size_t i, total = 0, cut, tail_from;
|
||||
char line[256];
|
||||
int did = 0;
|
||||
|
||||
(void)ctx;
|
||||
pthread_mutex_lock(&cps.lock);
|
||||
if (!cps.requested) {
|
||||
cps.idle++;
|
||||
snprintf(line, sizeof(line), sp_td("cps.idle", "idle (applied %lu, prepared %lu)"),
|
||||
cps.applied, cps.prepared);
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
return sp_host_widget_text(h, name, line);
|
||||
}
|
||||
cps.requested = 0;
|
||||
|
||||
for (i = 0; i < cps.n; i++)
|
||||
total += cps.m[i].len + 16;
|
||||
tail_from = cps.n > KEEP_TAIL ? cps.n - KEEP_TAIL : 1;
|
||||
cut = tail_from;
|
||||
if (cut <= 1)
|
||||
cut = 1;
|
||||
snprintf(cps.summary, sizeof(cps.summary),
|
||||
"[cps] %zu messages cut from the front to stay under budget; "
|
||||
"verbatim tail of %zu messages follows. Oldest cut turn began with: "
|
||||
"\"%.60s\"", cut - 1, cps.n - cut,
|
||||
cps.n > 1 ? cps.m[1].head : "");
|
||||
cps.before = total;
|
||||
cps.after = 0;
|
||||
for (i = cut; i < cps.n; i++)
|
||||
cps.after += cps.m[i].len + 16;
|
||||
cps.cut = cut;
|
||||
cps.ready = 1;
|
||||
cps.prepared++;
|
||||
did = 1;
|
||||
snprintf(line, sizeof(line), sp_td("cps.plan", "plan ready: cut %zu/%zu, %zu -> %zu B"),
|
||||
cut - 1, cps.n, cps.before, cps.after);
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
(void)did;
|
||||
return sp_host_widget_text(h, name, line);
|
||||
}
|
||||
|
||||
static const struct sp_compactor cps_compactor = { "cps", cps_compact };
|
||||
|
||||
static int
|
||||
cps_init(struct sp_host *h)
|
||||
{
|
||||
static const struct sp_widget w = {
|
||||
"cps", cps_tick, NULL, NULL, 100
|
||||
};
|
||||
|
||||
pthread_mutex_init(&cps.lock, NULL);
|
||||
cps.ready = 0;
|
||||
cps.requested = 0;
|
||||
if (sp_host_add_compactor(h, &cps_compactor) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_widget(h, &w) != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin cps_plugin = {
|
||||
SP_PLUGIN_ABI, "cps", "1.0.0", cps_init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &cps_plugin;
|
||||
}
|
||||
@@ -1,616 +0,0 @@
|
||||
/*
|
||||
* splinter -- focus: keep the goal in front of the model.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Long conversations drift. Ten turns in, the model is deep in a detail and the
|
||||
* thing the session was started for is somewhere behind it. This plugin puts a
|
||||
* short recap back on the table every seven turns - not as a new instruction
|
||||
* that overrides the user, but as one system message right before the turn, so
|
||||
* it can be read as a reminder and dismissed if the user has changed direction.
|
||||
*
|
||||
* `/goal <text>` sets the goal. The engine starts a turn with it, asking the
|
||||
* model for a short recap; the plugin remembers the answer and injects that
|
||||
* recap every seventh turn. There is no separate /recap command: recapping is
|
||||
* what a goal does.
|
||||
*
|
||||
* The goal is also the first thing the prompt carries. A session that starts
|
||||
* with a goal (config, resume, planner) gets one system message on its first
|
||||
* request, before the model has answered anything. A goal that is only
|
||||
* remembered internally is a goal the model never saw.
|
||||
*
|
||||
* A goal ends, and the model says so: the instructions ask it to end its final
|
||||
* answer with the single line GOAL_COMPLETE. The plugin looks for that line at
|
||||
* the end of the conversation and in the session log, records the state in the
|
||||
* session meta (sp_session_set_goal_state), and stops reminding. The sidebar
|
||||
* says [done] and /goal reports it; a new goal opens a new one.
|
||||
*
|
||||
* SPLINTER_FOCUS_GOAL text, exported from the config key `goal`
|
||||
* SPLINTER_FOCUS_EVERY turns between recaps, default 7
|
||||
*
|
||||
* A goal longer than 1000 characters is truncated with a marker: a reminder
|
||||
* that eats the budget it is meant to protect would be self-defeating.
|
||||
*
|
||||
* Position matters. The reminder is inserted before the newest user message,
|
||||
* not appended after it: the model then reads goal -> request and answers the
|
||||
* request, instead of reading the request and treating the goal as a reply.
|
||||
*/
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "i18n.h"
|
||||
|
||||
#define GOAL_MAX 1000
|
||||
#define RECAP_MAX 800
|
||||
#define GOAL_DONE "GOAL_COMPLETE"
|
||||
#define SESSION_TAIL (16 * 1024)
|
||||
|
||||
/*
|
||||
* goal, recap and reminders are shared by three threads: /goal runs on the UI
|
||||
* thread, the compactor on the turn thread, the tick on its own. One lock for
|
||||
* all of them; the tick used to read the goal while /goal was rewriting it.
|
||||
*/
|
||||
static pthread_mutex_t focus_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static char goal[GOAL_MAX + 1];
|
||||
static char recap[RECAP_MAX + 1]; /* the model's short recap of the goal */
|
||||
static int recap_pending; /* goal set, waiting for that answer */
|
||||
static char goal_state[16] = "open"; /* open | succeeded */
|
||||
static unsigned announced; /* the goal is already in a prompt */
|
||||
static unsigned armed; /* a GOAL_COMPLETE may now be an answer */
|
||||
static size_t armed_assistants; /* assistant messages when it was armed */
|
||||
static struct timespec armed_at; /* and when, for the session file */
|
||||
static unsigned every = 7;
|
||||
static unsigned last_reminder;
|
||||
static unsigned reminders;
|
||||
static char widget_text[192];
|
||||
static char session_id[64]; /* whose goal the statics belong to */
|
||||
static char env_goal[GOAL_MAX + 1]; /* SPLINTER_FOCUS_GOAL fallback */
|
||||
|
||||
/* One line, bounded: the recap travels in a system message, not a transcript. */
|
||||
static void
|
||||
recap_fit(char *s, size_t cap)
|
||||
{
|
||||
size_t i = 0, n = 0;
|
||||
|
||||
while (s[i] != '\0' && n + 1 < cap) {
|
||||
unsigned char c = (unsigned char)s[i++];
|
||||
|
||||
if (c == '\n' || c == '\r' || c == '\t') {
|
||||
if (n > 0 && s[n - 1] != ' ')
|
||||
s[n++] = ' ';
|
||||
} else if (c == ' ') {
|
||||
if (n > 0 && s[n - 1] != ' ')
|
||||
s[n++] = ' ';
|
||||
} else
|
||||
s[n++] = (char)c;
|
||||
}
|
||||
while (n > 0 && s[n - 1] == ' ')
|
||||
n--;
|
||||
s[n] = '\0';
|
||||
}
|
||||
|
||||
/*
|
||||
* The first answer after /goal is the recap. A tool round may put empty
|
||||
* assistant messages before it; only text without calls counts.
|
||||
*/
|
||||
static void
|
||||
recap_capture(struct sp_conv *conv)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (!recap_pending || conv == NULL)
|
||||
return;
|
||||
for (i = conv->n; i > 0; i--) {
|
||||
const struct sp_msg *m = &conv->v[i - 1];
|
||||
|
||||
if (m->role == NULL || strcmp(m->role, "assistant") != 0)
|
||||
continue;
|
||||
if (m->content == NULL || m->content[0] == '\0')
|
||||
continue;
|
||||
if (m->calls != NULL && m->calls[0] != '\0')
|
||||
continue;
|
||||
snprintf(recap, sizeof(recap), "%s", m->content);
|
||||
recap_fit(recap, sizeof(recap));
|
||||
recap_pending = 0;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* A plugin is not unloaded between sessions: the same focus statics serve the
|
||||
* next /open. Read the goal and its state from the session meta whenever the
|
||||
* session id changes, so a resumed session and a switched session see their
|
||||
* own goal. The caller holds focus_lock.
|
||||
*/
|
||||
static void
|
||||
focus_session_sync(struct sp_host *h)
|
||||
{
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *id = sp_host_session_id(h);
|
||||
char g[GOAL_MAX + 1], st[16];
|
||||
|
||||
if (id == NULL || *id == '\0' || strcmp(session_id, id) == 0)
|
||||
return;
|
||||
snprintf(session_id, sizeof(session_id), "%s", id);
|
||||
goal[0] = '\0';
|
||||
recap[0] = '\0';
|
||||
snprintf(goal_state, sizeof(goal_state), "open");
|
||||
recap_pending = 0;
|
||||
announced = 0;
|
||||
armed = 0;
|
||||
reminders = 0;
|
||||
last_reminder = 0;
|
||||
if (dir != NULL && *dir != '\0' &&
|
||||
sp_session_get_goal(dir, id, g, sizeof(g)) == 0) {
|
||||
snprintf(goal, sizeof(goal), "%s", g);
|
||||
if (sp_session_get_goal_state(dir, id, st, sizeof(st)) == 0 &&
|
||||
strcmp(st, "succeeded") == 0)
|
||||
snprintf(goal_state, sizeof(goal_state), "%s", st);
|
||||
} else if (env_goal[0] != '\0')
|
||||
snprintf(goal, sizeof(goal), "%s", env_goal);
|
||||
}
|
||||
|
||||
/*
|
||||
* The model declared the goal reached. Persist that in the session (a resumed
|
||||
* session must know), stop reminding, and say it in the sidebar and the
|
||||
* transcript once.
|
||||
*/
|
||||
static void
|
||||
focus_publish(struct sp_host *h)
|
||||
{
|
||||
char line[sizeof(widget_text) + 160];
|
||||
char rec[96];
|
||||
unsigned n;
|
||||
int done;
|
||||
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
done = strcmp(goal_state, "succeeded") == 0;
|
||||
n = reminders;
|
||||
if (goal[0] == '\0')
|
||||
line[0] = '\0'; /* no goal: the sidebar says nothing */
|
||||
else {
|
||||
snprintf(rec, sizeof(rec), sp_td("focus.widget_recap",
|
||||
"recap %u, every %u turns"), n, every);
|
||||
snprintf(line, sizeof(line), "%s%.160s%s\n%s",
|
||||
done ? "[done] " : "", goal,
|
||||
strlen(goal) > 160 ? "..." : "", rec);
|
||||
}
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
(void)sp_host_widget_text(h, "focus", line);
|
||||
}
|
||||
|
||||
static void
|
||||
focus_mark_succeeded(struct sp_host *h)
|
||||
{
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *id = sp_host_session_id(h);
|
||||
char g[GOAL_MAX + 1];
|
||||
int changed = 0;
|
||||
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
if (goal[0] != '\0' && strcmp(goal_state, "succeeded") != 0) {
|
||||
snprintf(goal_state, sizeof(goal_state), "succeeded");
|
||||
snprintf(g, sizeof(g), "%s", goal);
|
||||
changed = 1;
|
||||
}
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
if (!changed)
|
||||
return;
|
||||
if (dir != NULL && *dir != '\0' && id != NULL && *id != '\0') {
|
||||
struct sp_buf serr;
|
||||
|
||||
if (sp_buf_init(&serr) == 0) {
|
||||
(void)sp_session_set_goal_state(dir, id, "succeeded",
|
||||
&serr);
|
||||
sp_buf_free(&serr);
|
||||
}
|
||||
}
|
||||
focus_publish(h);
|
||||
{
|
||||
char msg[GOAL_MAX + 128];
|
||||
|
||||
snprintf(msg, sizeof(msg), sp_td("focus.succeeded",
|
||||
"goal succeeded: %s"), g);
|
||||
(void)sp_host_status_msg(h, msg);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* The newest assistant answer, and only that: a marker in an old turn does not
|
||||
* close a goal that was set after it. Tool rounds are skipped, they carry no
|
||||
* final text - and `after` is how many answers existed when the goal went into
|
||||
* the prompt, so an answer from before that point does not count.
|
||||
*/
|
||||
static size_t
|
||||
count_assistants(const struct sp_conv *conv)
|
||||
{
|
||||
size_t i, n = 0;
|
||||
|
||||
for (i = 0; conv != NULL && i < conv->n; i++)
|
||||
if (conv->v[i].role != NULL &&
|
||||
strcmp(conv->v[i].role, "assistant") == 0 &&
|
||||
conv->v[i].content != NULL && conv->v[i].content[0] != '\0')
|
||||
n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
static int
|
||||
conv_goal_complete(const struct sp_conv *conv, size_t after)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (conv == NULL || count_assistants(conv) <= after)
|
||||
return 0;
|
||||
for (i = conv->n; i > 0; i--) {
|
||||
const struct sp_msg *m = &conv->v[i - 1];
|
||||
|
||||
if (m->role == NULL || strcmp(m->role, "assistant") != 0)
|
||||
continue;
|
||||
if (m->content == NULL || m->content[0] == '\0')
|
||||
continue;
|
||||
if (m->calls != NULL && m->calls[0] != '\0')
|
||||
continue;
|
||||
return strstr(m->content, GOAL_DONE) != NULL;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The tick has no conversation in hand; it reads the session log. Only the tail
|
||||
* is read: the answer that closed the goal is the newest thing in the file, and
|
||||
* a session that has grown to megabytes must not be read every second.
|
||||
*/
|
||||
static int
|
||||
session_goal_complete(struct sp_host *h)
|
||||
{
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *id = sp_host_session_id(h);
|
||||
char path[800], tail[SESSION_TAIL + 1];
|
||||
struct stat st;
|
||||
off_t size, off;
|
||||
ssize_t n;
|
||||
int fd;
|
||||
char *line, *save = NULL, *last = NULL;
|
||||
|
||||
if (dir == NULL || *dir == '\0' || id == NULL || *id == '\0')
|
||||
return 0;
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
|
||||
/*
|
||||
* A file that has not been written since the goal was armed holds the
|
||||
* answer to an older goal, whatever its last line says.
|
||||
*/
|
||||
if (stat(path, &st) != 0)
|
||||
return 0;
|
||||
if (st.st_mtim.tv_sec < armed_at.tv_sec ||
|
||||
(st.st_mtim.tv_sec == armed_at.tv_sec &&
|
||||
st.st_mtim.tv_nsec <= armed_at.tv_nsec))
|
||||
return 0;
|
||||
fd = open(path, O_RDONLY);
|
||||
if (fd < 0)
|
||||
return 0;
|
||||
size = lseek(fd, 0, SEEK_END);
|
||||
if (size <= 0) {
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
off = size > (off_t)SESSION_TAIL ? size - (off_t)SESSION_TAIL : 0;
|
||||
if (lseek(fd, off, SEEK_SET) < 0) {
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
n = read(fd, tail, sizeof(tail) - 1);
|
||||
close(fd);
|
||||
if (n <= 0)
|
||||
return 0;
|
||||
tail[n] = '\0';
|
||||
/*
|
||||
* Only the newest final answer counts: an old GOAL_COMPLETE belongs to
|
||||
* the goal that was open then, and a new goal has been set since.
|
||||
*/
|
||||
for (line = strtok_r(tail, "\n", &save); line != NULL;
|
||||
line = strtok_r(NULL, "\n", &save)) {
|
||||
if (strstr(line, "\"role\":\"assistant\"") != NULL)
|
||||
last = line;
|
||||
}
|
||||
return last != NULL && strstr(last, GOAL_DONE) != NULL;
|
||||
}
|
||||
|
||||
/* a system message right before the newest user message, never after it */
|
||||
static int
|
||||
insert_before_user(struct sp_conv *conv, const char *text)
|
||||
{
|
||||
struct sp_msg m;
|
||||
size_t at;
|
||||
|
||||
if (conv == NULL || conv->n == 0)
|
||||
return -1;
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = "system";
|
||||
m.content = (char *)text;
|
||||
at = conv->n - 1;
|
||||
while (at > 0 && conv->v[at].role != NULL &&
|
||||
strcmp(conv->v[at].role, "user") != 0)
|
||||
at--;
|
||||
return sp_conv_insert(conv, at, &m);
|
||||
}
|
||||
|
||||
/*
|
||||
* The goal is in a prompt now. From here on an answer may close it - but only
|
||||
* one written after this point: the count of answers and the log's mtime are
|
||||
* the barrier that keeps an older GOAL_COMPLETE out.
|
||||
*/
|
||||
static void
|
||||
focus_arm(const struct sp_conv *conv)
|
||||
{
|
||||
armed = 1;
|
||||
armed_assistants = count_assistants(conv);
|
||||
(void)clock_gettime(CLOCK_REALTIME, &armed_at);
|
||||
}
|
||||
|
||||
/* /goal's own prompt already carries the goal: do not say it twice */
|
||||
static int
|
||||
newest_user_is_goal_prompt(const struct sp_conv *conv)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (conv == NULL)
|
||||
return 0;
|
||||
for (i = conv->n; i > 0; i--) {
|
||||
const struct sp_msg *m = &conv->v[i - 1];
|
||||
|
||||
if (m->role != NULL && strcmp(m->role, "user") == 0)
|
||||
return m->content != NULL &&
|
||||
strncmp(m->content, "Goal: ", 6) == 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
focus_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
unsigned turn)
|
||||
{
|
||||
char text[GOAL_MAX + 800];
|
||||
char rem[GOAL_MAX + 768];
|
||||
char r[GOAL_MAX + 1];
|
||||
unsigned n;
|
||||
int complete;
|
||||
|
||||
(void)budget;
|
||||
if (conv == NULL || conv->n == 0)
|
||||
return 0;
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
focus_session_sync(h);
|
||||
recap_capture(conv);
|
||||
/*
|
||||
* Only an answer to a prompt that carried this goal can close it: armed
|
||||
* is set when the goal goes into the request, so an old GOAL_COMPLETE
|
||||
* lying in the conversation cannot close a goal that was set after it.
|
||||
*/
|
||||
complete = armed && goal[0] != '\0' &&
|
||||
strcmp(goal_state, "succeeded") != 0 &&
|
||||
conv_goal_complete(conv, armed_assistants);
|
||||
if (complete) {
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
focus_mark_succeeded(h);
|
||||
return 0;
|
||||
}
|
||||
if (goal[0] == '\0' || strcmp(goal_state, "succeeded") == 0 ||
|
||||
turn == 0 || turn == last_reminder) { /* never twice in a turn */
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The first request carries the goal itself. Recap first, goal text
|
||||
* until a recap exists - the same rule the periodic reminder follows.
|
||||
*/
|
||||
if (!announced) {
|
||||
if (newest_user_is_goal_prompt(conv)) {
|
||||
/* /goal or /continue already wrote it into the prompt */
|
||||
announced = 1;
|
||||
focus_arm(conv);
|
||||
last_reminder = turn;
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
focus_publish(h);
|
||||
return 0;
|
||||
}
|
||||
snprintf(r, sizeof(r), "%s", recap[0] != '\0' ? recap : goal);
|
||||
announced = 1;
|
||||
focus_arm(conv);
|
||||
last_reminder = turn;
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
snprintf(rem, sizeof(rem), sp_td("focus.goal_prompt",
|
||||
"Goal: %s. Work toward it. When the goal is fully "
|
||||
"achieved, end your final answer with the single "
|
||||
"line GOAL_COMPLETE so splinter can mark it as "
|
||||
"succeeded."), r);
|
||||
snprintf(text, sizeof(text), "[focus] %s", rem);
|
||||
if (insert_before_user(conv, text) != 0)
|
||||
return -1;
|
||||
(void)sp_host_status_msg(h,
|
||||
sp_t("focus.note_goal"));
|
||||
focus_publish(h);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if ((turn % every) != 0) {
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
return 0;
|
||||
}
|
||||
snprintf(r, sizeof(r), "%s", recap[0] != '\0' ? recap : goal);
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
|
||||
snprintf(rem, sizeof(rem), sp_td("focus.reminder",
|
||||
"Recap to remember: %s. Before answering, check whether "
|
||||
"the last step moved closer to the goal; if not, say so "
|
||||
"and name the next step. When the goal is fully achieved, "
|
||||
"end your final answer with the single line "
|
||||
"GOAL_COMPLETE."), r);
|
||||
snprintf(text, sizeof(text), "[focus] %s", rem);
|
||||
if (insert_before_user(conv, text) != 0)
|
||||
return -1;
|
||||
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
last_reminder = turn;
|
||||
reminders++;
|
||||
n = reminders;
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
{
|
||||
char note[160];
|
||||
|
||||
snprintf(note, sizeof(note), sp_td("focus.note_recap",
|
||||
"recap applied (turn %u, every %u turns)"), turn, every);
|
||||
(void)sp_host_status_msg(h, note);
|
||||
}
|
||||
(void)n;
|
||||
focus_publish(h);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* /goal <text> set the goal; the engine starts the recap turn
|
||||
* /goal show what it is now
|
||||
*/
|
||||
static int
|
||||
focus_command(struct sp_host *h, const char *args, struct sp_buf *out,
|
||||
void *ctx)
|
||||
{
|
||||
char g[GOAL_MAX + 1], saveerr[256] = "";
|
||||
unsigned n;
|
||||
int done;
|
||||
|
||||
(void)ctx;
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
focus_session_sync(h);
|
||||
if (args == NULL || *args == '\0') {
|
||||
snprintf(g, sizeof(g), "%s", goal);
|
||||
n = reminders;
|
||||
done = strcmp(goal_state, "succeeded") == 0;
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
if (g[0] == '\0')
|
||||
return sp_buf_puts(out, sp_td("focus.none", "no goal set (/goal <text>)"));
|
||||
if (done)
|
||||
return sp_buf_printf(out, sp_td("focus.status_done",
|
||||
"goal: %s [succeeded] (%u recaps, every %u turns)"),
|
||||
g, n, every);
|
||||
return sp_buf_printf(out, sp_td("focus.status",
|
||||
"goal: %s (%u recaps, every %u turns)"), g, n, every);
|
||||
}
|
||||
snprintf(goal, sizeof(goal), "%.*s", GOAL_MAX, args);
|
||||
if (strlen(args) > GOAL_MAX)
|
||||
snprintf(goal + GOAL_MAX - 24, 25, "...[gekuerzt]");
|
||||
recap[0] = '\0';
|
||||
recap_pending = 1;
|
||||
snprintf(goal_state, sizeof(goal_state), "open");
|
||||
announced = 0;
|
||||
armed = 0;
|
||||
reminders = 0;
|
||||
last_reminder = 0;
|
||||
snprintf(g, sizeof(g), "%s", goal);
|
||||
{
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *id = sp_host_session_id(h);
|
||||
|
||||
if (dir != NULL && *dir != '\0' && id != NULL && *id != '\0') {
|
||||
struct sp_buf serr;
|
||||
|
||||
if (sp_buf_init(&serr) == 0) {
|
||||
if (sp_session_set_goal(dir, id, goal, &serr) != 0)
|
||||
snprintf(saveerr, sizeof(saveerr), "%s",
|
||||
serr.p != NULL ? serr.p :
|
||||
"not saved");
|
||||
sp_buf_free(&serr);
|
||||
}
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
/* publish now, so the sidebar does not wait for the next tick */
|
||||
focus_publish(h);
|
||||
(void)sp_buf_printf(out, sp_td("focus.set", "goal set: %s"), g);
|
||||
if (saveerr[0] != '\0')
|
||||
sp_buf_printf(out, " (%s)", saveerr);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
focus_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
char line[sizeof(widget_text)];
|
||||
int check = 0;
|
||||
|
||||
(void)ctx;
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
focus_session_sync(h);
|
||||
check = armed && goal[0] != '\0' &&
|
||||
strcmp(goal_state, "succeeded") != 0 &&
|
||||
session_goal_complete(h);
|
||||
if (!check) {
|
||||
if (goal[0] == '\0')
|
||||
line[0] = '\0'; /* no goal: the sidebar says nothing */
|
||||
else
|
||||
snprintf(line, sizeof(line), "%s%.160s%s",
|
||||
strcmp(goal_state, "succeeded") == 0 ?
|
||||
"[done] " : "", goal,
|
||||
strlen(goal) > 160 ? "..." : "");
|
||||
}
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
if (check) {
|
||||
focus_mark_succeeded(h);
|
||||
return 0;
|
||||
}
|
||||
return sp_host_widget_text(h, name, line);
|
||||
}
|
||||
|
||||
static const struct sp_compactor focus = { "focus", focus_compact };
|
||||
|
||||
static int
|
||||
focus_init(struct sp_host *h)
|
||||
{
|
||||
static const struct sp_widget w = { "focus", focus_tick, NULL, NULL, 1000 };
|
||||
const char *g = getenv("SPLINTER_FOCUS_GOAL");
|
||||
const char *e = getenv("SPLINTER_FOCUS_EVERY");
|
||||
|
||||
memset(goal, 0, sizeof(goal));
|
||||
memset(recap, 0, sizeof(recap));
|
||||
memset(env_goal, 0, sizeof(env_goal));
|
||||
session_id[0] = '\0';
|
||||
recap_pending = 0;
|
||||
snprintf(goal_state, sizeof(goal_state), "open");
|
||||
announced = 0;
|
||||
armed = 0;
|
||||
if (g != NULL) {
|
||||
snprintf(env_goal, sizeof(env_goal), "%.*s", GOAL_MAX, g);
|
||||
if (strlen(g) > GOAL_MAX)
|
||||
snprintf(env_goal + GOAL_MAX - 24, 25,
|
||||
"...[gekuerzt]");
|
||||
snprintf(goal, sizeof(goal), "%s", env_goal);
|
||||
}
|
||||
if (e != NULL && atoi(e) > 0 && atoi(e) < 1000)
|
||||
every = (unsigned)atoi(e);
|
||||
|
||||
if (sp_host_add_compactor(h, &focus) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_command(h, "goal", focus_command, NULL) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_widget(h, &w) != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin focus_plugin = {
|
||||
SP_PLUGIN_ABI, "focus", "1.1.0", focus_init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &focus_plugin;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,616 +0,0 @@
|
||||
/*
|
||||
* splinter -- kid mode.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* A child may talk to splinter. Every action that could change something goes to
|
||||
* a parent first, and the model is told to stay friendly and age-appropriate.
|
||||
*
|
||||
* SPLINTER_KIDS_APPROVE_CMD program that asks the parent; exit 0 = yes,
|
||||
* anything else = no. It gets the request as its
|
||||
* first argument. docs/kids/ask.sh speaks Telegram.
|
||||
* SPLINTER_KIDS_TIMEOUT seconds to wait for the parent (default 120)
|
||||
* ~/.splinter/kids/allow what is allowed without asking, one rule per
|
||||
* line: "read *" or "run ls*"
|
||||
*
|
||||
* Two rules matter more than the rest:
|
||||
*
|
||||
* - a timeout is a NO. A parent who is not looking does not approve anything.
|
||||
* - the whitelist matches the tool and its arguments, never the mood.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "ack.h"
|
||||
#include "mcp.h"
|
||||
|
||||
#define KIDS_RULES 64
|
||||
#define KIDS_RULE_LEN 256
|
||||
|
||||
static char allow_file[700];
|
||||
static char approve_cmd[512];
|
||||
static unsigned timeout_s = 120;
|
||||
static char child_name[64] = "das Kind";
|
||||
static char usage_file[700];
|
||||
static char domains_file[700];
|
||||
static int search_mode; /* 0 approve, 1 allow, 2 deny */
|
||||
static unsigned daily_minutes; /* 0 = no limit */
|
||||
static long used_seconds; /* today */
|
||||
static time_t last_seen;
|
||||
static char today[16];
|
||||
|
||||
/* One rule: "<tool> <glob>", where * matches anything and a missing glob is "*". */
|
||||
struct rule {
|
||||
char tool[32];
|
||||
char pattern[KIDS_RULE_LEN];
|
||||
};
|
||||
|
||||
static struct rule rules[KIDS_RULES];
|
||||
static size_t nrules;
|
||||
|
||||
/*
|
||||
* Daily budget.
|
||||
*
|
||||
* The time is counted where splinter actually works - one step at a time - and
|
||||
* stored per day in a plain file: "2026-11-08 4314". A new day starts at zero.
|
||||
* When the budget is gone the gate refuses every tool, including reading, and the
|
||||
* conversation is told to close the day: the child gets an answer that says so,
|
||||
* not a silent hang.
|
||||
*/
|
||||
static void
|
||||
usage_load(void)
|
||||
{
|
||||
FILE *f;
|
||||
char d[32];
|
||||
long s;
|
||||
|
||||
snprintf(today, sizeof(today), "%s",
|
||||
"1970-01-01");
|
||||
used_seconds = 0;
|
||||
f = fopen(usage_file, "r");
|
||||
if (f == NULL)
|
||||
return;
|
||||
if (fscanf(f, "%31s %ld", d, &s) == 2) {
|
||||
time_t now = time(NULL);
|
||||
struct tm tm;
|
||||
|
||||
(void)localtime_r(&now, &tm);
|
||||
{
|
||||
char now_s[16];
|
||||
|
||||
strftime(now_s, sizeof(now_s), "%Y-%m-%d", &tm);
|
||||
snprintf(today, sizeof(today), "%s", now_s);
|
||||
if (strcmp(d, now_s) == 0)
|
||||
used_seconds = s;
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static void
|
||||
usage_save(void)
|
||||
{
|
||||
FILE *f;
|
||||
|
||||
f = fopen(usage_file, "w");
|
||||
if (f == NULL)
|
||||
return;
|
||||
fprintf(f, "%s %ld\n", today, used_seconds);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
/* Count the time since the last step, capped so a pause is not a punishment. */
|
||||
static void
|
||||
usage_tick(void)
|
||||
{
|
||||
time_t now = time(NULL);
|
||||
|
||||
usage_load();
|
||||
if (last_seen != 0) {
|
||||
long delta = (long)(now - last_seen);
|
||||
|
||||
if (delta > 0) {
|
||||
if (delta > 120)
|
||||
delta = 120;
|
||||
used_seconds += delta;
|
||||
}
|
||||
}
|
||||
last_seen = now;
|
||||
usage_save();
|
||||
}
|
||||
|
||||
static int
|
||||
quota_left(void)
|
||||
{
|
||||
if (daily_minutes == 0)
|
||||
return -1; /* no limit */
|
||||
usage_load();
|
||||
return used_seconds < (long)daily_minutes * 60;
|
||||
}
|
||||
|
||||
/*
|
||||
* '*' matches any run of characters. Iterative, remembering only the last star:
|
||||
* the recursive version backtracked exponentially on model-written arguments.
|
||||
*/
|
||||
static int
|
||||
glob_match(const char *pattern, const char *text)
|
||||
{
|
||||
const char *star = NULL, *resume = NULL;
|
||||
|
||||
while (*text != '\0') {
|
||||
if (*pattern == '*') {
|
||||
star = pattern++;
|
||||
resume = text;
|
||||
} else if (*pattern == *text) {
|
||||
pattern++;
|
||||
text++;
|
||||
} else if (star != NULL) {
|
||||
pattern = star + 1;
|
||||
text = ++resume;
|
||||
} else
|
||||
return 0;
|
||||
}
|
||||
while (*pattern == '*')
|
||||
pattern++;
|
||||
return *pattern == '\0';
|
||||
}
|
||||
|
||||
static void
|
||||
load_rules(void)
|
||||
{
|
||||
FILE *f;
|
||||
char line[512];
|
||||
|
||||
nrules = 0;
|
||||
f = fopen(allow_file, "r");
|
||||
if (f == NULL)
|
||||
return;
|
||||
while (fgets(line, sizeof(line), f) != NULL && nrules < KIDS_RULES) {
|
||||
char *hash = strchr(line, '#');
|
||||
char *p = line, *sp;
|
||||
|
||||
if (hash != NULL)
|
||||
*hash = '\0';
|
||||
line[strcspn(line, "\r\n")] = '\0';
|
||||
while (*p == ' ' || *p == '\t')
|
||||
p++;
|
||||
if (*p == '\0')
|
||||
continue;
|
||||
sp = strchr(p, ' ');
|
||||
memset(&rules[nrules], 0, sizeof(rules[0]));
|
||||
if (sp == NULL) {
|
||||
snprintf(rules[nrules].tool, sizeof(rules[0].tool), "%.31s", p);
|
||||
snprintf(rules[nrules].pattern, sizeof(rules[0].pattern),
|
||||
"*");
|
||||
} else {
|
||||
size_t n = (size_t)(sp - p);
|
||||
|
||||
if (n >= sizeof(rules[0].tool))
|
||||
n = sizeof(rules[0].tool) - 1;
|
||||
memcpy(rules[nrules].tool, p, n);
|
||||
rules[nrules].tool[n] = '\0';
|
||||
while (*sp == ' ')
|
||||
sp++;
|
||||
snprintf(rules[nrules].pattern,
|
||||
sizeof(rules[0].pattern), "%.255s", sp);
|
||||
}
|
||||
nrules++;
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
/*
|
||||
* What a rule is matched against: the argument that says what the call does -
|
||||
* the command of 'run', else a path or a URL - not the raw JSON. Against the
|
||||
* JSON ('{"command":"ls"}') a rule like "run ls*" never matched at all, and
|
||||
* only "*" rules ever had an effect.
|
||||
*/
|
||||
static void
|
||||
rule_subject(const char *tool, const char *args, char *buf, size_t len)
|
||||
{
|
||||
static const char *keys[] = { "command", "path", "url", NULL };
|
||||
mcp_json *v;
|
||||
size_t k;
|
||||
|
||||
snprintf(buf, len, "%s", args != NULL ? args : "");
|
||||
if (args == NULL || args[0] != '{' || (v = mcp_parse(args)) == NULL)
|
||||
return;
|
||||
for (k = strcmp(tool, "run") == 0 ? 0 : 1; keys[k] != NULL; k++) {
|
||||
const char *val = mcp_arg_string(v, keys[k]);
|
||||
|
||||
if (val != NULL) {
|
||||
snprintf(buf, len, "%s", val);
|
||||
break;
|
||||
}
|
||||
}
|
||||
mcp_json_free(v);
|
||||
}
|
||||
|
||||
static int
|
||||
whitelisted(const char *tool, const char *args)
|
||||
{
|
||||
char subject[1024];
|
||||
size_t i;
|
||||
|
||||
rule_subject(tool, args, subject, sizeof(subject));
|
||||
/*
|
||||
* "run ls*" is meant to allow ls, not "ls; anything". A shell command
|
||||
* that can chain, substitute or redirect is never on the list: a parent
|
||||
* decides it.
|
||||
*/
|
||||
if (strcmp(tool, "run") == 0 && strpbrk(subject, ";&|`$<>\n\r(") != NULL)
|
||||
return 0;
|
||||
for (i = 0; i < nrules; i++) {
|
||||
if (strcmp(rules[i].tool, tool) != 0 && strcmp(rules[i].tool, "*"))
|
||||
continue;
|
||||
if (glob_match(rules[i].pattern, subject))
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* sh -c '<cmd>' sh '<arg>': the command string is parsed, the argument is not.
|
||||
* Returns the wait status, like system(3).
|
||||
*/
|
||||
static int
|
||||
run_with_arg(const char *cmd, const char *arg)
|
||||
{
|
||||
pid_t child;
|
||||
int status;
|
||||
|
||||
child = fork();
|
||||
if (child < 0)
|
||||
return -1;
|
||||
if (child == 0) {
|
||||
execl("/bin/sh", "sh", "-c", cmd, "sh", arg, (char *)NULL);
|
||||
_exit(127);
|
||||
}
|
||||
while (waitpid(child, &status, 0) < 0)
|
||||
if (errno != EINTR)
|
||||
return -1;
|
||||
return status;
|
||||
}
|
||||
|
||||
/*
|
||||
* Ask the parent. The command gets the request as one argument and answers with
|
||||
* its exit status; anything but 0 - including a timeout - means no.
|
||||
*/
|
||||
static int
|
||||
ask_parent(const char *tool, const char *args, char *reason, size_t reason_len)
|
||||
{
|
||||
char cmd[1024], request[1024];
|
||||
int rc;
|
||||
|
||||
/*
|
||||
* The general ack mechanism first: a request file plus whichever channels are
|
||||
* configured. Then any process may answer - the gateway, the parent's phone,
|
||||
* or 'splinter --ack <id> yes'. Only without it does the older single command
|
||||
* get used.
|
||||
*/
|
||||
if (getenv("SPLINTER_ACK_CHANNELS") != NULL ||
|
||||
getenv("SPLINTER_ACK_DIR") != NULL) {
|
||||
char who[64] = "";
|
||||
int id = sp_ack_request(tool, args, "kind will etwas aendern",
|
||||
(int)timeout_s);
|
||||
|
||||
if (id < 0) {
|
||||
snprintf(reason, reason_len, "Zustimmung nicht moeglich");
|
||||
return 0;
|
||||
}
|
||||
(void)sp_ack_notify(id, NULL);
|
||||
if (sp_ack_wait(id, (int)timeout_s, who, sizeof(who))) {
|
||||
snprintf(reason, reason_len, "zugestimmt von %s",
|
||||
who[0] != '\0' ? who : "einem Erwachsenen");
|
||||
return 1;
|
||||
}
|
||||
snprintf(reason, reason_len, "ein Erwachsener hat nicht "
|
||||
"zugestimmt (Zeit abgelaufen)");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The command is the operator's and may carry its own arguments, so it
|
||||
* still goes through sh. The request is the model's and must not: it is
|
||||
* handed over as "$1", a positional parameter the shell never parses. A
|
||||
* quote in the tool arguments is then just a quote.
|
||||
*/
|
||||
snprintf(cmd, sizeof(cmd), "%s \"$1\"", approve_cmd);
|
||||
snprintf(request, sizeof(request), "Anfrage: %s %s", tool,
|
||||
args != NULL ? args : "");
|
||||
rc = run_with_arg(cmd, request);
|
||||
if (rc == 0)
|
||||
return 1;
|
||||
snprintf(reason, reason_len, "ein Erwachsener hat nicht zugestimmt (%s)",
|
||||
WIFEXITED(rc) && WEXITSTATUS(rc) == 124 ? "Zeit abgelaufen" :
|
||||
"abgelehnt");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The web is not a filesystem. A child with a search box has the whole internet,
|
||||
* so search is its own decision, not "read, therefore allowed":
|
||||
*
|
||||
* SPLINTER_KIDS_SEARCH=approve every search asks a parent (default)
|
||||
* SPLINTER_KIDS_SEARCH=allow searching is fine, fetching still asks
|
||||
* SPLINTER_KIDS_SEARCH=deny no web at all
|
||||
*
|
||||
* webfetch additionally only reaches hosts listed in ~/.splinter/kids/domains,
|
||||
* because "the model picked this link" is not a safety argument.
|
||||
*/
|
||||
/*
|
||||
* The url out of the tool arguments, read with the same parser the tool itself
|
||||
* uses. A hand-rolled strstr took the first "url" key while the tool took the
|
||||
* one the parser picks, so two keys meant: check one host, fetch another.
|
||||
*/
|
||||
static void
|
||||
arg_url(const char *args, char *buf, size_t len)
|
||||
{
|
||||
mcp_json *v;
|
||||
const char *u;
|
||||
|
||||
buf[0] = '\0';
|
||||
if (args == NULL || args[0] != '{')
|
||||
return;
|
||||
v = mcp_parse(args);
|
||||
if (v == NULL)
|
||||
return;
|
||||
u = mcp_arg_string(v, "url");
|
||||
if (u != NULL && strlen(u) < len)
|
||||
snprintf(buf, len, "%s", u);
|
||||
mcp_json_free(v);
|
||||
}
|
||||
|
||||
static int
|
||||
host_allowed(const char *url)
|
||||
{
|
||||
FILE *f;
|
||||
char line[256];
|
||||
const char *host;
|
||||
int ok = 0;
|
||||
|
||||
if (url == NULL)
|
||||
return 0;
|
||||
if (strncmp(url, "http://", 7) == 0)
|
||||
host = url + 7;
|
||||
else if (strncmp(url, "https://", 8) == 0)
|
||||
host = url + 8;
|
||||
else
|
||||
return 0;
|
||||
/*
|
||||
* "https://allowed.org:x@evil.example/" names evil.example: whatever is
|
||||
* before an '@' is a user name, not the host. Rather than parse userinfo
|
||||
* correctly, a URL that has any is not on the list.
|
||||
*/
|
||||
{
|
||||
size_t auth = strcspn(host, "/?#");
|
||||
const char *at = memchr(host, '@', auth);
|
||||
|
||||
if (at != NULL || memchr(host, '\\', auth) != NULL)
|
||||
return 0;
|
||||
}
|
||||
f = fopen(domains_file, "r");
|
||||
if (f == NULL)
|
||||
return 0;
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
size_t n, hlen;
|
||||
|
||||
line[strcspn(line, "\r\n")] = '\0';
|
||||
if (line[0] == '#' || line[0] == '\0')
|
||||
continue;
|
||||
n = strlen(line);
|
||||
hlen = strcspn(host, "/:?#");
|
||||
if (hlen == n && strncmp(host, line, n) == 0) {
|
||||
ok = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
return ok;
|
||||
}
|
||||
|
||||
static int
|
||||
kids_gate(struct sp_host *h, const char *tool, int auth, const char *args,
|
||||
char *reason, size_t reason_len)
|
||||
{
|
||||
(void)h;
|
||||
if (strcmp(tool, "websearch") == 0 || strcmp(tool, "webfetch") == 0) {
|
||||
/*
|
||||
* The curated list is the safe ground and works in every mode: a
|
||||
* page a parent wrote down is allowed even when the open web is
|
||||
* shut. Everything else follows the mode.
|
||||
*/
|
||||
if (strcmp(tool, "webfetch") == 0) {
|
||||
char url[512];
|
||||
|
||||
arg_url(args, url, sizeof(url));
|
||||
if (url[0] != '\0' && host_allowed(url))
|
||||
return 1;
|
||||
}
|
||||
if (search_mode == 2) {
|
||||
snprintf(reason, reason_len, "das Internet ist fuer %s "
|
||||
"nicht freigeschaltet", child_name);
|
||||
return 0;
|
||||
}
|
||||
if (strcmp(tool, "websearch") == 0 && search_mode == 1)
|
||||
return 1;
|
||||
/* fall through to the approval path below */
|
||||
} else if (auth == SP_AUTH_READ)
|
||||
return 1;
|
||||
|
||||
if (quota_left() == 0) {
|
||||
snprintf(reason, reason_len, "fuer heute ist Schluss (%ld von %u "
|
||||
"Minuten)", used_seconds / 60, daily_minutes);
|
||||
return 0;
|
||||
}
|
||||
load_rules();
|
||||
if (whitelisted(tool, args))
|
||||
return 1;
|
||||
if (approve_cmd[0] == '\0') {
|
||||
snprintf(reason, reason_len, "kein Erwachsener erreichbar "
|
||||
"(SPLINTER_KIDS_APPROVE_CMD nicht gesetzt)");
|
||||
return 0;
|
||||
}
|
||||
return ask_parent(tool, args, reason, reason_len) ? 1 : 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The day ends here. Not "the model is asked to stop" - the model is not called
|
||||
* at all, so a chatty model cannot talk past the budget.
|
||||
*/
|
||||
static int
|
||||
kids_block_turn(struct sp_host *h, char *msg, size_t len)
|
||||
{
|
||||
(void)h;
|
||||
if (quota_left() != 0)
|
||||
return 0;
|
||||
snprintf(msg, len, "Fuer heute ist Schluss: %ld von %u Minuten sind "
|
||||
"verbraucht. Morgen geht es weiter.", used_seconds / 60,
|
||||
daily_minutes);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static const struct sp_gate gate = { "kids", kids_gate, kids_block_turn };
|
||||
|
||||
/*
|
||||
* Kid-safe conversation: a system message in front of every request, because a
|
||||
* rule stated once at the start is the first thing a long conversation buries.
|
||||
*/
|
||||
static int
|
||||
kids_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
unsigned turn)
|
||||
{
|
||||
struct sp_msg m;
|
||||
char text[768];
|
||||
size_t at, i;
|
||||
|
||||
(void)h;
|
||||
(void)budget;
|
||||
(void)turn;
|
||||
usage_tick();
|
||||
if (conv == NULL || conv->n == 0)
|
||||
return 0;
|
||||
if (quota_left() == 0) {
|
||||
struct sp_msg end;
|
||||
char txt[256];
|
||||
|
||||
snprintf(txt, sizeof(txt), "[kids] Die Zeit fuer heute ist um (%u "
|
||||
"Minuten). Sage %s freundlich, dass fuer heute Schluss ist und "
|
||||
"es morgen weitergeht - und biete nichts weiter an.",
|
||||
daily_minutes, child_name);
|
||||
memset(&end, 0, sizeof(end));
|
||||
end.role = "system";
|
||||
end.content = txt;
|
||||
if (sp_conv_add(conv, &end) != 0)
|
||||
return -1;
|
||||
return 1;
|
||||
}
|
||||
for (i = 0; i < conv->n; i++)
|
||||
if (conv->v[i].role != NULL &&
|
||||
strcmp(conv->v[i].role, "system") == 0 &&
|
||||
conv->v[i].content != NULL &&
|
||||
strstr(conv->v[i].content, "[kids]") != NULL)
|
||||
return 0; /* already told, once is enough */
|
||||
|
||||
snprintf(text, sizeof(text),
|
||||
"[kids] Du sprichst mit %s. Bleib freundlich, geduldig und "
|
||||
"altersgerecht: keine Gewalt, kein Grusel, keine Beleidigungen, keine "
|
||||
"Themen fuer Erwachsene. Erklaer einfache Dinge einfach, biete Hilfe "
|
||||
"beim Lernen an, und sage klar, wenn etwas nicht fuer Kinder ist. "
|
||||
"Aenderungen an Dateien oder Befehle fragt immer ein Erwachsener frei.",
|
||||
child_name);
|
||||
|
||||
at = conv->n;
|
||||
for (i = conv->n; i > 0; i--) {
|
||||
if (conv->v[i - 1].role != NULL &&
|
||||
strcmp(conv->v[i - 1].role, "user") == 0) {
|
||||
at = i - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = "system";
|
||||
m.content = text;
|
||||
if (sp_conv_add(conv, &m) != 0)
|
||||
return -1;
|
||||
if (at < conv->n - 1) {
|
||||
struct sp_msg moved = conv->v[conv->n - 1];
|
||||
|
||||
memmove(&conv->v[at + 1], &conv->v[at],
|
||||
sizeof(conv->v[0]) * (conv->n - 1 - at));
|
||||
conv->v[at] = moved;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static const struct sp_compactor compactor = { "kids", kids_compact };
|
||||
|
||||
static int
|
||||
kids_init(struct sp_host *h)
|
||||
{
|
||||
const char *home = getenv("HOME");
|
||||
const char *cmd = getenv("SPLINTER_KIDS_APPROVE_CMD");
|
||||
const char *to = getenv("SPLINTER_KIDS_TIMEOUT");
|
||||
const char *name = getenv("SPLINTER_KIDS_NAME");
|
||||
|
||||
if (home == NULL || *home == '\0') {
|
||||
(void)sp_host_note(h, "kids: no HOME");
|
||||
return -1;
|
||||
}
|
||||
snprintf(allow_file, sizeof(allow_file), "%s/.splinter/kids/allow", home);
|
||||
snprintf(usage_file, sizeof(usage_file), "%s/.splinter/kids/usage", home);
|
||||
snprintf(domains_file, sizeof(domains_file), "%s/.splinter/kids/domains",
|
||||
home);
|
||||
{
|
||||
const char *sm = getenv("SPLINTER_KIDS_SEARCH");
|
||||
|
||||
if (sm != NULL && strcmp(sm, "allow") == 0)
|
||||
search_mode = 1;
|
||||
else if (sm != NULL && strcmp(sm, "deny") == 0)
|
||||
search_mode = 2;
|
||||
}
|
||||
{
|
||||
const char *min = getenv("SPLINTER_KIDS_DAILY_MINUTES");
|
||||
|
||||
if (min != NULL && *min != '\0')
|
||||
daily_minutes = (unsigned)strtoul(min, NULL, 10);
|
||||
}
|
||||
if (cmd != NULL && *cmd != '\0')
|
||||
snprintf(approve_cmd, sizeof(approve_cmd), "%s", cmd);
|
||||
if (name != NULL && *name != '\0')
|
||||
snprintf(child_name, sizeof(child_name), "%s", name);
|
||||
if (to != NULL && *to != '\0')
|
||||
timeout_s = (unsigned)strtoul(to, NULL, 10);
|
||||
if (sp_host_add_gate(h, &gate) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_compactor(h, &compactor) != 0)
|
||||
return -1;
|
||||
(void)sp_host_note(h, approve_cmd[0] != '\0' ?
|
||||
"kids: parents reachable" : "kids: NO parent channel - everything "
|
||||
"mutating will be refused");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI,
|
||||
"kids",
|
||||
"1.0",
|
||||
kids_init,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &plugin;
|
||||
}
|
||||
@@ -1,348 +0,0 @@
|
||||
/*
|
||||
* splinter -- lcm: lossy compression memory for the conversation.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* The rule this plugin follows: a conversation that does not fit the budget is
|
||||
* cut from the front, but never silently. What is dropped is replaced by one
|
||||
* system message that says how much went, of which roles, and quotes the head
|
||||
* of the oldest dropped turn — so a model (and a human reading the session log)
|
||||
* can tell the difference between "the user never said that" and "that was
|
||||
* compacted away".
|
||||
*
|
||||
* Deterministic on purpose: no second model, no summary that costs another
|
||||
* call, nothing that makes a run unreproducible. The harder variant (an LLM
|
||||
* writes the summary) is a different plugin, not a flag on this one.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "mcp.h"
|
||||
|
||||
#define KEEP_TAIL 6 /* default: messages always kept verbatim */
|
||||
#define PREVIEW 120 /* chars of the oldest dropped message */
|
||||
#define TOOL_TRIM 8192 /* default: older tool outputs are cut to this */
|
||||
|
||||
static size_t keep_tail = KEEP_TAIL;
|
||||
static size_t tool_trim = TOOL_TRIM;
|
||||
|
||||
static int
|
||||
is_role(const struct sp_msg *m, const char *role)
|
||||
{
|
||||
return m->role != NULL && strcmp(m->role, role) == 0;
|
||||
}
|
||||
|
||||
/* the first line of a text, at most n bytes, for the marker */
|
||||
static void
|
||||
first_line(const char *s, char *out, size_t cap, size_t n)
|
||||
{
|
||||
size_t i = 0;
|
||||
|
||||
while (s[i] != '\0' && i < n && s[i] != '\n' && i + 1 < cap) {
|
||||
unsigned char c = (unsigned char)s[i];
|
||||
|
||||
out[i] = (c >= 32 && c != 127) ? (char)c : ' ';
|
||||
i++;
|
||||
}
|
||||
out[i] = '\0';
|
||||
}
|
||||
|
||||
/*
|
||||
* Tool outputs are the bulk of a long conversation. Before messages are
|
||||
* dropped, every old observation is cut to a head and a tail with a marker in
|
||||
* between; the middle is still in the session log, where the recall tool finds
|
||||
* it. The recent tail (the messages we keep verbatim) is never touched, so the
|
||||
* model always has the output it just asked for.
|
||||
*/
|
||||
static int
|
||||
trim_tools(struct sp_conv *conv, size_t first, size_t end, size_t cap)
|
||||
{
|
||||
size_t i;
|
||||
int n = 0;
|
||||
|
||||
if (cap == 0)
|
||||
return 0;
|
||||
for (i = first; i < end; i++) {
|
||||
struct sp_msg *m = &conv->v[i];
|
||||
size_t len, head, tail, off, room;
|
||||
char *hint = "", *nb;
|
||||
|
||||
if (!is_role(m, "tool") || m->content == NULL)
|
||||
continue;
|
||||
len = strlen(m->content);
|
||||
if (len <= cap)
|
||||
continue;
|
||||
head = cap / 2;
|
||||
tail = cap / 4;
|
||||
if (head + tail >= len)
|
||||
continue;
|
||||
{
|
||||
static char hbuf[72];
|
||||
|
||||
first_line(m->content, hbuf, sizeof(hbuf), 60);
|
||||
hint = hbuf;
|
||||
}
|
||||
nb = malloc(head + tail + 512);
|
||||
if (nb == NULL)
|
||||
continue;
|
||||
memcpy(nb, m->content, head);
|
||||
off = head;
|
||||
room = head + tail + 512 - off;
|
||||
off += (size_t)snprintf(nb + off, room,
|
||||
"\n[lcm] %zu bytes of tool output cut; recall \"%s\"\n",
|
||||
len - head - tail, hint);
|
||||
memcpy(nb + off, m->content + len - tail, tail);
|
||||
off += tail;
|
||||
nb[off] = '\0';
|
||||
free(m->content);
|
||||
m->content = nb;
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
static int
|
||||
lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
unsigned turn)
|
||||
{
|
||||
size_t bytes, i, drop, first, keep_from;
|
||||
char preview[PREVIEW + 1];
|
||||
char summary[512];
|
||||
size_t n_user = 0, n_asst = 0, n_tool = 0;
|
||||
size_t pin_at = 0;
|
||||
char *pin_content = NULL, *pin_name = NULL;
|
||||
int trimmed, pinned = 0;
|
||||
const char *oldest;
|
||||
|
||||
(void)turn;
|
||||
(void)h;
|
||||
if (conv == NULL || conv->n <= keep_tail + 1)
|
||||
return 0;
|
||||
if (budget == 0)
|
||||
return 0; /* no byte budget: nothing to do */
|
||||
bytes = sp_conv_bytes(conv);
|
||||
if (bytes <= budget)
|
||||
return 0; /* fits: nothing to do */
|
||||
|
||||
/* a leading system prompt stays; everything else may go */
|
||||
first = is_role(&conv->v[0], "system") ? 1 : 0;
|
||||
keep_from = conv->n - keep_tail;
|
||||
/*
|
||||
* The tail must not start with a tool result: its assistant turn, the
|
||||
* one carrying the tool_call, would be gone, and a provider answers an
|
||||
* orphaned tool message with a 400. Such results go with their call.
|
||||
*/
|
||||
while (keep_from < conv->n && is_role(&conv->v[keep_from], "tool"))
|
||||
keep_from++;
|
||||
if (keep_from >= conv->n || keep_from <= first)
|
||||
return 0;
|
||||
/*
|
||||
* First the cheap cut: old tool outputs. If that is enough the messages
|
||||
* stay, and only the observations shrink.
|
||||
*/
|
||||
trimmed = trim_tools(conv, first, keep_from, tool_trim);
|
||||
if (trimmed > 0) {
|
||||
bytes = sp_conv_bytes(conv);
|
||||
if (bytes <= budget)
|
||||
return 1;
|
||||
}
|
||||
/*
|
||||
* The newest user message is the task being answered. A long tool loop
|
||||
* can push it out of the verbatim tail; dropping it made the model ask
|
||||
* "what was the question?" and dig it out with recall. Pin it and put
|
||||
* it back right after the summary.
|
||||
*/
|
||||
for (i = conv->n; i > first; i--)
|
||||
if (is_role(&conv->v[i - 1], "user")) {
|
||||
pin_at = i - 1;
|
||||
break;
|
||||
}
|
||||
if (pin_at < keep_from && keep_from > first) {
|
||||
pin_content = strdup(conv->v[pin_at].content != NULL ?
|
||||
conv->v[pin_at].content : "");
|
||||
if (conv->v[pin_at].name != NULL)
|
||||
pin_name = strdup(conv->v[pin_at].name);
|
||||
pinned = pin_content != NULL;
|
||||
}
|
||||
drop = keep_from - first;
|
||||
|
||||
oldest = conv->v[first].content; /* the oldest one that goes */
|
||||
for (i = first; i < keep_from; i++) {
|
||||
if (is_role(&conv->v[i], "user"))
|
||||
n_user++;
|
||||
else if (is_role(&conv->v[i], "assistant"))
|
||||
n_asst++;
|
||||
else if (is_role(&conv->v[i], "tool"))
|
||||
n_tool++;
|
||||
}
|
||||
snprintf(preview, sizeof(preview), "%s", oldest != NULL ? oldest : "");
|
||||
snprintf(summary, sizeof(summary),
|
||||
"[lcm] %zu messages compacted out (user %zu, assistant %zu, tool %zu) "
|
||||
"to fit %zu bytes; the verbatim tail of %zu messages follows.%s "
|
||||
"Oldest dropped turn began with: \"%s\"",
|
||||
drop - (pinned ? 1 : 0), n_user - (pinned ? 1 : 0), n_asst, n_tool,
|
||||
budget, conv->n - keep_from,
|
||||
pinned ? " The current question was kept." :
|
||||
(trimmed > 0 ? " Older tool output was cut too (recall still has it)." :
|
||||
""),
|
||||
preview);
|
||||
|
||||
for (i = first; i < keep_from; i++) {
|
||||
free(conv->v[i].role);
|
||||
free(conv->v[i].name);
|
||||
free(conv->v[i].call_id);
|
||||
free(conv->v[i].content);
|
||||
free(conv->v[i].calls);
|
||||
}
|
||||
memmove(&conv->v[first], &conv->v[keep_from],
|
||||
(conv->n - keep_from) * sizeof(*conv->v));
|
||||
conv->n = first + (conv->n - keep_from);
|
||||
|
||||
{
|
||||
struct sp_msg m;
|
||||
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = "system";
|
||||
m.content = summary;
|
||||
if (sp_conv_insert(conv, first, &m) != 0)
|
||||
goto fail;
|
||||
}
|
||||
if (pinned) {
|
||||
struct sp_msg m;
|
||||
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = "user";
|
||||
m.name = pin_name;
|
||||
m.content = pin_content;
|
||||
if (sp_conv_insert(conv, first + 1, &m) != 0)
|
||||
goto fail;
|
||||
}
|
||||
free(pin_content);
|
||||
free(pin_name);
|
||||
return 1;
|
||||
|
||||
fail:
|
||||
free(pin_content);
|
||||
free(pin_name);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* case-blind substring for the recall tool */
|
||||
static int
|
||||
has_ci(const char *hay, const char *needle)
|
||||
{
|
||||
size_t n = strlen(needle), i;
|
||||
const char *p;
|
||||
|
||||
for (p = hay; *p != '\0'; p++) {
|
||||
for (i = 0; i < n && p[i] != '\0'; i++)
|
||||
if (tolower((unsigned char)p[i]) !=
|
||||
tolower((unsigned char)needle[i]))
|
||||
break;
|
||||
if (i == n)
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* What compaction dropped is still in the session log. This reads it: the
|
||||
* model can go back to an earlier turn instead of guessing, and the operator
|
||||
* can prove what was said.
|
||||
*/
|
||||
static int
|
||||
lcm_recall(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char query[256] = "", path[800], line[8192];
|
||||
struct sp_host *h = ctx;
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *id = sp_host_session_id(h);
|
||||
mcp_json *v;
|
||||
const char *q;
|
||||
FILE *f;
|
||||
int limit = 10, n = 0;
|
||||
|
||||
if (args != NULL && args[0] == '{') {
|
||||
v = mcp_parse(args);
|
||||
if (v != NULL) {
|
||||
q = mcp_arg_string(v, "query");
|
||||
if (q != NULL)
|
||||
snprintf(query, sizeof(query), "%s", q);
|
||||
limit = mcp_arg_int(v, "limit", 10);
|
||||
mcp_json_free(v);
|
||||
}
|
||||
}
|
||||
if (query[0] == '\0')
|
||||
return sp_buf_puts(out, "error: 'query' is required");
|
||||
if (limit < 1 || limit > 50)
|
||||
limit = 10;
|
||||
if (dir == NULL || *dir == '\0' || id == NULL || *id == '\0')
|
||||
return sp_buf_puts(out, "error: no session log");
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
return sp_buf_puts(out, "error: cannot read the session log");
|
||||
while (n < limit && fgets(line, sizeof(line), f) != NULL) {
|
||||
char *text;
|
||||
|
||||
if (!has_ci(line, query))
|
||||
continue;
|
||||
n++;
|
||||
text = line;
|
||||
sp_buf_printf(out, "%s", text);
|
||||
}
|
||||
fclose(f);
|
||||
if (n == 0)
|
||||
sp_buf_printf(out, "no line in the session log contains '%s'",
|
||||
query);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_tool recall_tool = {
|
||||
"recall",
|
||||
"Search the session log for text that is no longer in the context "
|
||||
"(compaction drops it from the prompt, not from the log). Use it "
|
||||
"before guessing about something that happened earlier.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"query\":{\"type\":\"string\",\"description\":\"text to find\"},"
|
||||
"\"limit\":{\"type\":\"integer\",\"description\":\"max matching lines, "
|
||||
"default 10\"}},\"required\":[\"query\"]}",
|
||||
SP_AUTH_READ,
|
||||
lcm_recall,
|
||||
NULL
|
||||
};
|
||||
|
||||
static const struct sp_compactor lcm = { "lcm", lcm_compact };
|
||||
|
||||
static int
|
||||
lcm_init(struct sp_host *h)
|
||||
{
|
||||
static struct sp_tool rt = recall_tool;
|
||||
const char *v;
|
||||
|
||||
v = sp_host_plugin_config(h, "lcm", "keep");
|
||||
if (v != NULL && atoi(v) > 0 && atoi(v) < 1000)
|
||||
keep_tail = (size_t)atoi(v);
|
||||
v = sp_host_plugin_config(h, "lcm", "tool_trim");
|
||||
if (v != NULL && atoi(v) >= 0)
|
||||
tool_trim = (size_t)atoi(v);
|
||||
rt.ctx = h;
|
||||
if (sp_host_add_compactor(h, &lcm) != 0)
|
||||
return -1;
|
||||
return sp_host_add_tool(h, &rt);
|
||||
}
|
||||
|
||||
static const struct sp_plugin lcm_plugin = {
|
||||
SP_PLUGIN_ABI, "lcm", "1.0.0", lcm_init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &lcm_plugin;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,561 +0,0 @@
|
||||
/*
|
||||
* splinter -- background tasks.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Some work should not hold the conversation. A build, a test run, a delegate on
|
||||
* another host: start it, keep talking, look at it later.
|
||||
*
|
||||
* Four at a time by default (SPLINTER_TASKS_MAX), because a machine that runs
|
||||
* twenty background shell commands at once is not doing the work faster, it is
|
||||
* only harder to read. A start beyond the limit is refused with the reason, not
|
||||
* queued into an invisible backlog.
|
||||
*
|
||||
* The tools:
|
||||
*
|
||||
* process_start command, label? -> id, starts at once
|
||||
* process_list -> id, state, seconds, bytes, label
|
||||
* process_result id -> output, exit status; fails while running
|
||||
* process_kill id -> stop it
|
||||
*
|
||||
* Tasks are shell commands, so starting one is destructive in the same sense that
|
||||
* `run` is: the gate and the approval path see it like any other change.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "mcp.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
#define TASKS_MAX 16
|
||||
|
||||
struct task {
|
||||
int id;
|
||||
volatile int running;
|
||||
int status; /* exit status once finished */
|
||||
char label[64];
|
||||
char cmd[512];
|
||||
struct sp_buf out;
|
||||
time_t started, ended;
|
||||
pid_t pid;
|
||||
pthread_t th;
|
||||
pthread_mutex_t lock;
|
||||
};
|
||||
|
||||
static struct task tasks[TASKS_MAX];
|
||||
static int ntasks;
|
||||
static int next_id = 1;
|
||||
static unsigned max_parallel = 4;
|
||||
static pthread_mutex_t tasks_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
static int
|
||||
running_count(void)
|
||||
{
|
||||
int i, n = 0;
|
||||
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
for (i = 0; i < ntasks; i++)
|
||||
if (tasks[i].running)
|
||||
n++;
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return n;
|
||||
}
|
||||
|
||||
static void
|
||||
set_process_fields(struct sp_meter *m, void *ctx)
|
||||
{
|
||||
const unsigned *run = ctx;
|
||||
|
||||
m->tasks_running = *run;
|
||||
m->tasks_max = max_parallel;
|
||||
}
|
||||
|
||||
/*
|
||||
* Only the task fields, under the host's lock. A copy of the whole meter,
|
||||
* changed and written back, raced with the UI doing the same with the token
|
||||
* fields: whichever wrote last erased the other's update.
|
||||
*/
|
||||
static void
|
||||
publish_meter(struct sp_host *h)
|
||||
{
|
||||
unsigned run = (unsigned)running_count();
|
||||
|
||||
sp_host_meter_update(h, set_process_fields, &run);
|
||||
}
|
||||
|
||||
static void
|
||||
refresh_widget(struct sp_host *h)
|
||||
{
|
||||
char text[1024];
|
||||
size_t used = 0;
|
||||
int i;
|
||||
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
for (i = 0; i < ntasks && used + 96 < sizeof(text); i++) {
|
||||
struct task *t = &tasks[i];
|
||||
int n;
|
||||
|
||||
/*
|
||||
* The sidebar is for what is happening now. A finished task
|
||||
* stays in process_list/process_result (its output is still there),
|
||||
* but it does not take a row of the sidebar forever.
|
||||
*/
|
||||
if (!t->running)
|
||||
continue;
|
||||
n = snprintf(text + used, sizeof(text) - used,
|
||||
"#%d %s %lds\n", t->id, t->label,
|
||||
(long)(time(NULL) - t->started));
|
||||
if (n < 0 || (size_t)n >= sizeof(text) - used)
|
||||
break;
|
||||
used += (size_t)n;
|
||||
}
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
if (used == 0)
|
||||
(void)sp_host_widget_text(h, "processes", "");
|
||||
else
|
||||
(void)sp_host_widget_text(h, "processes", text);
|
||||
}
|
||||
|
||||
extern char **environ;
|
||||
|
||||
/*
|
||||
* The end of a task, under tasks_lock: that is the lock process_list, the widget
|
||||
* and running_count read 'running', 'status' and 'ended' under. They used to
|
||||
* be written under the task's own lock only - two locks guarding one field
|
||||
* guard nothing.
|
||||
*/
|
||||
static void
|
||||
process_finish(struct task *t, int status)
|
||||
{
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
t->status = status;
|
||||
t->ended = time(NULL);
|
||||
t->running = 0;
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
}
|
||||
|
||||
/*
|
||||
* Run the task in its own process group, so process_kill can stop the shell and
|
||||
* everything it started. popen() gave no pid: t->pid stayed 0, and
|
||||
* kill(-0, SIGTERM) is "every process in my group" - process_kill killed
|
||||
* splinter itself. stdin is /dev/null (a task must not read the terminal), and
|
||||
* the environment loses splinter's keys, as for the 'run' tool.
|
||||
*/
|
||||
static void *
|
||||
process_run(void *arg)
|
||||
{
|
||||
struct task *t = arg;
|
||||
char chunk[2048];
|
||||
char **envp;
|
||||
ssize_t got;
|
||||
size_t n, i, j;
|
||||
int fds[2], st = 0;
|
||||
pid_t child;
|
||||
|
||||
for (n = 0; environ != NULL && environ[n] != NULL; n++)
|
||||
;
|
||||
envp = calloc(n + 1, sizeof(*envp));
|
||||
if (envp == NULL || pipe(fds) != 0) {
|
||||
free(envp);
|
||||
pthread_mutex_lock(&t->lock);
|
||||
sp_buf_printf(&t->out, "error: %s", strerror(errno));
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
process_finish(t, 127);
|
||||
return NULL;
|
||||
}
|
||||
for (i = 0, j = 0; i < n; i++)
|
||||
if (!sp_secret_env_is(environ[i]))
|
||||
envp[j++] = environ[i];
|
||||
envp[j] = NULL;
|
||||
child = fork();
|
||||
if (child == 0) {
|
||||
int dn = open("/dev/null", O_RDONLY);
|
||||
|
||||
(void)setpgid(0, 0);
|
||||
if (dn >= 0) {
|
||||
(void)dup2(dn, STDIN_FILENO);
|
||||
if (dn != STDIN_FILENO)
|
||||
close(dn);
|
||||
}
|
||||
(void)dup2(fds[1], STDOUT_FILENO);
|
||||
(void)dup2(fds[1], STDERR_FILENO);
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
execle("/bin/sh", "sh", "-c", t->cmd, (char *)NULL, envp);
|
||||
_exit(127);
|
||||
}
|
||||
close(fds[1]);
|
||||
free(envp);
|
||||
if (child < 0) {
|
||||
close(fds[0]);
|
||||
pthread_mutex_lock(&t->lock);
|
||||
sp_buf_printf(&t->out, "error: fork: %s", strerror(errno));
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
process_finish(t, 127);
|
||||
return NULL;
|
||||
}
|
||||
(void)setpgid(child, child);
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
t->pid = child;
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
for (;;) {
|
||||
got = read(fds[0], chunk, sizeof(chunk));
|
||||
if (got < 0 && errno == EINTR)
|
||||
continue;
|
||||
if (got <= 0)
|
||||
break;
|
||||
pthread_mutex_lock(&t->lock);
|
||||
if (t->out.len < (1u << 20)) /* 1 MiB, stated */
|
||||
(void)sp_buf_add(&t->out, chunk, (size_t)got);
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
}
|
||||
close(fds[0]);
|
||||
while (waitpid(child, &st, 0) < 0 && errno == EINTR)
|
||||
;
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
t->pid = 0; /* reaped: the id may be reused */
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
process_finish(t, st);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static struct task *
|
||||
find(int id)
|
||||
{
|
||||
int i;
|
||||
|
||||
for (i = 0; i < ntasks; i++)
|
||||
if (tasks[i].id == id)
|
||||
return &tasks[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* The value of an argument, with the parser the rest of splinter uses. The old
|
||||
* strstr() only matched "key":"..." - the schema declares 'id' an integer, so
|
||||
* {"id":3} came out empty and every process_kill said "no such task".
|
||||
*/
|
||||
static void
|
||||
arg_str(const char *args, const char *key, char *buf, size_t len)
|
||||
{
|
||||
mcp_json *v;
|
||||
const char *sv;
|
||||
|
||||
buf[0] = '\0';
|
||||
if (args == NULL || args[0] != '{' || (v = mcp_parse(args)) == NULL)
|
||||
return;
|
||||
sv = mcp_arg_string(v, key);
|
||||
if (sv != NULL)
|
||||
snprintf(buf, len, "%s", sv);
|
||||
else {
|
||||
int n = mcp_arg_int(v, key, INT_MIN);
|
||||
|
||||
if (n != INT_MIN)
|
||||
snprintf(buf, len, "%d", n);
|
||||
}
|
||||
mcp_json_free(v);
|
||||
}
|
||||
|
||||
static struct sp_host *host_ref;
|
||||
|
||||
/*
|
||||
* Tasks someone else owns - a delegate on another host. They get an entry and a
|
||||
* clock, but no thread here: the harness closes them when the call returns.
|
||||
*/
|
||||
static int
|
||||
ops_begin(struct sp_host *h, const char *label, const char *detail)
|
||||
{
|
||||
struct task *t;
|
||||
int id;
|
||||
|
||||
(void)detail;
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
if (ntasks == TASKS_MAX) {
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return -1;
|
||||
}
|
||||
t = &tasks[ntasks++];
|
||||
memset(t, 0, sizeof(*t));
|
||||
(void)pthread_mutex_init(&t->lock, NULL);
|
||||
t->id = next_id++;
|
||||
t->running = 1;
|
||||
t->started = time(NULL);
|
||||
snprintf(t->label, sizeof(t->label), "%.63s", label != NULL ? label : "?");
|
||||
id = t->id;
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
if (h != NULL) {
|
||||
publish_meter(h);
|
||||
refresh_widget(h);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
static void
|
||||
ops_end(struct sp_host *h, int id, int status, size_t tokens)
|
||||
{
|
||||
struct task *t;
|
||||
|
||||
if (id < 0)
|
||||
return;
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
t = find(id);
|
||||
if (t != NULL) {
|
||||
t->running = 0;
|
||||
t->status = status;
|
||||
t->ended = time(NULL);
|
||||
if (tokens > 0)
|
||||
(void)sp_buf_printf(&t->out, "[~%zu tokens]", tokens);
|
||||
}
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
if (h != NULL) {
|
||||
publish_meter(h);
|
||||
refresh_widget(h);
|
||||
}
|
||||
}
|
||||
|
||||
static const struct sp_task_ops task_ops = { ops_begin, ops_end };
|
||||
|
||||
static int
|
||||
tool_process_start(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char cmd[600], label[80];
|
||||
struct task *t;
|
||||
int id;
|
||||
|
||||
(void)ctx;
|
||||
arg_str(args, "command", cmd, sizeof(cmd));
|
||||
arg_str(args, "label", label, sizeof(label));
|
||||
if (cmd[0] == '\0')
|
||||
return sp_buf_puts(out, "error: empty command");
|
||||
if (label[0] == '\0')
|
||||
snprintf(label, sizeof(label), "%.40s", cmd);
|
||||
if (running_count() >= (int)max_parallel)
|
||||
return sp_buf_printf(out, "error: %u tasks already running "
|
||||
"(SPLINTER_TASKS_MAX) - finish or kill one first",
|
||||
max_parallel);
|
||||
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
if (ntasks == TASKS_MAX) {
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "error: task table full");
|
||||
}
|
||||
t = &tasks[ntasks++];
|
||||
memset(t, 0, sizeof(*t));
|
||||
t->id = next_id++;
|
||||
(void)pthread_mutex_init(&t->lock, NULL);
|
||||
snprintf(t->cmd, sizeof(t->cmd), "%.511s", cmd);
|
||||
snprintf(t->label, sizeof(t->label), "%.63s", label);
|
||||
t->started = time(NULL);
|
||||
t->running = 1;
|
||||
if (sp_buf_init(&t->out) != 0) {
|
||||
ntasks--;
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "error: no memory");
|
||||
}
|
||||
id = t->id;
|
||||
if (pthread_create(&t->th, NULL, process_run, t) != 0) {
|
||||
t->running = 0;
|
||||
ntasks--;
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "error: cannot start thread");
|
||||
}
|
||||
pthread_detach(t->th);
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
|
||||
if (host_ref != NULL) {
|
||||
publish_meter(host_ref);
|
||||
refresh_widget(host_ref);
|
||||
}
|
||||
return sp_buf_printf(out, "started #%d (%s) - %d/%u running", id, label,
|
||||
running_count(), max_parallel);
|
||||
}
|
||||
|
||||
static int
|
||||
tool_process_list(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
int i, any = 0;
|
||||
|
||||
(void)args;
|
||||
(void)ctx;
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
for (i = 0; i < ntasks; i++) {
|
||||
struct task *t = &tasks[i];
|
||||
|
||||
any = 1;
|
||||
if (t->running)
|
||||
sp_buf_printf(out, "#%d running %lds %zu B %s\n", t->id,
|
||||
(long)(time(NULL) - t->started), t->out.len,
|
||||
t->label);
|
||||
else
|
||||
sp_buf_printf(out, "#%d done %.2fs exit %d %zu B %s\n",
|
||||
t->id, difftime(t->ended, t->started), t->status,
|
||||
t->out.len, t->label);
|
||||
}
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
if (!any)
|
||||
sp_buf_puts(out, "keine Tasks");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_process_result(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char num[32];
|
||||
struct task *t;
|
||||
int id;
|
||||
|
||||
(void)ctx;
|
||||
arg_str(args, "id", num, sizeof(num));
|
||||
id = atoi(num);
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
t = find(id);
|
||||
if (t == NULL) {
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "error: no such task");
|
||||
}
|
||||
if (t->running) {
|
||||
long secs = (long)(time(NULL) - t->started);
|
||||
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_printf(out, "still running (%lds, %zu B so far)",
|
||||
secs, t->out.len);
|
||||
}
|
||||
pthread_mutex_lock(&t->lock);
|
||||
if (t->out.p != NULL)
|
||||
(void)sp_buf_add(out, t->out.p, t->out.len);
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
sp_buf_printf(out, "\n[exit %d, %.1fs]", t->status,
|
||||
difftime(t->ended, t->started));
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_process_kill(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char num[32];
|
||||
struct task *t;
|
||||
int id;
|
||||
|
||||
(void)ctx;
|
||||
arg_str(args, "id", num, sizeof(num));
|
||||
id = atoi(num);
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
t = find(id);
|
||||
if (t == NULL) {
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "error: no such task");
|
||||
}
|
||||
if (!t->running) {
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "already finished");
|
||||
}
|
||||
/*
|
||||
* Only a task with a process group of its own. A task opened by
|
||||
* ops_begin (a delegate on another host) has none here, and a pid of 0
|
||||
* or 1 would make kill(-pid) hit splinter's own group or everything.
|
||||
*/
|
||||
if (t->pid <= 1) {
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "error: this task has no local process "
|
||||
"to stop");
|
||||
}
|
||||
(void)kill(-(t->pid), SIGTERM);
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "kill signal sent");
|
||||
}
|
||||
|
||||
static const struct sp_tool t_start = {
|
||||
"process_start",
|
||||
"Start a shell command in the background and return its id. Use it for "
|
||||
"builds, tests or long runs instead of blocking the conversation.",
|
||||
"{\"type\":\"object\",\"properties\":{\"command\":{\"type\":\"string\"},"
|
||||
"\"label\":{\"type\":\"string\",\"description\":\"short name\"}},"
|
||||
"\"required\":[\"command\"]}",
|
||||
SP_AUTH_DESTRUCTIVE, tool_process_start, NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_list = {
|
||||
"process_list", "List background tasks: id, state, time, size, label.",
|
||||
"{\"type\":\"object\",\"properties\":{}}", SP_AUTH_READ, tool_process_list,
|
||||
NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_result = {
|
||||
"process_result", "Output and exit status of a finished task.",
|
||||
"{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"}},"
|
||||
"\"required\":[\"id\"]}", SP_AUTH_READ, tool_process_result, NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_kill = {
|
||||
"process_kill", "Stop a running task.",
|
||||
"{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"}},"
|
||||
"\"required\":[\"id\"]}", SP_AUTH_DESTRUCTIVE, tool_process_kill, NULL
|
||||
};
|
||||
|
||||
static int
|
||||
tasks_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
(void)name;
|
||||
(void)ctx;
|
||||
refresh_widget(h);
|
||||
publish_meter(h);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_widget widget = {
|
||||
"processes", /* name */
|
||||
tasks_tick, /* tick */
|
||||
NULL, /* draw */
|
||||
NULL, /* ctx */
|
||||
1000 /* interval: a running task is interesting every second */
|
||||
};
|
||||
|
||||
static int
|
||||
tasks_init(struct sp_host *h)
|
||||
{
|
||||
const char *m = getenv("SPLINTER_TASKS_MAX");
|
||||
|
||||
if (m != NULL && *m != '\0') {
|
||||
unsigned v = (unsigned)strtoul(m, NULL, 10);
|
||||
|
||||
if (v > 0 && v <= TASKS_MAX)
|
||||
max_parallel = v;
|
||||
}
|
||||
host_ref = h;
|
||||
(void)sp_host_add_tool(h, &t_start);
|
||||
(void)sp_host_add_tool(h, &t_list);
|
||||
(void)sp_host_add_tool(h, &t_result);
|
||||
(void)sp_host_add_tool(h, &t_kill);
|
||||
(void)sp_host_add_widget(h, &widget);
|
||||
(void)sp_host_widget_text(h, "processes", "");
|
||||
sp_host_set_task_ops(h, &task_ops);
|
||||
publish_meter(h);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI,
|
||||
"tasks",
|
||||
"1.0",
|
||||
tasks_init,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &plugin;
|
||||
}
|
||||
@@ -1,277 +0,0 @@
|
||||
/*
|
||||
* splinter -- provider adapters (OpenCode/Ollama/openai-compat), per-key quota/usage.
|
||||
*
|
||||
* Plugin-format adapters: dispatch by tr.provider ("opencode","ollama","openai-compat").
|
||||
* Shared per-(provider,key_id) state in ~/.splinter/providers/ (flock+atomic), so
|
||||
* multiple instances sharing a key see the same quota/burst view.
|
||||
*
|
||||
* - preflight: blocks on quota_ready_at; short backoff delays (<=30s) allowed by caller.
|
||||
* - account: records status/tokens; 429/402/529 -> quota wait (Retry-After honored by
|
||||
* transport/agent when known; defaults here). 503/408 -> short backoff.
|
||||
* - Ollama (local): quota gating relaxed (transient/backoff only) unless explicit quota.
|
||||
* - OpenCode/cloud: quota exhausted -> WAIT_QUOTA with ready_at; "quota back in N days"
|
||||
* surfaced via reason/note and durable delegation jobs (waiting_quota+run_after) +
|
||||
* scheduler auto-retry. Optional probe via SPLINTER_QUOTA_PROBE_URL (GET, bearer from
|
||||
* SPLINTER_QUOTA_PROBE_KEY) when SPLINTER_PROVIDER_PROBE=1.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <errno.h>
|
||||
#include <dirent.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
static int is_ollama(const char *p) { return p && strcmp(p,"ollama")==0; }
|
||||
static int is_opencode(const char *p){ return p && (strcmp(p,"opencode")==0 || strcmp(p,"open-code")==0); }
|
||||
|
||||
struct probe_apply { long ready; long now; };
|
||||
static void probe_apply_fn(struct sp_prov_state *s, void *p){
|
||||
struct probe_apply *c=p;
|
||||
if (c->ready > s->quota_ready_at) s->quota_ready_at = c->ready;
|
||||
if (c->ready > 0) snprintf(s->note,sizeof(s->note),"quota probe ready_at=%ld", c->ready);
|
||||
s->last_update = c->now;
|
||||
}
|
||||
static void probe_apply(const char *provider, const char *key_id, long ready){
|
||||
struct probe_apply c; c.ready=ready; c.now=(long)time(NULL);
|
||||
sp_provstate_update(provider,key_id,probe_apply_fn,&c);
|
||||
}
|
||||
|
||||
static void run_probe(const char *provider, const char *key_id)
|
||||
{
|
||||
const char *on = getenv("SPLINTER_PROVIDER_PROBE");
|
||||
const char *url = getenv("SPLINTER_QUOTA_PROBE_URL");
|
||||
const char *key = getenv("SPLINTER_QUOTA_PROBE_KEY");
|
||||
const char *kenv = getenv("SPLINTER_QUOTA_PROBE_KEY_ENV");
|
||||
char buf[4096];
|
||||
size_t n = 0;
|
||||
long ready = 0, ra = 0;
|
||||
const char *q;
|
||||
int in_pipe[2], out_pipe[2], devnull;
|
||||
pid_t pid;
|
||||
int st = 0;
|
||||
char cfg[4096];
|
||||
size_t off = 0, len;
|
||||
ssize_t wr, rd;
|
||||
|
||||
if (!on || strcmp(on, "1") != 0 || !url || !*url) return;
|
||||
if ((!key || !*key) && kenv && *kenv) key = getenv(kenv);
|
||||
if (strncmp(url, "http://", 7) != 0 && strncmp(url, "https://", 8) != 0) return;
|
||||
if (strpbrk(url, "\"\\\n\r") != NULL) return;
|
||||
if (key && *key && strpbrk(key, "\"\\\n\r") != NULL) return;
|
||||
|
||||
if (pipe(in_pipe) != 0) return;
|
||||
if (pipe(out_pipe) != 0) {
|
||||
close(in_pipe[0]);
|
||||
close(in_pipe[1]);
|
||||
return;
|
||||
}
|
||||
pid = fork();
|
||||
if (pid < 0) {
|
||||
close(in_pipe[0]); close(in_pipe[1]);
|
||||
close(out_pipe[0]); close(out_pipe[1]);
|
||||
return;
|
||||
}
|
||||
if (pid == 0) {
|
||||
char *const argv[] = {"curl", "-fsS", "-m", "10", "-K", "-", NULL};
|
||||
dup2(in_pipe[0], 0);
|
||||
dup2(out_pipe[1], 1);
|
||||
devnull = open("/dev/null", O_WRONLY);
|
||||
if (devnull >= 0) {
|
||||
dup2(devnull, 2);
|
||||
close(devnull);
|
||||
}
|
||||
close(in_pipe[0]); close(in_pipe[1]);
|
||||
close(out_pipe[0]); close(out_pipe[1]);
|
||||
execvp(argv[0], argv);
|
||||
_exit(127);
|
||||
}
|
||||
|
||||
close(in_pipe[0]);
|
||||
close(out_pipe[1]);
|
||||
len = (size_t)snprintf(cfg, sizeof(cfg), "url = \"%s\"\n", url);
|
||||
if (len < sizeof(cfg) && key && *key) {
|
||||
int m = snprintf(cfg + len, sizeof(cfg) - len,
|
||||
"header = \"Authorization: Bearer %s\"\n", key);
|
||||
len = (m < 0 || (size_t)m >= sizeof(cfg) - len) ? sizeof(cfg) : len + (size_t)m;
|
||||
}
|
||||
/* An over-long config is never sent: curl then reads an empty config and
|
||||
* fails, and the exit status below discards the result. */
|
||||
if (len >= sizeof(cfg))
|
||||
len = 0;
|
||||
{
|
||||
void (*old_pipe)(int) = signal(SIGPIPE, SIG_IGN);
|
||||
off = 0;
|
||||
while (off < len) {
|
||||
wr = write(in_pipe[1], cfg + off, len - off);
|
||||
if (wr <= 0) break;
|
||||
off += (size_t)wr;
|
||||
}
|
||||
close(in_pipe[1]);
|
||||
signal(SIGPIPE, old_pipe);
|
||||
}
|
||||
|
||||
n = 0;
|
||||
for (;;) {
|
||||
char rbuf[1024];
|
||||
rd = read(out_pipe[0], rbuf, sizeof(rbuf));
|
||||
if (rd <= 0) break;
|
||||
if (n < sizeof(buf) - 1) {
|
||||
size_t take = (size_t)rd;
|
||||
if (take > sizeof(buf) - 1 - n) take = sizeof(buf) - 1 - n;
|
||||
memcpy(buf + n, rbuf, take);
|
||||
n += take;
|
||||
}
|
||||
}
|
||||
buf[n] = '\0';
|
||||
close(out_pipe[0]);
|
||||
while (waitpid(pid, &st, 0) < 0 && errno == EINTR)
|
||||
;
|
||||
|
||||
if (WIFEXITED(st) && WEXITSTATUS(st) == 0) {
|
||||
q = strstr(buf, "\"quota_ready_at\""); if (q) { q = strchr(q, ':'); if (q) ready = strtol(q + 1, NULL, 10); }
|
||||
q = strstr(buf, "\"retry_after\""); if (q) { q = strchr(q, ':'); if (q) ra = strtol(q + 1, NULL, 10); }
|
||||
if (ready <= 0 && ra > 0) ready = (long)time(NULL) + ra;
|
||||
if (ready > 0) probe_apply(provider, key_id, ready);
|
||||
}
|
||||
}
|
||||
|
||||
static int
|
||||
prov_preflight(void *ctx, const char *provider, const char *key_id,
|
||||
struct sp_prov_result *out)
|
||||
{
|
||||
long now = (long)time(NULL);
|
||||
long ready = 0;
|
||||
int r;
|
||||
(void)ctx;
|
||||
if (!out) return 0;
|
||||
out->decision = SP_PROV_ADMIT;
|
||||
if (!provider || !*provider || !key_id || !*key_id)
|
||||
return 0;
|
||||
/* ollama local: no cloud quota gating unless state explicitly says quota */
|
||||
if (is_ollama(provider)) {
|
||||
struct sp_prov_state st;
|
||||
if (sp_provstate_load(provider,key_id,&st)==0 && st.quota_ready_at > now) {
|
||||
out->decision = SP_PROV_WAIT_QUOTA;
|
||||
out->ready_at = st.quota_ready_at;
|
||||
out->retry_after_s = st.quota_ready_at - now;
|
||||
snprintf(out->reason,sizeof(out->reason),"ollama quota/backoff until %ld", st.quota_ready_at);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
r = sp_provstate_preflight(provider, key_id, now, &ready,
|
||||
out->reason, sizeof(out->reason));
|
||||
if (r == 1) {
|
||||
out->decision = SP_PROV_WAIT_QUOTA;
|
||||
out->ready_at = ready;
|
||||
out->retry_after_s = ready > now ? ready - now : 0;
|
||||
if (out->retry_after_s > 3600)
|
||||
snprintf(out->reason, sizeof(out->reason),
|
||||
"%s quota exhausted: wait ~%ldh (ready_at=%ld), auto-scheduled when quota returns",
|
||||
is_opencode(provider)?"opencode":"provider",
|
||||
out->retry_after_s/3600, ready);
|
||||
else if (!out->reason[0])
|
||||
snprintf(out->reason, sizeof(out->reason),
|
||||
"quota/backoff until %ld (auto-schedule)", ready);
|
||||
/* optional probe to refine ready_at */
|
||||
run_probe(provider, key_id);
|
||||
} else if (r == 2) {
|
||||
out->decision = SP_PROV_DELAY;
|
||||
out->ready_at = ready;
|
||||
out->retry_after_s = ready > now ? ready - now : 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
prov_account(void *ctx, const char *provider, const char *key_id,
|
||||
long http_status, size_t tokens_in, size_t tokens_out)
|
||||
{
|
||||
long ra = 0;
|
||||
(void)ctx;
|
||||
if (!provider || !*provider || !key_id || !*key_id)
|
||||
return;
|
||||
if (is_ollama(provider) && (http_status==429||http_status==402||http_status==529)) {
|
||||
/* local ollama shouldn't quota like cloud, but handle gracefully */
|
||||
ra = 30;
|
||||
}
|
||||
/* retry_after_s: transport/agent apply parsed Retry-After via quota_hint/provstate;
|
||||
* here we record status/tokens and apply status-based defaults. */
|
||||
sp_provstate_account(provider, key_id, http_status, tokens_in, tokens_out, ra);
|
||||
/* on quota exhaustion, probe for accurate ready_at (opt-in) */
|
||||
if (http_status==429 || http_status==402 || http_status==529)
|
||||
run_probe(provider, key_id);
|
||||
}
|
||||
|
||||
static const struct sp_provider_ops ops = { .ctx=NULL, .preflight=prov_preflight, .account=prov_account };
|
||||
|
||||
static void fmt_dur(long s, char *out, size_t cap){
|
||||
if(s>=86400) snprintf(out,cap,"%ldd%ldh",s/86400,(s%86400)/3600);
|
||||
else if(s>=3600) snprintf(out,cap,"%ldh%ldm",s/3600,(s%3600)/60);
|
||||
else snprintf(out,cap,"%lds",s);
|
||||
}
|
||||
|
||||
static int
|
||||
cmd_quota(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char dir[512]; DIR *dp; struct dirent *prov;
|
||||
const char *home = getenv("HOME");
|
||||
long now=(long)time(NULL);
|
||||
(void)h;(void)args;(void)ctx;
|
||||
if(!home) home="/tmp";
|
||||
snprintf(dir,sizeof(dir),"%s/.splinter/providers", home);
|
||||
sp_buf_puts(out,"per-key provider quota/usage (shared):\n");
|
||||
dp=opendir(dir);
|
||||
if(!dp){ sp_buf_puts(out," (no provider state yet)\n"); return 0; }
|
||||
while((prov=readdir(dp))!=NULL){
|
||||
char pdir[600]; DIR *dp2; struct dirent *kf;
|
||||
if(prov->d_name[0]=='.') continue;
|
||||
snprintf(pdir,sizeof(pdir),"%.300s/%.255s",dir,prov->d_name);
|
||||
dp2=opendir(pdir); if(!dp2) continue;
|
||||
while((kf=readdir(dp2))!=NULL){
|
||||
char *dot, path[700], kid[64]; struct sp_prov_state st; char dur[32];
|
||||
if(kf->d_name[0]=='.') continue;
|
||||
dot=strstr(kf->d_name,".json"); if(!dot) continue;
|
||||
{ size_t kl=(size_t)(dot-kf->d_name); if(kl>=sizeof(kid)) kl=sizeof(kid)-1; memcpy(kid,kf->d_name,kl); kid[kl]='\0'; }
|
||||
snprintf(path,sizeof(path),"%.400s/%.255s",pdir,kf->d_name);
|
||||
(void)path;
|
||||
if(sp_provstate_load(prov->d_name,kid,&st)==0){
|
||||
sp_buf_printf(out," %s/%s req=%u tok=%lu/%lu status=%ld",
|
||||
prov->d_name,kid,st.req_count,st.tok_in,st.tok_out,st.last_status);
|
||||
if(st.quota_ready_at>now){ fmt_dur(st.quota_ready_at-now,dur,sizeof(dur)); sp_buf_printf(out," WAIT_QUOTA %s (ready_at=%ld)",dur,st.quota_ready_at); }
|
||||
else if(st.backoff_until>now){ fmt_dur(st.backoff_until-now,dur,sizeof(dur)); sp_buf_printf(out," backoff %s",dur); }
|
||||
if(st.note[0]) sp_buf_printf(out," [%s]",st.note);
|
||||
sp_buf_puts(out,"\n");
|
||||
}
|
||||
}
|
||||
closedir(dp2);
|
||||
}
|
||||
closedir(dp);
|
||||
sp_buf_puts(out,"adapters: opencode, ollama, openai-compat (per-key). probe: SPLINTER_PROVIDER_PROBE=1 + SPLINTER_QUOTA_PROBE_URL/KEY.\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
provider_init(struct sp_host *h)
|
||||
{
|
||||
sp_host_set_provider(h, &ops);
|
||||
sp_host_add_command(h, "quota", cmd_quota, NULL);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI, "provider", "0.2", provider_init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &plugin;
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
/*
|
||||
* splinter -- the reminder.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Every tenth turn the rules go back into the conversation, as a system message
|
||||
* right before the newest user message:
|
||||
*
|
||||
* SPLINTER_REMINDER_EVERY turns between reminders, default 10
|
||||
*
|
||||
* Why not in the system prompt? Because it is read once and then buried under
|
||||
* forty thousand tokens of conversation. A rule that matters every turn has to
|
||||
* come back, or it stops existing.
|
||||
*
|
||||
* The rules are short and factual. A reminder that lectures is a reminder the
|
||||
* model learns to skip.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "i18n.h"
|
||||
|
||||
#define REMINDER_MAX 1024
|
||||
|
||||
static unsigned every = 10;
|
||||
static unsigned last_reminder = (unsigned)-1;
|
||||
static unsigned sent;
|
||||
|
||||
static const char *const rules[] = {
|
||||
"Read the documentation before you build: README, AGENTS, man pages, "
|
||||
"the source itself. A hack that works against the documented way is a "
|
||||
"bug with good timing.",
|
||||
"Check what already exists before writing something new.",
|
||||
"Evidence over claims: run it, read the output, say what is verified.",
|
||||
"Never invent output, paths or results.",
|
||||
"Stop and ask before anything destructive or irreversible.",
|
||||
NULL
|
||||
};
|
||||
|
||||
static int
|
||||
reminder_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
unsigned turn)
|
||||
{
|
||||
char text[REMINDER_MAX];
|
||||
struct sp_msg m;
|
||||
size_t at, i, used = 0;
|
||||
|
||||
(void)budget;
|
||||
if (conv == NULL || conv->n == 0 || every == 0)
|
||||
return 0;
|
||||
if (turn % every != 0 || turn == last_reminder)
|
||||
return 0;
|
||||
last_reminder = turn;
|
||||
|
||||
used += (size_t)snprintf(text, sizeof(text) - used, "[reminder]\n");
|
||||
for (i = 0; rules[i] != NULL && used + 4 < sizeof(text); i++)
|
||||
used += (size_t)snprintf(text + used, sizeof(text) - used,
|
||||
"- %s\n", rules[i]);
|
||||
|
||||
/* before the newest user message, never after it */
|
||||
at = conv->n;
|
||||
for (i = conv->n; i > 0; i--) {
|
||||
if (conv->v[i - 1].role != NULL &&
|
||||
strcmp(conv->v[i - 1].role, "user") == 0) {
|
||||
at = i - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = "system";
|
||||
m.content = text;
|
||||
if (sp_conv_add(conv, &m) != 0) {
|
||||
(void)sp_host_note(h, "reminder: cannot add the message");
|
||||
return -1;
|
||||
}
|
||||
/* sp_conv_add appends; move it in front of the user message */
|
||||
if (at < conv->n - 1) {
|
||||
struct sp_msg moved = conv->v[conv->n - 1];
|
||||
|
||||
memmove(&conv->v[at + 1], &conv->v[at],
|
||||
sizeof(conv->v[0]) * (conv->n - 1 - at));
|
||||
conv->v[at] = moved;
|
||||
}
|
||||
sent++;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static const struct sp_compactor compactor = { "reminder", reminder_compact };
|
||||
|
||||
static int
|
||||
reminder_init(struct sp_host *h)
|
||||
{
|
||||
const char *env = getenv("SPLINTER_REMINDER_EVERY");
|
||||
|
||||
if (env != NULL && *env != '\0')
|
||||
every = (unsigned)strtoul(env, NULL, 10);
|
||||
if (sp_host_add_compactor(h, &compactor) != 0) {
|
||||
(void)sp_host_note(h, "reminder: cannot register (add_compactor)");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI,
|
||||
"reminder",
|
||||
"1.0",
|
||||
reminder_init,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &plugin;
|
||||
}
|
||||
@@ -1,322 +0,0 @@
|
||||
/*
|
||||
* splinter -- the exit ring.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* A turn should not die because one provider's free tier ran out at 03:14. The
|
||||
* ring holds several ways to reach a model and walks them in order:
|
||||
*
|
||||
* exit = go | OpenCode Go | endpoint=... | model=... | key_env=OPENCODE_KEY
|
||||
* exit = groq | Groq free tier | endpoint=... | model=... | key_env=GROQ_KEY
|
||||
* exit = local | kontron, lokal | endpoint=... | model=...
|
||||
*
|
||||
* Only pressure moves the ring: a rate limit, an exhausted quota, or a provider
|
||||
* that is down (500/502/503/504). A syntax error or a bad key stops the turn
|
||||
* where it is - pretending every failure is "try the next one" would hide real
|
||||
* breakage behind a random provider. Each step is reported, so the log says which
|
||||
* exit served the turn.
|
||||
*
|
||||
* And once an exit has streamed text to the screen, its failure is the turn's
|
||||
* failure: asking the next exit would show the operator a second answer after
|
||||
* half of the first one.
|
||||
*/
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "config.h"
|
||||
|
||||
#define MAX_EXITS SP_CONFIG_MAX_DELEGATES
|
||||
|
||||
struct ring {
|
||||
struct sp_host *host;
|
||||
const struct sp_config *cfg;
|
||||
struct sp_transport tr[MAX_EXITS];
|
||||
size_t n;
|
||||
int last; /* which exit served the last turn */
|
||||
int used[MAX_EXITS];
|
||||
/* last and used are written by the turn thread, read by the widget */
|
||||
pthread_mutex_t lock;
|
||||
};
|
||||
|
||||
static struct ring ring = { .lock = PTHREAD_MUTEX_INITIALIZER };
|
||||
|
||||
/* Pressure - a limit or a provider that is down - is worth another exit. */
|
||||
static int
|
||||
is_pressure(int rc, long status, const struct sp_buf *err)
|
||||
{
|
||||
if (status == 429 || status == 503 || status == 502 ||
|
||||
status == 504 || status == 500)
|
||||
return 1;
|
||||
if (rc == 0)
|
||||
return 0;
|
||||
if (err != NULL && err->p != NULL) {
|
||||
const char *p = err->p;
|
||||
|
||||
if (strstr(p, "429") != NULL || strstr(p, "rate limit") != NULL ||
|
||||
strstr(p, "rate_limit") != NULL ||
|
||||
strstr(p, "quota") != NULL ||
|
||||
strstr(p, "limit reached") != NULL ||
|
||||
strstr(p, "insufficient") != NULL ||
|
||||
strstr(p, "overloaded") != NULL)
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
publish(const char *text)
|
||||
{
|
||||
(void)sp_host_widget_text(ring.host, "ring", text);
|
||||
(void)sp_host_note(ring.host, text);
|
||||
}
|
||||
|
||||
static int
|
||||
build(void)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (ring.n > 0)
|
||||
return 0;
|
||||
if (ring.cfg == NULL || ring.cfg->nexits == 0) {
|
||||
publish("ring: no exit configured");
|
||||
return -1;
|
||||
}
|
||||
for (i = 0; i < ring.cfg->nexits && i < MAX_EXITS; i++) {
|
||||
const struct sp_exit *e = &ring.cfg->exit[i];
|
||||
const char *env = e->key_env[0] != '\0' ?
|
||||
e->key_env : "SPLINTER_API_KEY";
|
||||
const char *key = getenv(env);
|
||||
|
||||
{
|
||||
const char *hto = getenv("SPLINTER_HTTP_TIMEOUT");
|
||||
long hto_s = hto != NULL && *hto != '\0' ?
|
||||
strtol(hto, NULL, 10) : 0;
|
||||
|
||||
if (hto_s <= 0)
|
||||
hto_s = 900;
|
||||
ring.tr[ring.n] = sp_openai_transport(e->endpoint, e->model,
|
||||
key, sp_host_registry(ring.host), hto_s);
|
||||
}
|
||||
if (ring.tr[ring.n].send == NULL) {
|
||||
publish("ring: cannot build an exit");
|
||||
return -1;
|
||||
}
|
||||
ring.n++;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
ring_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
struct ring *r = ctx;
|
||||
size_t i;
|
||||
char line[128];
|
||||
|
||||
if (build() != 0)
|
||||
return -1;
|
||||
for (i = 0; i < r->n; i++) {
|
||||
struct sp_buf e;
|
||||
long status;
|
||||
int rc;
|
||||
|
||||
if (sp_buf_init(&e) != 0)
|
||||
return -1;
|
||||
sp_reply_free(out);
|
||||
rc = r->tr[i].send(r->tr[i].ctx, conv, out, &e);
|
||||
status = out->status;
|
||||
if (rc == 0) {
|
||||
pthread_mutex_lock(&r->lock);
|
||||
r->last = (int)i;
|
||||
r->used[i]++;
|
||||
pthread_mutex_unlock(&r->lock);
|
||||
snprintf(line, sizeof(line), "%s (%zu/%zu)",
|
||||
r->cfg->exit[i].label, i + 1, r->n);
|
||||
(void)sp_host_widget_text(r->host, "ring", line);
|
||||
sp_buf_free(&e);
|
||||
return 0;
|
||||
}
|
||||
if (!is_pressure(rc, status, &e)) {
|
||||
/* not a limit: this is a real failure, keep it */
|
||||
if (err != NULL)
|
||||
(void)sp_buf_puts(err, e.p != NULL ? e.p :
|
||||
"ring: exit failed");
|
||||
sp_buf_free(&e);
|
||||
return rc;
|
||||
}
|
||||
snprintf(line, sizeof(line), "ring: %s busy, next exit",
|
||||
r->cfg->exit[i].label);
|
||||
(void)sp_host_note(r->host, line);
|
||||
sp_buf_free(&e);
|
||||
}
|
||||
if (err != NULL)
|
||||
(void)sp_buf_puts(err, "ring: every exit is rate limited");
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* passes the stream through and remembers whether anything was shown */
|
||||
struct seen {
|
||||
sp_stream_cb cb;
|
||||
void *ctx;
|
||||
int shown;
|
||||
};
|
||||
|
||||
static void
|
||||
seen_cb(void *ctx, int kind, const char *text)
|
||||
{
|
||||
struct seen *s = ctx;
|
||||
|
||||
if (text != NULL && *text != '\0')
|
||||
s->shown = 1;
|
||||
if (s->cb != NULL)
|
||||
s->cb(s->ctx, kind, text);
|
||||
}
|
||||
|
||||
static int
|
||||
ring_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
struct sp_buf *err, sp_stream_cb cb, void *cbctx)
|
||||
{
|
||||
struct ring *r = ctx;
|
||||
size_t i;
|
||||
char line[128];
|
||||
struct seen seen;
|
||||
|
||||
if (build() != 0)
|
||||
return -1;
|
||||
for (i = 0; i < r->n; i++) {
|
||||
struct sp_buf e;
|
||||
long status;
|
||||
int rc;
|
||||
|
||||
if (sp_buf_init(&e) != 0)
|
||||
return -1;
|
||||
sp_reply_free(out);
|
||||
seen.cb = cb;
|
||||
seen.ctx = cbctx;
|
||||
seen.shown = 0;
|
||||
rc = r->tr[i].send_stream(r->tr[i].ctx, conv, out, &e, seen_cb,
|
||||
&seen);
|
||||
status = out->status;
|
||||
if (rc == 0) {
|
||||
pthread_mutex_lock(&r->lock);
|
||||
r->last = (int)i;
|
||||
r->used[i]++;
|
||||
pthread_mutex_unlock(&r->lock);
|
||||
snprintf(line, sizeof(line), "%s (%zu/%zu)",
|
||||
r->cfg->exit[i].label, i + 1, r->n);
|
||||
(void)sp_host_widget_text(r->host, "ring", line);
|
||||
sp_buf_free(&e);
|
||||
return 0;
|
||||
}
|
||||
if (!is_pressure(rc, status, &e) || seen.shown) {
|
||||
if (err != NULL) {
|
||||
(void)sp_buf_puts(err, e.p != NULL ? e.p :
|
||||
"ring: exit failed");
|
||||
if (seen.shown && is_pressure(rc, status, &e))
|
||||
(void)sp_buf_puts(err, " (after part of "
|
||||
"the answer was shown; not retried)");
|
||||
}
|
||||
sp_buf_free(&e);
|
||||
return rc != 0 ? rc : -1;
|
||||
}
|
||||
snprintf(line, sizeof(line), "ring: %s busy, next exit",
|
||||
r->cfg->exit[i].label);
|
||||
(void)sp_host_note(r->host, line);
|
||||
sp_buf_free(&e);
|
||||
}
|
||||
if (err != NULL)
|
||||
(void)sp_buf_puts(err, "ring: every exit is rate limited");
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int
|
||||
ring_widget(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
struct ring *r = ctx;
|
||||
char line[160];
|
||||
size_t i;
|
||||
|
||||
(void)h;
|
||||
if (r->n == 0) {
|
||||
(void)sp_host_widget_text(ring.host, name, "no exits");
|
||||
return 0;
|
||||
}
|
||||
pthread_mutex_lock(&r->lock);
|
||||
snprintf(line, sizeof(line), "%.16s |", r->cfg->exit[r->last].label);
|
||||
for (i = 0; i < r->n; i++) {
|
||||
char bit[16];
|
||||
|
||||
snprintf(bit, sizeof(bit), " %d", r->used[i]);
|
||||
strncat(line, bit, sizeof(line) - strlen(line) - 1);
|
||||
}
|
||||
pthread_mutex_unlock(&r->lock);
|
||||
(void)sp_host_widget_text(ring.host, name, line);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_widget widget = {
|
||||
"ring",
|
||||
ring_widget,
|
||||
NULL,
|
||||
&ring,
|
||||
3000
|
||||
};
|
||||
|
||||
static int
|
||||
ring_init(struct sp_host *h)
|
||||
{
|
||||
struct sp_transport t;
|
||||
|
||||
memset(&ring, 0, sizeof(ring));
|
||||
(void)pthread_mutex_init(&ring.lock, NULL);
|
||||
ring.host = h;
|
||||
ring.cfg = sp_host_config(h);
|
||||
if (ring.cfg == NULL || ring.cfg->nexits == 0) {
|
||||
(void)sp_host_note(h, "ring: no exit configured");
|
||||
return -1;
|
||||
}
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.send = ring_send;
|
||||
t.send_stream = ring_stream;
|
||||
t.ctx = ˚
|
||||
if (sp_host_add_transport(h, "ring", t) != 0) {
|
||||
(void)sp_host_note(h, "ring: cannot register the transport");
|
||||
return -1;
|
||||
}
|
||||
(void)sp_host_add_widget(h, &widget);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* the exits own their contexts; the plugin's lifetime is the process's */
|
||||
static void
|
||||
ring_shutdown(struct sp_host *h)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
(void)h;
|
||||
for (i = 0; i < ring.n; i++)
|
||||
sp_transport_dispose(&ring.tr[i]);
|
||||
ring.n = 0;
|
||||
(void)pthread_mutex_destroy(&ring.lock);
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI,
|
||||
"ring",
|
||||
"1.0",
|
||||
ring_init,
|
||||
NULL,
|
||||
ring_shutdown
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &plugin;
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/*
|
||||
* splinter -- delegation scheduler (auto-retry due jobs).
|
||||
*
|
||||
* Ticks periodically and retries one due durable delegation job
|
||||
* (waiting_quota / waiting_poll / queued with run_after/next_poll_at reached).
|
||||
* This enables "quota back in N days -> auto-scheduled" when combined with
|
||||
* provider preflight/account and durable job records.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
static struct sp_host *host_ref;
|
||||
static char last_status[256];
|
||||
static long last_run;
|
||||
|
||||
static void
|
||||
publish(struct sp_host *h)
|
||||
{
|
||||
char buf[320];
|
||||
if (!h) return;
|
||||
if (last_status[0])
|
||||
snprintf(buf, sizeof(buf), "%s", last_status);
|
||||
else
|
||||
buf[0] = '\0';
|
||||
sp_host_widget_text(h, "scheduler", buf);
|
||||
}
|
||||
|
||||
static int
|
||||
sched_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
struct sp_buf out;
|
||||
long now = (long)time(NULL);
|
||||
int rc;
|
||||
(void)name; (void)ctx;
|
||||
if (now - last_run < 15)
|
||||
return 0;
|
||||
last_run = now;
|
||||
if (sp_buf_init(&out) != 0)
|
||||
return 0;
|
||||
rc = sp_delegate_tick(&out);
|
||||
if (out.p && strstr(out.p, "none due") == NULL) {
|
||||
snprintf(last_status, sizeof(last_status), "%.200s",
|
||||
out.p ? out.p : (rc == 0 ? "ok" : "err"));
|
||||
} else if (last_status[0] == '\0') {
|
||||
snprintf(last_status, sizeof(last_status), "idle");
|
||||
}
|
||||
sp_buf_free(&out);
|
||||
publish(h ? h : host_ref);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_widget widget = {
|
||||
"scheduler",
|
||||
sched_tick,
|
||||
NULL,
|
||||
NULL,
|
||||
30000 /* 30s */
|
||||
};
|
||||
|
||||
static int
|
||||
scheduler_init(struct sp_host *h)
|
||||
{
|
||||
host_ref = h;
|
||||
snprintf(last_status, sizeof(last_status), "idle");
|
||||
(void)sp_host_add_widget(h, &widget);
|
||||
publish(h);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI,
|
||||
"scheduler",
|
||||
"0.1",
|
||||
scheduler_init,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &plugin;
|
||||
}
|
||||
@@ -1,424 +0,0 @@
|
||||
/*
|
||||
* splinter -- self: what this session costs the machine.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Every other widget talks about the world. This one talks about the process
|
||||
* the operator is looking at: how much memory, CPU, threads and file
|
||||
* descriptors splinter itself holds just by running, and how much its children
|
||||
* (a run tool, an MCP server child, a delegate, a CLI transport) hold under it.
|
||||
*
|
||||
* self
|
||||
* 84M rss 3.2% cpu
|
||||
* 18 thr 41 fd
|
||||
* kids 3 120M 1.4% cpu
|
||||
* io 12M r 300k w
|
||||
*
|
||||
* The numbers come from /proc: /proc/self/status (VmRSS, Threads), /proc/self/fd
|
||||
* (count), /proc/self/io (bytes), /proc/<pid>/stat (utime/stime, rss, PPid).
|
||||
* A child is any process whose parent chain reaches this pid; the walk is one
|
||||
* pass over /proc per tick, which is cheap next to what a model request costs.
|
||||
*
|
||||
* CPU is the delta between two ticks, not a lifetime average, so the widget
|
||||
* says "right now". IO is cumulative for the session; that is what "used"
|
||||
* means here.
|
||||
*
|
||||
* plugin self { interval = 2000 } # ms between samples
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <dirent.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
#define SELF_KIDS_MAX 256
|
||||
#define SELF_LIST_MAX 12
|
||||
#define SELF_DEFAULT_MS 2000
|
||||
|
||||
struct kid {
|
||||
int pid;
|
||||
int ppid;
|
||||
unsigned long rss_pages;
|
||||
unsigned long long ticks;
|
||||
};
|
||||
|
||||
struct sample {
|
||||
unsigned long rss_kb;
|
||||
int threads;
|
||||
int fds;
|
||||
double cpu_pct;
|
||||
unsigned long io_read;
|
||||
unsigned long io_write;
|
||||
unsigned long long self_ticks;
|
||||
double kids_cpu_pct;
|
||||
unsigned long kids_rss_kb;
|
||||
int kids;
|
||||
};
|
||||
|
||||
static pthread_mutex_t self_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct sample now_s;
|
||||
static char widget[512];
|
||||
static char detail[4096];
|
||||
|
||||
static long hz;
|
||||
static unsigned long long prev_self_ticks;
|
||||
static double prev_time;
|
||||
static struct { int pid; unsigned long long ticks; } prev_kids[SELF_KIDS_MAX];
|
||||
static size_t prev_nkids;
|
||||
|
||||
static double
|
||||
mono_now(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9;
|
||||
}
|
||||
|
||||
/* one /proc/<pid>/stat: ppid, resident pages and utime+stime in clock ticks */
|
||||
static int
|
||||
read_stat(int pid, struct kid *out)
|
||||
{
|
||||
char path[64], buf[2048], *p, *end;
|
||||
FILE *f;
|
||||
char state;
|
||||
long ppid;
|
||||
unsigned long pre[9]; /* pgrp .. cmajflt */
|
||||
unsigned long long utime, stime;
|
||||
unsigned long post[9]; /* cutime .. rss */
|
||||
|
||||
snprintf(path, sizeof(path), "/proc/%d/stat", pid);
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
return -1;
|
||||
if (fgets(buf, sizeof(buf), f) == NULL) {
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
fclose(f);
|
||||
end = strrchr(buf, ')');
|
||||
if (end == NULL)
|
||||
return -1;
|
||||
p = end + 2; /* after "comm)": state ppid ... */
|
||||
if (sscanf(p, "%c %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu "
|
||||
"%llu %llu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
|
||||
&state, &ppid,
|
||||
&pre[0], &pre[1], &pre[2], &pre[3], &pre[4], &pre[5], &pre[6],
|
||||
&pre[7], &pre[8],
|
||||
&utime, &stime,
|
||||
&post[0], &post[1], &post[2], &post[3], &post[4], &post[5],
|
||||
&post[6], &post[7], &post[8]) != 22)
|
||||
return -1;
|
||||
(void)state;
|
||||
out->pid = pid;
|
||||
out->ppid = (int)ppid;
|
||||
out->rss_pages = post[8]; /* the field named rss, in pages */
|
||||
out->ticks = utime + stime;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
read_self(struct sample *s)
|
||||
{
|
||||
FILE *f;
|
||||
char line[512];
|
||||
|
||||
s->rss_kb = 0;
|
||||
s->threads = 0;
|
||||
f = fopen("/proc/self/status", "r");
|
||||
if (f != NULL) {
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
unsigned long v;
|
||||
|
||||
if (sscanf(line, "VmRSS: %lu kB", &v) == 1)
|
||||
s->rss_kb = v;
|
||||
else if (sscanf(line, "Threads: %lu", &v) == 1)
|
||||
s->threads = (int)v;
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
{
|
||||
DIR *d = opendir("/proc/self/fd");
|
||||
int n = 0;
|
||||
|
||||
if (d != NULL) {
|
||||
struct dirent *e;
|
||||
|
||||
while ((e = readdir(d)) != NULL)
|
||||
if (e->d_name[0] != '.')
|
||||
n++;
|
||||
closedir(d);
|
||||
}
|
||||
s->fds = n;
|
||||
}
|
||||
f = fopen("/proc/self/io", "r");
|
||||
if (f != NULL) {
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
unsigned long v;
|
||||
|
||||
if (sscanf(line, "read_bytes: %lu", &v) == 1)
|
||||
s->io_read = v;
|
||||
else if (sscanf(line, "write_bytes: %lu", &v) == 1)
|
||||
s->io_write = v;
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
human(unsigned long kb, char *buf, size_t cap)
|
||||
{
|
||||
if (kb >= 1024 * 1024)
|
||||
snprintf(buf, cap, "%.1fG", (double)kb / (1024.0 * 1024.0));
|
||||
else if (kb >= 1024)
|
||||
snprintf(buf, cap, "%.0fM", (double)kb / 1024.0);
|
||||
else
|
||||
snprintf(buf, cap, "%luk", kb);
|
||||
}
|
||||
|
||||
static void
|
||||
human_bytes(unsigned long b, char *buf, size_t cap)
|
||||
{
|
||||
if (b >= 1024UL * 1024UL * 1024UL)
|
||||
snprintf(buf, cap, "%.1fG", (double)b / (1024.0 * 1024.0 * 1024.0));
|
||||
else if (b >= 1024UL * 1024UL)
|
||||
snprintf(buf, cap, "%.1fM", (double)b / (1024.0 * 1024.0));
|
||||
else if (b >= 1024)
|
||||
snprintf(buf, cap, "%.0fk", (double)b / 1024.0);
|
||||
else
|
||||
snprintf(buf, cap, "%luB", b);
|
||||
}
|
||||
|
||||
/*
|
||||
* Who is under this process: one read of every /proc/<pid>/stat, then include
|
||||
* anything whose parent is already included until nothing changes. The tree is
|
||||
* a few levels deep, so a handful of passes is enough.
|
||||
*/
|
||||
static void
|
||||
scan_kids(struct sample *s)
|
||||
{
|
||||
DIR *d;
|
||||
struct kid v[SELF_KIDS_MAX];
|
||||
unsigned char in[SELF_KIDS_MAX];
|
||||
size_t n = 0, i, pass;
|
||||
int self = (int)getpid();
|
||||
|
||||
d = opendir("/proc");
|
||||
if (d != NULL) {
|
||||
struct dirent *e;
|
||||
|
||||
while ((e = readdir(d)) != NULL && n < SELF_KIDS_MAX) {
|
||||
char *end;
|
||||
long pid = strtol(e->d_name, &end, 10);
|
||||
|
||||
if (*end != '\0' || pid <= 0)
|
||||
continue;
|
||||
memset(&v[n], 0, sizeof(v[n]));
|
||||
if (read_stat((int)pid, &v[n]) != 0)
|
||||
continue;
|
||||
in[n] = pid == self;
|
||||
n++;
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
for (pass = 0; pass < 8; pass++) {
|
||||
int changed = 0;
|
||||
|
||||
for (i = 0; i < n; i++) {
|
||||
size_t j;
|
||||
|
||||
if (in[i])
|
||||
continue;
|
||||
for (j = 0; j < n; j++)
|
||||
if (in[j] && v[j].pid == v[i].ppid) {
|
||||
in[i] = 1;
|
||||
changed = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!changed)
|
||||
break;
|
||||
}
|
||||
s->kids = 0;
|
||||
s->kids_rss_kb = 0;
|
||||
s->kids_cpu_pct = 0;
|
||||
{
|
||||
double dt = prev_time > 0 ? mono_now() - prev_time : 0;
|
||||
unsigned long long sum = 0;
|
||||
|
||||
for (i = 0; i < n; i++) {
|
||||
size_t pi2;
|
||||
|
||||
if (!in[i] || v[i].pid == self)
|
||||
continue;
|
||||
s->kids++;
|
||||
s->kids_rss_kb += v[i].rss_pages *
|
||||
(unsigned long)(sysconf(_SC_PAGESIZE) / 1024);
|
||||
for (pi2 = 0; pi2 < prev_nkids; pi2++)
|
||||
if (prev_kids[pi2].pid == v[i].pid) {
|
||||
sum += v[i].ticks -
|
||||
prev_kids[pi2].ticks;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (dt > 0 && hz > 0)
|
||||
s->kids_cpu_pct = (double)sum / (double)hz / dt * 100.0;
|
||||
}
|
||||
prev_nkids = 0;
|
||||
for (i = 0; i < n && prev_nkids < SELF_KIDS_MAX; i++)
|
||||
if (in[i] && v[i].pid != self) {
|
||||
prev_kids[prev_nkids].pid = v[i].pid;
|
||||
prev_kids[prev_nkids].ticks = v[i].ticks;
|
||||
prev_nkids++;
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
sample(struct sample *s)
|
||||
{
|
||||
struct kid self;
|
||||
double now = mono_now();
|
||||
double dt = prev_time > 0 ? now - prev_time : 0;
|
||||
|
||||
memset(s, 0, sizeof(*s));
|
||||
read_self(s);
|
||||
if (read_stat((int)getpid(), &self) == 0) {
|
||||
s->self_ticks = self.ticks;
|
||||
if (dt > 0 && hz > 0 && prev_self_ticks > 0)
|
||||
s->cpu_pct = (double)(self.ticks - prev_self_ticks) /
|
||||
(double)hz / dt * 100.0;
|
||||
prev_self_ticks = self.ticks;
|
||||
}
|
||||
scan_kids(s);
|
||||
prev_time = now;
|
||||
}
|
||||
|
||||
static void
|
||||
compose(struct sample *s)
|
||||
{
|
||||
char rss[24], kids[24], r[24], w[24];
|
||||
|
||||
human(s->rss_kb, rss, sizeof(rss));
|
||||
human(s->kids_rss_kb, kids, sizeof(kids));
|
||||
human_bytes(s->io_read, r, sizeof(r));
|
||||
human_bytes(s->io_write, w, sizeof(w));
|
||||
snprintf(widget, sizeof(widget),
|
||||
"%s rss %.1f%% cpu\n"
|
||||
"%d thr %d fd\n"
|
||||
"kids %d %s %.1f%% cpu\n"
|
||||
"io %s r %s w",
|
||||
rss, s->cpu_pct, s->threads, s->fds, s->kids, kids,
|
||||
s->kids_cpu_pct, r, w);
|
||||
|
||||
snprintf(detail, sizeof(detail),
|
||||
"self: pid %d\n"
|
||||
" rss: %s (%lu kB)\n"
|
||||
" threads: %d\n"
|
||||
" fds: %d\n"
|
||||
" cpu: %.1f%%\n"
|
||||
" io: %s read, %s written\n"
|
||||
"children: %d process(es), %s rss, %.1f%% cpu\n",
|
||||
(int)getpid(), rss, s->rss_kb, s->threads, s->fds, s->cpu_pct,
|
||||
r, w, s->kids, kids, s->kids_cpu_pct);
|
||||
}
|
||||
|
||||
static int
|
||||
self_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
struct sample s;
|
||||
|
||||
(void)ctx;
|
||||
if (hz <= 0)
|
||||
hz = sysconf(_SC_CLK_TCK);
|
||||
sample(&s);
|
||||
pthread_mutex_lock(&self_lock);
|
||||
now_s = s;
|
||||
compose(&s);
|
||||
pthread_mutex_unlock(&self_lock);
|
||||
return sp_host_widget_text(h, name, widget);
|
||||
}
|
||||
|
||||
static void
|
||||
copy_detail(char *out, size_t cap)
|
||||
{
|
||||
pthread_mutex_lock(&self_lock);
|
||||
snprintf(out, cap, "%s", detail);
|
||||
pthread_mutex_unlock(&self_lock);
|
||||
}
|
||||
|
||||
static int
|
||||
self_tool(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char buf[sizeof(detail)];
|
||||
|
||||
(void)args;
|
||||
(void)ctx;
|
||||
copy_detail(buf, sizeof(buf));
|
||||
sp_buf_puts(out, buf);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
self_command(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char buf[sizeof(detail)];
|
||||
|
||||
(void)h;
|
||||
(void)ctx;
|
||||
if (args != NULL && *args != '\0')
|
||||
return sp_buf_puts(out, "usage: /self");
|
||||
copy_detail(buf, sizeof(buf));
|
||||
sp_buf_puts(out, buf);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
self_init(struct sp_host *h)
|
||||
{
|
||||
struct sp_widget w;
|
||||
static const struct sp_status seg = { "self", NULL };
|
||||
static const struct sp_tool t = {
|
||||
"session_usage",
|
||||
"What this splinter process costs the machine: RSS, CPU, threads "
|
||||
"and file descriptors of the session itself, and the same for "
|
||||
"every child process under it.",
|
||||
"{\"type\":\"object\",\"properties\":{}}",
|
||||
SP_AUTH_READ,
|
||||
self_tool,
|
||||
NULL
|
||||
};
|
||||
const char *iv;
|
||||
|
||||
hz = sysconf(_SC_CLK_TCK);
|
||||
memset(&w, 0, sizeof(w));
|
||||
w.name = "self";
|
||||
w.tick = self_tick;
|
||||
iv = sp_host_plugin_config(h, "self", "interval");
|
||||
w.interval_ms = iv != NULL && atoi(iv) > 0 ?
|
||||
(unsigned)atoi(iv) : SELF_DEFAULT_MS;
|
||||
if (sp_host_add_widget(h, &w) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_tool(h, &t) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_command(h, "self", self_command, NULL) != 0)
|
||||
return -1;
|
||||
(void)seg;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin self_plugin = {
|
||||
SP_PLUGIN_ABI, "self", "1.0.0", self_init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &self_plugin;
|
||||
}
|
||||
@@ -1,219 +0,0 @@
|
||||
/*
|
||||
* splinter -- the status line.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Everything a long session makes you want to know, in one line:
|
||||
*
|
||||
* clock: 17:20:01 | ctx 12.3k/32k [|||||||...] | 41 tok/s | 1.2k tok | $0.0042
|
||||
*
|
||||
* The segments go to sp_host_add_status(): /status shows them in the
|
||||
* transcript and the Telegram gateway sends them with its replies. The chat has
|
||||
* no status bar - the prompt carries the running time and the tool.
|
||||
*
|
||||
* The numbers come from the harness (struct sp_meter), never from the plugin
|
||||
* counting for itself: two counters that disagree are worse than none.
|
||||
*
|
||||
* Prices are configuration, not knowledge:
|
||||
*
|
||||
* SPLINTER_PRICE_IN=3.0 dollars per million input tokens
|
||||
* SPLINTER_PRICE_OUT=15.0 dollars per million output tokens
|
||||
* SPLINTER_PRICE_CACHED=0.3
|
||||
*
|
||||
* Without them the cost segment says nothing rather than inventing a number.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
#define BAR_WIDTH 24
|
||||
|
||||
static double price_in, price_out, price_cached;
|
||||
|
||||
static void
|
||||
human(size_t n, char *buf, size_t len)
|
||||
{
|
||||
if (n >= 1000000)
|
||||
snprintf(buf, len, "%.1fM", (double)n / 1e6);
|
||||
else if (n >= 1000)
|
||||
snprintf(buf, len, "%.1fk", (double)n / 1e3);
|
||||
else
|
||||
snprintf(buf, len, "%zu", n);
|
||||
}
|
||||
|
||||
static void
|
||||
render_clock(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
time_t now = time(NULL);
|
||||
struct tm tm;
|
||||
|
||||
(void)h;
|
||||
(void)localtime_r(&now, &tm);
|
||||
strftime(buf, len, "%H:%M", &tm);
|
||||
}
|
||||
|
||||
static void
|
||||
render_ctx(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
struct sp_meter mm;
|
||||
const struct sp_meter *m = &mm;
|
||||
char used[24], max[24], bar[BAR_WIDTH + 1];
|
||||
size_t filled = 0, i;
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
human(m->ctx_used, used, sizeof(used));
|
||||
if (m->ctx_used == 0) {
|
||||
buf[0] = '\0'; /* nothing sent yet: nothing to show */
|
||||
return;
|
||||
}
|
||||
if (m->ctx_max == 0) {
|
||||
snprintf(buf, len, "ctx %s", used);
|
||||
return;
|
||||
}
|
||||
human(m->ctx_max, max, sizeof(max));
|
||||
filled = m->ctx_used >= m->ctx_max ? BAR_WIDTH :
|
||||
(size_t)((double)BAR_WIDTH * (double)m->ctx_used / (double)m->ctx_max);
|
||||
if (filled > BAR_WIDTH)
|
||||
filled = BAR_WIDTH;
|
||||
for (i = 0; i < BAR_WIDTH; i++)
|
||||
bar[i] = i < filled ? '|' : '.';
|
||||
bar[BAR_WIDTH] = '\0';
|
||||
snprintf(buf, len, "ctx %s/%s [%s] %u%%", used, max, bar,
|
||||
(unsigned)(100.0 * (double)m->ctx_used / (double)m->ctx_max));
|
||||
}
|
||||
|
||||
static void
|
||||
render_rate(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
struct sp_meter mm;
|
||||
const struct sp_meter *m = &mm;
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
if (m->tps <= 0) {
|
||||
buf[0] = '\0';
|
||||
return;
|
||||
}
|
||||
snprintf(buf, len, "%ld tok/s", m->tps);
|
||||
}
|
||||
|
||||
static void
|
||||
render_tokens(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
struct sp_meter mm;
|
||||
const struct sp_meter *m = &mm;
|
||||
char in[24], out[24];
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
if (m->tok_in == 0 && m->tok_out == 0) {
|
||||
buf[0] = '\0';
|
||||
return;
|
||||
}
|
||||
human(m->tok_in, in, sizeof(in));
|
||||
human(m->tok_out, out, sizeof(out));
|
||||
snprintf(buf, len, "%s in / %s out", in, out);
|
||||
}
|
||||
|
||||
static void
|
||||
render_cost(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
struct sp_meter mm;
|
||||
const struct sp_meter *m = &mm;
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
if (price_in == 0 && price_out == 0) {
|
||||
buf[0] = '\0';
|
||||
return;
|
||||
}
|
||||
/*
|
||||
* The price belongs to the model, the tokens belong to the harness: the
|
||||
* product is computed here so a price change needs no rebuild of anything
|
||||
* else.
|
||||
*/
|
||||
snprintf(buf, len, "$%.4f",
|
||||
(double)m->tok_in * price_in / 1e6 +
|
||||
(double)m->tok_out * price_out / 1e6);
|
||||
}
|
||||
|
||||
static void
|
||||
render_cache(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
struct sp_meter mm;
|
||||
const struct sp_meter *m = &mm;
|
||||
char hit[24];
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
if (m->ctx_used == 0 || m->cached == 0) {
|
||||
buf[0] = '\0';
|
||||
return;
|
||||
}
|
||||
human(m->cached, hit, sizeof(hit));
|
||||
snprintf(buf, len, "cache %s (%u%%)", hit,
|
||||
(unsigned)(100.0 * (double)m->cached / (double)m->ctx_used));
|
||||
}
|
||||
|
||||
static void
|
||||
render_tasks(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
struct sp_meter mm;
|
||||
const struct sp_meter *m = &mm;
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
if (m->tasks_max == 0 || m->tasks_running == 0) {
|
||||
buf[0] = '\0';
|
||||
return;
|
||||
}
|
||||
snprintf(buf, len, "tasks %u/%u", m->tasks_running, m->tasks_max);
|
||||
}
|
||||
|
||||
static const struct sp_status seg_clock = { "clock", render_clock };
|
||||
static const struct sp_status seg_ctx = { "ctx", render_ctx };
|
||||
static const struct sp_status seg_cache = { "cache", render_cache };
|
||||
static const struct sp_status seg_rate = { "rate", render_rate };
|
||||
static const struct sp_status seg_tokens = { "tokens", render_tokens };
|
||||
static const struct sp_status seg_cost = { "cost", render_cost };
|
||||
static const struct sp_status seg_tasks = { "tasks", render_tasks };
|
||||
|
||||
static int
|
||||
status_init(struct sp_host *h)
|
||||
{
|
||||
const char *in = getenv("SPLINTER_PRICE_IN");
|
||||
const char *out = getenv("SPLINTER_PRICE_OUT");
|
||||
const char *cached = getenv("SPLINTER_PRICE_CACHED");
|
||||
|
||||
if (in != NULL && *in != '\0')
|
||||
price_in = strtod(in, NULL);
|
||||
if (out != NULL && *out != '\0')
|
||||
price_out = strtod(out, NULL);
|
||||
if (cached != NULL && *cached != '\0')
|
||||
price_cached = strtod(cached, NULL);
|
||||
(void)price_cached;
|
||||
|
||||
(void)sp_host_add_status(h, &seg_clock);
|
||||
(void)sp_host_add_status(h, &seg_ctx);
|
||||
(void)sp_host_add_status(h, &seg_cache);
|
||||
(void)sp_host_add_status(h, &seg_rate);
|
||||
(void)sp_host_add_status(h, &seg_tokens);
|
||||
(void)sp_host_add_status(h, &seg_cost);
|
||||
(void)sp_host_add_status(h, &seg_tasks);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI,
|
||||
"status",
|
||||
"1.0",
|
||||
status_init,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &plugin;
|
||||
}
|
||||
@@ -1,258 +0,0 @@
|
||||
# splinter -- deutscher Katalog
|
||||
#
|
||||
# Format: key = text. '#' beginnt einen Kommentar. Fehlende Schluessel fallen
|
||||
# auf Englisch zurueck, ein nirgends vorhandener Schluessel erscheint als er
|
||||
# selbst - nie als leere Zeile.
|
||||
|
||||
ui.ready = bereit. Enter sendet, Ctrl-D beendet.
|
||||
ui.more_lines = ... %zu Zeilen mehr
|
||||
ui.working = laeuft...
|
||||
ui.command_running = Kommando laeuft...
|
||||
ui.reconnected = wieder verbunden
|
||||
ui.reconnecting = Verbindung weg - verbinde neu ...
|
||||
ui.no_sessions = noch keine Sitzungen
|
||||
ui.untitled = (ohne Titel)
|
||||
ui.session_opened = Sitzung geoeffnet
|
||||
ui.session_gone = Sitzung %s ist weg - jetzt auf %s
|
||||
ui.compacted = Kontext kompaktiert: %zu->%zu Nachrichten, %s->%s (%s->%s)
|
||||
ui.steering_queued = Steuerung eingereiht
|
||||
ui.steer_queued_line = Steuerung eingereiht: %s
|
||||
ui.steer_failed = Steuerung nicht angenommen (kein Turn laeuft)
|
||||
ui.model_title = Modell
|
||||
ui.model_filter = filter:
|
||||
ui.model_hint = tippen filtert Pfeile bewegen Enter waehlt Esc bricht ab
|
||||
ui.model_empty = keine Modelle konfiguriert
|
||||
ui.model_none = kein Treffer
|
||||
|
||||
sidebar.session = Sitzung
|
||||
sidebar.cwd = Verzeichnis
|
||||
sidebar.last_turn = letzter Turn
|
||||
sidebar.tokens = %zu Tok (ein %zu)
|
||||
|
||||
|
||||
role.you = du
|
||||
role.agent = modell
|
||||
role.thinking = denkt
|
||||
role.shell = shell
|
||||
role.splinter = splinter
|
||||
role.error = fehler
|
||||
|
||||
cmd.unknown = unbekanntes Kommando: /%s
|
||||
cmd.available = verfuegbar:
|
||||
widgets.none = kein Plugin hat eine Widget-Zeile veröffentlicht
|
||||
|
||||
err.oom = kein Speicher
|
||||
err.theme = Farbschema
|
||||
err.session = Sitzung
|
||||
err.plugin_failed = Plugin fehlgeschlagen
|
||||
|
||||
role.tool = werkzeug
|
||||
role.observation = ausgabe
|
||||
err.thread = Turn-Thread laesst sich nicht starten
|
||||
err.turn_failed = Turn fehlgeschlagen
|
||||
focus.goal_prompt = Ziel: %s. Arbeite darauf hin. Wenn das Ziel vollstaendig erreicht ist, beende deine letzte Antwort mit der einen Zeile GOAL_COMPLETE, damit splinter es als succeeded markieren kann.
|
||||
focus.reminder = Recap zum Merken: %s. Pruefe vor der Antwort, ob der letzte Schritt naeher am Ziel war; wenn nicht, sage das und nenne den naechsten Schritt. Wenn das Ziel vollstaendig erreicht ist, beende deine letzte Antwort mit der einen Zeile GOAL_COMPLETE.
|
||||
focus.recap_prompt = Ziel: %s. Schreibe einen kurzen Recap zum Merken: 3-5 Punkte, was am Ende stimmen muss, die ersten konkreten Schritte und offene Fragen. Wenn das Ziel vollstaendig erreicht ist, beende deine letzte Antwort mit der einen Zeile GOAL_COMPLETE.
|
||||
focus.continue_prompt = Arbeite an diesem Ziel weiter: %s. Mach dort weiter, wo die Sitzung aufgehoert hat: pruefe den Stand, tue den naechsten konkreten Schritt und berichte, was sich geaendert hat. Wenn das Ziel vollstaendig erreicht ist, beende deine letzte Antwort mit der einen Zeile GOAL_COMPLETE.
|
||||
focus.set = Ziel gesetzt: %s
|
||||
focus.none = kein Ziel gesetzt (/goal <text>)
|
||||
focus.status = Ziel: %s (%u Recaps, alle %u Turns)
|
||||
focus.status_done = Ziel: %s [succeeded] (%u Recaps, alle %u Turns)
|
||||
focus.widget_recap = Recap %u, alle %u Turns
|
||||
focus.note_goal = Ziel im Prompt
|
||||
focus.note_recap = Recap angewandt (Turn %u, alle %u Turns)
|
||||
focus.succeeded = Ziel erreicht: %s
|
||||
cps.idle = Leerlauf (angewandt %lu, vorbereitet %lu)
|
||||
cps.plan = Plan bereit: schnitt %zu/%zu, %zu -> %zu B
|
||||
cli.no_output = cli: '%s' lieferte keine Ausgabe
|
||||
cli.timeout = cli: '%s' lief nach %s s in das Zeitlimit
|
||||
cli.failed = cli: '%s' scheiterte (exit %d): %.400s
|
||||
ui.prompt_mark = >
|
||||
ui.steer_mark = steuern>
|
||||
ui.retry_note = neuer Versuch in %d s: %s
|
||||
ui.swarm_locked = [Schwarm gesperrt]
|
||||
ui.status_ctx_bar = ctx %zu/%zu %s %d%%
|
||||
ui.status_ctx = ctx %zu
|
||||
ui.status_cache = cache %d%%
|
||||
ui.status_cache_none = cache -
|
||||
ui.status_tps = %d tok/s
|
||||
ui.status_tps_none = - tok/s
|
||||
ui.approve = %s (%s)? y/N
|
||||
auth.mutate = aendert Dateien
|
||||
auth.destructive = zerstoerend
|
||||
role.diff = aenderung
|
||||
|
||||
# Zustimmung (ack): Kanalnachrichten, Antworten des Gateways, Terminal
|
||||
ack.request = Zustimmung %d: %s %s
|
||||
ack.how = Antwort: ok %d / no %d
|
||||
ack.prompt = Zustimmung %d: %s %s (%ds) - 'splinter --ack %d yes' oder hier y/N:
|
||||
ack.pending = Zustimmung %d: %s %s (%ds)
|
||||
ack.approved_by = splinter: zugestimmt von %s
|
||||
ack.none = keine offenen Anfragen
|
||||
ack.granted = Zustimmung erteilt.
|
||||
ack.refused = Abgelehnt.
|
||||
ack.gone = Diese Anfrage gibt es nicht (mehr).
|
||||
ack.waiting = Ich warte noch auf eine Zustimmung: ok %d / no %d
|
||||
|
||||
# openai transport
|
||||
openai.oom = openai: kein Speicher
|
||||
openai.build_request = openai: Anfrage kann nicht gebaut werden
|
||||
openai.fdopen = openai: fdopen: %s
|
||||
openai.mkstemp = openai: mkstemp: %s
|
||||
openai.short_write = openai: kurzer Schreibvorgang: %s
|
||||
openai.read_failed = openai: Lesen fehlgeschlagen
|
||||
openai.transfer_failed = openai: Uebertragung fehlgeschlagen fuer %s
|
||||
openai.unparseable = openai: Antwort nicht lesbar (kein Status)
|
||||
openai.stream_failed = openai: Stream fehlgeschlagen fuer %s: %.300s
|
||||
openai.no_sse = openai: Endpoint sendete keine SSE-Daten: %.300s
|
||||
openai.stream_no_answer = openai: Stream endete ohne Antwort: %.300s
|
||||
|
||||
# delegate
|
||||
delegate.timeout = Delegate: '%s' Zeitueberschreitung
|
||||
delegate.parallel_timeout = [parallel: Zeitueberschreitung, Rest wird beendet]
|
||||
|
||||
# telegram menu and approval buttons
|
||||
tg.cmd.start = Begruessung und Befehle
|
||||
tg.cmd.help = Hilfe und Befehle
|
||||
tg.cmd.goal = Ziel setzen oder zeigen, dann zusammenfassen
|
||||
tg.cmd.run = fuehrt /%s aus
|
||||
tg.cmd.tasks = Plandateien zeigen
|
||||
tg.help = Ich bin splinter. Schreib eine Nachricht fuer einen Turn. /goal setzt das Ziel und startet einen Recap-Turn, /tasks zeigt den Plan. Aenderungen fragen hier mit Ja/Nein oder ok <id> / no <id>.
|
||||
ack.yes = Ja
|
||||
ack.no = Nein
|
||||
ack.how = Antwort: Knopf unten oder ok %d / no %d
|
||||
|
||||
tg.cmd.interview = Profil im Chat anlegen
|
||||
tg.interview.start = Erstes Gespraech fuer '%s'. Ich stelle %zu Fragen; /skip ueberspringt eine, /cancel bricht ab.
|
||||
tg.interview.question = Frage %zu/%zu: %s
|
||||
tg.interview.how = Antworte einfach in den Chat.
|
||||
tg.interview.saved = Profil geschrieben: %s
|
||||
tg.interview.cancel = Interview abgebrochen.
|
||||
tg.interview.busy = Das Interview laeuft; antworte, /skip oder /cancel.
|
||||
|
||||
# interview questions (terminal and Telegram)
|
||||
interview.intro = Erstes Gespraech fuer '%s'. Enter ueberspringt eine Frage, Ctrl-D bricht ab.
|
||||
interview.header = _Geschrieben von `splinter --interview`. Von Hand aenderbar; splinter liest sie beim Start._
|
||||
interview.q.language = In welcher Sprache soll ich mit dir reden?
|
||||
interview.h.language = z.B. deutsch, english, portugues
|
||||
interview.q.about = Wer bist du und woran arbeitest du gerade?
|
||||
interview.h.about = zwei Saetze reichen
|
||||
interview.q.stack = Welche Sprachen und Werkzeuge benutzt du am liebsten?
|
||||
interview.h.stack = z.B. C99/POSIX, kein Python, Make statt CMake
|
||||
interview.q.style = Wie soll ich antworten?
|
||||
interview.h.style = kurz/lang, mit oder ohne Begruendung, Code zuerst?
|
||||
interview.q.never = Was soll ich NIE tun?
|
||||
interview.h.never = z.B. keine Commits ohne Auftrag, nichts in /tmp
|
||||
interview.q.paths = Welche Pfade sind heilig oder gefaehrlich?
|
||||
interview.h.paths = z.B. /home/carol nie anfassen
|
||||
interview.skipped = (nicht beantwortet)
|
||||
interview.written = Geschrieben: %s
|
||||
interview.error.nodir = interview: kein Sitzungsverzeichnis
|
||||
interview.error.write = interview: kann %s nicht schreiben
|
||||
# /model und /connect (Gateway)
|
||||
session.new = Neue Konversation: %s
|
||||
session.failed = Konnte keine neue Sitzung anlegen: %s
|
||||
session.renamed = Sitzung %s heisst jetzt "%s"
|
||||
session.rename_failed = Konnte die Sitzung nicht umbenennen: %s
|
||||
session.rename_usage = Aufruf: /rename [ID] TITEL
|
||||
session.removed = Sitzung %s entfernt
|
||||
session.remove_failed = Konnte %s nicht entfernen: %s
|
||||
session.rm_current = Die offene Sitzung nicht entfernbar; vorher /open auf eine andere
|
||||
session.rm_usage = Aufruf: /rm ID
|
||||
session.no_session = Keine solche Sitzung: %s
|
||||
tg.cmd.new = neue Konversation
|
||||
|
||||
tg.cmd.model = ein Modell waehlen
|
||||
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)"
|
||||
|
||||
model.saved = Modell: %s (Provider %s). Fuer den naechsten Start gespeichert.
|
||||
model.save_failed = Modell: %s (Provider %s). Nicht gespeichert: %s
|
||||
model.probe = Endpoints nach Modellen fragen
|
||||
model.probe_start = Frage %zu Provider nach ihren Modellen ...
|
||||
model.probe_none = Kein Endpoint hat seine Modelle genannt. /model zeigt weiter die konfigurierten.
|
||||
model.probe_stale = Die Liste ist nicht mehr da; /model probe noch einmal.
|
||||
|
||||
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? 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.
|
||||
connect.key = Welche Umgebungsvariable haelt den Key? `-` fuer keinen.
|
||||
connect.key_named = Welche Umgebungsvariable haelt den Key? `-` fuer keinen, /skip behaelt %s.
|
||||
connect.key_bad = Das ist kein Variablenname (Buchstaben, Ziffern, _).
|
||||
connect.saved = Provider %s gespeichert: %s an %s
|
||||
connect.failed = Speichern fehlgeschlagen: %s
|
||||
connect.nodir = Kein Konfigurationsverzeichnis zum Schreiben.
|
||||
connect.line_too_long = Die Provider-Zeile ist zu lang fuer die Konfiguration.
|
||||
connect.cancel = connect abgebrochen.
|
||||
connect.tested = Test bestanden: %s
|
||||
connect.test_failed = Der Test schlug fehl: %s (gespeichert ist er trotzdem)
|
||||
|
||||
connect.use = Jetzt nutzen
|
||||
connect.later = Spaeter
|
||||
|
||||
|
||||
reply.empty = (leer)
|
||||
|
||||
# Agent-Profile, Kontingent, Seitenleiste (mit den Profilen dazugekommen)
|
||||
sidebar.model = Modell
|
||||
sidebar.usage = Kontingent
|
||||
sidebar.turn_line = %.1f s, %zu Schritte, %zu Tools
|
||||
widget.focus = Ziel
|
||||
widget.plan = Plan
|
||||
widget.sysinfo = System
|
||||
widget.tasks = Aufgaben
|
||||
widget.tmux = tmux
|
||||
ui.limit_wait = Nutzungslimit: weiter um %s (Strg-C stoppt, /resume macht weiter)
|
||||
agent.switched = Agent: %s - %s %s
|
||||
agent.readonly = [nur lesen]
|
||||
agent.none = kein Agent '%s'
|
||||
agent.failed = Agent-Profil '%s' laesst sich nicht aktivieren
|
||||
agent.help = Tab wechselt, /agent NAME waehlt
|
||||
agent.desc.build = voller Zugriff: lesen, aendern, bauen, testen
|
||||
agent.desc.plan = nur lesen: analysieren, abwaegen, planen; aendert nichts
|
||||
usage.benched = am Limit, zurueck in %s
|
||||
usage.calls = %lu Aufrufe
|
||||
usage.room = , Platz in %s
|
||||
usage.of_calls = (%lu/%lu Aufrufe)
|
||||
usage.of_tokens = (%lu/%lu Tokens)
|
||||
plan.widget = %d offen, %d aktiv, %d erledigt
|
||||
plan.widget_active = #%d aktiv - %d offen, %d aktiv, %d erledigt
|
||||
ui.thinking = denkt
|
||||
status.title = Status (%s)
|
||||
status.session = Sitzung
|
||||
status.dir = Verzeichnis
|
||||
status.model = Modell
|
||||
status.endpoint = Endpunkt
|
||||
status.theme = Thema
|
||||
status.agent = Agent
|
||||
status.last = zuletzt
|
||||
status.last_value = %ld ms, %zu Schritte, %zu Toolaufrufe
|
||||
status.tokens = Tokens
|
||||
status.tokens_value = ein %zu, aus %zu
|
||||
status.compact = Kompaktierung
|
||||
status.compact_value = %zu angewandt, %zu fehlgeschlagen, %zu Runden (Agent %zu)
|
||||
status.limits = Limits
|
||||
status.limits_value = max_bytes %zu, max_steps %zu%s
|
||||
status.autonomous = , autonom
|
||||
status.meter = Messwert
|
||||
status.meter_value = ctx %zu/%zu, Cache %zu, Tok %zu/%zu
|
||||
status.bar = Leiste
|
||||
status.swarm = Schwarm
|
||||
status.swarm_value = %s (Id %d)
|
||||
|
||||
interview.system = Du bist splinter und arbeitest zum ersten Mal mit dieser Person. Interview sie, um sie kennenzulernen: woran sie arbeitet, welche Werkzeuge und Sprachen sie nutzt, wie sie angesprochen werden will, was sie nie will und welche Projekte zaehlen. Stelle eine Frage auf einmal, hoere zu und gehe nach, wo es wichtig ist. Frage nicht nach Codedetails, die du im Repository lesen kannst. Wenn du genug hast, schreibe eine kompakte Zusammenfassung der Person und ihrer Arbeitsweise (ein paar Absaetze oder Punkte) und beende deine Antwort mit der einen Zeile INTERVIEW_COMPLETE. Diese Zusammenfassung wird in ~/.splinter/USER.txt gespeichert und am Anfang jeder spaeteren Sitzung gelesen.
|
||||
interview.saved = Interview in USER.txt gespeichert
|
||||
tg.interview.begin = Interview gestartet. Beantworte die Fragen des Modells; /new beendet das Interview.
|
||||
@@ -1,257 +0,0 @@
|
||||
# splinter -- English catalogue (the fallback for every key)
|
||||
#
|
||||
# Format: key = text. '#' starts a comment. Missing keys fall back here, and a
|
||||
# key that exists nowhere is shown as itself, so nothing is silently empty.
|
||||
|
||||
ui.ready = ready. Enter sends, Ctrl-D quits.
|
||||
ui.more_lines = ... %zu more lines
|
||||
ui.working = working...
|
||||
ui.command_running = running command...
|
||||
ui.reconnected = reconnected
|
||||
ui.reconnecting = connection lost - reconnecting ...
|
||||
ui.no_sessions = no sessions yet
|
||||
ui.untitled = (untitled)
|
||||
ui.session_opened = session opened
|
||||
ui.session_gone = session %s is gone - now on %s
|
||||
ui.compacted = context compacted: %zu->%zu msgs, %s->%s (%s->%s)
|
||||
ui.steering_queued = steering queued
|
||||
ui.steer_queued_line = steering queued: %s
|
||||
ui.steer_failed = steering not accepted (no turn is running)
|
||||
ui.model_title = model
|
||||
ui.model_filter = filter:
|
||||
ui.model_hint = type to filter Up/Down move Enter selects Esc cancels
|
||||
ui.model_empty = no models configured
|
||||
ui.model_none = no match
|
||||
|
||||
sidebar.session = session
|
||||
sidebar.cwd = dir
|
||||
sidebar.last_turn = last turn
|
||||
sidebar.tokens = %zu tok (in %zu)
|
||||
|
||||
|
||||
role.you = you
|
||||
role.agent = agent
|
||||
role.thinking = thinking
|
||||
role.shell = shell
|
||||
role.splinter = splinter
|
||||
role.error = error
|
||||
|
||||
cmd.unknown = unknown command: /%s
|
||||
cmd.available = available:
|
||||
widgets.none = no plugin published a widget line
|
||||
|
||||
err.oom = out of memory
|
||||
err.theme = theme
|
||||
err.session = session
|
||||
err.plugin_failed = plugin failed
|
||||
|
||||
role.tool = tool
|
||||
role.observation = output
|
||||
err.thread = cannot start the turn thread
|
||||
err.turn_failed = turn failed
|
||||
focus.goal_prompt = Goal: %s. Work toward it. When the goal is fully achieved, end your final answer with the single line GOAL_COMPLETE so splinter can mark it as succeeded.
|
||||
focus.reminder = Recap to remember: %s. Before answering, check whether the last step moved closer to the goal; if not, say so and name the next step. When the goal is fully achieved, end your final answer with the single line GOAL_COMPLETE.
|
||||
focus.recap_prompt = Goal: %s. Write a short recap to remember: 3-5 bullets, what must be true at the end, the first concrete steps, and open questions. When the goal is fully achieved, end your final answer with the single line GOAL_COMPLETE.
|
||||
focus.continue_prompt = Continue working toward this goal: %s. Pick up where the session stopped: check the current state, do the next concrete step, and report what changed. When the goal is fully achieved, end your final answer with the single line GOAL_COMPLETE.
|
||||
focus.set = goal set: %s
|
||||
focus.none = no goal set (/goal <text>)
|
||||
focus.status = goal: %s (%u recaps, every %u turns)
|
||||
focus.status_done = goal: %s [succeeded] (%u recaps, every %u turns)
|
||||
focus.widget_recap = recap %u, every %u turns
|
||||
focus.note_goal = goal in the prompt
|
||||
focus.note_recap = recap applied (turn %u, every %u turns)
|
||||
focus.succeeded = goal succeeded: %s
|
||||
cps.idle = idle (applied %lu, prepared %lu)
|
||||
cps.plan = plan ready: cut %zu/%zu, %zu -> %zu B
|
||||
cli.no_output = cli: '%s' produced no output
|
||||
cli.timeout = cli: '%s' timed out after %s s
|
||||
cli.failed = cli: '%s' failed (exit %d): %.400s
|
||||
ui.prompt_mark = >
|
||||
ui.steer_mark = steer>
|
||||
ui.retry_note = retrying in %d s: %s
|
||||
ui.swarm_locked = [swarm locked]
|
||||
ui.status_ctx_bar = ctx %zu/%zu %s %d%%
|
||||
ui.status_ctx = ctx %zu
|
||||
ui.status_cache = cache %d%%
|
||||
ui.status_cache_none = cache -
|
||||
ui.status_tps = %d tok/s
|
||||
ui.status_tps_none = - tok/s
|
||||
ui.approve = %s (%s)? y/N
|
||||
auth.mutate = changes files
|
||||
auth.destructive = destructive
|
||||
role.diff = diff
|
||||
|
||||
# approvals (ack): channel messages, the gateway's replies, the terminal
|
||||
ack.request = Approval %d: %s %s
|
||||
ack.how = Answer: ok %d / no %d
|
||||
ack.prompt = approval %d: %s %s (%ds) - 'splinter --ack %d yes' or y/N here:
|
||||
ack.pending = approval %d: %s %s (%ds)
|
||||
ack.approved_by = splinter: approved by %s
|
||||
ack.none = no open requests
|
||||
ack.granted = Approved.
|
||||
ack.refused = Refused.
|
||||
ack.gone = There is no such request (any more).
|
||||
ack.waiting = Still waiting for an approval: ok %d / no %d
|
||||
|
||||
# openai transport
|
||||
openai.oom = openai: out of memory
|
||||
openai.build_request = openai: cannot build the request
|
||||
openai.fdopen = openai: fdopen: %s
|
||||
openai.mkstemp = openai: mkstemp: %s
|
||||
openai.short_write = openai: short write: %s
|
||||
openai.read_failed = openai: read failed
|
||||
openai.transfer_failed = openai: transfer failed for %s
|
||||
openai.unparseable = openai: unparseable response (no status)
|
||||
openai.stream_failed = openai: stream failed for %s: %.300s
|
||||
openai.no_sse = openai: endpoint sent no SSE data: %.300s
|
||||
openai.stream_no_answer = openai: stream ended with no answer: %.300s
|
||||
|
||||
# delegate
|
||||
delegate.timeout = delegate: '%s' timed out
|
||||
delegate.parallel_timeout = [parallel: timeout, killing the rest]
|
||||
|
||||
# telegram menu and approval buttons
|
||||
tg.cmd.start = Greeting and commands
|
||||
tg.cmd.help = Help and commands
|
||||
tg.cmd.goal = Set or show the goal, then recap it
|
||||
tg.cmd.run = run /%s
|
||||
tg.cmd.tasks = Show the plan
|
||||
tg.help = I am splinter. Send a message for a turn. /goal sets the goal and starts a recap turn, /tasks shows the plan. Changes ask here with Yes/No or ok <id> / no <id>.
|
||||
ack.yes = Yes
|
||||
ack.no = No
|
||||
ack.how = Answer: button below or ok %d / no %d
|
||||
|
||||
tg.cmd.interview = create the profile in the chat
|
||||
tg.interview.start = First conversation for '%s'. I ask %zu questions; /skip skips one, /cancel stops.
|
||||
tg.interview.question = Question %zu/%zu: %s
|
||||
tg.interview.how = Just answer in the chat.
|
||||
tg.interview.saved = profile written: %s
|
||||
tg.interview.cancel = interview cancelled.
|
||||
tg.interview.busy = The interview is running; answer, /skip or /cancel.
|
||||
|
||||
# interview questions (terminal and Telegram)
|
||||
interview.intro = First conversation for '%s'. Enter skips a question, Ctrl-D aborts.
|
||||
interview.header = _Written by `splinter --interview`. Edit it by hand whenever you like; splinter reads it at start._
|
||||
interview.q.language = Which language should I speak with you in?
|
||||
interview.h.language = e.g. deutsch, english, portugues
|
||||
interview.q.about = Who are you and what are you working on right now?
|
||||
interview.h.about = two sentences are enough
|
||||
interview.q.stack = Which languages and tools do you prefer?
|
||||
interview.h.stack = e.g. C99/POSIX, no Python, make instead of CMake
|
||||
interview.q.style = How should I answer?
|
||||
interview.h.style = short/long, with or without reasoning, code first?
|
||||
interview.q.never = What should I NEVER do?
|
||||
interview.h.never = e.g. no commits without a request, nothing in /tmp
|
||||
interview.q.paths = Which paths are sacred or dangerous?
|
||||
interview.h.paths = e.g. never touch /home/carol
|
||||
interview.skipped = (not answered)
|
||||
interview.written = Written: %s
|
||||
interview.error.nodir = interview: no session directory
|
||||
interview.error.write = interview: cannot write %s
|
||||
# /model and /connect (gateway)
|
||||
session.new = New conversation: %s
|
||||
session.failed = Could not start a new session: %s
|
||||
session.renamed = Session %s renamed to "%s"
|
||||
session.rename_failed = Cannot rename the session: %s
|
||||
session.rename_usage = Usage: /rename [ID] TITLE
|
||||
session.removed = Session %s removed
|
||||
session.remove_failed = Cannot remove %s: %s
|
||||
session.rm_current = Cannot remove the open session; /open another first
|
||||
session.rm_usage = Usage: /rm ID
|
||||
session.no_session = No such session: %s
|
||||
tg.cmd.new = new conversation
|
||||
|
||||
tg.cmd.model = choose a model
|
||||
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)"
|
||||
|
||||
model.saved = Model: %s (provider %s). Saved for the next start.
|
||||
model.save_failed = Model: %s (provider %s). Not saved: %s
|
||||
model.probe = Ask the endpoints for their models
|
||||
model.probe_start = Asking %zu provider(s) for their models...
|
||||
model.probe_none = No endpoint listed its models. /model still shows the configured ones.
|
||||
model.probe_stale = That list is gone; run /model probe again.
|
||||
|
||||
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? 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.
|
||||
connect.key = Which environment variable holds the key? `-` for none.
|
||||
connect.key_named = Which environment variable holds the key? `-` for none, /skip keeps %s.
|
||||
connect.key_bad = That is not a variable name (letters, digits, _).
|
||||
connect.saved = Provider %s saved: %s at %s
|
||||
connect.failed = Could not save: %s
|
||||
connect.nodir = No configuration directory to write to.
|
||||
connect.line_too_long = That provider line is too long for the configuration.
|
||||
connect.cancel = connect cancelled.
|
||||
connect.tested = Test passed: %s
|
||||
connect.test_failed = The test failed: %s (it is saved anyway)
|
||||
|
||||
connect.use = Use now
|
||||
connect.later = Later
|
||||
|
||||
|
||||
reply.empty = (empty)
|
||||
|
||||
# agent profiles, usage, sidebar (added with the profiles)
|
||||
sidebar.model = model
|
||||
sidebar.usage = usage
|
||||
sidebar.turn_line = %.1f s, %zu steps, %zu tools
|
||||
widget.focus = goal
|
||||
widget.plan = plan
|
||||
widget.sysinfo = system
|
||||
widget.tasks = tasks
|
||||
widget.tmux = tmux
|
||||
ui.limit_wait = usage limit: continuing at %s (Ctrl-C stops, /resume goes on)
|
||||
agent.switched = agent: %s - %s %s
|
||||
agent.readonly = [read-only]
|
||||
agent.none = no agent '%s'
|
||||
agent.failed = cannot activate the agent profile '%s'
|
||||
agent.help = Tab switches, /agent NAME picks
|
||||
agent.desc.build = full access: reads, changes, builds, tests
|
||||
agent.desc.plan = read-only: analyse, weigh, plan; changes nothing
|
||||
usage.benched = at its limit, back in %s
|
||||
usage.calls = %lu calls
|
||||
usage.room = , room in %s
|
||||
usage.of_calls = (%lu/%lu calls)
|
||||
usage.of_tokens = (%lu/%lu tokens)
|
||||
plan.widget = todo %d, doing %d, done %d
|
||||
plan.widget_active = #%d active - todo %d, doing %d, done %d
|
||||
ui.thinking = thinking
|
||||
status.title = status (%s)
|
||||
status.session = session
|
||||
status.dir = dir
|
||||
status.model = model
|
||||
status.endpoint = endpoint
|
||||
status.theme = theme
|
||||
status.agent = agent
|
||||
status.last = last
|
||||
status.last_value = %ld ms, %zu steps, %zu tool calls
|
||||
status.tokens = tokens
|
||||
status.tokens_value = in %zu, out %zu
|
||||
status.compact = compact
|
||||
status.compact_value = %zu applied, %zu failed, %zu turns (agent %zu)
|
||||
status.limits = limits
|
||||
status.limits_value = max_bytes %zu, max_steps %zu%s
|
||||
status.autonomous = , autonomous
|
||||
status.meter = meter
|
||||
status.meter_value = ctx %zu/%zu, cache %zu, tok %zu/%zu
|
||||
status.bar = bar
|
||||
status.swarm = swarm
|
||||
status.swarm_value = %s (id %d)
|
||||
|
||||
interview.system = You are splinter, about to work with this person for the first time. Interview them to get to know them: what they work on, the tools and languages they reach for, how they want to be spoken to, what they never want, and which projects matter. Ask one question at a time, listen, and go deeper where it matters. Do not ask about code details you can read from the repository. When you have enough, write a compact summary of the person and how they want to work (a few paragraphs or bullets), then end your answer with the single line INTERVIEW_COMPLETE. That summary is saved to ~/.splinter/USER.txt and read at the start of every later session.
|
||||
interview.saved = interview saved to USER.txt
|
||||
tg.interview.begin = Interview started. Answer the model's questions; /new leaves the interview.
|
||||
@@ -1,261 +0,0 @@
|
||||
# splinter -- catalogo em portugues do Brasil
|
||||
#
|
||||
# Formato: chave = texto. '#' inicia um comentario. Chaves ausentes caem para o
|
||||
# ingles, e uma chave que nao existe em lugar nenhum aparece como ela mesma -
|
||||
# uma linha vazia esconderia um bug.
|
||||
|
||||
ui.ready = pronto. Enter envia, Ctrl-D sai.
|
||||
ui.more_lines = ... %zu linhas a mais
|
||||
ui.working = trabalhando...
|
||||
ui.command_running = executando comando...
|
||||
ui.reconnected = reconectado
|
||||
ui.reconnecting = conexao perdida - reconectando ...
|
||||
ui.no_sessions = nenhuma sessao ainda
|
||||
ui.untitled = (sem titulo)
|
||||
ui.session_opened = sessao aberta
|
||||
ui.session_gone = sessao %s sumiu - agora em %s
|
||||
ui.compacted = contexto compactado: %zu->%zu msgs, %s->%s (%s->%s)
|
||||
ui.steering_queued = direcionamento na fila
|
||||
ui.steer_queued_line = direcionamento na fila: %s
|
||||
ui.steer_failed = direcionamento nao aceito (nenhum turno em andamento)
|
||||
ui.model_title = modelo
|
||||
ui.model_filter = filtro:
|
||||
ui.model_hint = digite para filtrar setas movem Enter escolhe Esc cancela
|
||||
ui.model_empty = nenhum modelo configurado
|
||||
ui.model_none = nenhum resultado
|
||||
ui.prompt_mark = >
|
||||
ui.steer_mark = direcionar>
|
||||
ui.retry_note = nova tentativa em %d s: %s
|
||||
ui.swarm_locked = [enxame bloqueado]
|
||||
ui.status_ctx_bar = ctx %zu/%zu %s %d%%
|
||||
ui.status_ctx = ctx %zu
|
||||
ui.status_cache = cache %d%%
|
||||
ui.status_cache_none = cache -
|
||||
ui.status_tps = %d tok/s
|
||||
ui.status_tps_none = - tok/s
|
||||
ui.approve = %s (%s)? y/N
|
||||
|
||||
sidebar.session = sessao
|
||||
sidebar.cwd = diretorio
|
||||
sidebar.last_turn = ultimo turno
|
||||
sidebar.tokens = %zu tok (entrada %zu)
|
||||
|
||||
|
||||
role.you = voce
|
||||
role.agent = modelo
|
||||
role.thinking = pensando
|
||||
role.tool = ferramenta
|
||||
role.observation = saida
|
||||
role.shell = shell
|
||||
role.splinter = splinter
|
||||
role.error = erro
|
||||
role.diff = alteracao
|
||||
|
||||
cmd.unknown = comando desconhecido: /%s
|
||||
cmd.available = disponiveis:
|
||||
widgets.none = nenhum plugin publicou uma linha de widget
|
||||
|
||||
err.oom = sem memoria
|
||||
err.theme = tema
|
||||
err.session = sessao
|
||||
err.plugin_failed = plugin falhou
|
||||
err.thread = nao foi possivel iniciar a thread do turno
|
||||
err.turn_failed = turno falhou
|
||||
|
||||
auth.mutate = altera arquivos
|
||||
auth.destructive = destrutivo
|
||||
|
||||
focus.goal_prompt = Objetivo: %s. Trabalhe nisso. Quando o objetivo estiver totalmente alcancado, termine sua resposta final com a linha unica GOAL_COMPLETE para que o splinter possa marcar como succeeded.
|
||||
focus.reminder = Recap para lembrar: %s. Antes de responder, verifique se o ultimo passo aproximou do objetivo; se nao, diga isso e proponha o proximo passo. Quando o objetivo estiver totalmente alcancado, termine sua resposta final com a linha unica GOAL_COMPLETE.
|
||||
focus.recap_prompt = Objetivo: %s. Escreva um recap curto para lembrar: 3-5 pontos, o que precisa estar certo no final, os primeiros passos concretos e as perguntas abertas. Quando o objetivo estiver totalmente alcancado, termine sua resposta final com a linha unica GOAL_COMPLETE.
|
||||
focus.continue_prompt = Continue trabalhando neste objetivo: %s. Retome de onde a sessao parou: verifique o estado, faca o proximo passo concreto e relate o que mudou. Quando o objetivo estiver totalmente alcancado, termine sua resposta final com a linha unica GOAL_COMPLETE.
|
||||
focus.set = objetivo definido: %s
|
||||
focus.none = nenhum objetivo definido (/goal <texto>)
|
||||
focus.status = objetivo: %s (%u recaps, a cada %u turnos)
|
||||
focus.status_done = objetivo: %s [succeeded] (%u recaps, a cada %u turnos)
|
||||
focus.widget_recap = recap %u, a cada %u turnos
|
||||
focus.note_goal = objetivo no prompt
|
||||
focus.note_recap = recap aplicado (turno %u, a cada %u turnos)
|
||||
focus.succeeded = objetivo alcancado: %s
|
||||
|
||||
cps.idle = ocioso (aplicado %lu, preparado %lu)
|
||||
cps.plan = plano pronto: corte %zu/%zu, %zu -> %zu B
|
||||
|
||||
cli.no_output = cli: '%s' nao produziu saida
|
||||
cli.timeout = cli: '%s' passou do limite de %s s
|
||||
cli.failed = cli: '%s' falhou (exit %d): %.400s
|
||||
|
||||
# aprovacoes (ack): mensagens dos canais, respostas do gateway, terminal
|
||||
ack.request = Aprovacao %d: %s %s
|
||||
ack.how = Resposta: ok %d / no %d
|
||||
ack.prompt = aprovacao %d: %s %s (%ds) - 'splinter --ack %d yes' ou y/N aqui:
|
||||
ack.pending = aprovacao %d: %s %s (%ds)
|
||||
ack.approved_by = splinter: aprovado por %s
|
||||
ack.none = nenhum pedido aberto
|
||||
ack.granted = Aprovado.
|
||||
ack.refused = Recusado.
|
||||
ack.gone = Esse pedido nao existe (mais).
|
||||
ack.waiting = Ainda aguardando uma aprovacao: ok %d / no %d
|
||||
|
||||
# openai transport
|
||||
openai.oom = openai: sem memoria
|
||||
openai.build_request = openai: nao foi possivel montar a requisicao
|
||||
openai.fdopen = openai: fdopen: %s
|
||||
openai.mkstemp = openai: mkstemp: %s
|
||||
openai.short_write = openai: escrita incompleta: %s
|
||||
openai.read_failed = openai: falha na leitura
|
||||
openai.transfer_failed = openai: falha na transferencia para %s
|
||||
openai.unparseable = openai: resposta ilegivel (sem status)
|
||||
openai.stream_failed = openai: stream falhou para %s: %.300s
|
||||
openai.no_sse = openai: endpoint nao enviou dados SSE: %.300s
|
||||
openai.stream_no_answer = openai: stream terminou sem resposta: %.300s
|
||||
|
||||
# delegate
|
||||
delegate.timeout = delegate: '%s' excedeu o tempo
|
||||
delegate.parallel_timeout = [paralelo: tempo esgotado, encerrando o resto]
|
||||
|
||||
# telegram menu and approval buttons
|
||||
tg.cmd.start = Saudacao e comandos
|
||||
tg.cmd.help = Ajuda e comandos
|
||||
tg.cmd.goal = Definir ou mostrar a meta, depois resumir
|
||||
tg.cmd.run = executa /%s
|
||||
tg.cmd.tasks = Mostrar o plano
|
||||
tg.help = Eu sou o splinter. Envie uma mensagem para um turno. /goal define a meta e inicia um turno de recap, /tasks mostra o plano. Mudancas perguntam aqui com Sim/Nao ou ok <id> / no <id>.
|
||||
ack.yes = Sim
|
||||
ack.no = Nao
|
||||
ack.how = Resposta: botao abaixo ou ok %d / no %d
|
||||
|
||||
tg.cmd.interview = criar o perfil no chat
|
||||
tg.interview.start = Primeira conversa para '%s'. Sao %zu perguntas; /skip pula uma, /cancel cancela.
|
||||
tg.interview.question = Pergunta %zu/%zu: %s
|
||||
tg.interview.how = Responda no chat.
|
||||
tg.interview.saved = perfil escrito: %s
|
||||
tg.interview.cancel = entrevista cancelada.
|
||||
tg.interview.busy = A entrevista esta em andamento; responda, /skip ou /cancel.
|
||||
|
||||
# interview questions (terminal and Telegram)
|
||||
interview.intro = Primeira conversa para '%s'. Enter pula uma pergunta, Ctrl-D cancela.
|
||||
interview.header = _Escrito por `splinter --interview`. Edite a mao quando quiser; splinter le no inicio._
|
||||
interview.q.language = Em que lingua devo falar com voce?
|
||||
interview.h.language = ex.: deutsch, english, portugues
|
||||
interview.q.about = Quem e voce e no que esta trabalhando agora?
|
||||
interview.h.about = duas frases bastam
|
||||
interview.q.stack = Quais linguagens e ferramentas voce prefere?
|
||||
interview.h.stack = ex.: C99/POSIX, sem Python, make em vez de CMake
|
||||
interview.q.style = Como devo responder?
|
||||
interview.h.style = curto/longo, com ou sem justificativa, codigo primeiro?
|
||||
interview.q.never = O que eu NUNCA devo fazer?
|
||||
interview.h.never = ex.: nenhum commit sem pedido, nada em /tmp
|
||||
interview.q.paths = Quais caminhos sao sagrados ou perigosos?
|
||||
interview.h.paths = ex.: nunca tocar em /home/carol
|
||||
interview.skipped = (nao respondido)
|
||||
interview.written = Escrito: %s
|
||||
interview.error.nodir = interview: sem diretorio de sessao
|
||||
interview.error.write = interview: nao consigo escrever %s
|
||||
# /model e /connect (gateway)
|
||||
session.new = Nova conversa: %s
|
||||
session.failed = Nao consegui abrir uma sessao nova: %s
|
||||
session.renamed = Sessao %s agora se chama "%s"
|
||||
session.rename_failed = Nao consegui renomear a sessao: %s
|
||||
session.rename_usage = Uso: /rename [ID] TITULO
|
||||
session.removed = Sessao %s removida
|
||||
session.remove_failed = Nao consegui remover %s: %s
|
||||
session.rm_current = Nao posso remover a sessao aberta; use /open em outra antes
|
||||
session.rm_usage = Uso: /rm ID
|
||||
session.no_session = Nenhuma sessao assim: %s
|
||||
tg.cmd.new = nova conversa
|
||||
|
||||
tg.cmd.model = escolher um modelo
|
||||
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)"
|
||||
|
||||
model.saved = Modelo: %s (provedor %s). Salvo para a proxima sessao.
|
||||
model.save_failed = Modelo: %s (provedor %s). Nao salvo: %s
|
||||
model.probe = Perguntar aos endpoints quais modelos servem
|
||||
model.probe_start = Perguntando a %zu provedor(es) pelos modelos...
|
||||
model.probe_none = Nenhum endpoint listou seus modelos. /model continua mostrando os configurados.
|
||||
model.probe_stale = A lista sumiu; rode /model probe de novo.
|
||||
|
||||
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? 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.
|
||||
connect.key = Qual variavel de ambiente guarda a chave? `-` para nenhuma.
|
||||
connect.key_named = Qual variavel de ambiente guarda a chave? `-` para nenhuma, /skip mantem %s.
|
||||
connect.key_bad = Isso nao e um nome de variavel (letras, digitos, _).
|
||||
connect.saved = Provedor %s salvo: %s em %s
|
||||
connect.failed = Nao consegui salvar: %s
|
||||
connect.nodir = Nenhum diretorio de configuracao para escrever.
|
||||
connect.line_too_long = A linha do provedor e longa demais para a configuracao.
|
||||
connect.cancel = connect cancelado.
|
||||
connect.tested = Teste passou: %s
|
||||
connect.test_failed = O teste falhou: %s (mesmo assim esta salvo)
|
||||
|
||||
connect.use = Usar agora
|
||||
connect.later = Depois
|
||||
|
||||
|
||||
reply.empty = (vazio)
|
||||
|
||||
# perfis de agente, uso, barra lateral (junto com os perfis)
|
||||
sidebar.model = modelo
|
||||
sidebar.usage = uso
|
||||
sidebar.turn_line = %.1f s, %zu passos, %zu ferramentas
|
||||
widget.focus = meta
|
||||
widget.plan = plano
|
||||
widget.sysinfo = sistema
|
||||
widget.tasks = tarefas
|
||||
widget.tmux = tmux
|
||||
ui.limit_wait = limite de uso: continua as %s (Ctrl-C para, /resume continua)
|
||||
agent.switched = agente: %s - %s %s
|
||||
agent.readonly = [somente leitura]
|
||||
agent.none = nenhum agente '%s'
|
||||
agent.failed = nao foi possivel ativar o perfil de agente '%s'
|
||||
agent.help = Tab alterna, /agent NOME escolhe
|
||||
agent.desc.build = acesso total: ler, alterar, compilar, testar
|
||||
agent.desc.plan = somente leitura: analisar, ponderar, planejar; nao altera nada
|
||||
usage.benched = no limite, volta em %s
|
||||
usage.calls = %lu chamadas
|
||||
usage.room = , vaga em %s
|
||||
usage.of_calls = (%lu/%lu chamadas)
|
||||
usage.of_tokens = (%lu/%lu tokens)
|
||||
plan.widget = %d a fazer, %d em curso, %d feitas
|
||||
plan.widget_active = #%d ativa - %d a fazer, %d em curso, %d feitas
|
||||
ui.thinking = pensando
|
||||
status.title = status (%s)
|
||||
status.session = sessao
|
||||
status.dir = diretorio
|
||||
status.model = modelo
|
||||
status.endpoint = endpoint
|
||||
status.theme = tema
|
||||
status.agent = agente
|
||||
status.last = ultimo
|
||||
status.last_value = %ld ms, %zu passos, %zu chamadas de ferramenta
|
||||
status.tokens = tokens
|
||||
status.tokens_value = entrada %zu, saida %zu
|
||||
status.compact = compactacao
|
||||
status.compact_value = %zu aplicadas, %zu falharam, %zu turnos (agente %zu)
|
||||
status.limits = limites
|
||||
status.limits_value = max_bytes %zu, max_steps %zu%s
|
||||
status.autonomous = , autonomo
|
||||
status.meter = medidor
|
||||
status.meter_value = ctx %zu/%zu, cache %zu, tok %zu/%zu
|
||||
status.bar = barra
|
||||
status.swarm = enxame
|
||||
status.swarm_value = %s (id %d)
|
||||
|
||||
interview.system = Voce e o splinter e vai trabalhar com esta pessoa pela primeira vez. Entreviste-a para conhece-la: no que trabalha, quais ferramentas e linguagens usa, como quer ser tratada, o que nunca quer e quais projetos importam. Faca uma pergunta por vez, escute e aprofunde onde importa. Nao pergunte detalhes de codigo que voce pode ler no repositorio. Quando tiver o suficiente, escreva um resumo compacto da pessoa e de como ela quer trabalhar (alguns paragrafos ou pontos) e termine sua resposta com a linha unica INTERVIEW_COMPLETE. Esse resumo e salvo em ~/.splinter/USER.txt e lido no inicio de cada sessao posterior.
|
||||
interview.saved = entrevista salva em USER.txt
|
||||
tg.interview.begin = Entrevista iniciada. Responda as perguntas do modelo; /new encerra a entrevista.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,30 +0,0 @@
|
||||
/*
|
||||
* splinter -- the A2A server.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_A2ASERVER_H
|
||||
#define SPLINTER_A2ASERVER_H
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
/*
|
||||
* Serve one A2A agent over HTTP+JSON-RPC until SIGINT/SIGTERM.
|
||||
*
|
||||
* splinter --a2a-server-listen 127.0.0.1 --a2a-listen-port 8099
|
||||
* SPLINTER_A2A_SERVER_TOKEN=... splinter --a2a-server-listen 0.0.0.0 ...
|
||||
*
|
||||
* SendMessage runs one turn and returns a completed Task; GetTask returns a
|
||||
* task from the in-memory store; SendStreamingMessage writes SSE events;
|
||||
* SubscribeToTask replays the stored state once (one request at a time, so a
|
||||
* task cannot progress while a subscription is open); the agent card is served
|
||||
* at /.well-known/agent-card.json.
|
||||
*
|
||||
* A bind beyond loopback without a token is refused, as for MCP: 'read' alone
|
||||
* hands out every file this user can open.
|
||||
*/
|
||||
int sp_a2a_serve(struct sp_agent *ag, const char *ip, int port,
|
||||
struct sp_buf *err);
|
||||
|
||||
#endif /* SPLINTER_A2ASERVER_H */
|
||||
@@ -1,426 +0,0 @@
|
||||
/*
|
||||
* splinter -- approvals that do not care who answers.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* A tool call that changes something needs a yes from a human. The human may be
|
||||
* at the terminal, on Telegram, or behind a command that a script answers; there
|
||||
* may be several of them and the first answer wins.
|
||||
*
|
||||
* The shape that makes that work without two processes fighting over the same
|
||||
* Telegram updates:
|
||||
*
|
||||
* ~/.splinter/ack/pending/<id> the request, written by whoever is blocked
|
||||
* ~/.splinter/ack/<id>.answer the answer, written by whoever knows it
|
||||
*
|
||||
* So the asking process only waits on a file. Channels are notifiers: they push
|
||||
* the pending request out (a command per channel, e.g. a Telegram sendMessage) and
|
||||
* whoever reads the reply - the gateway, a pager, a script - drops the answer file.
|
||||
* No polling loop in two places, no lost updates, and the same mechanism works
|
||||
* for the terminal, a phone and an ack button.
|
||||
*
|
||||
* A timeout is a no. Silence is not consent.
|
||||
*/
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "i18n.h"
|
||||
#include "ack.h"
|
||||
|
||||
static char ack_root[512];
|
||||
|
||||
static int
|
||||
ensure_dir(const char *path)
|
||||
{
|
||||
struct stat st;
|
||||
|
||||
if (mkdir(path, 0700) != 0 && errno != EEXIST)
|
||||
return -1;
|
||||
/*
|
||||
* An answer file is a yes. A directory that someone else owns, or that
|
||||
* others may write into, lets them write that yes: refuse it instead of
|
||||
* trusting it. lstat, so a symlink planted in its place is refused too.
|
||||
*/
|
||||
if (lstat(path, &st) != 0 || !S_ISDIR(st.st_mode) ||
|
||||
st.st_uid != getuid() || (st.st_mode & 022) != 0) {
|
||||
errno = EPERM;
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_ack_dir(void)
|
||||
{
|
||||
const char *env = getenv("SPLINTER_ACK_DIR");
|
||||
const char *home = getenv("HOME");
|
||||
|
||||
if (env != NULL && *env != '\0') {
|
||||
snprintf(ack_root, sizeof(ack_root), "%s", env);
|
||||
return ack_root;
|
||||
}
|
||||
if (home == NULL || *home == '\0')
|
||||
return NULL;
|
||||
snprintf(ack_root, sizeof(ack_root), "%s/.splinter/ack", home);
|
||||
return ack_root;
|
||||
}
|
||||
|
||||
static int
|
||||
ack_id_path(char *buf, size_t len, int id, const char *suffix)
|
||||
{
|
||||
const char *root = sp_ack_dir();
|
||||
char dir[600];
|
||||
|
||||
if (root == NULL)
|
||||
return -1;
|
||||
snprintf(dir, sizeof(dir), "%s/pending", root);
|
||||
if (ensure_dir(root) != 0 || ensure_dir(dir) != 0)
|
||||
return -1;
|
||||
snprintf(buf, len, "%s/%d%s", dir, id, suffix);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* An id nobody can guess and nobody reuses. It used to be the pid, so the next
|
||||
* request of the same process - or of a later process with a recycled pid -
|
||||
* found the previous answer waiting and was approved by it. Nine digits at most,
|
||||
* because a human types it into a phone.
|
||||
*/
|
||||
static int
|
||||
new_id(void)
|
||||
{
|
||||
unsigned char r[4] = { 0, 0, 0, 0 };
|
||||
unsigned long v;
|
||||
int fd = open("/dev/urandom", O_RDONLY);
|
||||
|
||||
if (fd >= 0) {
|
||||
if (read(fd, r, sizeof(r)) != (ssize_t)sizeof(r))
|
||||
memset(r, 0, sizeof(r));
|
||||
close(fd);
|
||||
}
|
||||
v = ((unsigned long)r[0] << 24) | ((unsigned long)r[1] << 16) |
|
||||
((unsigned long)r[2] << 8) | (unsigned long)r[3];
|
||||
if (v == 0) /* no randomness: refuse, do not guess */
|
||||
return -1;
|
||||
return (int)(100000 + v % 900000000UL);
|
||||
}
|
||||
|
||||
/* the expiry recorded in a request file, or 0 when there is none */
|
||||
static long
|
||||
request_expires(const char *path)
|
||||
{
|
||||
FILE *f = fopen(path, "r");
|
||||
char line[256];
|
||||
long exp = 0;
|
||||
|
||||
if (f == NULL)
|
||||
return -1;
|
||||
while (fgets(line, sizeof(line), f) != NULL)
|
||||
if (strncmp(line, "expires=", 8) == 0)
|
||||
exp = atol(line + 8);
|
||||
fclose(f);
|
||||
return exp;
|
||||
}
|
||||
|
||||
/* sh -c '<cmd>' sh '<arg>': the command is parsed, the argument is not */
|
||||
static int
|
||||
run_with_arg(const char *cmd, const char *arg)
|
||||
{
|
||||
pid_t child;
|
||||
int status;
|
||||
|
||||
child = fork();
|
||||
if (child < 0)
|
||||
return -1;
|
||||
if (child == 0) {
|
||||
execl("/bin/sh", "sh", "-c", cmd, "sh", arg, (char *)NULL);
|
||||
_exit(127);
|
||||
}
|
||||
while (waitpid(child, &status, 0) < 0)
|
||||
if (errno != EINTR)
|
||||
return -1;
|
||||
return status;
|
||||
}
|
||||
|
||||
/*
|
||||
* Write the request under a fresh random id. O_EXCL, so two requests never share
|
||||
* a file, and 0600, because the arguments may be what is being protected.
|
||||
*/
|
||||
int
|
||||
sp_ack_request(const char *tool, const char *args, const char *why, int ttl)
|
||||
{
|
||||
char path[700];
|
||||
FILE *f = NULL;
|
||||
int id = -1, fd = -1, tries;
|
||||
time_t now = time(NULL);
|
||||
|
||||
for (tries = 0; tries < 8 && fd < 0; tries++) {
|
||||
id = new_id();
|
||||
if (id < 0 || ack_id_path(path, sizeof(path), id, "") != 0)
|
||||
return -1;
|
||||
fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
|
||||
if (fd < 0 && errno != EEXIST)
|
||||
return -1;
|
||||
}
|
||||
if (fd < 0 || (f = fdopen(fd, "w")) == NULL) {
|
||||
if (fd >= 0)
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
{
|
||||
/*
|
||||
* An answer that raced the end of an earlier request with this id
|
||||
* may still lie here. It belongs to nobody; it must not become the
|
||||
* answer to this one.
|
||||
*/
|
||||
char ans[700];
|
||||
|
||||
if (ack_id_path(ans, sizeof(ans), id, ".answer") == 0)
|
||||
(void)unlink(ans);
|
||||
}
|
||||
fprintf(f, "id=%d\n", id);
|
||||
fprintf(f, "tool=%s\n", tool != NULL ? tool : "");
|
||||
fprintf(f, "args=%s\n", args != NULL ? args : "");
|
||||
fprintf(f, "why=%s\n", why != NULL ? why : "");
|
||||
fprintf(f, "pid=%d\n", (int)getpid());
|
||||
fprintf(f, "expires=%ld\n", (long)now + (ttl > 0 ? ttl : 120));
|
||||
if (fclose(f) != 0) {
|
||||
(void)unlink(path);
|
||||
return -1;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/*
|
||||
* Fire every configured channel. Each entry is a command; the request is appended
|
||||
* as one argument. A channel that fails is not fatal - another one may reach a
|
||||
* human - but the failure is named.
|
||||
*/
|
||||
/* one "key=" line of a request file, without the newline */
|
||||
static void
|
||||
request_field(int id, const char *key, char *buf, size_t len)
|
||||
{
|
||||
char path[700], line[1024];
|
||||
size_t kl = strlen(key);
|
||||
FILE *f;
|
||||
|
||||
buf[0] = '\0';
|
||||
if (ack_id_path(path, sizeof(path), id, "") != 0 ||
|
||||
(f = fopen(path, "r")) == NULL)
|
||||
return;
|
||||
while (fgets(line, sizeof(line), f) != NULL)
|
||||
if (strncmp(line, key, kl) == 0 && line[kl] == '=') {
|
||||
line[strcspn(line, "\r\n")] = '\0';
|
||||
snprintf(buf, len, "%s", line + kl + 1);
|
||||
break;
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
int
|
||||
sp_ack_notify(int id, struct sp_buf *log)
|
||||
{
|
||||
const char *chans = getenv("SPLINTER_ACK_CHANNELS");
|
||||
char list[512], *save = NULL, *tok;
|
||||
char tool[64], args[400], msg[600];
|
||||
int fired = 0;
|
||||
|
||||
if (chans == NULL || *chans == '\0')
|
||||
return 0;
|
||||
/*
|
||||
* The message says what is being approved. It used to be "Zustimmung
|
||||
* <id>" alone: a parent on a phone said yes to a number. Arguments are
|
||||
* cut at 300 bytes - enough to see the command, not a whole file.
|
||||
*/
|
||||
request_field(id, "tool", tool, sizeof(tool));
|
||||
request_field(id, "args", args, sizeof(args));
|
||||
if (strlen(args) > 300)
|
||||
memcpy(args + 297, "...", 4);
|
||||
{
|
||||
char head[480], how[100];
|
||||
|
||||
snprintf(head, sizeof(head), sp_td("ack.request",
|
||||
"Approval %d: %s %s"), id, tool[0] != '\0' ? tool : "?", args);
|
||||
snprintf(how, sizeof(how), sp_td("ack.how",
|
||||
"Answer: ok %d / no %d"), id, id);
|
||||
snprintf(msg, sizeof(msg), "%s\n%s", head, how);
|
||||
}
|
||||
snprintf(list, sizeof(list), "%s", chans);
|
||||
for (tok = strtok_r(list, ",", &save); tok != NULL;
|
||||
tok = strtok_r(NULL, ",", &save)) {
|
||||
char cmd[600];
|
||||
int rc;
|
||||
|
||||
while (*tok == ' ')
|
||||
tok++;
|
||||
if (*tok == '\0')
|
||||
continue;
|
||||
/*
|
||||
* The channel command is the operator's; the message carries the
|
||||
* model's arguments and therefore goes in as "$1", never parsed.
|
||||
*/
|
||||
snprintf(cmd, sizeof(cmd), "%s \"$1\"", tok);
|
||||
rc = run_with_arg(cmd, msg);
|
||||
if (rc == 0)
|
||||
fired++;
|
||||
else if (log != NULL)
|
||||
sp_buf_printf(log, "ack: channel '%s' failed (%d)\n", tok,
|
||||
rc);
|
||||
}
|
||||
return fired;
|
||||
}
|
||||
|
||||
/*
|
||||
* Wait for the answer. Returns 1 yes, 0 no, -1 nothing yet. 'who' says where the
|
||||
* answer came from, which is worth recording when a child asks and an adult
|
||||
* answers from a phone.
|
||||
*/
|
||||
int
|
||||
sp_ack_wait(int id, int ttl, char *who, size_t who_len)
|
||||
{
|
||||
char path[700], req[700];
|
||||
time_t end = time(NULL) + (ttl > 0 ? ttl : 120);
|
||||
int ok = 0;
|
||||
|
||||
if (ack_id_path(path, sizeof(path), id, ".answer") != 0 ||
|
||||
ack_id_path(req, sizeof(req), id, "") != 0)
|
||||
return 0;
|
||||
for (;;) {
|
||||
FILE *f;
|
||||
char line[256];
|
||||
|
||||
if ((f = fopen(path, "r")) != NULL) {
|
||||
if (fgets(line, sizeof(line), f) != NULL) {
|
||||
line[strcspn(line, "\r\n")] = '\0';
|
||||
ok = strncmp(line, "yes ", 4) == 0;
|
||||
if (who != NULL) {
|
||||
char *sp = strchr(line, ' ');
|
||||
|
||||
snprintf(who, who_len, "%s",
|
||||
sp != NULL ? sp + 1 : "unknown");
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
break;
|
||||
}
|
||||
if (time(NULL) >= end)
|
||||
break; /* silence is not consent */
|
||||
{
|
||||
struct timespec ts = { 0, 200 * 1000 * 1000 };
|
||||
|
||||
(void)nanosleep(&ts, NULL);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Answered or not, the request is over. Removing it is what makes a late
|
||||
* answer fail ("no such request") instead of lying in wait for the next one.
|
||||
*/
|
||||
(void)unlink(req);
|
||||
(void)unlink(path);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/*
|
||||
* Any process may answer, once, while the request is still open. The answer is
|
||||
* written to a private temp file and then link(2)ed into place: link fails when
|
||||
* the name exists, so the first answer wins and a waiter never reads half a
|
||||
* file.
|
||||
*/
|
||||
int
|
||||
sp_ack_answer(int id, int yes, const char *who)
|
||||
{
|
||||
char req[700], path[700], tmp[760];
|
||||
long exp;
|
||||
int fd, rc;
|
||||
FILE *f;
|
||||
|
||||
if (id <= 0 || ack_id_path(req, sizeof(req), id, "") != 0 ||
|
||||
ack_id_path(path, sizeof(path), id, ".answer") != 0)
|
||||
return -1;
|
||||
exp = request_expires(req);
|
||||
if (exp < 0)
|
||||
return -1; /* no such request */
|
||||
if (exp > 0 && (long)time(NULL) >= exp)
|
||||
return -1; /* too late: the request was a no already */
|
||||
snprintf(tmp, sizeof(tmp), "%s.%ld", path, (long)getpid());
|
||||
fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL, 0600);
|
||||
if (fd < 0 || (f = fdopen(fd, "w")) == NULL) {
|
||||
if (fd >= 0) {
|
||||
close(fd);
|
||||
(void)unlink(tmp);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
fprintf(f, "%s %s\n", yes ? "yes" : "no",
|
||||
who != NULL && *who != '\0' ? who : "unknown");
|
||||
if (fclose(f) != 0) {
|
||||
(void)unlink(tmp);
|
||||
return -1;
|
||||
}
|
||||
rc = link(tmp, path);
|
||||
(void)unlink(tmp);
|
||||
return rc == 0 ? 0 : -1;
|
||||
}
|
||||
|
||||
int
|
||||
sp_ack_answered(int id)
|
||||
{
|
||||
char path[700];
|
||||
|
||||
return ack_id_path(path, sizeof(path), id, ".answer") == 0 &&
|
||||
access(path, F_OK) == 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_ack_list(struct sp_buf *out)
|
||||
{
|
||||
const char *root = sp_ack_dir();
|
||||
char dir[600];
|
||||
struct dirent **ents;
|
||||
int n, i;
|
||||
|
||||
if (root == NULL)
|
||||
return -1;
|
||||
snprintf(dir, sizeof(dir), "%s/pending", root);
|
||||
n = scandir(dir, &ents, NULL, alphasort);
|
||||
if (n < 0) {
|
||||
sp_buf_printf(out, "%s\n", sp_td("ack.none",
|
||||
"no open requests"));
|
||||
return 0;
|
||||
}
|
||||
for (i = 0; i < n; i++) {
|
||||
char path[1024], line[256];
|
||||
FILE *f;
|
||||
|
||||
if (strchr(ents[i]->d_name, '.') != NULL) { /* answers, temp files */
|
||||
free(ents[i]);
|
||||
continue;
|
||||
}
|
||||
snprintf(path, sizeof(path), "%s/%s", dir, ents[i]->d_name);
|
||||
sp_buf_printf(out, "%s ", ents[i]->d_name);
|
||||
if ((f = fopen(path, "r")) != NULL) {
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
if (strncmp(line, "args=", 5) == 0 ||
|
||||
strncmp(line, "expires=", 8) == 0) {
|
||||
line[strcspn(line, "\r\n")] = '\0';
|
||||
sp_buf_printf(out, "%s ", line);
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
sp_buf_puts(out, "\n");
|
||||
free(ents[i]);
|
||||
}
|
||||
free(ents);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
/*
|
||||
* splinter -- approvals that do not care who answers.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_ACK_H
|
||||
#define SPLINTER_ACK_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
const char *sp_ack_dir(void);
|
||||
int sp_ack_request(const char *tool, const char *args,
|
||||
const char *why, int ttl);
|
||||
int sp_ack_notify(int id, struct sp_buf *log);
|
||||
int sp_ack_wait(int id, int ttl, char *who, size_t who_len);
|
||||
int sp_ack_answer(int id, int yes, const char *who);
|
||||
int sp_ack_list(struct sp_buf *out);
|
||||
/* 1 when an answer for 'id' is waiting, without consuming it */
|
||||
int sp_ack_answered(int id);
|
||||
|
||||
#endif /* SPLINTER_ACK_H */
|
||||
@@ -1,899 +0,0 @@
|
||||
/*
|
||||
* splinter -- the turn loop.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* One turn: append the user message, ask the transport, run the tools it asks
|
||||
* for, repeat until it answers or the step limit is hit. The conversation
|
||||
* lives in sp_conv and survives the turn, so splinter is not an amnesiac
|
||||
* one-shot.
|
||||
*
|
||||
* Invariants, in this order, before any tool runs:
|
||||
* 1. the conversation fits the byte budget, otherwise the turn fails and
|
||||
* nothing is sent (never rely on the endpoint to truncate);
|
||||
* 2. the tool exists in the registry, otherwise the model is told so;
|
||||
* 3. the tool's authorization class is honoured; a denial is reported back
|
||||
* as the observation, not silently skipped.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <errno.h>
|
||||
#include <poll.h>
|
||||
#include <time.h>
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "i18n.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "ack.h"
|
||||
#include "log.h"
|
||||
#include "usage.h"
|
||||
|
||||
/*
|
||||
* The terminal as one more approval channel. It must be stoppable: when the
|
||||
* phone answers first, or the request times out, the agent goes on, and a
|
||||
* thread still sitting in fgets() would hold it until somebody pressed Enter.
|
||||
* So it polls the terminal together with a pipe, and a byte on the pipe ends it.
|
||||
*/
|
||||
struct ack_thread {
|
||||
int id;
|
||||
FILE *in;
|
||||
int stop; /* read end of the stop pipe */
|
||||
};
|
||||
|
||||
|
||||
struct quota_set_ctx { long status; long now; long retry_after_s; };
|
||||
static void quota_set_fn(struct sp_prov_state *st, void *p) {
|
||||
struct quota_set_ctx *c = p;
|
||||
long ra = 0;
|
||||
if (c->retry_after_s > 0) ra = c->now + c->retry_after_s;
|
||||
else if (c->status == 429 || c->status == 402) ra = c->now + 60;
|
||||
else if (c->status == 529) ra = c->now + 120;
|
||||
if (ra > 0 && st->quota_ready_at < ra) st->quota_ready_at = ra;
|
||||
if (ra > 0) st->last_429_at = c->now;
|
||||
if (ra > 0) snprintf(st->note, sizeof(st->note), "quota %ld ready_at=%ld", c->status, ra);
|
||||
}
|
||||
static void quota_hint(const char *provider, const char *key_id, long status, long retry_after_s) {
|
||||
struct quota_set_ctx c;
|
||||
if (!provider||!*provider||!key_id||!*key_id) return;
|
||||
if (status!=429 && status!=402 && status!=529) return;
|
||||
c.status = status; c.now = (long)time(NULL); c.retry_after_s = retry_after_s;
|
||||
sp_provstate_update(provider, key_id, quota_set_fn, &c);
|
||||
}
|
||||
|
||||
static void *
|
||||
ack_stdin_thread(void *arg)
|
||||
{
|
||||
struct ack_thread *at = arg;
|
||||
char line[64];
|
||||
struct pollfd pfd[2];
|
||||
|
||||
pfd[0].fd = fileno(at->in);
|
||||
pfd[0].events = POLLIN;
|
||||
pfd[1].fd = at->stop;
|
||||
pfd[1].events = POLLIN;
|
||||
for (;;) {
|
||||
pfd[0].revents = pfd[1].revents = 0;
|
||||
if (poll(pfd, 2, -1) < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
if (pfd[1].revents != 0)
|
||||
break; /* answered elsewhere or expired */
|
||||
if (pfd[0].revents != 0) {
|
||||
if (fgets(line, sizeof(line), at->in) != NULL)
|
||||
(void)sp_ack_answer(at->id,
|
||||
line[0] == 'y' || line[0] == 'Y', "terminal");
|
||||
break;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* Approval through the ack mechanism: the request becomes a file, the channels are
|
||||
* fired, and whoever answers first wins - the person at this terminal, a phone, or
|
||||
* a script. Without any channel configured this falls back to the plain prompt, so
|
||||
* nothing starts hanging that used to be synchronous.
|
||||
*/
|
||||
static int
|
||||
ack_approval(struct sp_agent *a, const struct sp_tool *t, const char *args)
|
||||
{
|
||||
const char *chans = getenv("SPLINTER_ACK_CHANNELS");
|
||||
const char *ttl_s = getenv("SPLINTER_ACK_TTL");
|
||||
struct sp_buf log;
|
||||
char who[64] = "";
|
||||
int id, ttl, yes;
|
||||
pthread_t th;
|
||||
int th_started = 0;
|
||||
int stop[2] = { -1, -1 };
|
||||
struct ack_thread at;
|
||||
|
||||
if (chans == NULL || *chans == '\0')
|
||||
return -1;
|
||||
ttl = ttl_s != NULL && *ttl_s != '\0' ? atoi(ttl_s) : 120;
|
||||
if (ttl <= 0)
|
||||
ttl = 120;
|
||||
id = sp_ack_request(t->name, args,
|
||||
t->auth == SP_AUTH_MUTATE ? "mutate" : "destructive", ttl);
|
||||
if (id < 0) {
|
||||
/* fail closed, but say why: a silent "denied" sends people hunting */
|
||||
fprintf(stderr, "splinter: cannot file an approval request in %s "
|
||||
"(missing, not yours, or writable by others): %s denied\n",
|
||||
sp_ack_dir() != NULL ? sp_ack_dir() : "(no ack dir)", t->name);
|
||||
return 0;
|
||||
}
|
||||
if (sp_buf_init(&log) == 0) {
|
||||
(void)sp_ack_notify(id, &log);
|
||||
if (log.p != NULL && *log.p != '\0')
|
||||
fprintf(stderr, "%s", log.p);
|
||||
sp_buf_free(&log);
|
||||
}
|
||||
if (a->cfg->approval_out != NULL)
|
||||
fprintf(a->cfg->approval_out, sp_td("ack.prompt",
|
||||
"approval %d: %s %s (%ds) - 'splinter --ack %d yes' or y/N "
|
||||
"here: "), id, t->name, args, ttl, id);
|
||||
else
|
||||
fprintf(stderr, sp_td("ack.pending", "approval %d: %s %s (%ds)\n"),
|
||||
id, t->name, args, ttl);
|
||||
if (a->cfg->approval_out != NULL)
|
||||
fflush(a->cfg->approval_out);
|
||||
|
||||
/* the terminal is one more channel, not a special case */
|
||||
if (a->cfg->approval_in != NULL && pipe(stop) == 0) {
|
||||
at.id = id;
|
||||
at.in = a->cfg->approval_in;
|
||||
at.stop = stop[0];
|
||||
if (pthread_create(&th, NULL, ack_stdin_thread, &at) == 0)
|
||||
th_started = 1;
|
||||
}
|
||||
yes = sp_ack_wait(id, ttl, who, sizeof(who));
|
||||
if (th_started) {
|
||||
(void)write(stop[1], "x", 1);
|
||||
(void)pthread_join(th, NULL);
|
||||
}
|
||||
if (stop[0] >= 0) {
|
||||
close(stop[0]);
|
||||
close(stop[1]);
|
||||
}
|
||||
if (yes && who[0] != '\0')
|
||||
fprintf(stderr, sp_td("ack.approved_by",
|
||||
"splinter: approved by %s\n"), who);
|
||||
return yes;
|
||||
}
|
||||
|
||||
static int
|
||||
ask_operator(struct sp_agent *a, const struct sp_tool *t, const char *args)
|
||||
{
|
||||
char line[64];
|
||||
int verdict;
|
||||
|
||||
if (a->cfg->approve != NULL && a->cfg->approve_is_channel)
|
||||
return a->cfg->approve(a->cfg->approve_ctx, t->name, (int)t->auth,
|
||||
args);
|
||||
verdict = ack_approval(a, t, args);
|
||||
if (verdict >= 0)
|
||||
return verdict;
|
||||
|
||||
if (a->cfg->approve != NULL)
|
||||
return a->cfg->approve(a->cfg->approve_ctx, t->name, (int)t->auth,
|
||||
args);
|
||||
if (a->cfg->approval_out != NULL) {
|
||||
fprintf(a->cfg->approval_out, "run %s (%s) %s? [y/N] ", t->name,
|
||||
t->auth == SP_AUTH_MUTATE ? "mutate" : "destructive", args);
|
||||
fflush(a->cfg->approval_out);
|
||||
}
|
||||
if (a->cfg->approval_in == NULL)
|
||||
return 0; /* fail closed */
|
||||
if (fgets(line, sizeof(line), a->cfg->approval_in) == NULL)
|
||||
return 0;
|
||||
return (line[0] == 'y' || line[0] == 'Y');
|
||||
}
|
||||
|
||||
/* The observation is always written: an error is an observation too. */
|
||||
/*
|
||||
* 0 = ran (obs is the observation), 1 = a person has to decide first (nothing
|
||||
* ran). have_decision/decision are used by a resume: the decision applies to
|
||||
* the pending calls instead of asking again.
|
||||
*/
|
||||
/* a name against a comma list of names; a trailing '*' is a prefix */
|
||||
static int
|
||||
in_name_list(const char *list, const char *name)
|
||||
{
|
||||
char buf[512], *t, *save = NULL;
|
||||
|
||||
snprintf(buf, sizeof(buf), "%s", list);
|
||||
for (t = strtok_r(buf, ", ", &save); t != NULL;
|
||||
t = strtok_r(NULL, ", ", &save)) {
|
||||
size_t n = strlen(t);
|
||||
|
||||
if (n > 0 && t[n - 1] == '*') {
|
||||
if (strncmp(name, t, n - 1) == 0)
|
||||
return 1;
|
||||
} else if (strcmp(name, t) == 0)
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
policy_allows(const struct sp_tool_policy *p, const struct sp_tool *t)
|
||||
{
|
||||
if (p == NULL)
|
||||
return 1;
|
||||
if (in_name_list(p->deny, t->name))
|
||||
return 0;
|
||||
if (in_name_list(p->allow, t->name))
|
||||
return 1;
|
||||
return p->max_auth < 0 || (int)t->auth <= p->max_auth;
|
||||
}
|
||||
|
||||
static int
|
||||
run_one_call(struct sp_agent *a, const struct sp_toolcall *call,
|
||||
struct sp_buf *obs, int have_decision, int decision)
|
||||
{
|
||||
const struct sp_tool *t;
|
||||
int verdict;
|
||||
|
||||
a->stats.tool_calls++;
|
||||
t = sp_registry_find(a->reg, call->name);
|
||||
if (t == NULL) {
|
||||
sp_buf_printf(obs, "error: unknown tool '%s'", call->name);
|
||||
return 0;
|
||||
}
|
||||
if (!policy_allows(a->policy, t)) {
|
||||
a->stats.denied++;
|
||||
sp_buf_printf(obs, "denied: '%s' is not available in the '%s' "
|
||||
"agent (%s); ask the user to switch agent (Tab) or use a "
|
||||
"tool that is allowed", t->name, a->policy->name,
|
||||
a->policy->max_auth == 0 ? "read-only" : "restricted");
|
||||
return 0;
|
||||
}
|
||||
/*
|
||||
* A gate may decide before anybody else: a plugin's policy (kid mode, a
|
||||
* sandbox) can allow a call outright or refuse it with a reason. Only when
|
||||
* no gate has an opinion do the normal rules apply.
|
||||
*/
|
||||
if (a->host != NULL) {
|
||||
char reason[256];
|
||||
|
||||
verdict = sp_host_gate(a->host, t->name, (int)t->auth,
|
||||
call->args, reason, sizeof(reason));
|
||||
if (verdict == 0) {
|
||||
a->stats.denied++;
|
||||
sp_buf_printf(obs, "denied: %s", reason[0] != '\0' ?
|
||||
reason : "by policy");
|
||||
sp_logf("gate", "%s denied: %s", t->name, reason);
|
||||
return 0;
|
||||
}
|
||||
if (verdict == 1) {
|
||||
if (t->run(call->args, obs, t->ctx) != 0)
|
||||
sp_buf_printf(obs, "error: tool '%s' failed",
|
||||
call->name);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (t->auth != SP_AUTH_READ && !a->cfg->autonomous) {
|
||||
if (have_decision)
|
||||
verdict = decision ? 1 : 0;
|
||||
else {
|
||||
verdict = ask_operator(a, t, call->args);
|
||||
if (verdict == 2)
|
||||
return 1; /* pause; nothing has run */
|
||||
}
|
||||
if (!verdict) {
|
||||
a->stats.denied++;
|
||||
sp_buf_puts(obs, "error: denied by operator");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (t->run(call->args, obs, t->ctx) != 0)
|
||||
sp_buf_printf(obs, "error: tool '%s' failed", call->name);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* run one call and add its observation; 1 means approval is still required */
|
||||
static int
|
||||
run_one(struct sp_agent *a, struct sp_conv *conv,
|
||||
const struct sp_toolcall *call, int have_decision, int decision,
|
||||
struct sp_buf *obs, struct sp_buf *err)
|
||||
{
|
||||
struct sp_msg tm;
|
||||
int rc;
|
||||
|
||||
sp_buf_clear(obs);
|
||||
sp_logf("tool", "%s %s", call->name,
|
||||
call->args != NULL ? call->args : "");
|
||||
if (a->cfg->tool_begin != NULL)
|
||||
a->cfg->tool_begin(a->cfg->tool_begin_ctx, call->name,
|
||||
call->args);
|
||||
rc = run_one_call(a, call, obs, have_decision, decision);
|
||||
if (rc != 0)
|
||||
return rc;
|
||||
if (a->cfg->tool_end != NULL)
|
||||
a->cfg->tool_end(a->cfg->tool_end_ctx, call->name,
|
||||
obs->p != NULL ? obs->p : "");
|
||||
sp_logf("observation", "%s", obs->p != NULL ? obs->p : "");
|
||||
if (obs->p != NULL && strncmp(obs->p, "error", 5) == 0)
|
||||
sp_logf("tool failed", "%s: %s", call->name, obs->p);
|
||||
memset(&tm, 0, sizeof(tm));
|
||||
tm.role = "tool";
|
||||
tm.name = call->name;
|
||||
tm.call_id = call->id;
|
||||
tm.content = obs->p;
|
||||
if (sp_conv_add(conv, &tm) != 0) {
|
||||
sp_buf_puts(err, "agent: out of memory");
|
||||
return -1;
|
||||
}
|
||||
if (a->sess != NULL &&
|
||||
sp_session_append(a->sess, "observation", obs->p, err) != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The waiter for callers without a screen (-p, the daemon, the servers): say
|
||||
* when the run goes on and sleep until then. 'ctx' points at the longest wait
|
||||
* in seconds; a longer one fails the turn instead, so a limit that lifts next
|
||||
* week does not hold a process for a week.
|
||||
*/
|
||||
int
|
||||
sp_limit_wait_default(void *ctx, long until, const char *why)
|
||||
{
|
||||
const long *maxw = ctx;
|
||||
long now = (long)time(NULL), cap = maxw != NULL &&
|
||||
*maxw > 0 ? *maxw : 12 * 3600;
|
||||
char when[32];
|
||||
struct tm tm;
|
||||
time_t tt = (time_t)until;
|
||||
|
||||
if (until - now > cap)
|
||||
return 0;
|
||||
strftime(when, sizeof(when), "%Y-%m-%d %H:%M", localtime_r(&tt, &tm));
|
||||
fprintf(stderr, "splinter: usage limit reached (%.80s); continuing at %s\n",
|
||||
why != NULL ? why : "", when);
|
||||
while ((long)time(NULL) < until)
|
||||
sleep(1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* A request ran into a usage limit. When the caller can wait, find out when the
|
||||
* limit lifts -- from the status and Retry-After, from "ready_at=", or from the
|
||||
* reset the provider named in its message -- bench the provider until then,
|
||||
* wait, and tell the loop to ask again. 0: not a limit, or not waiting.
|
||||
*/
|
||||
static int
|
||||
limit_retry(struct sp_agent *a, struct sp_buf *err, long status,
|
||||
long retry_after, long ready_at, int *tries)
|
||||
{
|
||||
long now = (long)time(NULL), until = 0;
|
||||
const char *e = err != NULL && err->p != NULL ? err->p : "";
|
||||
|
||||
if ((a->cfg->limit_wait == NULL && a->cfg->limit_switch == NULL) ||
|
||||
*tries >= 50)
|
||||
return 0;
|
||||
if (ready_at > now)
|
||||
until = ready_at;
|
||||
else if (status == 429 || status == 402 || status == 529)
|
||||
until = now + (retry_after > 0 ? retry_after :
|
||||
(status == 529 ? 120 : 60));
|
||||
else if (!sp_limit_parse(e, &until)) {
|
||||
const char *r = strstr(e, "ready_at=");
|
||||
|
||||
until = r != NULL ? strtol(r + 9, NULL, 10) : 0;
|
||||
} else if (strstr(e, "ready_at=") != NULL)
|
||||
until = strtol(strstr(e, "ready_at=") + 9, NULL, 10);
|
||||
if (until <= now)
|
||||
return 0;
|
||||
sp_cooldown_set(sp_usage_active(), until, e);
|
||||
if (a->cfg->limit_switch != NULL &&
|
||||
a->cfg->limit_switch(a->cfg->switch_ctx)) {
|
||||
if (err != NULL)
|
||||
sp_buf_clear(err);
|
||||
return 1;
|
||||
}
|
||||
(*tries)++;
|
||||
if (a->cfg->limit_wait == NULL ||
|
||||
!a->cfg->limit_wait(a->cfg->limit_ctx, until, e))
|
||||
return 0;
|
||||
if (err != NULL)
|
||||
sp_buf_clear(err);
|
||||
return 1;
|
||||
}
|
||||
|
||||
#define SP_NET_RETRIES 3
|
||||
#define SP_NET_WAIT_S 5
|
||||
|
||||
/* mark whether anything was streamed before an error: a retry after that
|
||||
* would print the same answer a second time */
|
||||
struct stream_guard {
|
||||
sp_stream_cb cb;
|
||||
void *ctx;
|
||||
int produced;
|
||||
};
|
||||
|
||||
static void
|
||||
guarded_stream(void *ctx, int kind, const char *text)
|
||||
{
|
||||
struct stream_guard *g = ctx;
|
||||
|
||||
/*
|
||||
* Only an answer (or a tool call) makes a retry unsafe. Reasoning that
|
||||
* was streamed before a provider cut the stream is not an answer: a
|
||||
* retry may repeat it, but a turn without one would be lost. This is
|
||||
* why "stream ended with no answer" after a reasoning-only stream used
|
||||
* to abort with no retry at all.
|
||||
*/
|
||||
if (kind == SP_STREAM_TEXT || kind == SP_STREAM_TOOL)
|
||||
g->produced = 1;
|
||||
if (g->cb != NULL)
|
||||
g->cb(g->ctx, kind, text);
|
||||
}
|
||||
|
||||
/*
|
||||
* Five seconds between retries; SPLINTER_RETRY_WAIT_MS overrides it so the
|
||||
* tests do not sleep through their own suite, and an operator can shorten a
|
||||
* long wait on a flaky link.
|
||||
*/
|
||||
static int
|
||||
retry_wait_ms(void)
|
||||
{
|
||||
static int ms = -1;
|
||||
|
||||
if (ms < 0) {
|
||||
const char *v = getenv("SPLINTER_RETRY_WAIT_MS");
|
||||
|
||||
ms = v != NULL && atoi(v) >= 0 ? atoi(v) : SP_NET_WAIT_S * 1000;
|
||||
}
|
||||
return ms;
|
||||
}
|
||||
|
||||
/* sleep in small steps, so Ctrl-C does not have to wait out a retry */
|
||||
static int
|
||||
retry_sleep(struct sp_agent *a, int ms)
|
||||
{
|
||||
int left = ms;
|
||||
|
||||
while (left > 0) {
|
||||
struct timespec ts;
|
||||
int step = left > 100 ? 100 : left;
|
||||
|
||||
if (a->cfg->cancel != NULL && *a->cfg->cancel)
|
||||
return 0;
|
||||
ts.tv_sec = 0;
|
||||
ts.tv_nsec = (long)step * 1000000L;
|
||||
(void)nanosleep(&ts, NULL);
|
||||
left -= step;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* One request, with the retry policy: a failure that left no text on the
|
||||
* screen is tried again up to three times, five seconds apart. After the
|
||||
* first streamed chunk a retry would duplicate the answer, so the turn fails
|
||||
* with the provider's error instead. A 401 or 404 is the configuration's
|
||||
* answer, not a transient fault, and is not repeated.
|
||||
*
|
||||
* 0: reply is the answer; 1: a usage limit was waited out, ask again;
|
||||
* -1: failed, err explains.
|
||||
*/
|
||||
static int
|
||||
agent_request(struct sp_agent *a, struct sp_conv *conv, struct sp_reply *reply,
|
||||
struct sp_buf *err, int *limit_tries)
|
||||
{
|
||||
struct stream_guard guard;
|
||||
int attempt;
|
||||
|
||||
memset(reply, 0, sizeof(*reply));
|
||||
guard.cb = a->cfg->stream;
|
||||
guard.ctx = a->cfg->stream_ctx;
|
||||
for (attempt = 0; ; attempt++) {
|
||||
int sent_rc;
|
||||
|
||||
guard.produced = 0;
|
||||
if (guard.cb != NULL && a->tr.send_stream != NULL)
|
||||
sent_rc = a->tr.send_stream(a->tr.ctx, conv, reply, err,
|
||||
guarded_stream, &guard);
|
||||
else
|
||||
sent_rc = a->tr.send(a->tr.ctx, conv, reply, err);
|
||||
if (sent_rc == 0 && reply->status >= 200 &&
|
||||
reply->status <= 299) {
|
||||
if (a->host != NULL && reply->served_by[0] != '\0')
|
||||
sp_host_set_served_by(a->host,
|
||||
reply->served_by);
|
||||
if (a->cfg->note != NULL)
|
||||
a->cfg->note(a->cfg->note_ctx, "");
|
||||
return 0;
|
||||
}
|
||||
if (sent_rc != 0) {
|
||||
sp_host_provider_account(a->host, a->tr.provider,
|
||||
a->tr.key_id, reply->status, 0, 0);
|
||||
} else {
|
||||
sp_host_provider_account(a->host, a->tr.provider,
|
||||
a->tr.key_id, reply->status,
|
||||
(size_t)(reply->tokens_in > 0 ?
|
||||
reply->tokens_in : 0),
|
||||
(size_t)(reply->tokens_out > 0 ?
|
||||
reply->tokens_out : 0));
|
||||
quota_hint(a->tr.provider, a->tr.key_id, reply->status,
|
||||
reply->retry_after_s);
|
||||
/* a refused call benches the provider the run is on */
|
||||
if (reply->status == 429 || reply->status == 402 ||
|
||||
reply->status == 529)
|
||||
sp_cooldown_set(sp_usage_active(),
|
||||
(long)time(NULL) +
|
||||
(reply->retry_after_s > 0 ?
|
||||
reply->retry_after_s : 300),
|
||||
"refused (HTTP limit)");
|
||||
sp_buf_printf(err, "agent: transport status %ld",
|
||||
reply->status);
|
||||
}
|
||||
if (limit_retry(a, err, reply->status, reply->retry_after_s,
|
||||
0, limit_tries)) {
|
||||
sp_reply_free(reply);
|
||||
return 1;
|
||||
}
|
||||
if (attempt < SP_NET_RETRIES && !guard.produced &&
|
||||
(sent_rc != 0 || reply->status == 0 ||
|
||||
reply->status >= 500)) {
|
||||
sp_logf("agent", "retry %d/%d in %dms: %s",
|
||||
attempt + 1, SP_NET_RETRIES, retry_wait_ms(),
|
||||
err->p != NULL ? err->p : "?");
|
||||
if (a->cfg->note != NULL) {
|
||||
char line[300];
|
||||
|
||||
snprintf(line, sizeof(line), sp_td("ui.retry_note",
|
||||
"retrying in %d s: %s"),
|
||||
retry_wait_ms() / 1000,
|
||||
err->p != NULL ? err->p : "no answer");
|
||||
a->cfg->note(a->cfg->note_ctx, line);
|
||||
}
|
||||
sp_buf_clear(err);
|
||||
sp_reply_free(reply);
|
||||
if (!retry_sleep(a, retry_wait_ms())) {
|
||||
sp_buf_puts(err,
|
||||
"agent: cancelled by operator");
|
||||
return -1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (a->cfg->note != NULL)
|
||||
a->cfg->note(a->cfg->note_ctx, "");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
static int
|
||||
agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
|
||||
struct sp_buf *answer, struct sp_buf *err)
|
||||
{
|
||||
struct sp_buf obs;
|
||||
size_t step, i;
|
||||
int rc = -1, limit_tries = 0;
|
||||
|
||||
if (sp_buf_init(&obs) != 0) {
|
||||
sp_buf_puts(err, "agent: out of memory");
|
||||
return -1;
|
||||
}
|
||||
if (resume) {
|
||||
if (!a->has_pending || a->pending_from > a->pending.ncalls) {
|
||||
sp_buf_puts(err, "agent: no turn is waiting for input");
|
||||
goto out;
|
||||
}
|
||||
for (i = a->pending_from; i < a->pending.ncalls; i++) {
|
||||
int r = run_one(a, conv, &a->pending.calls[i], 1,
|
||||
decision, &obs, err);
|
||||
|
||||
if (r != 0) {
|
||||
if (r > 0)
|
||||
sp_buf_puts(err, "agent: approval "
|
||||
"needed again");
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
sp_reply_free(&a->pending);
|
||||
a->has_pending = 0;
|
||||
a->pending_from = 0;
|
||||
}
|
||||
/*
|
||||
* max_steps counts tool rounds, not requests: a turn with N tool rounds
|
||||
* needs N+1 requests, because the last one carries the answer and runs
|
||||
* no tool. Counting requests against max_steps therefore refused the
|
||||
* answer of a turn that had spent exactly its budget and ended in
|
||||
* "step limit (8) reached without an answer" after eight rounds.
|
||||
* So 'step' keeps counting requests (it is also what a quota wait
|
||||
* rewinds), and the budget is judged by the guard below, which lets one
|
||||
* request past the last round - the one that may answer.
|
||||
*/
|
||||
for (step = 0; ; step++) {
|
||||
struct sp_reply reply;
|
||||
size_t sent;
|
||||
|
||||
memset(&reply, 0, sizeof(reply));
|
||||
if (a->cfg->cancel != NULL && *a->cfg->cancel) {
|
||||
sp_buf_puts(err, "agent: cancelled by operator");
|
||||
goto out;
|
||||
}
|
||||
if (a->cfg->steer != NULL) {
|
||||
struct sp_buf steer;
|
||||
|
||||
if (sp_buf_init(&steer) != 0)
|
||||
goto oom;
|
||||
if (a->cfg->steer(a->cfg->steer_ctx, &steer) > 0 &&
|
||||
steer.len > 0) {
|
||||
if (sp_conv_push(conv, "user", NULL, steer.p) != 0) {
|
||||
sp_buf_free(&steer);
|
||||
goto oom;
|
||||
}
|
||||
sp_logf("user", "%s", steer.p);
|
||||
if (a->sess != NULL)
|
||||
(void)sp_session_append(a->sess, "user",
|
||||
steer.p, err);
|
||||
}
|
||||
sp_buf_free(&steer);
|
||||
}
|
||||
/* compaction happens before the budget is judged, never after */
|
||||
if (a->host != NULL) {
|
||||
size_t cb = sp_conv_bytes(conv), cn = conv->n;
|
||||
size_t cbudget = a->cfg->max_bytes;
|
||||
|
||||
/*
|
||||
* The token threshold is the automatic compaction: past
|
||||
* it, the request is compacted to the target instead of
|
||||
* waiting for the byte ceiling.
|
||||
*/
|
||||
if (a->cfg->compact_threshold > 0 &&
|
||||
a->cfg->compact_target > 0 &&
|
||||
a->stats.last_in > a->cfg->compact_threshold)
|
||||
cbudget = a->cfg->compact_target * 4;
|
||||
if (sp_host_compact(a->host, conv, cbudget) > 0) {
|
||||
a->stats.compactions++;
|
||||
if (a->cfg != NULL && a->cfg->on_compact != NULL)
|
||||
a->cfg->on_compact(a->cfg->on_compact_ctx,
|
||||
cb, sp_conv_bytes(conv), cn, conv->n);
|
||||
}
|
||||
}
|
||||
sent = sp_conv_bytes(conv);
|
||||
if (a->cfg->max_bytes > 0 && sent > a->cfg->max_bytes) {
|
||||
sp_buf_printf(err, "agent: conversation budget exceeded "
|
||||
"(~%zu > %zu bytes); nothing sent", sent,
|
||||
a->cfg->max_bytes);
|
||||
goto out;
|
||||
}
|
||||
a->stats.bytes_sent += sent;
|
||||
a->stats.steps++;
|
||||
|
||||
{
|
||||
struct sp_prov_result pr;
|
||||
enum sp_prov_decision pd;
|
||||
|
||||
pd = sp_host_provider_preflight(a->host, a->tr.provider,
|
||||
a->tr.key_id, &pr);
|
||||
if (pd == SP_PROV_WAIT_QUOTA || pd == SP_PROV_DENY) {
|
||||
sp_buf_printf(err,
|
||||
"provider quota/policy: %s (ready_at=%ld retry_after=%lds)",
|
||||
pr.reason[0] ? pr.reason : "denied",
|
||||
pr.ready_at, pr.retry_after_s);
|
||||
if (pd == SP_PROV_WAIT_QUOTA &&
|
||||
limit_retry(a, err, 0, 0, pr.ready_at,
|
||||
&limit_tries)) {
|
||||
a->stats.steps--;
|
||||
step--;
|
||||
continue;
|
||||
}
|
||||
goto out;
|
||||
}
|
||||
if (pd == SP_PROV_DELAY && pr.retry_after_s > 0) {
|
||||
if (pr.retry_after_s <= 30)
|
||||
sleep((unsigned)pr.retry_after_s);
|
||||
else {
|
||||
sp_buf_printf(err,
|
||||
"provider quota/policy: %s (ready_at=%ld retry_after=%lds)",
|
||||
pr.reason[0] ? pr.reason : "delay",
|
||||
pr.ready_at, pr.retry_after_s);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
int req_rc = agent_request(a, conv, &reply, err,
|
||||
&limit_tries);
|
||||
|
||||
if (req_rc == 1) { /* limit waited out: ask again */
|
||||
a->stats.steps--;
|
||||
step--;
|
||||
continue;
|
||||
}
|
||||
if (req_rc != 0)
|
||||
goto out;
|
||||
}
|
||||
|
||||
sp_usage_record(sp_usage_active(), reply.tokens_in,
|
||||
reply.tokens_out);
|
||||
a->stats.tokens_in += (size_t)(reply.tokens_in > 0 ?
|
||||
reply.tokens_in : 0);
|
||||
a->stats.tokens_out += (size_t)(reply.tokens_out > 0 ?
|
||||
reply.tokens_out : 0);
|
||||
/*
|
||||
* Some providers do not report usage on a tool-call step. A zero
|
||||
* there is "unknown", not "the context became empty": keep the
|
||||
* last known prompt size, or the status bar drops to 0 after
|
||||
* every tool call.
|
||||
*/
|
||||
if (reply.tokens_in > 0) {
|
||||
a->stats.last_in = (size_t)reply.tokens_in;
|
||||
a->stats.last_cached = (size_t)(reply.tokens_cached > 0 ?
|
||||
reply.tokens_cached : 0);
|
||||
}
|
||||
sp_host_provider_account(a->host, a->tr.provider, a->tr.key_id,
|
||||
reply.status,
|
||||
(size_t)(reply.tokens_in > 0 ? reply.tokens_in : 0),
|
||||
(size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0));
|
||||
|
||||
if (reply.ncalls == 0) {
|
||||
const char *text = reply.content != NULL ?
|
||||
reply.content : "";
|
||||
|
||||
if (sp_buf_puts(answer, text) != 0 ||
|
||||
sp_conv_push(conv, "assistant", NULL, text) != 0) {
|
||||
sp_reply_free(&reply);
|
||||
goto oom;
|
||||
}
|
||||
if (a->sess != NULL &&
|
||||
sp_session_append(a->sess, "assistant", text,
|
||||
err) != 0) {
|
||||
sp_reply_free(&reply);
|
||||
goto out;
|
||||
}
|
||||
sp_reply_free(&reply);
|
||||
rc = 0;
|
||||
goto out;
|
||||
}
|
||||
|
||||
/*
|
||||
* The reply asks for a tool round. 'step' requests have been sent
|
||||
* so far, the first max_steps of which were allowed to run one
|
||||
* round each; when the budget is spent this one may not open
|
||||
* another. It is refused before the assistant message and its
|
||||
* calls enter the conversation, so the turn ends on the last
|
||||
* complete round instead of on a call with no observation.
|
||||
*/
|
||||
if (step >= a->cfg->max_steps) {
|
||||
sp_reply_free(&reply);
|
||||
sp_buf_printf(err,
|
||||
"agent: step limit (%zu) reached without an answer",
|
||||
a->cfg->max_steps);
|
||||
goto out;
|
||||
}
|
||||
|
||||
{
|
||||
struct sp_msg am;
|
||||
|
||||
memset(&am, 0, sizeof(am));
|
||||
am.role = "assistant";
|
||||
am.content = reply.content;
|
||||
am.calls = reply.calls_json;
|
||||
if (sp_conv_add(conv, &am) != 0) {
|
||||
sp_reply_free(&reply);
|
||||
goto oom;
|
||||
}
|
||||
}
|
||||
for (i = 0; i < reply.ncalls; i++) {
|
||||
int r = run_one(a, conv, &reply.calls[i], 0, 0, &obs,
|
||||
err);
|
||||
|
||||
if (r == 1) {
|
||||
/*
|
||||
* Pause with the assistant message already in the
|
||||
* conversation; the calls from here on have no
|
||||
* observation yet. The next run resumes them.
|
||||
*/
|
||||
a->pending = reply;
|
||||
memset(&reply, 0, sizeof(reply));
|
||||
a->pending_from = i;
|
||||
a->has_pending = 1;
|
||||
rc = SP_AGENT_INPUT_REQUIRED;
|
||||
goto out;
|
||||
}
|
||||
if (r != 0) {
|
||||
sp_reply_free(&reply);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
sp_reply_free(&reply);
|
||||
}
|
||||
|
||||
oom:
|
||||
sp_buf_puts(err, "agent: out of memory");
|
||||
out:
|
||||
sp_buf_free(&obs);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int
|
||||
sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
struct sp_conv local;
|
||||
struct sp_conv *conv;
|
||||
int rc;
|
||||
|
||||
if (a == NULL || a->reg == NULL || a->cfg == NULL)
|
||||
return -1;
|
||||
if (a->cfg->max_steps == 0)
|
||||
return -1;
|
||||
if (a->has_pending) {
|
||||
sp_buf_puts(err, "agent: a turn is waiting for input");
|
||||
return -1;
|
||||
}
|
||||
if (a->conv != NULL) {
|
||||
conv = a->conv;
|
||||
} else {
|
||||
sp_conv_init(&local);
|
||||
conv = &local;
|
||||
}
|
||||
sp_buf_clear(answer);
|
||||
/*
|
||||
* A turn gate runs before the model does. Kid mode ends the day here: the
|
||||
* child gets a sentence, the model gets nothing to answer.
|
||||
*/
|
||||
if (a->host != NULL) {
|
||||
char msg[256];
|
||||
|
||||
msg[0] = '\0';
|
||||
if (sp_host_turn_blocked(a->host, msg, sizeof(msg))) {
|
||||
sp_buf_puts(answer, msg[0] != '\0' ? msg :
|
||||
"today is over");
|
||||
if (conv == &local)
|
||||
sp_conv_free(&local);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
sp_host_turn(a->host);
|
||||
sp_logf("user", "%s", user_text != NULL ? user_text : "");
|
||||
if (sp_conv_push(conv, "user", NULL, user_text) != 0) {
|
||||
sp_buf_puts(err, "agent: out of memory");
|
||||
if (conv == &local)
|
||||
sp_conv_free(&local);
|
||||
return -1;
|
||||
}
|
||||
if (a->sess != NULL &&
|
||||
sp_session_append(a->sess, "user", user_text, err) != 0) {
|
||||
if (conv == &local)
|
||||
sp_conv_free(&local);
|
||||
return -1;
|
||||
}
|
||||
rc = agent_loop(a, conv, 0, 0, answer, err);
|
||||
if (rc == SP_AGENT_INPUT_REQUIRED && conv == &local) {
|
||||
/* nowhere to resume from: do not leave a dangling pending turn */
|
||||
sp_reply_free(&a->pending);
|
||||
a->has_pending = 0;
|
||||
a->pending_from = 0;
|
||||
sp_buf_puts(err, "agent: input required without a persistent "
|
||||
"conversation");
|
||||
rc = -1;
|
||||
}
|
||||
if (conv == &local)
|
||||
sp_conv_free(&local);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int
|
||||
sp_agent_resume(struct sp_agent *a, int decision, struct sp_buf *answer,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
if (a == NULL || a->cfg == NULL || a->conv == NULL || !a->has_pending) {
|
||||
sp_buf_puts(err, "agent: no turn is waiting for input");
|
||||
return -1;
|
||||
}
|
||||
sp_buf_clear(answer);
|
||||
return agent_loop(a, a->conv, 1, decision ? 1 : 0, answer, err);
|
||||
}
|
||||
@@ -1,393 +0,0 @@
|
||||
/* splinter -- agent profiles; see agents.h. */
|
||||
#include <ctype.h>
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
|
||||
#include "agents.h"
|
||||
|
||||
#define MAX_AGENTS 32
|
||||
|
||||
static char *
|
||||
trim(char *s)
|
||||
{
|
||||
char *e;
|
||||
|
||||
while (*s == ' ' || *s == '\t')
|
||||
s++;
|
||||
e = s + strlen(s);
|
||||
while (e > s && (e[-1] == ' ' || e[-1] == '\t' || e[-1] == '\r' ||
|
||||
e[-1] == '\n'))
|
||||
*--e = '\0';
|
||||
return s;
|
||||
}
|
||||
|
||||
/* "[a, b]" or a, "quoted": comma list without brackets or quotes */
|
||||
static void
|
||||
list_value(const char *v, char *out, size_t cap)
|
||||
{
|
||||
size_t n = 0;
|
||||
|
||||
for (; *v != '\0' && n + 1 < cap; v++) {
|
||||
if (*v == '[' || *v == ']' || *v == '"' || *v == '\'')
|
||||
continue;
|
||||
if (*v == ' ' && (n == 0 || out[n - 1] == ','))
|
||||
continue;
|
||||
out[n++] = *v;
|
||||
}
|
||||
while (n > 0 && (out[n - 1] == ' ' || out[n - 1] == ','))
|
||||
n--;
|
||||
out[n] = '\0';
|
||||
}
|
||||
|
||||
static int
|
||||
truthy(const char *v)
|
||||
{
|
||||
return !strcmp(v, "true") || !strcmp(v, "yes") || !strcmp(v, "on") ||
|
||||
!strcmp(v, "1");
|
||||
}
|
||||
|
||||
static int
|
||||
add_def(struct sp_agents *a, const struct sp_agent_def *d)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < a->n; i++)
|
||||
if (strcmp(a->v[i].name, d->name) == 0) {
|
||||
/* the later source replaces the earlier one */
|
||||
free(a->v[i].prompt);
|
||||
a->v[i] = *d;
|
||||
return 0;
|
||||
}
|
||||
if (a->n == MAX_AGENTS) {
|
||||
free(d->prompt);
|
||||
return -1;
|
||||
}
|
||||
if (a->v == NULL) {
|
||||
a->v = calloc(MAX_AGENTS, sizeof(*a->v));
|
||||
if (a->v == NULL) {
|
||||
free(d->prompt);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
a->v[a->n++] = *d;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* one markdown file into a definition; 1 added, 0 skipped */
|
||||
static int
|
||||
read_file(struct sp_agents *a, const char *path, const char *name)
|
||||
{
|
||||
FILE *f = fopen(path, "r");
|
||||
char line[2048];
|
||||
struct sp_agent_def d;
|
||||
struct sp_buf body;
|
||||
int in_front = 0, seen_front = 0, subagent = 0, first = 1;
|
||||
|
||||
if (f == NULL)
|
||||
return 0;
|
||||
memset(&d, 0, sizeof(d));
|
||||
d.max_auth = -1;
|
||||
d.autonomous = -1;
|
||||
snprintf(d.name, sizeof(d.name), "%s", name);
|
||||
snprintf(d.source, sizeof(d.source), "%s", path);
|
||||
if (sp_buf_init(&body) != 0) {
|
||||
fclose(f);
|
||||
return 0;
|
||||
}
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
char *l = line;
|
||||
|
||||
if (first && strncmp(l, "---", 3) == 0 && trim(l + 3)[0] == '\0') {
|
||||
in_front = 1;
|
||||
seen_front = 1;
|
||||
first = 0;
|
||||
continue;
|
||||
}
|
||||
first = 0;
|
||||
if (in_front) {
|
||||
char *colon, *k, *v;
|
||||
|
||||
if (strncmp(l, "---", 3) == 0 && trim(l + 3)[0] == '\0') {
|
||||
in_front = 0;
|
||||
continue;
|
||||
}
|
||||
if (*l == ' ' || *l == '\t' || *l == '#')
|
||||
continue; /* nested yaml: not ours */
|
||||
colon = strchr(l, ':');
|
||||
if (colon == NULL)
|
||||
continue;
|
||||
*colon = '\0';
|
||||
k = trim(l);
|
||||
v = trim(colon + 1);
|
||||
if (!strcmp(k, "description")) {
|
||||
size_t n;
|
||||
|
||||
if (*v == '"' || *v == '\'')
|
||||
v++;
|
||||
snprintf(d.description, sizeof(d.description), "%s", v);
|
||||
n = strlen(d.description);
|
||||
if (n > 0 && (d.description[n - 1] == '"' ||
|
||||
d.description[n - 1] == '\''))
|
||||
d.description[n - 1] = '\0';
|
||||
}
|
||||
else if (!strcmp(k, "model"))
|
||||
list_value(v, d.model, sizeof(d.model));
|
||||
else if (!strcmp(k, "tools")) {
|
||||
char t[32];
|
||||
|
||||
list_value(v, t, sizeof(t));
|
||||
if (!strcmp(t, "read"))
|
||||
d.max_auth = 0;
|
||||
else if (!strcmp(t, "mutate"))
|
||||
d.max_auth = 1;
|
||||
else if (!strcmp(t, "all"))
|
||||
d.max_auth = -1;
|
||||
} else if (!strcmp(k, "allow"))
|
||||
list_value(v, d.allow, sizeof(d.allow));
|
||||
else if (!strcmp(k, "deny"))
|
||||
list_value(v, d.deny, sizeof(d.deny));
|
||||
else if (!strcmp(k, "autonomous"))
|
||||
d.autonomous = truthy(v);
|
||||
else if (!strcmp(k, "mode")) {
|
||||
char t[32];
|
||||
|
||||
list_value(v, t, sizeof(t));
|
||||
subagent = !strcmp(t, "subagent");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
sp_buf_puts(&body, l);
|
||||
}
|
||||
fclose(f);
|
||||
(void)seen_front;
|
||||
if (subagent) {
|
||||
sp_buf_free(&body);
|
||||
return 0;
|
||||
}
|
||||
{
|
||||
char *p = body.p != NULL ? trim(body.p) : (char *)"";
|
||||
|
||||
d.prompt = strdup(p);
|
||||
}
|
||||
sp_buf_free(&body);
|
||||
if (d.prompt == NULL)
|
||||
return 0;
|
||||
return add_def(a, &d) == 0;
|
||||
}
|
||||
|
||||
static void
|
||||
read_dir(struct sp_agents *a, const char *dir)
|
||||
{
|
||||
DIR *dp = opendir(dir);
|
||||
struct dirent *e;
|
||||
char *names[64];
|
||||
size_t n = 0, i;
|
||||
|
||||
if (dp == NULL)
|
||||
return;
|
||||
while ((e = readdir(dp)) != NULL && n < 64) {
|
||||
size_t len = strlen(e->d_name);
|
||||
|
||||
if (len < 4 || strcmp(e->d_name + len - 3, ".md") != 0 ||
|
||||
e->d_name[0] == '.')
|
||||
continue;
|
||||
if (!strcasecmp(e->d_name, "README.md") ||
|
||||
!strcasecmp(e->d_name, "AGENTS.md"))
|
||||
continue;
|
||||
names[n] = strdup(e->d_name);
|
||||
if (names[n] != NULL)
|
||||
n++;
|
||||
}
|
||||
closedir(dp);
|
||||
for (i = 0; i < n; i++) {
|
||||
char path[900], name[48];
|
||||
size_t len = strlen(names[i]) - 3;
|
||||
|
||||
if (len >= sizeof(name))
|
||||
len = sizeof(name) - 1;
|
||||
memcpy(name, names[i], len);
|
||||
name[len] = '\0';
|
||||
snprintf(path, sizeof(path), "%.700s/%.150s", dir, names[i]);
|
||||
free(names[i]);
|
||||
(void)read_file(a, path, name);
|
||||
}
|
||||
}
|
||||
|
||||
static int
|
||||
cmp_def(const void *x, const void *y)
|
||||
{
|
||||
return strcmp(((const struct sp_agent_def *)x)->name,
|
||||
((const struct sp_agent_def *)y)->name);
|
||||
}
|
||||
|
||||
int
|
||||
sp_agents_load(struct sp_agents *a, const char *cwd, const char *home)
|
||||
{
|
||||
struct sp_agent_def b, p;
|
||||
char dirs[10][700];
|
||||
size_t nd = 0, i;
|
||||
char cur[700];
|
||||
|
||||
memset(a, 0, sizeof(*a));
|
||||
memset(&b, 0, sizeof(b));
|
||||
snprintf(b.name, sizeof(b.name), "build");
|
||||
snprintf(b.description, sizeof(b.description),
|
||||
"full access: reads, changes, builds, tests");
|
||||
b.max_auth = -1;
|
||||
b.autonomous = -1;
|
||||
b.prompt = strdup("");
|
||||
snprintf(b.source, sizeof(b.source), "(built in)");
|
||||
memset(&p, 0, sizeof(p));
|
||||
snprintf(p.name, sizeof(p.name), "plan");
|
||||
snprintf(p.description, sizeof(p.description),
|
||||
"read-only: analyse, weigh, plan; changes nothing");
|
||||
p.max_auth = 0;
|
||||
p.autonomous = -1;
|
||||
snprintf(p.allow, sizeof(p.allow), "delegate*,plan_task_*");
|
||||
p.prompt = strdup("You are in PLAN mode. You may read, search and "
|
||||
"analyse, but you change nothing: no edits, no commands that "
|
||||
"modify state. Work out what is wrong or what to do, weigh the "
|
||||
"options and end with a concrete plan: steps, files, risks. Ask "
|
||||
"the user where a decision is theirs. For analysis and decisions "
|
||||
"you may hand the question to another model with the delegate "
|
||||
"tool. The user switches to build mode (Tab) to have it done.");
|
||||
snprintf(p.source, sizeof(p.source), "(built in)");
|
||||
if (b.prompt == NULL || p.prompt == NULL) {
|
||||
free(b.prompt);
|
||||
free(p.prompt);
|
||||
return -1;
|
||||
}
|
||||
add_def(a, &b);
|
||||
add_def(a, &p);
|
||||
|
||||
/* the user's, then the project's from far to near: the nearest wins */
|
||||
if (home != NULL && *home != '\0') {
|
||||
snprintf(dirs[nd++], sizeof(dirs[0]), "%s/.splinter/agents", home);
|
||||
}
|
||||
if (cwd != NULL && *cwd != '\0') {
|
||||
char chain[8][700];
|
||||
size_t nc = 0, k;
|
||||
|
||||
snprintf(cur, sizeof(cur), "%s", cwd);
|
||||
while (nc < 8) {
|
||||
snprintf(chain[nc++], sizeof(chain[0]), "%s", cur);
|
||||
if (home != NULL && strcmp(cur, home) == 0)
|
||||
break;
|
||||
{
|
||||
char *slash = strrchr(cur, '/');
|
||||
|
||||
if (slash == NULL || slash == cur)
|
||||
break;
|
||||
*slash = '\0';
|
||||
}
|
||||
}
|
||||
for (k = nc; k > 0 && nd + 2 <= 10; k--) {
|
||||
snprintf(dirs[nd++], sizeof(dirs[0]), "%s/.agents",
|
||||
chain[k - 1]);
|
||||
snprintf(dirs[nd++], sizeof(dirs[0]), "%s/.splinter/agents",
|
||||
chain[k - 1]);
|
||||
}
|
||||
}
|
||||
for (i = 0; i < nd; i++) {
|
||||
read_dir(a, dirs[i]);
|
||||
}
|
||||
/* build and plan stay first; the rest by name */
|
||||
if (a->n > 2)
|
||||
qsort(a->v + 2, a->n - 2, sizeof(*a->v), cmp_def);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void
|
||||
sp_agents_free(struct sp_agents *a)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < a->n; i++)
|
||||
free(a->v[i].prompt);
|
||||
free(a->v);
|
||||
memset(a, 0, sizeof(*a));
|
||||
}
|
||||
|
||||
int
|
||||
sp_agents_find(const struct sp_agents *a, const char *name)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; name != NULL && i < a->n; i++)
|
||||
if (strcmp(a->v[i].name, name) == 0)
|
||||
return (int)i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
void
|
||||
sp_agent_policy(const struct sp_agent_def *d, struct sp_tool_policy *p)
|
||||
{
|
||||
memset(p, 0, sizeof(*p));
|
||||
snprintf(p->name, sizeof(p->name), "%s", d->name);
|
||||
p->max_auth = d->max_auth;
|
||||
snprintf(p->allow, sizeof(p->allow), "%s", d->allow);
|
||||
snprintf(p->deny, sizeof(p->deny), "%s", d->deny);
|
||||
}
|
||||
|
||||
int
|
||||
sp_agent_prompt(const struct sp_agent_def *d, const char *base,
|
||||
struct sp_buf *out)
|
||||
{
|
||||
if (sp_buf_puts(out, base != NULL ? base : "") != 0)
|
||||
return -1;
|
||||
if (d->prompt != NULL && d->prompt[0] != '\0')
|
||||
return sp_buf_printf(out, "\n\n[agent: %s]\n%s", d->name, d->prompt);
|
||||
return 0;
|
||||
}
|
||||
|
||||
char *
|
||||
sp_agents_base(const struct sp_conv *conv)
|
||||
{
|
||||
if (conv != NULL && conv->n > 0 && conv->v[0].role != NULL &&
|
||||
strcmp(conv->v[0].role, "system") == 0 && conv->v[0].content != NULL)
|
||||
return strdup(conv->v[0].content);
|
||||
return strdup("");
|
||||
}
|
||||
|
||||
int
|
||||
sp_agents_activate(struct sp_agent *ag, const struct sp_agent_def *d,
|
||||
const char *base, struct sp_tool_policy *pol)
|
||||
{
|
||||
struct sp_buf b;
|
||||
int rc = 0;
|
||||
|
||||
sp_agent_policy(d, pol);
|
||||
ag->policy = pol;
|
||||
if (ag->conv == NULL)
|
||||
return 0;
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return -1;
|
||||
if (sp_agent_prompt(d, base, &b) != 0) {
|
||||
sp_buf_free(&b);
|
||||
return -1;
|
||||
}
|
||||
if (ag->conv->n > 0 && ag->conv->v[0].role != NULL &&
|
||||
strcmp(ag->conv->v[0].role, "system") == 0) {
|
||||
char *nc = strdup(b.p != NULL ? b.p : "");
|
||||
|
||||
if (nc == NULL)
|
||||
rc = -1;
|
||||
else {
|
||||
free(ag->conv->v[0].content);
|
||||
ag->conv->v[0].content = nc;
|
||||
}
|
||||
} else if (b.len > 0) {
|
||||
struct sp_msg m;
|
||||
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = "system";
|
||||
m.content = b.p;
|
||||
rc = sp_conv_insert(ag->conv, 0, &m);
|
||||
}
|
||||
sp_buf_free(&b);
|
||||
return rc;
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
/* splinter -- agent profiles: build, plan and the ones you write. */
|
||||
#ifndef SP_AGENTS_H
|
||||
#define SP_AGENTS_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include "splinter.h"
|
||||
|
||||
/*
|
||||
* A profile is a way of working: a prompt, the tools it may use, optionally a
|
||||
* model. Tab in the chat switches through them; build (everything) and plan
|
||||
* (read-only, analyses and decides) are always there, and a file of the same
|
||||
* name replaces them.
|
||||
*
|
||||
* A profile is a markdown file, the way opencode does it:
|
||||
*
|
||||
* ---
|
||||
* description: Reviews without touching anything
|
||||
* model: analyst # what -m takes: provider, pool, provider/model
|
||||
* tools: read # all (default) | mutate | read
|
||||
* allow: [delegate*] # names (or prefix*) allowed beyond that
|
||||
* deny: [run] # names never allowed
|
||||
* autonomous: false # run mutating tools without asking?
|
||||
* ---
|
||||
* The prompt: added to the system prompt while this profile is active.
|
||||
*
|
||||
* Where: ~/.splinter/agents/, and, from the working directory up to your home,
|
||||
* .splinter/agents/ and .agents/ (the nearest wins). A file with
|
||||
* "mode: subagent" is not a profile for the chat and is skipped.
|
||||
*/
|
||||
struct sp_agent_def {
|
||||
char name[48];
|
||||
char description[200];
|
||||
char model[96];
|
||||
int max_auth; /* -1 any */
|
||||
int autonomous; /* -1: as configured */
|
||||
char allow[512];
|
||||
char deny[512];
|
||||
char *prompt;
|
||||
char source[900]; /* the file, or "(built in)" */
|
||||
};
|
||||
|
||||
struct sp_agents {
|
||||
struct sp_agent_def *v;
|
||||
size_t n;
|
||||
};
|
||||
|
||||
/* built-ins first (build, plan), then the others by name */
|
||||
int sp_agents_load(struct sp_agents *, const char *cwd, const char *home);
|
||||
void sp_agents_free(struct sp_agents *);
|
||||
int sp_agents_find(const struct sp_agents *, const char *name);
|
||||
/* the tool policy of a profile */
|
||||
void sp_agent_policy(const struct sp_agent_def *, struct sp_tool_policy *);
|
||||
/* base prompt + the profile's prompt, into 'out' */
|
||||
int sp_agent_prompt(const struct sp_agent_def *, const char *base,
|
||||
struct sp_buf *out);
|
||||
|
||||
/* the system prompt the conversation started with (malloc'ed, "" if none) */
|
||||
char *sp_agents_base(const struct sp_conv *);
|
||||
/*
|
||||
* Make 'd' the agent's profile: its tool policy (stored in 'pol', which must
|
||||
* outlive the agent) and its prompt on top of 'base' in the system message.
|
||||
*/
|
||||
int sp_agents_activate(struct sp_agent *, const struct sp_agent_def *,
|
||||
const char *base, struct sp_tool_policy *pol);
|
||||
|
||||
#endif
|
||||
@@ -1,945 +0,0 @@
|
||||
/*
|
||||
* 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_opts(const struct sp_conv *conv, const char *model,
|
||||
const struct sp_registry *reg, int streaming, int oauth,
|
||||
const struct sp_gen_opts *gen, 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, mt;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/* the API requires max_tokens; a caller's value wins inside its range */
|
||||
mt = max_tokens();
|
||||
if (gen != NULL && gen->have_max_tokens &&
|
||||
gen->max_tokens >= 256 && gen->max_tokens <= 128000)
|
||||
mt = (int)gen->max_tokens;
|
||||
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,",
|
||||
mt, streaming ? "true" : "false") != 0)
|
||||
goto out;
|
||||
if (gen != NULL && gen->have_temperature &&
|
||||
sp_buf_printf(out, "\"temperature\":%.17g,",
|
||||
gen->temperature) != 0)
|
||||
goto out;
|
||||
if (gen != NULL && gen->have_top_p &&
|
||||
sp_buf_printf(out, "\"top_p\":%.17g,", gen->top_p) != 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 */
|
||||
/*
|
||||
* Same role as the message before (observations of a parallel
|
||||
* round, or a user turn that failed and was asked again): its
|
||||
* blocks join the open message. The message stays open until
|
||||
* the role changes -- closing it first put the blocks outside
|
||||
* any message, and the API answered 400 "messages.N.role".
|
||||
*/
|
||||
if (nmsg > 0 && prev_assistant == assistant) {
|
||||
if (sp_buf_puts(out, ",") != 0 ||
|
||||
sp_buf_add(out, blocks.p, blocks.len) != 0)
|
||||
goto out;
|
||||
continue;
|
||||
}
|
||||
if (nmsg > 0 && sp_buf_puts(out, "]},") != 0)
|
||||
goto out;
|
||||
nmsg++;
|
||||
if (sp_buf_printf(out, "{\"role\":\"%s\",\"content\":[",
|
||||
assistant ? "assistant" : "user") != 0 ||
|
||||
sp_buf_add(out, blocks.p, blocks.len) != 0)
|
||||
goto out;
|
||||
prev_assistant = assistant;
|
||||
}
|
||||
if (nmsg > 0 && sp_buf_puts(out, "]}") != 0)
|
||||
goto out;
|
||||
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;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
return sp_anthropic_request_opts(conv, model, reg, streaming, oauth,
|
||||
NULL, out);
|
||||
}
|
||||
|
||||
/* 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;
|
||||
}
|
||||
|
||||
static void as_usage_set(long *in, long *cached, const mcp_json *usage);
|
||||
|
||||
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) {
|
||||
long in = 0, cached = 0;
|
||||
int pout = mcp_arg_int(usage, "output_tokens", -1);
|
||||
|
||||
as_usage_set(&in, &cached, usage);
|
||||
out->tokens_in = in;
|
||||
out->tokens_cached = cached;
|
||||
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;
|
||||
long tokens_cached;
|
||||
int done;
|
||||
};
|
||||
|
||||
/*
|
||||
* Anthropic reports the prompt in pieces: input_tokens excludes the cache
|
||||
* reads and writes. The context the request carried is the sum, and the cache
|
||||
* share is the read part. A later usage block with no cache fields (the
|
||||
* message_delta event) must not throw that away.
|
||||
*/
|
||||
static void
|
||||
as_usage_set(long *in, long *cached, const mcp_json *usage)
|
||||
{
|
||||
int pin = mcp_arg_int(usage, "input_tokens", -1);
|
||||
int cr = mcp_arg_int(usage, "cache_read_input_tokens", -1);
|
||||
int cc = mcp_arg_int(usage, "cache_creation_input_tokens", -1);
|
||||
|
||||
if (pin >= 0) {
|
||||
if (*in == 0 || cr >= 0 || cc >= 0) {
|
||||
*in = (pin > 0 ? pin : 0) +
|
||||
(cr > 0 ? cr : 0) + (cc > 0 ? cc : 0);
|
||||
if (cr >= 0)
|
||||
*cached = cr > 0 ? cr : 0;
|
||||
}
|
||||
} else if (cr >= 0) {
|
||||
*in += cr > 0 ? cr : 0;
|
||||
*cached = cr > 0 ? cr : 0;
|
||||
}
|
||||
}
|
||||
|
||||
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 == '\t')
|
||||
line++;
|
||||
if (*line == '\0')
|
||||
return 0; /* an empty data line is a keepalive */
|
||||
if (strncmp(line, "[DONE]", 6) == 0) {
|
||||
s->done = 1;
|
||||
return 0;
|
||||
}
|
||||
v = mcp_parse(line);
|
||||
if (v == NULL) {
|
||||
if (*line != '{')
|
||||
return 0; /* text keepalive, not a JSON event */
|
||||
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)
|
||||
as_usage_set(&s->tokens_in, &s->tokens_cached, usage);
|
||||
} else if (strcmp(type, "message_delta") == 0) {
|
||||
usage = mcp_arg(v, "usage");
|
||||
if (usage != NULL) {
|
||||
int outt = mcp_arg_int(usage, "output_tokens", -1);
|
||||
|
||||
if (outt >= 0)
|
||||
s->tokens_out = outt;
|
||||
as_usage_set(&s->tokens_in, &s->tokens_cached, usage);
|
||||
}
|
||||
} 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->tokens_cached = s->tokens_cached;
|
||||
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);
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
/*
|
||||
* splinter -- base64 for A2A raw parts.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Small on purpose: A2A's raw part is base64, and the harness only needs to
|
||||
* turn a text/plain part back into text. Whitespace is ignored, padding is
|
||||
* optional, and a character outside the alphabet is an error rather than a
|
||||
* silently different byte.
|
||||
*/
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "b64.h"
|
||||
|
||||
static int
|
||||
b64_val(unsigned char c)
|
||||
{
|
||||
if (c >= 'A' && c <= 'Z')
|
||||
return c - 'A';
|
||||
if (c >= 'a' && c <= 'z')
|
||||
return c - 'a' + 26;
|
||||
if (c >= '0' && c <= '9')
|
||||
return c - '0' + 52;
|
||||
if (c == '+')
|
||||
return 62;
|
||||
if (c == '/')
|
||||
return 63;
|
||||
return -1;
|
||||
}
|
||||
|
||||
int
|
||||
sp_b64_decode(const char *in, size_t len, struct sp_buf *out)
|
||||
{
|
||||
unsigned acc = 0;
|
||||
int bits = 0;
|
||||
size_t i;
|
||||
int pad = 0;
|
||||
|
||||
if (in == NULL || out == NULL)
|
||||
return -1;
|
||||
for (i = 0; i < len; i++) {
|
||||
unsigned char c = (unsigned char)in[i];
|
||||
int v;
|
||||
|
||||
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
|
||||
continue;
|
||||
if (c == '=') {
|
||||
pad = 1;
|
||||
continue;
|
||||
}
|
||||
if (pad)
|
||||
return -1; /* data after padding */
|
||||
v = b64_val(c);
|
||||
if (v < 0)
|
||||
return -1;
|
||||
acc = (acc << 6) | (unsigned)v;
|
||||
bits += 6;
|
||||
if (bits >= 8) {
|
||||
char ch;
|
||||
|
||||
bits -= 8;
|
||||
ch = (char)((acc >> bits) & 0xff);
|
||||
if (sp_buf_add(out, &ch, 1) != 0)
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_b64_encode(const void *data, size_t len, struct sp_buf *out)
|
||||
{
|
||||
static const char tab[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
const unsigned char *p = data;
|
||||
size_t i;
|
||||
|
||||
if (out == NULL || (data == NULL && len > 0))
|
||||
return -1;
|
||||
for (i = 0; i + 2 < len; i += 3) {
|
||||
char o[4];
|
||||
|
||||
o[0] = tab[p[i] >> 2];
|
||||
o[1] = tab[((p[i] & 0x03) << 4) | (p[i + 1] >> 4)];
|
||||
o[2] = tab[((p[i + 1] & 0x0f) << 2) | (p[i + 2] >> 6)];
|
||||
o[3] = tab[p[i + 2] & 0x3f];
|
||||
if (sp_buf_add(out, o, 4) != 0)
|
||||
return -1;
|
||||
}
|
||||
if (i < len) {
|
||||
unsigned a = p[i];
|
||||
unsigned b = i + 1 < len ? p[i + 1] : 0;
|
||||
char o[4];
|
||||
|
||||
o[0] = tab[a >> 2];
|
||||
o[1] = tab[((a & 0x03) << 4) | (b >> 4)];
|
||||
o[2] = i + 1 < len ? tab[(b & 0x0f) << 2] : '=';
|
||||
o[3] = '=';
|
||||
if (sp_buf_add(out, o, 4) != 0)
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
/* splinter -- base64 for A2A raw parts. */
|
||||
#ifndef SPLINTER_B64_H
|
||||
#define SPLINTER_B64_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_buf;
|
||||
|
||||
/*
|
||||
* Decode standard base64 (A-Z a-z 0-9 + /, '=' padding, whitespace ignored)
|
||||
* and append the bytes to 'out'. Padding is optional. Returns 0, or -1 for an
|
||||
* invalid character or allocation failure.
|
||||
*/
|
||||
int sp_b64_decode(const char *in, size_t len, struct sp_buf *out);
|
||||
|
||||
/*
|
||||
* The other direction: append the base64 of 'data' (with padding) to 'out'.
|
||||
* Returns 0, or -1 when memory runs out.
|
||||
*/
|
||||
int sp_b64_encode(const void *data, size_t len, struct sp_buf *out);
|
||||
|
||||
#endif /* SPLINTER_B64_H */
|
||||
@@ -1,171 +0,0 @@
|
||||
/*
|
||||
* splinter -- growable buffers, JSON escaping.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
#define SP_MIN_CAP 64
|
||||
|
||||
int
|
||||
sp_buf_reserve(struct sp_buf *b, size_t want)
|
||||
{
|
||||
size_t ncap;
|
||||
char *np;
|
||||
|
||||
if (want <= b->cap)
|
||||
return 0;
|
||||
ncap = b->cap ? b->cap : SP_MIN_CAP;
|
||||
while (ncap < want) {
|
||||
if (ncap > (size_t)-1 / 2) {
|
||||
errno = ENOMEM;
|
||||
return -1;
|
||||
}
|
||||
ncap *= 2;
|
||||
}
|
||||
np = realloc(b->p, ncap);
|
||||
if (np == NULL)
|
||||
return -1;
|
||||
b->p = np;
|
||||
b->cap = ncap;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_buf_init(struct sp_buf *b)
|
||||
{
|
||||
memset(b, 0, sizeof(*b));
|
||||
if (sp_buf_reserve(b, SP_MIN_CAP) != 0)
|
||||
return -1;
|
||||
b->p[0] = '\0';
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_buf_add(struct sp_buf *b, const char *data, size_t n)
|
||||
{
|
||||
if (n == 0)
|
||||
return 0;
|
||||
/* keep one spare byte for the NUL we always maintain */
|
||||
if (b->len + n + 1 < b->len) { /* overflow of the sum */
|
||||
errno = ENOMEM;
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_reserve(b, b->len + n + 1) != 0)
|
||||
return -1;
|
||||
memcpy(b->p + b->len, data, n);
|
||||
b->len += n;
|
||||
b->p[b->len] = '\0';
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_buf_puts(struct sp_buf *b, const char *s)
|
||||
{
|
||||
return sp_buf_add(b, s, strlen(s));
|
||||
}
|
||||
|
||||
int
|
||||
sp_buf_printf(struct sp_buf *b, const char *fmt, ...)
|
||||
{
|
||||
va_list ap, ap2;
|
||||
int need;
|
||||
|
||||
va_start(ap, fmt);
|
||||
va_copy(ap2, ap);
|
||||
need = vsnprintf(NULL, 0, fmt, ap);
|
||||
va_end(ap);
|
||||
if (need < 0) {
|
||||
va_end(ap2);
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_reserve(b, b->len + (size_t)need + 1) != 0) {
|
||||
va_end(ap2);
|
||||
return -1;
|
||||
}
|
||||
vsnprintf(b->p + b->len, b->cap - b->len, fmt, ap2);
|
||||
va_end(ap2);
|
||||
b->len += (size_t)need;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void
|
||||
sp_buf_clear(struct sp_buf *b)
|
||||
{
|
||||
b->len = 0;
|
||||
if (b->p != NULL)
|
||||
b->p[0] = '\0';
|
||||
}
|
||||
|
||||
void
|
||||
sp_buf_free(struct sp_buf *b)
|
||||
{
|
||||
free(b->p);
|
||||
memset(b, 0, sizeof(*b));
|
||||
}
|
||||
|
||||
int
|
||||
sp_json_escape(struct sp_buf *b, const char *s)
|
||||
{
|
||||
static const char hex[] = "0123456789abcdef";
|
||||
const unsigned char *p = (const unsigned char *)s;
|
||||
|
||||
while (*p != '\0') {
|
||||
unsigned char c = *p;
|
||||
|
||||
switch (c) {
|
||||
case '"': if (sp_buf_puts(b, "\\\"") != 0) return -1; p++; break;
|
||||
case '\\': if (sp_buf_puts(b, "\\\\") != 0) return -1; p++; break;
|
||||
case '\n': if (sp_buf_puts(b, "\\n") != 0) return -1; p++; break;
|
||||
case '\r': if (sp_buf_puts(b, "\\r") != 0) return -1; p++; break;
|
||||
case '\t': if (sp_buf_puts(b, "\\t") != 0) return -1; p++; break;
|
||||
default:
|
||||
if (c < 0x20) {
|
||||
char esc[7] = { '\\', 'u', '0', '0',
|
||||
hex[c >> 4], hex[c & 0xf], '\0' };
|
||||
if (sp_buf_puts(b, esc) != 0)
|
||||
return -1;
|
||||
p++;
|
||||
} else if (c < 0x80) {
|
||||
if (sp_buf_add(b, (const char *)p, 1) != 0)
|
||||
return -1;
|
||||
p++;
|
||||
} else {
|
||||
/* Valid UTF-8 passes through; invalid bytes become \u00XX
|
||||
* so the JSON string stays well-formed UTF-8. */
|
||||
size_t n = 0;
|
||||
|
||||
if ((c & 0xe0) == 0xc0 && (p[1] & 0xc0) == 0x80 &&
|
||||
c >= 0xc2)
|
||||
n = 2;
|
||||
else if ((c & 0xf0) == 0xe0 && (p[1] & 0xc0) == 0x80 &&
|
||||
(p[2] & 0xc0) == 0x80)
|
||||
n = 3;
|
||||
else if ((c & 0xf8) == 0xf0 && (p[1] & 0xc0) == 0x80 &&
|
||||
(p[2] & 0xc0) == 0x80 && (p[3] & 0xc0) == 0x80 &&
|
||||
c <= 0xf4)
|
||||
n = 4;
|
||||
if (n > 0) {
|
||||
if (sp_buf_add(b, (const char *)p, n) != 0)
|
||||
return -1;
|
||||
p += n;
|
||||
} else {
|
||||
char esc[7] = { '\\', 'u', '0', '0',
|
||||
hex[c >> 4], hex[c & 0xf], '\0' };
|
||||
if (sp_buf_puts(b, esc) != 0)
|
||||
return -1;
|
||||
p++;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,223 +0,0 @@
|
||||
/*
|
||||
* splinter -- slash commands that are just programs.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Anything executable in ~/.splinter/commands/ becomes /name. It gets the rest
|
||||
* of the line as its first argument, and whatever it prints goes to the model as
|
||||
* context - not to the operator as a message. That is the point: a command is a
|
||||
* way to hand the model something it cannot get itself (a git log, a database
|
||||
* query, a screenshot's OCR), without the operator copying text around.
|
||||
*
|
||||
* Rule: the program decides what to print; the harness decides that the model
|
||||
* sees it. A program that prints nothing is a bug the operator will notice,
|
||||
* because the model will be told exactly that.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "cmdscript.h"
|
||||
|
||||
#define CMD_TIMEOUT_MS 300000
|
||||
#define CMD_MAX_BYTES (4u << 20)
|
||||
|
||||
/*
|
||||
* Where the programs live: $SPLINTER_COMMANDS_DIR, else ~/.splinter/commands.
|
||||
*
|
||||
* Not the session directory: commands are the operator's tools, not a session's
|
||||
* private property - the first version keyed them off --session and found
|
||||
* nothing whenever a session lived anywhere else.
|
||||
*/
|
||||
int
|
||||
sp_cmdscript_dir(const char *session_dir, char *buf, size_t len)
|
||||
{
|
||||
const char *env = getenv("SPLINTER_COMMANDS_DIR");
|
||||
const char *home = getenv("HOME");
|
||||
|
||||
(void)session_dir;
|
||||
if (env != NULL && *env != '\0') {
|
||||
snprintf(buf, len, "%s", env);
|
||||
return 0;
|
||||
}
|
||||
if (home == NULL || *home == '\0')
|
||||
return -1;
|
||||
snprintf(buf, len, "%s/.splinter/commands", home);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Is there an executable by that name? No paths, no dots: /foo is a name. */
|
||||
int
|
||||
sp_cmdscript_exists(const char *dir, const char *name)
|
||||
{
|
||||
char path[700];
|
||||
size_t i;
|
||||
|
||||
if (dir == NULL || name == NULL || *name == '\0')
|
||||
return 0;
|
||||
for (i = 0; name[i] != '\0'; i++)
|
||||
if (!((name[i] >= 'a' && name[i] <= 'z') ||
|
||||
(name[i] >= 'A' && name[i] <= 'Z') ||
|
||||
(name[i] >= '0' && name[i] <= '9') ||
|
||||
name[i] == '-' || name[i] == '_' || name[i] == '.'))
|
||||
return 0;
|
||||
if (strstr(name, "..") != NULL)
|
||||
return 0;
|
||||
snprintf(path, sizeof(path), "%s/%s", dir, name);
|
||||
return access(path, X_OK) == 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_cmdscript_list(const char *dir, struct sp_buf *out)
|
||||
{
|
||||
DIR *d;
|
||||
struct dirent *e;
|
||||
int n = 0;
|
||||
|
||||
d = opendir(dir);
|
||||
if (d == NULL)
|
||||
return 0;
|
||||
while ((e = readdir(d)) != NULL) {
|
||||
char path[700];
|
||||
|
||||
if (e->d_name[0] == '.')
|
||||
continue;
|
||||
snprintf(path, sizeof(path), "%s/%s", dir, e->d_name);
|
||||
if (access(path, X_OK) != 0)
|
||||
continue;
|
||||
sp_buf_printf(out, "/%s ", e->d_name);
|
||||
n++;
|
||||
}
|
||||
closedir(d);
|
||||
return n;
|
||||
}
|
||||
|
||||
/*
|
||||
* Run it. The argument is the whole rest of the line, one string: a command
|
||||
* that wants words can split it itself, and a command that takes a commit
|
||||
* message keeps its spaces.
|
||||
*/
|
||||
int
|
||||
sp_cmdscript_run(const char *dir, const char *name, const char *args,
|
||||
struct sp_buf *out, struct sp_buf *err)
|
||||
{
|
||||
char path[700];
|
||||
int fds[2];
|
||||
pid_t child;
|
||||
|
||||
snprintf(path, sizeof(path), "%s/%s", dir, name);
|
||||
if (pipe(fds) != 0) {
|
||||
sp_buf_printf(err, "%s: pipe: %s", name, strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
child = fork();
|
||||
if (child < 0) {
|
||||
sp_buf_printf(err, "%s: fork: %s", name, strerror(errno));
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
return -1;
|
||||
}
|
||||
if (child == 0) {
|
||||
char *argv[3];
|
||||
int devnull = open("/dev/null", O_RDONLY);
|
||||
|
||||
(void)dup2(fds[1], STDOUT_FILENO);
|
||||
(void)dup2(fds[1], STDERR_FILENO);
|
||||
if (devnull >= 0) {
|
||||
(void)dup2(devnull, STDIN_FILENO);
|
||||
close(devnull);
|
||||
}
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
argv[0] = path;
|
||||
argv[1] = (char *)(args != NULL ? args : "");
|
||||
argv[2] = NULL;
|
||||
execv(path, argv);
|
||||
fprintf(stderr, "%s: %s\n", path, strerror(errno));
|
||||
_exit(126);
|
||||
}
|
||||
close(fds[1]);
|
||||
{
|
||||
struct pollfd pfd;
|
||||
char chunk[4096];
|
||||
int timed_out = 0;
|
||||
|
||||
for (;;) {
|
||||
ssize_t got;
|
||||
|
||||
pfd.fd = fds[0];
|
||||
pfd.events = POLLIN;
|
||||
if (poll(&pfd, 1, CMD_TIMEOUT_MS) <= 0) {
|
||||
(void)kill(child, SIGKILL);
|
||||
timed_out = 1;
|
||||
break;
|
||||
}
|
||||
got = read(fds[0], chunk, sizeof(chunk));
|
||||
if (got <= 0)
|
||||
break;
|
||||
if (out->len + (size_t)got > CMD_MAX_BYTES) {
|
||||
sp_buf_puts(out, "\n[command output truncated]\n");
|
||||
(void)kill(child, SIGKILL);
|
||||
break;
|
||||
}
|
||||
if (sp_buf_add(out, chunk, (size_t)got) != 0)
|
||||
break;
|
||||
}
|
||||
close(fds[0]);
|
||||
{
|
||||
int st = 0;
|
||||
|
||||
(void)waitpid(child, &st, 0);
|
||||
if (timed_out) {
|
||||
sp_buf_printf(err, "/%s: timed out after %d s",
|
||||
name, CMD_TIMEOUT_MS / 1000);
|
||||
return -1;
|
||||
}
|
||||
if (WIFEXITED(st) && WEXITSTATUS(st) != 0)
|
||||
sp_buf_printf(out, "[exit status %d]\n",
|
||||
WEXITSTATUS(st));
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The entry point UI and gateway share: run /name and hand back the text the
|
||||
* model should see, already framed so it cannot be mistaken for the user's own
|
||||
* words.
|
||||
*/
|
||||
int
|
||||
sp_slash_script(const char *dir, const char *name, const char *args,
|
||||
struct sp_buf *out, struct sp_buf *err)
|
||||
{
|
||||
struct sp_buf raw, errb;
|
||||
|
||||
(void)err;
|
||||
if (sp_buf_init(&raw) != 0 || sp_buf_init(&errb) != 0)
|
||||
return -1;
|
||||
if (sp_cmdscript_run(dir, name, args, &raw, &errb) != 0) {
|
||||
sp_buf_printf(out, "error: %s", errb.p != NULL ? errb.p : "failed");
|
||||
sp_buf_free(&raw);
|
||||
sp_buf_free(&errb);
|
||||
return 0;
|
||||
}
|
||||
if (raw.p == NULL || raw.p[0] == '\0')
|
||||
sp_buf_printf(out, "Der Befehl /%s hat nichts ausgegeben.", name);
|
||||
else
|
||||
sp_buf_printf(out, "Ausgabe von /%s%s%s:\n\n%s", name,
|
||||
args != NULL && *args != '\0' ? " " : "",
|
||||
args != NULL ? args : "", raw.p);
|
||||
sp_buf_free(&raw);
|
||||
sp_buf_free(&errb);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
/*
|
||||
* splinter -- programs as slash commands.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_CMDSCRIPT_H
|
||||
#define SPLINTER_CMDSCRIPT_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <dirent.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
int sp_cmdscript_dir(const char *session_dir, char *buf, size_t len);
|
||||
int sp_cmdscript_exists(const char *dir, const char *name);
|
||||
int sp_cmdscript_list(const char *dir, struct sp_buf *out);
|
||||
int sp_cmdscript_run(const char *dir, const char *name, const char *args,
|
||||
struct sp_buf *out, struct sp_buf *err);
|
||||
|
||||
#endif /* SPLINTER_CMDSCRIPT_H */
|
||||
@@ -1,909 +0,0 @@
|
||||
/* splinter -- config block syntax; see confblock.h. */
|
||||
#include <ctype.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "confblock.h"
|
||||
|
||||
#define MAX_ITEMS 64
|
||||
#define MAX_ENTRIES 64
|
||||
|
||||
struct val {
|
||||
char *items[MAX_ITEMS];
|
||||
size_t n;
|
||||
int list;
|
||||
};
|
||||
|
||||
struct ent {
|
||||
char key[48];
|
||||
char sub[96]; /* key NAME { ... }: the NAME */
|
||||
struct val v;
|
||||
unsigned line;
|
||||
int block; /* a nested { } block: items are A=b */
|
||||
};
|
||||
|
||||
struct cb {
|
||||
const char *p;
|
||||
unsigned line;
|
||||
const char *path;
|
||||
struct sp_buf *err;
|
||||
struct sp_buf *out;
|
||||
unsigned *map;
|
||||
size_t nmap, capmap;
|
||||
int failed;
|
||||
};
|
||||
|
||||
static void
|
||||
fail(struct cb *c, unsigned line, const char *fmt, ...)
|
||||
{
|
||||
va_list ap;
|
||||
char msg[400];
|
||||
|
||||
if (c->failed)
|
||||
return;
|
||||
c->failed = 1;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(msg, sizeof(msg), fmt, ap);
|
||||
va_end(ap);
|
||||
sp_buf_printf(c->err, "config: %s:%u: %s", c->path, line, msg);
|
||||
}
|
||||
|
||||
static void
|
||||
val_free(struct val *v)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < v->n; i++)
|
||||
free(v->items[i]);
|
||||
v->n = 0;
|
||||
}
|
||||
|
||||
static void
|
||||
ents_free(struct ent *e, size_t n)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < n; i++)
|
||||
val_free(&e[i].v);
|
||||
}
|
||||
|
||||
/* blanks and comments; newlines too when 'nl' */
|
||||
static void
|
||||
skip(struct cb *c, int nl)
|
||||
{
|
||||
for (;;) {
|
||||
if (*c->p == ' ' || *c->p == '\t' || *c->p == '\r')
|
||||
c->p++;
|
||||
else if (*c->p == '\n' && nl) {
|
||||
c->line++;
|
||||
c->p++;
|
||||
} else if (*c->p == '#') {
|
||||
while (*c->p != '\0' && *c->p != '\n')
|
||||
c->p++;
|
||||
} else
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* ${NAME} becomes the variable's value, empty when it is not set */
|
||||
static char *
|
||||
expand(const char *s)
|
||||
{
|
||||
struct sp_buf b;
|
||||
char *r;
|
||||
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return NULL;
|
||||
while (*s != '\0') {
|
||||
if (s[0] == '$' && s[1] == '{') {
|
||||
const char *e = strchr(s + 2, '}');
|
||||
char name[96];
|
||||
size_t n;
|
||||
const char *v;
|
||||
|
||||
if (e != NULL && (size_t)(e - s - 2) < sizeof(name)) {
|
||||
n = (size_t)(e - s - 2);
|
||||
memcpy(name, s + 2, n);
|
||||
name[n] = '\0';
|
||||
v = getenv(name);
|
||||
if (v != NULL)
|
||||
sp_buf_puts(&b, v);
|
||||
s = e + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
sp_buf_add(&b, s, 1);
|
||||
s++;
|
||||
}
|
||||
r = b.p != NULL ? strdup(b.p) : strdup("");
|
||||
sp_buf_free(&b);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* one scalar: "quoted with \" \\ \n" or a bare word */
|
||||
static char *
|
||||
scalar(struct cb *c)
|
||||
{
|
||||
char tmp[2048];
|
||||
size_t n = 0;
|
||||
char *r;
|
||||
|
||||
if (*c->p == '"') {
|
||||
unsigned start = c->line;
|
||||
|
||||
c->p++;
|
||||
while (*c->p != '"') {
|
||||
if (*c->p == '\0' || *c->p == '\n') {
|
||||
fail(c, start, "string without a closing quote");
|
||||
return NULL;
|
||||
}
|
||||
if (*c->p == '\\' && c->p[1] != '\0') {
|
||||
c->p++;
|
||||
tmp[n] = *c->p == 'n' ? '\n' : *c->p;
|
||||
} else
|
||||
tmp[n] = *c->p;
|
||||
if (n + 1 < sizeof(tmp))
|
||||
n++;
|
||||
c->p++;
|
||||
}
|
||||
c->p++;
|
||||
} else {
|
||||
while (*c->p != '\0' && !isspace((unsigned char)*c->p) &&
|
||||
*c->p != '#' && *c->p != ',' && *c->p != ']' &&
|
||||
*c->p != '}' && *c->p != '[' && *c->p != '{') {
|
||||
tmp[n] = *c->p++;
|
||||
if (n + 1 < sizeof(tmp))
|
||||
n++;
|
||||
}
|
||||
if (n == 0) {
|
||||
fail(c, c->line, "a value is missing");
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
tmp[n] = '\0';
|
||||
r = expand(tmp);
|
||||
if (r == NULL)
|
||||
fail(c, c->line, "out of memory");
|
||||
return r;
|
||||
}
|
||||
|
||||
static int
|
||||
value(struct cb *c, struct val *v)
|
||||
{
|
||||
memset(v, 0, sizeof(*v));
|
||||
skip(c, 0);
|
||||
if (*c->p == '[') {
|
||||
unsigned start = c->line;
|
||||
|
||||
v->list = 1;
|
||||
c->p++;
|
||||
for (;;) {
|
||||
skip(c, 1);
|
||||
if (*c->p == ',') {
|
||||
c->p++;
|
||||
continue;
|
||||
}
|
||||
if (*c->p == ']') {
|
||||
c->p++;
|
||||
break;
|
||||
}
|
||||
if (*c->p == '\0') {
|
||||
fail(c, start, "list without a closing ]");
|
||||
return -1;
|
||||
}
|
||||
if (v->n == MAX_ITEMS) {
|
||||
fail(c, c->line, "more than %d items in a list",
|
||||
MAX_ITEMS);
|
||||
return -1;
|
||||
}
|
||||
v->items[v->n] = scalar(c);
|
||||
if (v->items[v->n] == NULL)
|
||||
return -1;
|
||||
v->n++;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
v->items[0] = scalar(c);
|
||||
if (v->items[0] == NULL)
|
||||
return -1;
|
||||
v->n = 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const char *
|
||||
one(struct cb *c, const struct ent *e)
|
||||
{
|
||||
if (e->v.n != 1 || e->v.list) {
|
||||
fail(c, e->line, "%s wants one value, not a list", e->key);
|
||||
return NULL;
|
||||
}
|
||||
return e->v.items[0];
|
||||
}
|
||||
|
||||
/* the items as "a,b,c" */
|
||||
static void
|
||||
joined(const struct val *v, char *buf, size_t cap)
|
||||
{
|
||||
size_t i, n = 0;
|
||||
|
||||
buf[0] = '\0';
|
||||
for (i = 0; i < v->n && n + 1 < cap; i++)
|
||||
n += (size_t)snprintf(buf + n, cap - n, "%s%s", i > 0 ? "," : "",
|
||||
v->items[i]);
|
||||
if (n >= cap)
|
||||
buf[cap - 1] = '\0';
|
||||
}
|
||||
|
||||
static int
|
||||
boolean(const char *s)
|
||||
{
|
||||
return !strcmp(s, "true") || !strcmp(s, "yes") || !strcmp(s, "on") ||
|
||||
!strcmp(s, "1");
|
||||
}
|
||||
|
||||
static void
|
||||
emit(struct cb *c, unsigned line, const char *fmt, ...)
|
||||
{
|
||||
va_list ap;
|
||||
char l[4096];
|
||||
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(l, sizeof(l), fmt, ap);
|
||||
va_end(ap);
|
||||
sp_buf_puts(c->out, l);
|
||||
sp_buf_puts(c->out, "\n");
|
||||
if (c->nmap == c->capmap) {
|
||||
size_t nc = c->capmap != 0 ? c->capmap * 2 : 64;
|
||||
unsigned *nm = realloc(c->map, nc * sizeof(*nm));
|
||||
|
||||
if (nm == NULL) {
|
||||
fail(c, line, "out of memory");
|
||||
return;
|
||||
}
|
||||
c->map = nm;
|
||||
c->capmap = nc;
|
||||
}
|
||||
c->map[c->nmap++] = line;
|
||||
}
|
||||
|
||||
/* a field value goes into a '|' separated line: it must not hold one */
|
||||
static int
|
||||
clean(struct cb *c, const struct ent *e, const char *s)
|
||||
{
|
||||
if (strchr(s, '|') != NULL || strchr(s, '\n') != NULL) {
|
||||
fail(c, e->line, "%s must not contain '|' or a newline", e->key);
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int
|
||||
in_list(const char *const *list, const char *k)
|
||||
{
|
||||
for (; *list != NULL; list++)
|
||||
if (!strcmp(*list, k))
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
do_core(struct cb *c, struct ent *e, size_t n)
|
||||
{
|
||||
size_t i, j;
|
||||
|
||||
for (i = 0; i < n && !c->failed; i++) {
|
||||
const char *k = e[i].key, *s;
|
||||
char list[2048];
|
||||
|
||||
if (!strcmp(k, "plugins") || !strcmp(k, "skills")) {
|
||||
for (j = 0; j < e[i].v.n; j++)
|
||||
emit(c, e[i].line, "%s = %s",
|
||||
k[0] == 'p' ? "plugin" : "skills_dir",
|
||||
e[i].v.items[j]);
|
||||
continue;
|
||||
}
|
||||
if (e[i].v.list) {
|
||||
joined(&e[i].v, list, sizeof(list));
|
||||
emit(c, e[i].line, "%s = %s", k, list);
|
||||
continue;
|
||||
}
|
||||
s = one(c, &e[i]);
|
||||
if (s == NULL)
|
||||
return;
|
||||
if (!strcmp(k, "autonomous") || !strcmp(k, "env_delegates"))
|
||||
emit(c, e[i].line, "%s = %d", k, boolean(s));
|
||||
else
|
||||
emit(c, e[i].line, "%s = %s", k, s);
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
do_provider(struct cb *c, const char *name, unsigned line, struct ent *e,
|
||||
size_t n)
|
||||
{
|
||||
static const char *const plain[] = { "kind", "cmd", "provider", "host",
|
||||
"endpoint", "model", "key_env", "ctx", "prio", "max_parallel",
|
||||
"limit", "tokens", NULL };
|
||||
struct sp_buf l;
|
||||
const char *about = "";
|
||||
size_t i, j;
|
||||
int skip_it = 0;
|
||||
|
||||
if (sp_buf_init(&l) != 0) {
|
||||
fail(c, line, "out of memory");
|
||||
return;
|
||||
}
|
||||
for (i = 0; i < n; i++) {
|
||||
if (!strcmp(e[i].key, "about") || !strcmp(e[i].key, "description")) {
|
||||
about = one(c, &e[i]);
|
||||
if (about == NULL || !clean(c, &e[i], about))
|
||||
goto done;
|
||||
} else if (!strcmp(e[i].key, "delegate")) {
|
||||
const char *s = one(c, &e[i]);
|
||||
|
||||
if (s == NULL)
|
||||
goto done;
|
||||
skip_it = !boolean(s);
|
||||
}
|
||||
}
|
||||
sp_buf_printf(&l, "delegate = %s", name);
|
||||
if (about[0] != '\0')
|
||||
sp_buf_printf(&l, " | %s", about);
|
||||
for (i = 0; i < n; i++) {
|
||||
const char *k = e[i].key, *s;
|
||||
char list[1024];
|
||||
|
||||
if (!strcmp(k, "about") || !strcmp(k, "description") ||
|
||||
!strcmp(k, "delegate"))
|
||||
continue;
|
||||
if (!strcmp(k, "tags")) {
|
||||
joined(&e[i].v, list, sizeof(list));
|
||||
if (!clean(c, &e[i], list))
|
||||
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, '=');
|
||||
|
||||
/* NAME= with nothing after it: the variable was not set */
|
||||
if (eq == NULL || eq[1] == '\0')
|
||||
continue;
|
||||
if (!clean(c, &e[i], kv))
|
||||
goto done;
|
||||
sp_buf_printf(&l, " | env=%s", kv);
|
||||
}
|
||||
} else if (in_list(plain, k)) {
|
||||
s = one(c, &e[i]);
|
||||
if (s == NULL || !clean(c, &e[i], s))
|
||||
goto done;
|
||||
sp_buf_printf(&l, " | %s=%s", k, s);
|
||||
} else {
|
||||
fail(c, e[i].line, "unknown provider field '%s'", k);
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
if (!skip_it && l.p != NULL)
|
||||
emit(c, line, "%s", l.p);
|
||||
done:
|
||||
sp_buf_free(&l);
|
||||
}
|
||||
|
||||
static void
|
||||
do_pool(struct cb *c, const char *name, unsigned line, struct ent *e, size_t n)
|
||||
{
|
||||
char members[512] = "";
|
||||
const char *strategy = "failover";
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < n; i++) {
|
||||
if (!strcmp(e[i].key, "members"))
|
||||
joined(&e[i].v, members, sizeof(members));
|
||||
else if (!strcmp(e[i].key, "strategy")) {
|
||||
strategy = one(c, &e[i]);
|
||||
if (strategy == NULL)
|
||||
return;
|
||||
} else {
|
||||
fail(c, e[i].line, "unknown pool field '%s'", e[i].key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (members[0] == '\0') {
|
||||
fail(c, line, "pool %s has no members", name);
|
||||
return;
|
||||
}
|
||||
emit(c, line, "pool = %s | strategy=%s | members=%s", name, strategy,
|
||||
members);
|
||||
}
|
||||
|
||||
static void
|
||||
do_mcp(struct cb *c, const char *name, unsigned line, struct ent *e, size_t n)
|
||||
{
|
||||
struct sp_buf l;
|
||||
size_t i;
|
||||
|
||||
if (sp_buf_init(&l) != 0)
|
||||
return;
|
||||
sp_buf_printf(&l, "mcp = %s", name);
|
||||
for (i = 0; i < n; i++) {
|
||||
const char *s = one(c, &e[i]);
|
||||
|
||||
if (s == NULL || !clean(c, &e[i], s))
|
||||
goto done;
|
||||
if (!strcmp(e[i].key, "url") || !strcmp(e[i].key, "cmd") ||
|
||||
!strcmp(e[i].key, "header"))
|
||||
sp_buf_printf(&l, " | %s=%s", e[i].key, s);
|
||||
else if (!strcmp(e[i].key, "enabled"))
|
||||
sp_buf_printf(&l, " | enabled=%d", boolean(s));
|
||||
else {
|
||||
fail(c, e[i].line, "unknown mcp field '%s'", e[i].key);
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
emit(c, line, "%s", l.p);
|
||||
done:
|
||||
sp_buf_free(&l);
|
||||
}
|
||||
|
||||
/* one setting of a plugin: plugin_conf = NAME | key=value */
|
||||
static void
|
||||
plugin_kv(struct cb *c, const struct ent *e, const char *plugin,
|
||||
const char *key, const char *val)
|
||||
{
|
||||
if (strchr(key, '=') != NULL || strchr(key, '|') != NULL) {
|
||||
fail(c, e->line, "bad plugin setting name '%s'", key);
|
||||
return;
|
||||
}
|
||||
if (!clean(c, e, val))
|
||||
return;
|
||||
emit(c, e->line, "plugin_conf = %s | %s=%s", plugin, key, val);
|
||||
}
|
||||
|
||||
/* plugin mcp { server ID { url = ... } }: the servers the mcp plugin runs */
|
||||
static void
|
||||
mcp_server(struct cb *c, const struct ent *e)
|
||||
{
|
||||
struct sp_buf l;
|
||||
size_t j;
|
||||
|
||||
if (e->sub[0] == '\0') {
|
||||
fail(c, e->line, "server needs a name: server NAME { url = ... }");
|
||||
return;
|
||||
}
|
||||
if (sp_buf_init(&l) != 0)
|
||||
return;
|
||||
sp_buf_printf(&l, "mcp = %s", e->sub);
|
||||
for (j = 0; j < e->v.n; j++) {
|
||||
const char *kv = e->v.items[j], *eq = strchr(kv, '=');
|
||||
size_t kl = eq != NULL ? (size_t)(eq - kv) : 0;
|
||||
|
||||
if (eq == NULL || !clean(c, e, kv))
|
||||
goto done;
|
||||
if ((kl == 3 && !strncmp(kv, "url", 3)) ||
|
||||
(kl == 3 && !strncmp(kv, "cmd", 3)) ||
|
||||
(kl == 6 && !strncmp(kv, "header", 6)))
|
||||
sp_buf_printf(&l, " | %s", kv);
|
||||
else if (kl == 7 && !strncmp(kv, "enabled", 7))
|
||||
sp_buf_printf(&l, " | enabled=%d", boolean(eq + 1));
|
||||
else {
|
||||
fail(c, e->line, "unknown mcp server field '%.*s'",
|
||||
(int)kl, kv);
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
emit(c, e->line, "%s", l.p);
|
||||
done:
|
||||
sp_buf_free(&l);
|
||||
}
|
||||
|
||||
/*
|
||||
* plugin NAME { path = ... enabled = false anything = else }
|
||||
*
|
||||
* The block loads the plugin -- the shipped one for NAME unless 'path' names
|
||||
* another -- and everything else in it is the plugin's own configuration,
|
||||
* which it reads with sp_host_plugin_config(host, NAME, key).
|
||||
*/
|
||||
static void
|
||||
do_plugin(struct cb *c, const char *name, unsigned line, struct ent *e,
|
||||
size_t n)
|
||||
{
|
||||
const char *path = NULL;
|
||||
char full[1024], list[2048], key[200];
|
||||
size_t i, j;
|
||||
int on = 1;
|
||||
|
||||
for (i = 0; name[i] != '\0'; i++)
|
||||
if (!isalnum((unsigned char)name[i]) && name[i] != '_' &&
|
||||
name[i] != '-') {
|
||||
fail(c, line, "plugin name '%s': letters, digits, _ and - "
|
||||
"only", name);
|
||||
return;
|
||||
}
|
||||
for (i = 0; i < n && !c->failed; i++) {
|
||||
if (!strcmp(e[i].key, "path") && !e[i].block) {
|
||||
path = one(c, &e[i]);
|
||||
if (path != NULL && !clean(c, &e[i], path))
|
||||
return;
|
||||
} else if (!strcmp(e[i].key, "enabled") && !e[i].block) {
|
||||
const char *s = one(c, &e[i]);
|
||||
|
||||
if (s == NULL)
|
||||
return;
|
||||
on = boolean(s);
|
||||
}
|
||||
}
|
||||
if (c->failed || !on)
|
||||
return;
|
||||
if (path != NULL && path[0] == '~' && path[1] == '/' &&
|
||||
getenv("HOME") != NULL) {
|
||||
snprintf(full, sizeof(full), "%s%s", getenv("HOME"), path + 1);
|
||||
path = full;
|
||||
}
|
||||
/* a bare name is the shipped plugin: main.c looks it up */
|
||||
emit(c, line, "plugin = %s", path != NULL ? path : name);
|
||||
for (i = 0; i < n && !c->failed; i++) {
|
||||
const struct ent *x = &e[i];
|
||||
|
||||
if ((!strcmp(x->key, "path") || !strcmp(x->key, "enabled")) &&
|
||||
!x->block)
|
||||
continue;
|
||||
if (x->block) {
|
||||
if (!strcmp(name, "mcp") && !strcmp(x->key, "server")) {
|
||||
mcp_server(c, x);
|
||||
continue;
|
||||
}
|
||||
for (j = 0; j < x->v.n && !c->failed; j++) {
|
||||
const char *kv = x->v.items[j];
|
||||
const char *eq = strchr(kv, '=');
|
||||
|
||||
if (eq == NULL)
|
||||
continue;
|
||||
if (x->sub[0] != '\0')
|
||||
snprintf(key, sizeof(key), "%s.%s.%.*s",
|
||||
x->key, x->sub, (int)(eq - kv), kv);
|
||||
else
|
||||
snprintf(key, sizeof(key), "%s.%.*s",
|
||||
x->key, (int)(eq - kv), kv);
|
||||
plugin_kv(c, x, name, key, eq + 1);
|
||||
}
|
||||
} else if (x->v.list) {
|
||||
joined(&x->v, list, sizeof(list));
|
||||
plugin_kv(c, x, name, x->key, list);
|
||||
} else {
|
||||
const char *s = one(c, x);
|
||||
|
||||
if (s == NULL)
|
||||
return;
|
||||
plugin_kv(c, x, name, x->key, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
do_exit(struct cb *c, const char *name, unsigned line, struct ent *e, size_t n)
|
||||
{
|
||||
struct sp_buf l;
|
||||
size_t i;
|
||||
|
||||
if (sp_buf_init(&l) != 0)
|
||||
return;
|
||||
sp_buf_printf(&l, "exit = %s", name);
|
||||
for (i = 0; i < n; i++) {
|
||||
const char *s = one(c, &e[i]);
|
||||
|
||||
if (s == NULL || !clean(c, &e[i], s))
|
||||
goto done;
|
||||
if (!strcmp(e[i].key, "label") || !strcmp(e[i].key, "about"))
|
||||
sp_buf_printf(&l, " | %s", s);
|
||||
else if (!strcmp(e[i].key, "endpoint") ||
|
||||
!strcmp(e[i].key, "model") || !strcmp(e[i].key, "key_env"))
|
||||
sp_buf_printf(&l, " | %s=%s", e[i].key, s);
|
||||
else {
|
||||
fail(c, e[i].line, "unknown exit field '%s'", e[i].key);
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
emit(c, line, "%s", l.p);
|
||||
done:
|
||||
sp_buf_free(&l);
|
||||
}
|
||||
|
||||
/*
|
||||
* The body of a block, after its '{': key = value entries, and for 'env' a
|
||||
* nested block of NAME = value lines which becomes the list of NAME=value.
|
||||
*/
|
||||
static size_t
|
||||
body(struct cb *c, struct ent *e, int *closed)
|
||||
{
|
||||
size_t n = 0;
|
||||
|
||||
*closed = 0;
|
||||
for (;;) {
|
||||
char key[48];
|
||||
size_t k = 0;
|
||||
unsigned line;
|
||||
|
||||
skip(c, 1);
|
||||
if (*c->p == '}') {
|
||||
c->p++;
|
||||
*closed = 1;
|
||||
return n;
|
||||
}
|
||||
if (*c->p == '\0') {
|
||||
fail(c, c->line, "block without a closing }");
|
||||
return n;
|
||||
}
|
||||
line = c->line;
|
||||
while (isalnum((unsigned char)*c->p) || *c->p == '_' ||
|
||||
*c->p == '-' || *c->p == '.') {
|
||||
if (k + 1 < sizeof(key))
|
||||
key[k++] = *c->p;
|
||||
c->p++;
|
||||
}
|
||||
key[k] = '\0';
|
||||
if (k == 0) {
|
||||
fail(c, line, "expected a name, found '%c'", *c->p);
|
||||
return n;
|
||||
}
|
||||
if (n == MAX_ENTRIES) {
|
||||
fail(c, line, "more than %d entries in a block", MAX_ENTRIES);
|
||||
return n;
|
||||
}
|
||||
memset(&e[n], 0, sizeof(e[n]));
|
||||
snprintf(e[n].key, sizeof(e[n].key), "%s", key);
|
||||
e[n].line = line;
|
||||
skip(c, 0);
|
||||
if (*c->p != '{' && *c->p != '=' && *c->p != '\0' &&
|
||||
*c->p != '\n') {
|
||||
/* key NAME { ... }: a named nested block (server junction) */
|
||||
size_t m = 0;
|
||||
|
||||
while (isalnum((unsigned char)*c->p) || *c->p == '_' ||
|
||||
*c->p == '-' || *c->p == '.') {
|
||||
if (m + 1 < sizeof(e[n].sub))
|
||||
e[n].sub[m++] = *c->p;
|
||||
c->p++;
|
||||
}
|
||||
e[n].sub[m] = '\0';
|
||||
skip(c, 0);
|
||||
if (m == 0 || *c->p != '{') {
|
||||
fail(c, line, "expected '{' after %s %s", key,
|
||||
e[n].sub);
|
||||
return n;
|
||||
}
|
||||
}
|
||||
if (*c->p == '{') {
|
||||
/* env { A = b }, server junction { url = ... } */
|
||||
c->p++;
|
||||
e[n].v.list = 1;
|
||||
e[n].block = 1;
|
||||
for (;;) {
|
||||
char nm[96];
|
||||
size_t m = 0;
|
||||
char *v;
|
||||
unsigned vl;
|
||||
|
||||
skip(c, 1);
|
||||
if (*c->p == '}') {
|
||||
c->p++;
|
||||
break;
|
||||
}
|
||||
if (*c->p == '\0') {
|
||||
fail(c, line, "block without a closing }");
|
||||
n++;
|
||||
return n;
|
||||
}
|
||||
vl = c->line;
|
||||
while (isalnum((unsigned char)*c->p) || *c->p == '_' ||
|
||||
*c->p == '-' || *c->p == '.') {
|
||||
if (m + 1 < sizeof(nm))
|
||||
nm[m++] = *c->p;
|
||||
c->p++;
|
||||
}
|
||||
nm[m] = '\0';
|
||||
skip(c, 0);
|
||||
if (m == 0 || *c->p != '=') {
|
||||
fail(c, vl, "expected NAME = value");
|
||||
n++;
|
||||
return n;
|
||||
}
|
||||
c->p++;
|
||||
skip(c, 0);
|
||||
v = scalar(c);
|
||||
if (v == NULL) {
|
||||
n++;
|
||||
return n;
|
||||
}
|
||||
if (e[n].v.n < MAX_ITEMS) {
|
||||
size_t len = strlen(nm) + strlen(v) + 2;
|
||||
char *kv = malloc(len);
|
||||
|
||||
if (kv != NULL) {
|
||||
snprintf(kv, len, "%s=%s", nm, v);
|
||||
e[n].v.items[e[n].v.n++] = kv;
|
||||
}
|
||||
}
|
||||
free(v);
|
||||
}
|
||||
n++;
|
||||
continue;
|
||||
}
|
||||
if (*c->p != '=') {
|
||||
fail(c, line, "expected '=' after %s", key);
|
||||
return n;
|
||||
}
|
||||
c->p++;
|
||||
if (value(c, &e[n].v) != 0) {
|
||||
n++;
|
||||
return n;
|
||||
}
|
||||
n++;
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
sp_confblock_is(const char *text)
|
||||
{
|
||||
const char *p = text;
|
||||
|
||||
while (*p != '\0') {
|
||||
const char *eol = strchr(p, '\n'), *q;
|
||||
|
||||
if (eol == NULL)
|
||||
eol = p + strlen(p);
|
||||
for (q = p; q < eol && (*q == ' ' || *q == '\t'); q++)
|
||||
;
|
||||
if (q < eol && *q != '#') {
|
||||
for (; q < eol; q++) {
|
||||
if (*q == '=')
|
||||
return 0;
|
||||
if (*q == '{')
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
p = *eol == '\n' ? eol + 1 : eol;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_confblock_translate(const char *text, const char *path, struct sp_buf *out,
|
||||
unsigned **map, size_t *nmap, struct sp_buf *err)
|
||||
{
|
||||
struct cb c;
|
||||
struct ent *e;
|
||||
|
||||
memset(&c, 0, sizeof(c));
|
||||
c.p = text;
|
||||
c.line = 1;
|
||||
c.path = path;
|
||||
c.err = err;
|
||||
c.out = out;
|
||||
e = calloc(MAX_ENTRIES, sizeof(*e));
|
||||
if (e == NULL) {
|
||||
sp_buf_printf(err, "config: %s: out of memory", path);
|
||||
return -1;
|
||||
}
|
||||
for (;;) {
|
||||
char kind[48], name[96];
|
||||
size_t k = 0, n;
|
||||
unsigned line;
|
||||
int closed;
|
||||
|
||||
skip(&c, 1);
|
||||
if (*c.p == '\0' || c.failed)
|
||||
break;
|
||||
line = c.line;
|
||||
while (isalnum((unsigned char)*c.p) || *c.p == '_' || *c.p == '-')
|
||||
if (k + 1 < sizeof(kind))
|
||||
kind[k++] = *c.p++;
|
||||
else
|
||||
c.p++;
|
||||
kind[k] = '\0';
|
||||
if (k == 0) {
|
||||
fail(&c, line, "expected a block or a setting, found '%c'",
|
||||
*c.p);
|
||||
break;
|
||||
}
|
||||
skip(&c, 0);
|
||||
if (*c.p == '=') {
|
||||
/* a bare setting at the top level belongs to core */
|
||||
c.p++;
|
||||
snprintf(e[0].key, sizeof(e[0].key), "%s", kind);
|
||||
e[0].line = line;
|
||||
if (value(&c, &e[0].v) != 0)
|
||||
break;
|
||||
do_core(&c, e, 1);
|
||||
ents_free(e, 1);
|
||||
continue;
|
||||
}
|
||||
name[0] = '\0';
|
||||
if (*c.p != '{') {
|
||||
size_t m = 0;
|
||||
|
||||
while (*c.p != '\0' && !isspace((unsigned char)*c.p) &&
|
||||
*c.p != '{' && *c.p != '#')
|
||||
if (m + 1 < sizeof(name))
|
||||
name[m++] = *c.p++;
|
||||
else
|
||||
c.p++;
|
||||
name[m] = '\0';
|
||||
skip(&c, 0);
|
||||
}
|
||||
if (*c.p != '{') {
|
||||
fail(&c, line, "expected '{' after %s", kind);
|
||||
break;
|
||||
}
|
||||
c.p++;
|
||||
n = body(&c, e, &closed);
|
||||
if (!c.failed && closed) {
|
||||
int needs_name = !strcmp(kind, "provider") ||
|
||||
!strcmp(kind, "pool") || !strcmp(kind, "exit") ||
|
||||
!strcmp(kind, "mcp") || !strcmp(kind, "plugin");
|
||||
|
||||
if (needs_name && name[0] == '\0')
|
||||
fail(&c, line, "%s needs a name: %s NAME { ... }",
|
||||
kind, kind);
|
||||
else if (!needs_name && name[0] != '\0')
|
||||
fail(&c, line, "%s takes no name", kind);
|
||||
else if (!strcmp(kind, "core"))
|
||||
do_core(&c, e, n);
|
||||
else if (!strcmp(kind, "telegram")) {
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < n && !c.failed; i++) {
|
||||
if (!strcmp(e[i].key, "allow")) {
|
||||
char list[256];
|
||||
|
||||
joined(&e[i].v, list, sizeof(list));
|
||||
emit(&c, e[i].line, "telegram_allow = %s", list);
|
||||
} else
|
||||
fail(&c, e[i].line,
|
||||
"unknown telegram field '%s'", e[i].key);
|
||||
}
|
||||
} else if (!strcmp(kind, "provider"))
|
||||
do_provider(&c, name, line, e, n);
|
||||
else if (!strcmp(kind, "pool"))
|
||||
do_pool(&c, name, line, e, n);
|
||||
else if (!strcmp(kind, "exit"))
|
||||
do_exit(&c, name, line, e, n);
|
||||
else if (!strcmp(kind, "plugin"))
|
||||
do_plugin(&c, name, line, e, n);
|
||||
else if (!strcmp(kind, "mcp"))
|
||||
/* deprecated: plugin mcp { server ID { ... } } */
|
||||
do_mcp(&c, name, line, e, n);
|
||||
else
|
||||
fail(&c, line, "unknown block '%s' (core, telegram, "
|
||||
"provider, pool, exit, plugin)", kind);
|
||||
}
|
||||
ents_free(e, n);
|
||||
if (c.failed)
|
||||
break;
|
||||
}
|
||||
free(e);
|
||||
if (c.failed) {
|
||||
free(c.map);
|
||||
return -1;
|
||||
}
|
||||
*map = c.map;
|
||||
*nmap = c.nmap;
|
||||
return 0;
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/* splinter -- the block syntax of the config file. */
|
||||
#ifndef SP_CONFBLOCK_H
|
||||
#define SP_CONFBLOCK_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include "splinter.h"
|
||||
|
||||
/*
|
||||
* The config file is written as blocks:
|
||||
*
|
||||
* core { theme = Delphinium steps = 40 plugins = [a.so, b.so] }
|
||||
* provider claude-a {
|
||||
* kind = cli
|
||||
* cmd = "claude -p"
|
||||
* env { CLAUDE_CODE_OAUTH_TOKEN = "${CLAUDE_A}" }
|
||||
* limit = 45/5h
|
||||
* }
|
||||
* pool claude { members = [claude-a, claude-b] strategy = balance }
|
||||
*
|
||||
* Reading it is translation: every block becomes the lines the flat reader
|
||||
* already knows, and 'map' says which line of the file each of them came from,
|
||||
* so an error names the line you wrote, not a line of the translation.
|
||||
*/
|
||||
|
||||
/* 1 when the text is written in blocks, 0 for the flat key = value form */
|
||||
int sp_confblock_is(const char *text);
|
||||
|
||||
/*
|
||||
* 'out' gets the flat lines; *map gets, per flat line, the line number in the
|
||||
* source (malloc'ed, free it). 0 or -1 with a message in 'err'.
|
||||
*/
|
||||
int sp_confblock_translate(const char *text, const char *path,
|
||||
struct sp_buf *out, unsigned **map, size_t *nmap,
|
||||
struct sp_buf *err);
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,222 +0,0 @@
|
||||
/*
|
||||
* splinter -- configuration file.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Format: one `key = value` per line, `#` starts a comment, blank lines are
|
||||
* ignored. Deliberately not JSON: this file is meant to be edited by hand at
|
||||
* 2 a.m., and a missing comma must not be the reason the harness will not
|
||||
* start.
|
||||
*
|
||||
* Precedence, highest first: command line, then this file, then the built-in
|
||||
* default. Every key is documented in `docs/CONFIG.md`; an unknown key is an
|
||||
* error with the line number, because a typo that is silently ignored is a
|
||||
* config that lies about what it does.
|
||||
*/
|
||||
#ifndef SPLINTER_CONFIG_H
|
||||
#define SPLINTER_CONFIG_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
#define SP_CONFIG_MAX_PLUGINS 32
|
||||
#define SP_CONFIG_MAX_PLUGIN_KV 96
|
||||
|
||||
/*
|
||||
* One setting of a plugin's own configuration: plugin NAME { key = value }.
|
||||
* A nested block (server junction { url = ... }) gives dotted keys,
|
||||
* "server.junction.url"; a list becomes "a,b,c".
|
||||
*/
|
||||
struct sp_plugin_kv {
|
||||
char plugin[48];
|
||||
char key[96];
|
||||
char val[512];
|
||||
};
|
||||
|
||||
/*
|
||||
* A delegate is another model splinter may hand work to: a name, what it is
|
||||
* good at, and where it lives. No profiles - a profile is a directory with a
|
||||
* dozen files, and all this needs is a line you can read at 2 a.m.
|
||||
*/
|
||||
#define SP_CONFIG_MAX_DELEGATES 32
|
||||
|
||||
/*
|
||||
* Extra environment for a program splinter starts: NAME=VALUE, set in the
|
||||
* child right before exec. Lets two delegates run the same cli with two
|
||||
* different accounts.
|
||||
*/
|
||||
#define SP_CONFIG_MAX_ENV 8
|
||||
#define SP_CONFIG_ENV_LEN 512
|
||||
|
||||
/*
|
||||
* An exit is one way to reach a model: an endpoint, a model name and where its
|
||||
* key lives. The ring tries them in order, so a rate limit costs a step, not the
|
||||
* turn.
|
||||
*/
|
||||
struct sp_exit {
|
||||
char id[32];
|
||||
char label[64]; /* the short name /usage and the logs show */
|
||||
char endpoint[512];
|
||||
char model[256];
|
||||
char key_env[64];
|
||||
};
|
||||
|
||||
struct sp_delegate {
|
||||
char id[32];
|
||||
char kind[16]; /* "openai" (default) or "cli" */
|
||||
char cmd[256]; /* for kind=cli: the program, e.g. "claude -p" */
|
||||
char cli_provider[64]; /* kind=cli: prefix for a bare model,
|
||||
* "opencode" -> opencode/<model> */
|
||||
char key[256]; /* a literal key from the environment, if any */
|
||||
char host[128]; /* ssh target; empty means this machine */
|
||||
int prio; /* tie-break: higher wins */
|
||||
int max_parallel; /* how many of these may run at once */
|
||||
char about[128]; /* what it is good at, in words */
|
||||
char tags[128]; /* comma separated, matched against the task */
|
||||
char endpoint[512];
|
||||
char model[256];
|
||||
char key_env[64];
|
||||
unsigned long ctx; /* context window in tokens, 0 = unknown */
|
||||
char env[SP_CONFIG_MAX_ENV][SP_CONFIG_ENV_LEN]; /* NAME=VALUE */
|
||||
size_t nenv;
|
||||
/* the allowance, 0: none declared (see usage.h) */
|
||||
unsigned long req_limit, tok_limit;
|
||||
long req_window, tok_window;
|
||||
};
|
||||
|
||||
/*
|
||||
* A pool: providers that stand in for each other. 'failover' takes the first
|
||||
* member that has room, in the order listed; 'balance' the one with the most
|
||||
* left of its allowance.
|
||||
*/
|
||||
#define SP_CONFIG_MAX_POOLS 16
|
||||
#define SP_CONFIG_POOL_MEMBERS 16
|
||||
struct sp_pool {
|
||||
char id[32];
|
||||
char strategy[16];
|
||||
char member[SP_CONFIG_POOL_MEMBERS][32];
|
||||
size_t nmembers;
|
||||
};
|
||||
|
||||
/*
|
||||
* An MCP server: tools splinter may use. Two ways to reach one, and the config
|
||||
* says which: a program that speaks MCP on stdin/stdout (`cmd`), or an endpoint
|
||||
* that speaks it over HTTP (`url`, the streamable-HTTP transport). A header is
|
||||
* kept here rather than in the command line, because it is where the token is.
|
||||
*/
|
||||
#define SP_CONFIG_MAX_MCP 8
|
||||
#define SP_CONFIG_MCP_URL 512
|
||||
#define SP_CONFIG_MCP_HEADER 512
|
||||
#define SP_CONFIG_MCP_CMD 512
|
||||
|
||||
struct sp_mcpserver {
|
||||
char id[32];
|
||||
char url[SP_CONFIG_MCP_URL]; /* set: HTTP, else stdio */
|
||||
char cmd[SP_CONFIG_MCP_CMD]; /* started for stdio */
|
||||
char header[SP_CONFIG_MCP_HEADER]; /* one line, e.g. Authorization */
|
||||
int enabled; /* 1 by default */
|
||||
};
|
||||
|
||||
struct sp_config {
|
||||
struct sp_pool pool[SP_CONFIG_MAX_POOLS];
|
||||
size_t npools;
|
||||
char default_id[32]; /* the provider or pool the conversation starts on */
|
||||
struct sp_delegate delegate[SP_CONFIG_MAX_DELEGATES];
|
||||
size_t ndelegates;
|
||||
char skills_dir[SP_CONFIG_MAX_DELEGATES][512];
|
||||
size_t nskills_dir;
|
||||
struct sp_exit exit[SP_CONFIG_MAX_DELEGATES];
|
||||
size_t nexits;
|
||||
char endpoint[512];
|
||||
char model[256];
|
||||
char key_env[64];
|
||||
unsigned long ctx; /* of the main provider, 0 = unknown */
|
||||
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];
|
||||
char theme[64];
|
||||
char system_prompt[1024];
|
||||
char session_dir[512];
|
||||
char cli_cmd[512];
|
||||
char cli_env[SP_CONFIG_MAX_ENV][SP_CONFIG_ENV_LEN]; /* NAME=VALUE */
|
||||
size_t ncli_env;
|
||||
char cli_fallback[256]; /* cli delegate ids, comma separated */
|
||||
char telegram_allow[256]; /* comma separated user ids */
|
||||
char locale[32]; /* language code, exported as SPLINTER_LOCALE */
|
||||
char plugins[SP_CONFIG_MAX_PLUGINS][512];
|
||||
size_t nplugins;
|
||||
struct sp_plugin_kv plugin_conf[SP_CONFIG_MAX_PLUGIN_KV];
|
||||
size_t nplugin_conf;
|
||||
struct sp_mcpserver mcp[SP_CONFIG_MAX_MCP];
|
||||
size_t nmcp;
|
||||
size_t steps; /* 0: not set */
|
||||
size_t max_bytes; /* 0: not set */
|
||||
size_t compact_threshold; /* tokens, 0 = off */
|
||||
size_t compact_target; /* tokens */
|
||||
long http_timeout; /* seconds for HTTP/SSE requests, 0: default */
|
||||
long cli_timeout; /* seconds for cli transport, 0: default */
|
||||
long delegate_timeout; /* seconds for delegate children, 0: default */
|
||||
long run_timeout; /* seconds for the run tool, 0: default */
|
||||
int autonomous; /* -1 not set, 0 off, 1 on */
|
||||
int on_limit_fail; /* 1: a usage limit fails the turn instead of waiting */
|
||||
long max_wait; /* longest wait for a limit, seconds, 0: 12 h */
|
||||
/*
|
||||
* Delegates built from environment tokens (CLAUDE_CODE_OAUTH_TOKEN and the
|
||||
* numbered variants) are off unless asked for. An entry that appears because
|
||||
* a variable happens to be exported competes for work nobody assigned it,
|
||||
* and there is already an explicit cli delegate for the same program.
|
||||
*/
|
||||
int env_delegates;
|
||||
};
|
||||
|
||||
void sp_config_init(struct sp_config *);
|
||||
|
||||
/*
|
||||
* Providers from the environment: OLLAMA_KEY, OLLAMA_KEY_0..N and
|
||||
* CLAUDE_CODE_OAUTH_TOKEN, _0..N. Each one becomes a delegate, so several keys
|
||||
* mean several models to hand work to - and the Ollama ones also become exits,
|
||||
* so a rate limit moves the ring instead of ending the turn.
|
||||
*
|
||||
* Returns how many entries were added.
|
||||
*/
|
||||
size_t sp_config_scan_env(struct sp_config *);
|
||||
|
||||
/* Path of the file: $SPLINTER_CONFIG, else $XDG_CONFIG_HOME/splinter/config,
|
||||
* else ~/.config/splinter/config. Returns 0 or -1 when no home is known. */
|
||||
int sp_config_path(char *buf, size_t len);
|
||||
|
||||
/* Returns 0 when the file was read, -1 with a message otherwise. A missing
|
||||
* file is reported as such: "not found" is different from "broken". */
|
||||
int sp_config_load(struct sp_config *, const char *path, struct sp_buf *err);
|
||||
|
||||
/* The path sp_config_load() read, or NULL when no file was loaded. */
|
||||
const char *sp_config_loaded_path(void);
|
||||
|
||||
/* Write a commented starter file. Returns 0 or -1. */
|
||||
int sp_config_write_example(const char *path, struct sp_buf *err);
|
||||
|
||||
/*
|
||||
* A plugin's own setting (plugin NAME { key = value }), or NULL. 'key' may be
|
||||
* dotted for a nested block: "server.junction.url".
|
||||
*/
|
||||
const char *sp_config_plugin_value(const struct sp_config *,
|
||||
const char *plugin, const char *key);
|
||||
|
||||
/* Set every NAME=VALUE of 'env' in this process, overwriting. */
|
||||
void sp_config_apply_env(const char (*env)[SP_CONFIG_ENV_LEN], size_t n);
|
||||
|
||||
/*
|
||||
* The command a cli provider runs with 'model' (NULL or "": its configured
|
||||
* model). A bare model gets the provider prefix ("provider = opencode" turns
|
||||
* big-pickle into opencode/big-pickle); one with a '/' is taken as it is.
|
||||
* {model} in cmd is replaced; without it the model is appended as
|
||||
* --model. No model at all: cmd unchanged. -1 for a model with characters a
|
||||
* shell would read (the command goes through /bin/sh).
|
||||
*/
|
||||
int sp_cli_command(const struct sp_delegate *d, const char *model,
|
||||
char *out, size_t cap);
|
||||
|
||||
#endif /* SPLINTER_CONFIG_H */
|
||||
@@ -1,169 +0,0 @@
|
||||
/*
|
||||
* splinter -- the conversation.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* The conversation is the harness's memory inside one turn and across turns.
|
||||
* It is a plain array of owned messages: no sharing, no copy-on-write, no
|
||||
* pointers into other messages. A compaction step therefore has to produce a
|
||||
* new array, which is exactly what makes it reviewable.
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
void
|
||||
sp_conv_init(struct sp_conv *c)
|
||||
{
|
||||
memset(c, 0, sizeof(*c));
|
||||
}
|
||||
|
||||
static void
|
||||
msg_free(struct sp_msg *m)
|
||||
{
|
||||
free(m->role);
|
||||
free(m->name);
|
||||
free(m->call_id);
|
||||
free(m->content);
|
||||
free(m->calls);
|
||||
memset(m, 0, sizeof(*m));
|
||||
}
|
||||
|
||||
void
|
||||
sp_conv_free(struct sp_conv *c)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (c == NULL)
|
||||
return;
|
||||
for (i = 0; i < c->n; i++)
|
||||
msg_free(&c->v[i]);
|
||||
free(c->v);
|
||||
memset(c, 0, sizeof(*c));
|
||||
}
|
||||
|
||||
int
|
||||
sp_conv_reset(struct sp_conv *c, const char *system_prompt)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (c == NULL)
|
||||
return -1;
|
||||
for (i = 0; i < c->n; i++)
|
||||
msg_free(&c->v[i]);
|
||||
c->n = 0;
|
||||
if (system_prompt != NULL && *system_prompt != '\0')
|
||||
return sp_conv_push(c, "system", NULL, system_prompt);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static char *
|
||||
dup_or_empty(const char *s)
|
||||
{
|
||||
if (s == NULL)
|
||||
s = "";
|
||||
return strdup(s);
|
||||
}
|
||||
|
||||
int
|
||||
sp_conv_add(struct sp_conv *c, const struct sp_msg *in)
|
||||
{
|
||||
struct sp_msg *m;
|
||||
|
||||
if (c == NULL || in == NULL || in->role == NULL)
|
||||
return -1;
|
||||
if (c->n == c->cap) {
|
||||
size_t ncap = c->cap == 0 ? 8 : c->cap * 2;
|
||||
struct sp_msg *nv = realloc(c->v, ncap * sizeof(*nv));
|
||||
|
||||
if (nv == NULL)
|
||||
return -1;
|
||||
c->v = nv;
|
||||
c->cap = ncap;
|
||||
}
|
||||
m = &c->v[c->n];
|
||||
m->role = dup_or_empty(in->role);
|
||||
m->name = in->name != NULL ? dup_or_empty(in->name) : NULL;
|
||||
m->call_id = in->call_id != NULL ? dup_or_empty(in->call_id) : NULL;
|
||||
m->content = dup_or_empty(in->content);
|
||||
m->calls = in->calls != NULL ? dup_or_empty(in->calls) : NULL;
|
||||
if (m->role == NULL || m->content == NULL ||
|
||||
(in->name != NULL && m->name == NULL) ||
|
||||
(in->call_id != NULL && m->call_id == NULL) ||
|
||||
(in->calls != NULL && m->calls == NULL)) {
|
||||
free(m->role);
|
||||
free(m->name);
|
||||
free(m->call_id);
|
||||
free(m->content);
|
||||
free(m->calls);
|
||||
return -1;
|
||||
}
|
||||
c->n++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_conv_insert(struct sp_conv *c, size_t at, const struct sp_msg *in)
|
||||
{
|
||||
struct sp_msg m;
|
||||
|
||||
if (c == NULL || in == NULL || in->role == NULL || at > c->n)
|
||||
return -1;
|
||||
/* append, then rotate the new last element into place */
|
||||
if (sp_conv_add(c, in) != 0)
|
||||
return -1;
|
||||
m = c->v[c->n - 1];
|
||||
memmove(&c->v[at + 1], &c->v[at], (c->n - 1 - at) * sizeof(*c->v));
|
||||
c->v[at] = m;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_conv_push(struct sp_conv *c, const char *role, const char *name,
|
||||
const char *content)
|
||||
{
|
||||
struct sp_msg m;
|
||||
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = (char *)role;
|
||||
m.name = (char *)name;
|
||||
m.content = (char *)content;
|
||||
return sp_conv_add(c, &m);
|
||||
}
|
||||
|
||||
size_t
|
||||
sp_conv_bytes(const struct sp_conv *c)
|
||||
{
|
||||
size_t i, total = 0;
|
||||
|
||||
for (i = 0; i < c->n; i++) {
|
||||
total += c->v[i].role != NULL ? strlen(c->v[i].role) : 0;
|
||||
total += c->v[i].name != NULL ? strlen(c->v[i].name) : 0;
|
||||
total += c->v[i].content != NULL ? strlen(c->v[i].content) : 0;
|
||||
total += c->v[i].calls != NULL ? strlen(c->v[i].calls) : 0;
|
||||
total += 16; /* JSON scaffolding, estimated */
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
int
|
||||
sp_conv_trim(struct sp_conv *c, size_t keep_last)
|
||||
{
|
||||
size_t drop, i;
|
||||
|
||||
if (c == NULL || keep_last >= c->n)
|
||||
return 0;
|
||||
drop = c->n - keep_last;
|
||||
for (i = 0; i < drop; i++) {
|
||||
free(c->v[i].role);
|
||||
free(c->v[i].name);
|
||||
free(c->v[i].call_id);
|
||||
free(c->v[i].content);
|
||||
free(c->v[i].calls);
|
||||
}
|
||||
memmove(c->v, c->v + drop, (c->n - drop) * sizeof(*c->v));
|
||||
c->n -= drop;
|
||||
return 0;
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
/*
|
||||
* splinter -- curl(1) without secrets on its command line.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Every argument of a process is readable by every user of the machine
|
||||
* (/proc/<pid>/cmdline, ps -ef). An API key in "-H 'Authorization: Bearer ...'"
|
||||
* or a Telegram token in the URL was therefore public for as long as the request
|
||||
* ran. curl reads a config from stdin with "-K -"; the URL and the secret
|
||||
* headers go there, and argv keeps only what may be seen.
|
||||
*
|
||||
* It is also the end of building curl command lines as shell strings: no quote
|
||||
* in a URL can change what runs.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
#include "curl.h"
|
||||
|
||||
#define CURL_MAX_ARGS 32
|
||||
|
||||
int
|
||||
sp_curl_config_line(struct sp_buf *b, const char *key, const char *value)
|
||||
{
|
||||
const char *s;
|
||||
|
||||
if (sp_buf_printf(b, "%s = \"", key) != 0)
|
||||
return -1;
|
||||
for (s = value; *s != '\0'; s++) {
|
||||
const char *esc = NULL;
|
||||
|
||||
switch (*s) {
|
||||
case '"': esc = "\\\""; break;
|
||||
case '\\': esc = "\\\\"; break;
|
||||
case '\n': esc = "\\n"; break;
|
||||
case '\r': esc = "\\r"; break;
|
||||
case '\t': esc = "\\t"; break;
|
||||
}
|
||||
if (esc != NULL ? sp_buf_puts(b, esc) : sp_buf_add(b, s, 1))
|
||||
return -1;
|
||||
}
|
||||
return sp_buf_puts(b, "\"\n");
|
||||
}
|
||||
|
||||
static int
|
||||
write_all(int fd, const char *p, size_t n)
|
||||
{
|
||||
while (n > 0) {
|
||||
ssize_t w = write(fd, p, n);
|
||||
|
||||
if (w < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
p += w;
|
||||
n -= (size_t)w;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_curl_start(const char *const *args, const char *url,
|
||||
const char *const *headers, int quiet, pid_t *pid, struct sp_buf *err)
|
||||
{
|
||||
struct sp_buf cfg;
|
||||
char *argv[CURL_MAX_ARGS + 4];
|
||||
int in[2], out[2], n = 0, i, failed;
|
||||
pid_t child;
|
||||
|
||||
if (sp_buf_init(&cfg) != 0)
|
||||
return -1;
|
||||
failed = sp_curl_config_line(&cfg, "url", url != NULL ? url : "");
|
||||
for (i = 0; !failed && headers != NULL && headers[i] != NULL; i++)
|
||||
failed = sp_curl_config_line(&cfg, "header", headers[i]);
|
||||
if (failed) {
|
||||
sp_buf_free(&cfg);
|
||||
sp_buf_puts(err, "curl: out of memory");
|
||||
return -1;
|
||||
}
|
||||
|
||||
argv[n++] = "curl";
|
||||
for (i = 0; args != NULL && args[i] != NULL; i++) {
|
||||
if (i >= CURL_MAX_ARGS) {
|
||||
sp_buf_free(&cfg);
|
||||
sp_buf_puts(err, "curl: too many arguments");
|
||||
return -1;
|
||||
}
|
||||
argv[n++] = (char *)args[i];
|
||||
}
|
||||
argv[n++] = "-K";
|
||||
argv[n++] = "-";
|
||||
argv[n] = NULL;
|
||||
|
||||
if (pipe(in) != 0) {
|
||||
sp_buf_free(&cfg);
|
||||
sp_buf_printf(err, "curl: pipe: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
if (pipe(out) != 0) {
|
||||
close(in[0]);
|
||||
close(in[1]);
|
||||
sp_buf_free(&cfg);
|
||||
sp_buf_printf(err, "curl: pipe: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
child = fork();
|
||||
if (child < 0) {
|
||||
close(in[0]);
|
||||
close(in[1]);
|
||||
close(out[0]);
|
||||
close(out[1]);
|
||||
sp_buf_free(&cfg);
|
||||
sp_buf_printf(err, "curl: fork: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
if (child == 0) {
|
||||
(void)dup2(in[0], STDIN_FILENO);
|
||||
(void)dup2(out[1], STDOUT_FILENO);
|
||||
if (quiet) {
|
||||
int dn = open("/dev/null", O_WRONLY);
|
||||
|
||||
if (dn >= 0) {
|
||||
(void)dup2(dn, STDERR_FILENO);
|
||||
close(dn);
|
||||
}
|
||||
}
|
||||
close(in[0]);
|
||||
close(in[1]);
|
||||
close(out[0]);
|
||||
close(out[1]);
|
||||
execvp("curl", argv);
|
||||
_exit(127);
|
||||
}
|
||||
close(in[0]);
|
||||
close(out[1]);
|
||||
/*
|
||||
* The config is a few hundred bytes, far below a pipe's buffer, and curl
|
||||
* reads all of it before it starts: writing first cannot deadlock.
|
||||
*/
|
||||
if (write_all(in[1], cfg.p, cfg.len) != 0) {
|
||||
sp_buf_printf(err, "curl: writing the config: %s",
|
||||
strerror(errno));
|
||||
close(in[1]);
|
||||
close(out[0]);
|
||||
(void)kill(child, SIGKILL);
|
||||
(void)waitpid(child, NULL, 0);
|
||||
sp_buf_free(&cfg);
|
||||
return -1;
|
||||
}
|
||||
close(in[1]);
|
||||
/* the copy in memory holds the key too: do not leave it lying around */
|
||||
memset(cfg.p, 0, cfg.cap);
|
||||
sp_buf_free(&cfg);
|
||||
*pid = child;
|
||||
return out[0];
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
/*
|
||||
* splinter -- curl(1) without secrets on its command line.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_CURL_H
|
||||
#define SPLINTER_CURL_H
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
/*
|
||||
* Start curl and return the read end of its stdout, or -1.
|
||||
*
|
||||
* args options that anybody may see in ps(1), NULL-terminated, without
|
||||
* "curl" itself; may be NULL
|
||||
* url the URL; it travels on stdin, because a Telegram URL is the token
|
||||
* headers header lines that are secret ("Authorization: Bearer ..."),
|
||||
* NULL-terminated; may be NULL
|
||||
* quiet nonzero sends curl's stderr to /dev/null (a curses screen)
|
||||
*
|
||||
* stdin of curl is the config pipe, so it never reads the terminal.
|
||||
*/
|
||||
int sp_curl_start(const char *const *args, const char *url,
|
||||
const char *const *headers, int quiet, pid_t *pid, struct sp_buf *err);
|
||||
|
||||
/* Append key = "value" in curl's config syntax; exposed for the tests. */
|
||||
int sp_curl_config_line(struct sp_buf *b, const char *key, const char *value);
|
||||
|
||||
#endif /* SPLINTER_CURL_H */
|
||||
@@ -1,278 +0,0 @@
|
||||
/*
|
||||
* Generated by tools/gen_decomp.py from Unicode decompositions.
|
||||
* Do not edit by hand. The UI transliterates with this table because the
|
||||
* vendored curses writes Latin-1 bytes for wide characters.
|
||||
*/
|
||||
#include <stddef.h>
|
||||
#include "decomp.h"
|
||||
|
||||
const struct sp_decomp sp_decomp_table[] = {
|
||||
{ 0x00c0, "A" },
|
||||
{ 0x00c1, "A" },
|
||||
{ 0x00c2, "A" },
|
||||
{ 0x00c3, "A" },
|
||||
{ 0x00c4, "Ae" },
|
||||
{ 0x00c5, "A" },
|
||||
{ 0x00c6, "AE" },
|
||||
{ 0x00c7, "C" },
|
||||
{ 0x00c8, "E" },
|
||||
{ 0x00c9, "E" },
|
||||
{ 0x00ca, "E" },
|
||||
{ 0x00cb, "E" },
|
||||
{ 0x00cc, "I" },
|
||||
{ 0x00cd, "I" },
|
||||
{ 0x00ce, "I" },
|
||||
{ 0x00cf, "I" },
|
||||
{ 0x00d0, "D" },
|
||||
{ 0x00d1, "N" },
|
||||
{ 0x00d2, "O" },
|
||||
{ 0x00d3, "O" },
|
||||
{ 0x00d4, "O" },
|
||||
{ 0x00d5, "O" },
|
||||
{ 0x00d6, "Oe" },
|
||||
{ 0x00d8, "O" },
|
||||
{ 0x00d9, "U" },
|
||||
{ 0x00da, "U" },
|
||||
{ 0x00db, "U" },
|
||||
{ 0x00dc, "Ue" },
|
||||
{ 0x00dd, "Y" },
|
||||
{ 0x00de, "Th" },
|
||||
{ 0x00df, "ss" },
|
||||
{ 0x00e0, "a" },
|
||||
{ 0x00e1, "a" },
|
||||
{ 0x00e2, "a" },
|
||||
{ 0x00e3, "a" },
|
||||
{ 0x00e4, "ae" },
|
||||
{ 0x00e5, "a" },
|
||||
{ 0x00e6, "ae" },
|
||||
{ 0x00e7, "c" },
|
||||
{ 0x00e8, "e" },
|
||||
{ 0x00e9, "e" },
|
||||
{ 0x00ea, "e" },
|
||||
{ 0x00eb, "e" },
|
||||
{ 0x00ec, "i" },
|
||||
{ 0x00ed, "i" },
|
||||
{ 0x00ee, "i" },
|
||||
{ 0x00ef, "i" },
|
||||
{ 0x00f0, "d" },
|
||||
{ 0x00f1, "n" },
|
||||
{ 0x00f2, "o" },
|
||||
{ 0x00f3, "o" },
|
||||
{ 0x00f4, "o" },
|
||||
{ 0x00f5, "o" },
|
||||
{ 0x00f6, "oe" },
|
||||
{ 0x00f8, "o" },
|
||||
{ 0x00f9, "u" },
|
||||
{ 0x00fa, "u" },
|
||||
{ 0x00fb, "u" },
|
||||
{ 0x00fc, "ue" },
|
||||
{ 0x00fd, "y" },
|
||||
{ 0x00fe, "th" },
|
||||
{ 0x00ff, "y" },
|
||||
{ 0x0100, "A" },
|
||||
{ 0x0101, "a" },
|
||||
{ 0x0102, "A" },
|
||||
{ 0x0103, "a" },
|
||||
{ 0x0104, "A" },
|
||||
{ 0x0105, "a" },
|
||||
{ 0x0106, "C" },
|
||||
{ 0x0107, "c" },
|
||||
{ 0x0108, "C" },
|
||||
{ 0x0109, "c" },
|
||||
{ 0x010a, "C" },
|
||||
{ 0x010b, "c" },
|
||||
{ 0x010c, "C" },
|
||||
{ 0x010d, "c" },
|
||||
{ 0x010e, "D" },
|
||||
{ 0x010f, "d" },
|
||||
{ 0x0110, "D" },
|
||||
{ 0x0111, "d" },
|
||||
{ 0x0112, "E" },
|
||||
{ 0x0113, "e" },
|
||||
{ 0x0114, "E" },
|
||||
{ 0x0115, "e" },
|
||||
{ 0x0116, "E" },
|
||||
{ 0x0117, "e" },
|
||||
{ 0x0118, "E" },
|
||||
{ 0x0119, "e" },
|
||||
{ 0x011a, "E" },
|
||||
{ 0x011b, "e" },
|
||||
{ 0x011c, "G" },
|
||||
{ 0x011d, "g" },
|
||||
{ 0x011e, "G" },
|
||||
{ 0x011f, "g" },
|
||||
{ 0x0120, "G" },
|
||||
{ 0x0121, "g" },
|
||||
{ 0x0122, "G" },
|
||||
{ 0x0123, "g" },
|
||||
{ 0x0124, "H" },
|
||||
{ 0x0125, "h" },
|
||||
{ 0x0126, "H" },
|
||||
{ 0x0127, "h" },
|
||||
{ 0x0128, "I" },
|
||||
{ 0x0129, "i" },
|
||||
{ 0x012a, "I" },
|
||||
{ 0x012b, "i" },
|
||||
{ 0x012c, "I" },
|
||||
{ 0x012d, "i" },
|
||||
{ 0x012e, "I" },
|
||||
{ 0x012f, "i" },
|
||||
{ 0x0130, "I" },
|
||||
{ 0x0131, "i" },
|
||||
{ 0x0134, "J" },
|
||||
{ 0x0135, "j" },
|
||||
{ 0x0136, "K" },
|
||||
{ 0x0137, "k" },
|
||||
{ 0x0138, "k" },
|
||||
{ 0x0139, "L" },
|
||||
{ 0x013a, "l" },
|
||||
{ 0x013b, "L" },
|
||||
{ 0x013c, "l" },
|
||||
{ 0x013d, "L" },
|
||||
{ 0x013e, "l" },
|
||||
{ 0x0141, "L" },
|
||||
{ 0x0142, "l" },
|
||||
{ 0x0143, "N" },
|
||||
{ 0x0144, "n" },
|
||||
{ 0x0145, "N" },
|
||||
{ 0x0146, "n" },
|
||||
{ 0x0147, "N" },
|
||||
{ 0x0148, "n" },
|
||||
{ 0x014c, "O" },
|
||||
{ 0x014d, "o" },
|
||||
{ 0x014e, "O" },
|
||||
{ 0x014f, "o" },
|
||||
{ 0x0150, "O" },
|
||||
{ 0x0151, "o" },
|
||||
{ 0x0152, "OE" },
|
||||
{ 0x0153, "oe" },
|
||||
{ 0x0154, "R" },
|
||||
{ 0x0155, "r" },
|
||||
{ 0x0156, "R" },
|
||||
{ 0x0157, "r" },
|
||||
{ 0x0158, "R" },
|
||||
{ 0x0159, "r" },
|
||||
{ 0x015a, "S" },
|
||||
{ 0x015b, "s" },
|
||||
{ 0x015c, "S" },
|
||||
{ 0x015d, "s" },
|
||||
{ 0x015e, "S" },
|
||||
{ 0x015f, "s" },
|
||||
{ 0x0160, "S" },
|
||||
{ 0x0161, "s" },
|
||||
{ 0x0162, "T" },
|
||||
{ 0x0163, "t" },
|
||||
{ 0x0164, "T" },
|
||||
{ 0x0165, "t" },
|
||||
{ 0x0166, "T" },
|
||||
{ 0x0167, "t" },
|
||||
{ 0x0168, "U" },
|
||||
{ 0x0169, "u" },
|
||||
{ 0x016a, "U" },
|
||||
{ 0x016b, "u" },
|
||||
{ 0x016c, "U" },
|
||||
{ 0x016d, "u" },
|
||||
{ 0x016e, "U" },
|
||||
{ 0x016f, "u" },
|
||||
{ 0x0170, "U" },
|
||||
{ 0x0171, "u" },
|
||||
{ 0x0172, "U" },
|
||||
{ 0x0173, "u" },
|
||||
{ 0x0174, "W" },
|
||||
{ 0x0175, "w" },
|
||||
{ 0x0176, "Y" },
|
||||
{ 0x0177, "y" },
|
||||
{ 0x0178, "Y" },
|
||||
{ 0x0179, "Z" },
|
||||
{ 0x017a, "z" },
|
||||
{ 0x017b, "Z" },
|
||||
{ 0x017c, "z" },
|
||||
{ 0x017d, "Z" },
|
||||
{ 0x017e, "z" },
|
||||
{ 0x017f, "s" },
|
||||
{ 0x01a0, "O" },
|
||||
{ 0x01a1, "o" },
|
||||
{ 0x01af, "U" },
|
||||
{ 0x01b0, "u" },
|
||||
{ 0x01cd, "A" },
|
||||
{ 0x01ce, "a" },
|
||||
{ 0x01cf, "I" },
|
||||
{ 0x01d0, "i" },
|
||||
{ 0x01d1, "O" },
|
||||
{ 0x01d2, "o" },
|
||||
{ 0x01d3, "U" },
|
||||
{ 0x01d4, "u" },
|
||||
{ 0x01d5, "U" },
|
||||
{ 0x01d6, "u" },
|
||||
{ 0x01d7, "U" },
|
||||
{ 0x01d8, "u" },
|
||||
{ 0x01d9, "U" },
|
||||
{ 0x01da, "u" },
|
||||
{ 0x01db, "U" },
|
||||
{ 0x01dc, "u" },
|
||||
{ 0x01de, "A" },
|
||||
{ 0x01df, "a" },
|
||||
{ 0x01e0, "A" },
|
||||
{ 0x01e1, "a" },
|
||||
{ 0x01e6, "G" },
|
||||
{ 0x01e7, "g" },
|
||||
{ 0x01e8, "K" },
|
||||
{ 0x01e9, "k" },
|
||||
{ 0x01ea, "O" },
|
||||
{ 0x01eb, "o" },
|
||||
{ 0x01ec, "O" },
|
||||
{ 0x01ed, "o" },
|
||||
{ 0x01f0, "j" },
|
||||
{ 0x01f4, "G" },
|
||||
{ 0x01f5, "g" },
|
||||
{ 0x01f8, "N" },
|
||||
{ 0x01f9, "n" },
|
||||
{ 0x01fa, "A" },
|
||||
{ 0x01fb, "a" },
|
||||
{ 0x0200, "A" },
|
||||
{ 0x0201, "a" },
|
||||
{ 0x0202, "A" },
|
||||
{ 0x0203, "a" },
|
||||
{ 0x0204, "E" },
|
||||
{ 0x0205, "e" },
|
||||
{ 0x0206, "E" },
|
||||
{ 0x0207, "e" },
|
||||
{ 0x0208, "I" },
|
||||
{ 0x0209, "i" },
|
||||
{ 0x020a, "I" },
|
||||
{ 0x020b, "i" },
|
||||
{ 0x020c, "O" },
|
||||
{ 0x020d, "o" },
|
||||
{ 0x020e, "O" },
|
||||
{ 0x020f, "o" },
|
||||
{ 0x0210, "R" },
|
||||
{ 0x0211, "r" },
|
||||
{ 0x0212, "R" },
|
||||
{ 0x0213, "r" },
|
||||
{ 0x0214, "U" },
|
||||
{ 0x0215, "u" },
|
||||
{ 0x0216, "U" },
|
||||
{ 0x0217, "u" },
|
||||
{ 0x0218, "S" },
|
||||
{ 0x0219, "s" },
|
||||
{ 0x021a, "T" },
|
||||
{ 0x021b, "t" },
|
||||
{ 0x021e, "H" },
|
||||
{ 0x021f, "h" },
|
||||
{ 0x0226, "A" },
|
||||
{ 0x0227, "a" },
|
||||
{ 0x0228, "E" },
|
||||
{ 0x0229, "e" },
|
||||
{ 0x022a, "O" },
|
||||
{ 0x022b, "o" },
|
||||
{ 0x022c, "O" },
|
||||
{ 0x022d, "o" },
|
||||
{ 0x022e, "O" },
|
||||
{ 0x022f, "o" },
|
||||
{ 0x0230, "O" },
|
||||
{ 0x0231, "o" },
|
||||
{ 0x0232, "Y" },
|
||||
{ 0x0233, "y" },
|
||||
};
|
||||
|
||||
const size_t sp_decomp_count = sizeof(sp_decomp_table) / sizeof(sp_decomp_table[0]);
|
||||
@@ -1,15 +0,0 @@
|
||||
/* splinter -- UTF-8 letter table for the screen, generated by tools/gen_decomp.py. */
|
||||
#ifndef SPLINTER_DECOMP_H
|
||||
#define SPLINTER_DECOMP_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_decomp {
|
||||
unsigned short cp; /* Unicode code point */
|
||||
const char *ascii; /* ASCII replacement, never empty */
|
||||
};
|
||||
|
||||
extern const struct sp_decomp sp_decomp_table[];
|
||||
extern const size_t sp_decomp_count;
|
||||
|
||||
#endif /* SPLINTER_DECOMP_H */
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,63 +0,0 @@
|
||||
/*
|
||||
* splinter -- the folder's memory.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* A model that is asked "what happened here" should not guess. Every session
|
||||
* records the directory it was started in, so the answer is a lookup:
|
||||
* folder_history lists the sessions of a directory, newest first, with the
|
||||
* number of turns and the last thing that was asked.
|
||||
*/
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "mcp.h"
|
||||
#include "folder.h"
|
||||
|
||||
static char sessions_dir[512];
|
||||
|
||||
static int
|
||||
tool_folder_history(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char path[512];
|
||||
const char *want = NULL;
|
||||
mcp_json *v;
|
||||
|
||||
(void)ctx;
|
||||
if (args != NULL && args[0] == '{') {
|
||||
v = mcp_parse(args);
|
||||
if (v != NULL) {
|
||||
want = mcp_arg_string(v, "path");
|
||||
if (want != NULL)
|
||||
snprintf(path, sizeof(path), "%s", want);
|
||||
mcp_json_free(v);
|
||||
}
|
||||
}
|
||||
if (want == NULL) {
|
||||
if (getcwd(path, sizeof(path)) == NULL)
|
||||
return sp_buf_puts(out, "error: cannot read the working "
|
||||
"directory");
|
||||
}
|
||||
return sp_session_folder_history(sessions_dir, path, 10, out) == 0 ? 0 :
|
||||
-1;
|
||||
}
|
||||
|
||||
int
|
||||
sp_folder_register(struct sp_registry *r, const char *sessions)
|
||||
{
|
||||
struct sp_tool t;
|
||||
|
||||
snprintf(sessions_dir, sizeof(sessions_dir), "%s", sessions);
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "folder_history";
|
||||
t.description = "What happened in a directory before: the sessions started "
|
||||
"there, how many turns, and the last question. Defaults to the "
|
||||
"current directory.";
|
||||
t.params = "{\"type\":\"object\",\"properties\":{\"path\":"
|
||||
"{\"type\":\"string\",\"description\":\"directory to look at\"}}}";
|
||||
t.auth = SP_AUTH_READ;
|
||||
t.run = tool_folder_history;
|
||||
return sp_registry_add(r, &t);
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
/*
|
||||
* splinter -- the folder's memory.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_FOLDER_H
|
||||
#define SPLINTER_FOLDER_H
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
int sp_folder_register(struct sp_registry *, const char *sessions);
|
||||
|
||||
#endif /* SPLINTER_FOLDER_H */
|
||||
@@ -1,290 +0,0 @@
|
||||
/*
|
||||
* splinter -- shared HTTP/1.1 request and reply helpers.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "http.h"
|
||||
|
||||
int
|
||||
sp_http_write_all(int fd, const char *buf, size_t len)
|
||||
{
|
||||
while (len > 0) {
|
||||
ssize_t n = write(fd, buf, len);
|
||||
|
||||
if (n <= 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
buf += n;
|
||||
len -= (size_t)n;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_http_header_value(const char *hdr, const char *name)
|
||||
{
|
||||
const char *p;
|
||||
size_t n;
|
||||
|
||||
if (hdr == NULL || name == NULL)
|
||||
return NULL;
|
||||
p = strstr(hdr, "\r\n");
|
||||
n = strlen(name);
|
||||
if (p == NULL)
|
||||
return NULL;
|
||||
while ((p = strstr(p, "\r\n")) != NULL) {
|
||||
p += 2;
|
||||
if (*p == '\0')
|
||||
break;
|
||||
if (strncasecmp(p, name, n) == 0 && p[n] == ':') {
|
||||
const char *v = p + n + 1;
|
||||
|
||||
while (*v == ' ' || *v == '\t')
|
||||
v++;
|
||||
return v;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int
|
||||
sp_http_bearer_is(const char *auth, const char *token)
|
||||
{
|
||||
size_t n;
|
||||
|
||||
if (auth == NULL || token == NULL)
|
||||
return 0;
|
||||
if (strncasecmp(auth, "Bearer ", 7) != 0)
|
||||
return 0;
|
||||
n = strlen(token);
|
||||
if (strncmp(auth + 7, token, n) != 0)
|
||||
return 0;
|
||||
return auth[7 + n] == '\r' || auth[7 + n] == '\n' ||
|
||||
auth[7 + n] == '\0';
|
||||
}
|
||||
|
||||
void
|
||||
sp_http_reply(int fd, int code, const char *reason, const char *type,
|
||||
const char *body)
|
||||
{
|
||||
char hdr[512];
|
||||
int n;
|
||||
|
||||
n = snprintf(hdr, sizeof(hdr),
|
||||
"HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\n"
|
||||
"Connection: close\r\n\r\n", code, reason,
|
||||
type != NULL ? type : "application/json",
|
||||
strlen(body != NULL ? body : ""));
|
||||
if (n > 0)
|
||||
(void)sp_http_write_all(fd, hdr, (size_t)n);
|
||||
(void)sp_http_write_all(fd, body != NULL ? body : "",
|
||||
strlen(body != NULL ? body : ""));
|
||||
}
|
||||
|
||||
/* the bytes already read with the header, then the socket */
|
||||
struct http_src {
|
||||
int fd;
|
||||
const char *pre;
|
||||
size_t prelen;
|
||||
size_t pos;
|
||||
};
|
||||
|
||||
static ssize_t
|
||||
src_read(struct http_src *src, char *buf, size_t cap)
|
||||
{
|
||||
size_t n;
|
||||
|
||||
if (src->pos < src->prelen) {
|
||||
n = src->prelen - src->pos;
|
||||
if (n > cap)
|
||||
n = cap;
|
||||
memcpy(buf, src->pre + src->pos, n);
|
||||
src->pos += n;
|
||||
return (ssize_t)n;
|
||||
}
|
||||
return read(src->fd, buf, cap);
|
||||
}
|
||||
|
||||
/* one CRLF-terminated line, without its terminator; -1 on EOF or overflow */
|
||||
static int
|
||||
src_line(struct http_src *src, char *line, size_t cap)
|
||||
{
|
||||
size_t n = 0;
|
||||
|
||||
for (;;) {
|
||||
char ch;
|
||||
ssize_t got = src_read(src, &ch, 1);
|
||||
|
||||
if (got <= 0)
|
||||
return -1;
|
||||
if (ch == '\n')
|
||||
break;
|
||||
if (ch == '\r')
|
||||
continue;
|
||||
if (n + 1 >= cap)
|
||||
return -1;
|
||||
line[n++] = ch;
|
||||
}
|
||||
line[n] = '\0';
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
src_exact(struct http_src *src, size_t n, struct sp_buf *body)
|
||||
{
|
||||
char chunk[4096];
|
||||
|
||||
while (n > 0) {
|
||||
size_t want = n > sizeof(chunk) ? sizeof(chunk) : n;
|
||||
ssize_t got = src_read(src, chunk, want);
|
||||
|
||||
if (got <= 0)
|
||||
return -1;
|
||||
if (sp_buf_add(body, chunk, (size_t)got) != 0)
|
||||
return -1;
|
||||
n -= (size_t)got;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
read_chunked(struct http_src *src, struct sp_buf *body, size_t body_max)
|
||||
{
|
||||
char line[256];
|
||||
|
||||
for (;;) {
|
||||
char *end;
|
||||
unsigned long long n;
|
||||
size_t ln;
|
||||
char tail[2];
|
||||
|
||||
if (src_line(src, line, sizeof(line)) != 0)
|
||||
return -1;
|
||||
if ((end = strchr(line, ';')) != NULL)
|
||||
*end = '\0';
|
||||
ln = strlen(line);
|
||||
while (ln > 0 && (line[ln - 1] == ' ' ||
|
||||
line[ln - 1] == '\t'))
|
||||
line[--ln] = '\0';
|
||||
errno = 0;
|
||||
n = strtoull(line, &end, 16);
|
||||
if (errno != 0 || end == line || *end != '\0')
|
||||
return -1;
|
||||
if (n == 0)
|
||||
break;
|
||||
if (n > (unsigned long long)(body_max - body->len))
|
||||
return -1;
|
||||
if (src_exact(src, (size_t)n, body) != 0)
|
||||
return -1;
|
||||
/* the CRLF that closes the chunk */
|
||||
if (src_read(src, tail, 2) != 2 || tail[1] != '\n')
|
||||
return -1;
|
||||
}
|
||||
/* trailer section: header lines up to the empty one */
|
||||
for (;;) {
|
||||
if (src_line(src, line, sizeof(line)) != 0)
|
||||
return -1;
|
||||
if (line[0] == '\0')
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
sp_http_begin_stream(int fd)
|
||||
{
|
||||
static const char hdr[] =
|
||||
"HTTP/1.1 200 OK\r\n"
|
||||
"Content-Type: text/event-stream\r\n"
|
||||
"Cache-Control: no-cache\r\n"
|
||||
"X-Accel-Buffering: no\r\n"
|
||||
"Connection: close\r\n\r\n";
|
||||
|
||||
return sp_http_write_all(fd, hdr, sizeof(hdr) - 1);
|
||||
}
|
||||
|
||||
int
|
||||
sp_http_read_request(int fd, char *hdr, size_t cap, struct sp_buf *body,
|
||||
size_t body_max)
|
||||
{
|
||||
size_t used = 0;
|
||||
char *hend;
|
||||
|
||||
for (;;) {
|
||||
ssize_t n;
|
||||
|
||||
if (used >= cap - 1)
|
||||
return -1;
|
||||
n = read(fd, hdr + used, cap - 1 - used);
|
||||
if (n <= 0)
|
||||
return -1;
|
||||
used += (size_t)n;
|
||||
hdr[used] = '\0';
|
||||
if ((hend = strstr(hdr, "\r\n\r\n")) != NULL)
|
||||
break;
|
||||
}
|
||||
{
|
||||
const char *te = sp_http_header_value(hdr,
|
||||
"Transfer-Encoding");
|
||||
|
||||
if (te != NULL) {
|
||||
/*
|
||||
* Only "chunked" is understood. A client that streams
|
||||
* its body has no Content-Length to trust.
|
||||
*/
|
||||
if (strncasecmp(te, "chunked", 7) != 0 ||
|
||||
(te[7] != '\r' && te[7] != '\n' &&
|
||||
te[7] != '\0' && te[7] != ' ' &&
|
||||
te[7] != '\t' && te[7] != ','))
|
||||
return -1;
|
||||
{
|
||||
struct http_src src;
|
||||
|
||||
src.fd = fd;
|
||||
src.pre = hend + 4;
|
||||
src.prelen = used - (size_t)(hend + 4 - hdr);
|
||||
src.pos = 0;
|
||||
if (src.prelen > body_max)
|
||||
return -1;
|
||||
return read_chunked(&src, body, body_max);
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
const char *v = sp_http_header_value(hdr, "Content-Length");
|
||||
long clen = v != NULL ? strtol(v, NULL, 10) : 0;
|
||||
size_t have;
|
||||
|
||||
if (clen < 0 || (size_t)clen > body_max)
|
||||
return -1;
|
||||
have = used - (size_t)(hend + 4 - hdr);
|
||||
if (have > (size_t)clen)
|
||||
have = (size_t)clen;
|
||||
if (have > 0 && sp_buf_add(body, hend + 4, have) != 0)
|
||||
return -1;
|
||||
while (body->len < (size_t)clen) {
|
||||
char chunk[4096];
|
||||
size_t want = (size_t)clen - body->len;
|
||||
ssize_t n;
|
||||
|
||||
if (want > sizeof(chunk))
|
||||
want = sizeof(chunk);
|
||||
n = read(fd, chunk, want);
|
||||
if (n <= 0)
|
||||
return -1;
|
||||
if (sp_buf_add(body, chunk, (size_t)n) != 0)
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
/*
|
||||
* splinter -- the little HTTP/1.1 pieces the JSON servers share.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Not a web framework: one request per connection, Content-Length only, one
|
||||
* reply, close. That is what a local tool endpoint needs, and it keeps the
|
||||
* parsing auditable. The A2A and MCP servers carry their own older copies;
|
||||
* new services use this one.
|
||||
*/
|
||||
#ifndef SPLINTER_HTTP_H
|
||||
#define SPLINTER_HTTP_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_buf;
|
||||
|
||||
#define SP_HTTP_HDR_MAX 16384
|
||||
#define SP_HTTP_BODY_MAX (4 * 1024 * 1024)
|
||||
|
||||
int sp_http_write_all(int fd, const char *buf, size_t len);
|
||||
/* the value of a header, terminated by the CRLF of the next line */
|
||||
const char *sp_http_header_value(const char *hdr, const char *name);
|
||||
int sp_http_bearer_is(const char *auth, const char *token);
|
||||
/* one complete reply; type is the Content-Type, body is NUL-terminated */
|
||||
void sp_http_reply(int fd, int code, const char *reason, const char *type,
|
||||
const char *body);
|
||||
/*
|
||||
* Start an event stream: status 200, text/event-stream, no Content-Length,
|
||||
* then the caller writes frames and closes the socket.
|
||||
*/
|
||||
int sp_http_begin_stream(int fd);
|
||||
/* headers into hdr, exactly Content-Length bytes into body; 0 or -1 */
|
||||
int sp_http_read_request(int fd, char *hdr, size_t cap,
|
||||
struct sp_buf *body, size_t body_max);
|
||||
|
||||
#endif /* SPLINTER_HTTP_H */
|
||||
@@ -1,339 +0,0 @@
|
||||
/*
|
||||
* splinter -- tiny message catalogues.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "i18n.h"
|
||||
|
||||
#define MAX_KEYS 512
|
||||
#define MAX_DIRS 8
|
||||
|
||||
struct entry {
|
||||
char key[96];
|
||||
char text[1024];
|
||||
};
|
||||
|
||||
static struct entry main_cat[MAX_KEYS];
|
||||
static size_t main_n;
|
||||
static struct entry fallback[MAX_KEYS];
|
||||
static size_t fallback_n;
|
||||
static char lang[16] = "en";
|
||||
static char dirs[MAX_DIRS][256];
|
||||
static size_t ndirs;
|
||||
|
||||
void
|
||||
sp_i18n_add_dir(const char *dir)
|
||||
{
|
||||
if (dir == NULL || ndirs == MAX_DIRS)
|
||||
return;
|
||||
snprintf(dirs[ndirs++], sizeof(dirs[0]), "%s", dir);
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_i18n_lang(void)
|
||||
{
|
||||
return lang;
|
||||
}
|
||||
|
||||
static char *
|
||||
trim(char *s)
|
||||
{
|
||||
char *end;
|
||||
|
||||
while (*s == ' ' || *s == '\t')
|
||||
s++;
|
||||
end = s + strlen(s);
|
||||
while (end > s && (end[-1] == '\n' || end[-1] == '\r' ||
|
||||
end[-1] == ' ' || end[-1] == '\t'))
|
||||
*--end = '\0';
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Detect the language from the environment, ignoring the regional part. */
|
||||
static void
|
||||
detect_language(const char *override_lang)
|
||||
{
|
||||
const char *cand = override_lang;
|
||||
|
||||
if (cand == NULL || *cand == '\0')
|
||||
cand = getenv("SPLINTER_LOCALE");
|
||||
if (cand == NULL || *cand == '\0')
|
||||
cand = getenv("LC_ALL");
|
||||
if (cand == NULL || *cand == '\0')
|
||||
cand = getenv("LC_MESSAGES");
|
||||
if (cand == NULL || *cand == '\0')
|
||||
cand = getenv("LANG");
|
||||
|
||||
memset(lang, 0, sizeof(lang));
|
||||
if (cand == NULL || *cand == '\0') {
|
||||
snprintf(lang, sizeof(lang), "en");
|
||||
return;
|
||||
}
|
||||
{
|
||||
/*
|
||||
* Keep the region: pt_BR and pt are different catalogues and a
|
||||
* Brazilian child should not be handed European Portuguese. The
|
||||
* loader tries the full tag first and falls back to the language.
|
||||
*/
|
||||
size_t i = 0;
|
||||
|
||||
while (cand[i] != '\0' && cand[i] != '.' && cand[i] != '@' &&
|
||||
i < sizeof(lang) - 1) {
|
||||
char c = cand[i];
|
||||
|
||||
/* de_DE -> de_DE as pt_BR.msg is written: language lower, region upper */
|
||||
if (c == '-')
|
||||
c = '_';
|
||||
lang[i] = strchr(lang, '_') != NULL ?
|
||||
(char)toupper((unsigned char)c) :
|
||||
(char)tolower((unsigned char)c);
|
||||
i++;
|
||||
}
|
||||
lang[i] = '\0';
|
||||
if (i == 0 || (i == 1 && lang[0] == 'c'))
|
||||
snprintf(lang, sizeof(lang), "en");
|
||||
}
|
||||
}
|
||||
|
||||
static size_t
|
||||
parse_stream(FILE *f, struct entry *cat, size_t max)
|
||||
{
|
||||
char line[1400];
|
||||
size_t n = 0;
|
||||
|
||||
while (n < max && fgets(line, sizeof(line), f) != NULL) {
|
||||
char *eq, *key, *val;
|
||||
|
||||
key = trim(line);
|
||||
if (*key == '\0' || *key == '#')
|
||||
continue;
|
||||
eq = strchr(key, '=');
|
||||
if (eq == NULL)
|
||||
continue; /* a catalogue is data, not config:
|
||||
* a bad line is skipped, not fatal */
|
||||
*eq = '\0';
|
||||
val = trim(eq + 1);
|
||||
key = trim(key);
|
||||
if (*key == '\0')
|
||||
continue;
|
||||
snprintf(cat[n].key, sizeof(cat[n].key), "%s", key);
|
||||
snprintf(cat[n].text, sizeof(cat[n].text), "%s", val);
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
static size_t
|
||||
parse_file(const char *path, struct entry *cat, size_t max)
|
||||
{
|
||||
FILE *f = fopen(path, "r");
|
||||
size_t n;
|
||||
|
||||
if (f == NULL)
|
||||
return 0;
|
||||
n = parse_stream(f, cat, max);
|
||||
fclose(f);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* the catalogue compiled into the program, for languages without a file */
|
||||
static size_t
|
||||
parse_embedded(const char *lang, struct entry *cat, size_t max)
|
||||
{
|
||||
const struct sp_embedded *e;
|
||||
|
||||
/* "pt" is served by pt_BR when there is no plain pt */
|
||||
size_t ll = strlen(lang);
|
||||
|
||||
for (e = sp_embedded_catalogs; e->lang != NULL; e++)
|
||||
if (strcmp(e->lang, lang) == 0 ||
|
||||
(strncmp(e->lang, lang, ll) == 0 && e->lang[ll] == '_')) {
|
||||
FILE *f = fmemopen((void *)e->text, strlen(e->text), "r");
|
||||
size_t n;
|
||||
|
||||
if (f == NULL)
|
||||
return 0;
|
||||
n = parse_stream(f, cat, max);
|
||||
fclose(f);
|
||||
return n;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_i18n_load(struct sp_buf *err, const char *want)
|
||||
{
|
||||
size_t i, tried = 0;
|
||||
char path[512];
|
||||
|
||||
main_n = 0;
|
||||
if (want == NULL || *want == '\0')
|
||||
want = lang;
|
||||
|
||||
for (i = 0; i < ndirs; i++) {
|
||||
snprintf(path, sizeof(path), "%s/%s.msg", dirs[i], want);
|
||||
main_n = parse_file(path, main_cat, MAX_KEYS);
|
||||
tried++;
|
||||
if (main_n > 0)
|
||||
break;
|
||||
}
|
||||
if (main_n == 0)
|
||||
main_n = parse_embedded(want, main_cat, MAX_KEYS);
|
||||
/* English is the fallback for every key, always loaded */
|
||||
for (i = 0; i < ndirs; i++) {
|
||||
if (strcmp(want, "en") == 0 && main_n > 0)
|
||||
break;
|
||||
snprintf(path, sizeof(path), "%s/en.msg", dirs[i]);
|
||||
fallback_n = parse_file(path, fallback, MAX_KEYS);
|
||||
if (fallback_n > 0)
|
||||
break;
|
||||
}
|
||||
|
||||
if (fallback_n == 0)
|
||||
fallback_n = parse_embedded("en", fallback, MAX_KEYS);
|
||||
if (main_n == 0 && fallback_n == 0) {
|
||||
if (err != NULL)
|
||||
sp_buf_printf(err, "i18n: no catalogue for '%s' in %zu "
|
||||
"directories", want, tried);
|
||||
return -1;
|
||||
}
|
||||
/* "want" may be the very buffer "lang": copying it onto itself empties it */
|
||||
if (want != lang)
|
||||
snprintf(lang, sizeof(lang), "%s", want);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const char *
|
||||
lookup(struct entry *cat, size_t n, const char *key)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < n; i++)
|
||||
if (strcmp(cat[i].key, key) == 0)
|
||||
return cat[i].text;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_t(const char *key)
|
||||
{
|
||||
const char *v;
|
||||
|
||||
if (key == NULL)
|
||||
return "";
|
||||
v = lookup(main_cat, main_n, key);
|
||||
if (v != NULL)
|
||||
return v;
|
||||
v = lookup(fallback, fallback_n, key);
|
||||
if (v != NULL)
|
||||
return v;
|
||||
return key; /* untranslated keys are visible */
|
||||
}
|
||||
|
||||
size_t
|
||||
sp_i18n_count(void)
|
||||
{
|
||||
return main_n;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_i18n_key(size_t index)
|
||||
{
|
||||
return index < main_n ? main_cat[index].key : NULL;
|
||||
}
|
||||
|
||||
int
|
||||
sp_i18n_fallback_count(void)
|
||||
{
|
||||
return (int)fallback_n;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_i18n_fallback_key(size_t index)
|
||||
{
|
||||
return index < fallback_n ? fallback[index].key : NULL;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_td(const char *key, const char *dflt)
|
||||
{
|
||||
const char *v;
|
||||
|
||||
if (key == NULL)
|
||||
return dflt != NULL ? dflt : "";
|
||||
v = lookup(main_cat, main_n, key);
|
||||
if (v != NULL)
|
||||
return v;
|
||||
v = lookup(fallback, fallback_n, key);
|
||||
if (v != NULL)
|
||||
return v;
|
||||
return dflt != NULL ? dflt : key;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_i18n_init(const char *override_lang)
|
||||
{
|
||||
struct sp_buf err;
|
||||
|
||||
detect_language(override_lang);
|
||||
|
||||
/*
|
||||
* Where catalogues may live. The executable's own directory comes first,
|
||||
* so `splinter` works from any working directory; then the explicit
|
||||
* override, then the source tree, then an installed prefix.
|
||||
*/
|
||||
{
|
||||
const char *env = getenv("SPLINTER_LOCALE_DIR");
|
||||
|
||||
if (env != NULL && *env != '\0')
|
||||
sp_i18n_add_dir(env);
|
||||
}
|
||||
{
|
||||
char exe[512];
|
||||
ssize_t n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
|
||||
|
||||
if (n > 0) {
|
||||
char dir[600];
|
||||
char *slash;
|
||||
|
||||
exe[n] = '\0';
|
||||
slash = strrchr(exe, '/');
|
||||
if (slash != NULL) {
|
||||
*slash = '\0';
|
||||
snprintf(dir, sizeof(dir), "%s/share/locale", exe);
|
||||
sp_i18n_add_dir(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
sp_i18n_add_dir("share/locale");
|
||||
sp_i18n_add_dir("/usr/local/share/splinter/locale");
|
||||
|
||||
if (sp_buf_init(&err) != 0)
|
||||
return lang;
|
||||
/*
|
||||
* pt_BR first, then pt: a region we have no catalogue for is not a reason
|
||||
* to fall all the way back to English.
|
||||
*/
|
||||
if (sp_i18n_load(&err, lang) != 0 || main_n == 0) {
|
||||
char base[16];
|
||||
size_t i = 0;
|
||||
|
||||
while (lang[i] != '\0' && lang[i] != '_' && i < sizeof(base) - 1) {
|
||||
base[i] = lang[i];
|
||||
i++;
|
||||
}
|
||||
base[i] = '\0';
|
||||
if (strcmp(base, lang) != 0)
|
||||
(void)sp_i18n_load(&err, base);
|
||||
}
|
||||
sp_buf_free(&err);
|
||||
return lang;
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
* splinter -- tiny message catalogues.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Not gettext. The whole point of this harness is that it starts in ten years
|
||||
* without a build system, and gettext needs msgfmt at build time and .mo files
|
||||
* at run time. So: plain `key = text` files, read at startup, hot enough.
|
||||
*
|
||||
* share/locale/en.msg
|
||||
* share/locale/de.msg
|
||||
*
|
||||
* A missing translation falls back to English, and a key that exists in neither
|
||||
* returns itself - visible in the UI instead of an empty line.
|
||||
*
|
||||
* The locale comes from, in order: $SPLINTER_LOCALE, LC_ALL, LC_MESSAGES, LANG.
|
||||
* Only the language part is used ("de_DE.UTF-8" -> "de"), because a harness does
|
||||
* not need regional variants to say "Sitzung".
|
||||
*/
|
||||
#ifndef SPLINTER_I18N_H
|
||||
#define SPLINTER_I18N_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
/* Load the catalogue for the current environment. Returns the language code in
|
||||
* use ("en" when nothing matched). Never NULL. */
|
||||
const char *sp_i18n_init(const char *override_lang);
|
||||
|
||||
/* Translate a key. Never NULL: falls back to English, then to the key. */
|
||||
const char *sp_t(const char *key);
|
||||
|
||||
/*
|
||||
* For format strings: the compiled-in English text is the last resort, so a
|
||||
* missing catalogue never costs a placeholder (a printf format without its %s
|
||||
* silently drops the value it was meant to carry).
|
||||
*/
|
||||
const char *sp_td(const char *key, const char *dflt);
|
||||
|
||||
/* For tests and for plugins that ship their own catalogue. */
|
||||
int sp_i18n_load(struct sp_buf *err, const char *lang);
|
||||
const char *sp_i18n_lang(void);
|
||||
/* Enumerate the loaded catalogue, so a test can prove two catalogues agree. */
|
||||
size_t sp_i18n_count(void);
|
||||
const char *sp_i18n_key(size_t index);
|
||||
int sp_i18n_fallback_count(void);
|
||||
const char *sp_i18n_fallback_key(size_t index);
|
||||
void sp_i18n_add_dir(const char *dir);
|
||||
|
||||
/* the catalogues compiled in (src/catalogs.c): used when no file is found */
|
||||
struct sp_embedded {
|
||||
const char *lang;
|
||||
const char *text;
|
||||
};
|
||||
extern const struct sp_embedded sp_embedded_catalogs[];
|
||||
|
||||
#endif /* SPLINTER_I18N_H */
|
||||
@@ -1,165 +0,0 @@
|
||||
/*
|
||||
* splinter -- the first conversation, and what it leaves behind.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* No questionnaire: the model talks to the user, one question at a time, about
|
||||
* whatever it needs to know to work well with them. When it has enough it
|
||||
* writes a summary and ends the answer with INTERVIEW_COMPLETE; that summary
|
||||
* goes to ~/.splinter/USER.txt and is put into the system prompt of every later
|
||||
* session. Facts about the operator should be the operator's, in one readable
|
||||
* file, not six fields a plugin guessed.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "i18n.h"
|
||||
#include "interview.h"
|
||||
|
||||
#define USER_FILE "USER.txt"
|
||||
#define USER_MAX (16 * 1024)
|
||||
#define DONE_LINE "INTERVIEW_COMPLETE"
|
||||
|
||||
static const char *
|
||||
user_path(const char *dir, char *buf, size_t cap)
|
||||
{
|
||||
if (dir == NULL || *dir == '\0')
|
||||
return NULL;
|
||||
snprintf(buf, cap, "%s/%s", dir, USER_FILE);
|
||||
return buf;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_interview_system(void)
|
||||
{
|
||||
return sp_td("interview.system",
|
||||
"You are splinter, about to work with this person for the first "
|
||||
"time. Interview them to get to know them: what they work on, the "
|
||||
"tools and languages they reach for, how they want to be spoken "
|
||||
"to, what they never want, and which projects matter. Ask one "
|
||||
"question at a time, listen, and go deeper where it matters. Do "
|
||||
"not ask about code details you can read from the repository. "
|
||||
"When you have enough, write a compact summary of the person and "
|
||||
"how they want to work (a few paragraphs or bullets), then end "
|
||||
"your answer with the single line INTERVIEW_COMPLETE. That "
|
||||
"summary is saved to ~/.splinter/USER.txt and read at the start "
|
||||
"of every later session.");
|
||||
}
|
||||
|
||||
char *
|
||||
sp_interview_user_block(const char *session_dir)
|
||||
{
|
||||
char path[700];
|
||||
FILE *f;
|
||||
struct sp_buf b;
|
||||
char chunk[4096];
|
||||
size_t n;
|
||||
|
||||
if (user_path(session_dir, path, sizeof(path)) == NULL)
|
||||
return NULL;
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL) {
|
||||
/* an installation from before USER.txt still has the profile */
|
||||
snprintf(path, sizeof(path), "%s/profile/%s.md", session_dir,
|
||||
sp_user_name());
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
return NULL;
|
||||
}
|
||||
if (sp_buf_init(&b) != 0) {
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
while ((n = fread(chunk, 1, sizeof(chunk), f)) > 0 &&
|
||||
b.len < USER_MAX)
|
||||
if (sp_buf_add(&b, chunk, n) != 0)
|
||||
break;
|
||||
fclose(f);
|
||||
if (b.len == 0) {
|
||||
sp_buf_free(&b);
|
||||
return NULL;
|
||||
}
|
||||
{
|
||||
struct sp_buf out;
|
||||
|
||||
if (sp_buf_init(&out) != 0) {
|
||||
sp_buf_free(&b);
|
||||
return NULL;
|
||||
}
|
||||
if (sp_buf_puts(&out, "\n\nWhat you know about the user "
|
||||
"(from the interview):\n") != 0 ||
|
||||
sp_buf_add(&out, b.p, b.len) != 0) {
|
||||
sp_buf_free(&b);
|
||||
sp_buf_free(&out);
|
||||
return NULL;
|
||||
}
|
||||
sp_buf_free(&b);
|
||||
return out.p;
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
sp_interview_capture(const char *session_dir, const char *answer, char *clean,
|
||||
size_t cap)
|
||||
{
|
||||
char path[700], tmp[800];
|
||||
const char *mark;
|
||||
FILE *f;
|
||||
size_t n;
|
||||
|
||||
if (session_dir == NULL || *session_dir == '\0' || answer == NULL ||
|
||||
clean == NULL || cap == 0)
|
||||
return 0;
|
||||
mark = strstr(answer, DONE_LINE);
|
||||
if (mark == NULL)
|
||||
return 0;
|
||||
n = (size_t)(mark - answer);
|
||||
while (n > 0 && (answer[n - 1] == '\n' || answer[n - 1] == '\r' ||
|
||||
answer[n - 1] == ' ' || answer[n - 1] == '\t'))
|
||||
n--;
|
||||
if (n == 0)
|
||||
return 0;
|
||||
snprintf(clean, cap, "%.*s", (int)(n < cap ? n : cap - 1), answer);
|
||||
if (user_path(session_dir, path, sizeof(path)) == NULL)
|
||||
return 0;
|
||||
snprintf(tmp, sizeof(tmp), "%s.tmp", path);
|
||||
f = fopen(tmp, "w");
|
||||
if (f == NULL)
|
||||
return 0;
|
||||
if (fprintf(f, "%s\n", clean) < 0 || fclose(f) != 0) {
|
||||
(void)unlink(tmp);
|
||||
return 0;
|
||||
}
|
||||
(void)chmod(tmp, 0600);
|
||||
if (rename(tmp, path) != 0) {
|
||||
(void)unlink(tmp);
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
int
|
||||
sp_profile_exists(const char *session_dir)
|
||||
{
|
||||
char path[700];
|
||||
|
||||
if (user_path(session_dir, path, sizeof(path)) == NULL)
|
||||
return 0;
|
||||
if (access(path, F_OK) == 0)
|
||||
return 1;
|
||||
/* an installation from before USER.txt: profile/<user>.md */
|
||||
{
|
||||
char dir[700];
|
||||
const char *user = sp_user_name();
|
||||
|
||||
snprintf(dir, sizeof(dir), "%s/profile/%s.md", session_dir, user);
|
||||
return access(dir, F_OK) == 0;
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
* splinter -- the first conversation, and what it leaves behind.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_INTERVIEW_H
|
||||
#define SPLINTER_INTERVIEW_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
/*
|
||||
* The interview is a model-driven conversation: the system prompt tells the
|
||||
* model to get to know the user and end with INTERVIEW_COMPLETE. The summary
|
||||
* before that line is written to <session dir>/USER.txt and read at the start
|
||||
* of every later session.
|
||||
*/
|
||||
const char *sp_interview_system(void);
|
||||
|
||||
/* "\n\nWhat you know about the user:\n...", malloc'd; NULL when there is none. */
|
||||
char *sp_interview_user_block(const char *session_dir);
|
||||
|
||||
/*
|
||||
* If answer carries INTERVIEW_COMPLETE, write the summary to USER.txt and copy
|
||||
* the answer without the marker to clean. 1 when it captured something.
|
||||
*/
|
||||
int sp_interview_capture(const char *session_dir, const char *answer,
|
||||
char *clean, size_t cap);
|
||||
|
||||
/* 1 when USER.txt exists (the old profile/<user>.md still counts). */
|
||||
int sp_profile_exists(const char *session_dir);
|
||||
|
||||
#endif /* SPLINTER_INTERVIEW_H */
|
||||
@@ -1,12 +0,0 @@
|
||||
/*
|
||||
* splinter -- the JSON implementation, instantiated once.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* libmcp's parser is header-only: exactly one translation unit defines
|
||||
* MCP_IMPLEMENTATION, every other one only sees the declarations. Doing it
|
||||
* twice is a link error, not a subtle bug, which is the point.
|
||||
*/
|
||||
#define MCP_IMPLEMENTATION
|
||||
#include "mcp.h"
|
||||
@@ -1,143 +0,0 @@
|
||||
/*
|
||||
* splinter -- what happened, on disk.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Every session keeps a log directory next to it:
|
||||
*
|
||||
* ~/.splinter/logs/<session-id>/session.log readable, everything, in order
|
||||
* ~/.splinter/logs/<session-id>/wire.jsonl request bodies and replies, raw
|
||||
*
|
||||
* "Everything" means everything: the user's words, the model's answer, its
|
||||
* reasoning, every tool call with its arguments, every observation, the token
|
||||
* counts, and every failure. A log that only keeps what looked good is a log
|
||||
* that cannot explain a bad turn.
|
||||
*
|
||||
* Text is written as it arrived - no truncation, no escaping - so a diff or a
|
||||
* stack trace reads the same as it did on screen. Records are separated by a
|
||||
* blank line and start with a timestamp and the kind.
|
||||
*/
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "log.h"
|
||||
|
||||
static char log_path[700];
|
||||
static char wire_path[700];
|
||||
static int active;
|
||||
|
||||
static void
|
||||
mkdirs(const char *path)
|
||||
{
|
||||
char tmp[700];
|
||||
size_t i;
|
||||
|
||||
snprintf(tmp, sizeof(tmp), "%s", path);
|
||||
for (i = 1; tmp[i] != '\0'; i++) {
|
||||
if (tmp[i] != '/')
|
||||
continue;
|
||||
tmp[i] = '\0';
|
||||
(void)mkdir(tmp, 0700);
|
||||
tmp[i] = '/';
|
||||
}
|
||||
(void)mkdir(tmp, 0700);
|
||||
}
|
||||
|
||||
int
|
||||
sp_log_open(const char *session_dir, const char *id)
|
||||
{
|
||||
if (session_dir == NULL || id == NULL)
|
||||
return -1;
|
||||
snprintf(log_path, sizeof(log_path), "%s/logs/%s", session_dir, id);
|
||||
mkdirs(log_path);
|
||||
snprintf(wire_path, sizeof(wire_path), "%s/logs/%s/wire.jsonl",
|
||||
session_dir, id);
|
||||
active = 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_log_active(void)
|
||||
{
|
||||
return active;
|
||||
}
|
||||
|
||||
/*
|
||||
* One record: timestamp, kind, then the text untouched, then a blank line.
|
||||
* Append-only and unbuffered per call, so a crash leaves what happened up to
|
||||
* the crash instead of nothing.
|
||||
*/
|
||||
void
|
||||
sp_logf(const char *kind, const char *fmt, ...)
|
||||
{
|
||||
char path[800], stamp[32];
|
||||
time_t now = time(NULL);
|
||||
struct tm tm;
|
||||
va_list ap;
|
||||
FILE *f;
|
||||
|
||||
if (!active)
|
||||
return;
|
||||
(void)localtime_r(&now, &tm);
|
||||
strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", &tm);
|
||||
snprintf(path, sizeof(path), "%s/session.log", log_path);
|
||||
f = fopen(path, "a");
|
||||
if (f == NULL)
|
||||
return;
|
||||
fprintf(f, "[%s] %s\n", stamp, kind);
|
||||
va_start(ap, fmt);
|
||||
vfprintf(f, fmt, ap);
|
||||
va_end(ap);
|
||||
fprintf(f, "\n\n");
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
/* The wire: what was actually sent and received, one JSON record per line. */
|
||||
void
|
||||
sp_log_wire(const char *dir, const char *direction, const char *body,
|
||||
size_t len)
|
||||
{
|
||||
char path[800];
|
||||
FILE *f;
|
||||
|
||||
if (!active || body == NULL)
|
||||
return;
|
||||
snprintf(path, sizeof(path), "%s/wire.jsonl", dir);
|
||||
f = fopen(path, "a");
|
||||
if (f == NULL)
|
||||
return;
|
||||
fprintf(f, "{\"dir\":\"%s\",\"bytes\":%zu,\"body\":\"", direction, len);
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < len && i < 262144; i++) {
|
||||
unsigned char c = (unsigned char)body[i];
|
||||
|
||||
if (c == '"' || c == '\\')
|
||||
fprintf(f, "\\%c", c);
|
||||
else if (c == '\n')
|
||||
fputs("\\n", f);
|
||||
else if (c == '\r')
|
||||
fputs("\\r", f);
|
||||
else if (c == '\t')
|
||||
fputs("\\t", f);
|
||||
else if (c < 0x20)
|
||||
fprintf(f, "\\u%04x", c);
|
||||
else
|
||||
fputc(c, f);
|
||||
}
|
||||
}
|
||||
fprintf(f, "\"}\n");
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_log_dir(void)
|
||||
{
|
||||
return active ? log_path : NULL;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
/*
|
||||
* splinter -- session logs.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_LOG_H
|
||||
#define SPLINTER_LOG_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
/* Open the log directory for a session: <session_dir>/logs/<id>/. */
|
||||
int sp_log_open(const char *session_dir, const char *id);
|
||||
int sp_log_active(void);
|
||||
const char *sp_log_dir(void);
|
||||
|
||||
/* Append a record: timestamp, kind, text, blank line. */
|
||||
void sp_logf(const char *kind, const char *fmt, ...);
|
||||
|
||||
/* Append one wire record (request/reply) to wire.jsonl in the same directory. */
|
||||
void sp_log_wire(const char *dir, const char *direction, const char *body,
|
||||
size_t len);
|
||||
|
||||
#endif /* SPLINTER_LOG_H */
|
||||
@@ -1,487 +0,0 @@
|
||||
/*
|
||||
* splinter -- the MCP server.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* The other direction of plugins/mcp: here splinter *is* the server, so another
|
||||
* agent can use its tools over MCP.
|
||||
*
|
||||
* splinter --mcp-server-listen 127.0.0.1 --mcp-listen-port 8098
|
||||
* SPLINTER_MCP_TOKEN=... splinter --mcp-server-listen 0.0.0.0 ...
|
||||
*
|
||||
* Speaks newline-delimited JSON-RPC over TCP - the same framing MCP uses on
|
||||
* stdio, just on a socket. Handles initialize, tools/list and tools/call, plus
|
||||
* the notifications a client sends.
|
||||
*
|
||||
* Authorization is the point: a read tool is served, a mutating or destructive
|
||||
* one is refused unless the server was started with --autonomous. A remote agent
|
||||
* does not get to run shell commands on this machine because it asked nicely. *
|
||||
* Who may connect at all is the step before that. 'read' alone hands out every
|
||||
* file this user can open, so an address other than loopback needs a token:
|
||||
* SPLINTER_MCP_TOKEN, and every connection starts with the line
|
||||
*
|
||||
* AUTH <token>
|
||||
*
|
||||
* before any JSON-RPC; anything else closes it. Without a token the server
|
||||
* refuses to listen beyond 127.0.0.0/8. There is no TLS - put it behind ssh or
|
||||
* a tunnel when the network is not yours.
|
||||
*/
|
||||
#include <arpa/inet.h>
|
||||
#include <errno.h>
|
||||
#include <netinet/in.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_engine.h"
|
||||
#include "mcp.h"
|
||||
#include "mcpserver.h"
|
||||
#include "mcpsession.h"
|
||||
|
||||
static volatile int mcp_stop;
|
||||
|
||||
/*
|
||||
* What a connection works on. With an engine the registry is asked from it on
|
||||
* every call (a session switch replaces the engine and with it the registry);
|
||||
* without one the server serves the registry it was handed.
|
||||
*/
|
||||
struct srv {
|
||||
struct sp_engine **eng;
|
||||
const struct sp_engine_opts *opts;
|
||||
const struct sp_registry *reg;
|
||||
};
|
||||
|
||||
static const struct sp_registry *
|
||||
srv_reg(const struct srv *s)
|
||||
{
|
||||
if (s->eng != NULL && *s->eng != NULL)
|
||||
return sp_engine_registry(*s->eng);
|
||||
return s->reg;
|
||||
}
|
||||
|
||||
static void
|
||||
on_signal(int sig)
|
||||
{
|
||||
(void)sig;
|
||||
mcp_stop = 1;
|
||||
}
|
||||
|
||||
/* The object that follows "arguments" in the raw line, braces balanced. */
|
||||
static const char *
|
||||
slice_object(const char *at, size_t *lenp)
|
||||
{
|
||||
const char *start;
|
||||
int depth = 0, in_str = 0, esc = 0;
|
||||
|
||||
start = strchr(at, '{');
|
||||
if (start == NULL)
|
||||
return NULL;
|
||||
for (at = start; *at != '\0'; at++) {
|
||||
if (in_str) {
|
||||
if (esc)
|
||||
esc = 0;
|
||||
else if (*at == '\\')
|
||||
esc = 1;
|
||||
else if (*at == '"')
|
||||
in_str = 0;
|
||||
continue;
|
||||
}
|
||||
if (*at == '"')
|
||||
in_str = 1;
|
||||
else if (*at == '{')
|
||||
depth++;
|
||||
else if (*at == '}') {
|
||||
depth--;
|
||||
if (depth == 0) {
|
||||
*lenp = (size_t)(at - start) + 1;
|
||||
return start;
|
||||
}
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void
|
||||
write_all(int fd, const char *buf, size_t len)
|
||||
{
|
||||
while (len > 0) {
|
||||
ssize_t n = write(fd, buf, len);
|
||||
|
||||
if (n <= 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
buf += n;
|
||||
len -= (size_t)n;
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
reply_ok(int fd, int id, const char *result)
|
||||
{
|
||||
struct sp_buf b;
|
||||
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return;
|
||||
sp_buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"result\":%s}\n",
|
||||
id, result);
|
||||
write_all(fd, b.p, b.len);
|
||||
sp_buf_free(&b);
|
||||
}
|
||||
|
||||
static void
|
||||
reply_error(int fd, int id, int code, const char *message)
|
||||
{
|
||||
struct sp_buf b;
|
||||
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return;
|
||||
sp_buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"error\":"
|
||||
"{\"code\":%d,\"message\":\"", id, code);
|
||||
(void)sp_json_escape(&b, message);
|
||||
sp_buf_puts(&b, "\"}}\n");
|
||||
write_all(fd, b.p, b.len);
|
||||
sp_buf_free(&b);
|
||||
}
|
||||
|
||||
static void
|
||||
reply_tools(int fd, int id, const struct srv *s)
|
||||
{
|
||||
struct sp_buf b;
|
||||
size_t i, ntv = 0;
|
||||
const struct sp_tool *tv = NULL;
|
||||
int first = 1;
|
||||
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return;
|
||||
sp_buf_puts(&b, "{\"tools\":[");
|
||||
if (srv_reg(s) != NULL)
|
||||
tv = sp_registry_tools(srv_reg(s), &ntv);
|
||||
for (i = 0; i < ntv; i++) {
|
||||
const struct sp_tool *t = &tv[i];
|
||||
|
||||
if (!first)
|
||||
sp_buf_puts(&b, ",");
|
||||
first = 0;
|
||||
sp_buf_puts(&b, "{\"name\":\"");
|
||||
(void)sp_json_escape(&b, t->name);
|
||||
sp_buf_puts(&b, "\",\"description\":\"");
|
||||
(void)sp_json_escape(&b, t->description != NULL ? t->description :
|
||||
"");
|
||||
sp_buf_puts(&b, "\",\"inputSchema\":");
|
||||
sp_buf_puts(&b, t->params != NULL ? t->params :
|
||||
"{\"type\":\"object\",\"properties\":{}}");
|
||||
sp_buf_puts(&b, "}");
|
||||
}
|
||||
sp_mcpsession_tools(&b, &first);
|
||||
sp_buf_puts(&b, "]}");
|
||||
reply_ok(fd, id, b.p);
|
||||
sp_buf_free(&b);
|
||||
}
|
||||
|
||||
static void
|
||||
call_tool(int fd, int id, const struct srv *s, const char *line,
|
||||
int allow_mutate)
|
||||
{
|
||||
const struct sp_tool *t;
|
||||
const char *name, *argstart = NULL;
|
||||
char namebuf[128];
|
||||
struct sp_buf raw, out;
|
||||
mcp_json *v;
|
||||
size_t arglen = 0;
|
||||
int mine;
|
||||
|
||||
v = mcp_parse(line);
|
||||
if (v == NULL) {
|
||||
reply_error(fd, id, -32700, "parse error");
|
||||
return;
|
||||
}
|
||||
name = NULL;
|
||||
{
|
||||
const mcp_json *params = mcp_arg(v, "params");
|
||||
const mcp_json *args;
|
||||
|
||||
if (params != NULL) {
|
||||
name = mcp_arg_string(params, "name");
|
||||
args = mcp_arg(params, "arguments");
|
||||
(void)args;
|
||||
}
|
||||
}
|
||||
if (name == NULL) {
|
||||
mcp_json_free(v);
|
||||
reply_error(fd, id, -32602, "params.name is required");
|
||||
return;
|
||||
}
|
||||
/* the name lives in the parsed JSON: copy it before freeing that */
|
||||
snprintf(namebuf, sizeof(namebuf), "%s", name);
|
||||
name = namebuf;
|
||||
mine = sp_mcpsession_has(name);
|
||||
/* the arguments object, as text - tools parse their own arguments */
|
||||
{
|
||||
const char *p = strstr(line, "\"arguments\"");
|
||||
|
||||
if (p != NULL) {
|
||||
const char *slice = slice_object(p, &arglen);
|
||||
|
||||
argstart = slice;
|
||||
}
|
||||
}
|
||||
mcp_json_free(v);
|
||||
|
||||
if (sp_buf_init(&raw) != 0)
|
||||
return;
|
||||
if (argstart != NULL)
|
||||
(void)sp_buf_add(&raw, argstart, arglen);
|
||||
else
|
||||
(void)sp_buf_puts(&raw, "{}");
|
||||
if (sp_buf_init(&out) != 0) {
|
||||
sp_buf_free(&raw);
|
||||
return;
|
||||
}
|
||||
if (mine) {
|
||||
if (sp_mcpsession_auth(name) != SP_AUTH_READ && !allow_mutate) {
|
||||
sp_buf_free(&raw);
|
||||
sp_buf_free(&out);
|
||||
reply_error(fd, id, -32000, "tool needs authorization; "
|
||||
"start the server with --autonomous to allow "
|
||||
"mutating calls");
|
||||
return;
|
||||
}
|
||||
(void)sp_mcpsession_call(name, raw.p, &out);
|
||||
} else {
|
||||
t = srv_reg(s) != NULL ? sp_registry_find(srv_reg(s), name) : NULL;
|
||||
if (t == NULL) {
|
||||
sp_buf_free(&raw);
|
||||
sp_buf_free(&out);
|
||||
reply_error(fd, id, -32601, "unknown tool");
|
||||
return;
|
||||
}
|
||||
if (t->auth != SP_AUTH_READ && !allow_mutate) {
|
||||
sp_buf_free(&raw);
|
||||
sp_buf_free(&out);
|
||||
reply_error(fd, id, -32000, "tool needs authorization; "
|
||||
"start the server with --autonomous to allow "
|
||||
"mutating calls");
|
||||
return;
|
||||
}
|
||||
if (t->run(raw.p, &out, t->ctx) != 0)
|
||||
sp_buf_puts(&out, "error: tool failed");
|
||||
}
|
||||
{
|
||||
struct sp_buf res;
|
||||
|
||||
if (sp_buf_init(&res) == 0) {
|
||||
sp_buf_puts(&res, "{\"content\":[{\"type\":\"text\",\"text\":\"");
|
||||
(void)sp_json_escape(&res, out.p != NULL ? out.p : "");
|
||||
sp_buf_puts(&res, "\"}]}");
|
||||
reply_ok(fd, id, res.p);
|
||||
sp_buf_free(&res);
|
||||
}
|
||||
}
|
||||
sp_buf_free(&raw);
|
||||
sp_buf_free(&out);
|
||||
}
|
||||
|
||||
static void
|
||||
handle_line(int fd, const struct srv *s, const char *line, int allow_mutate)
|
||||
{
|
||||
mcp_json *v;
|
||||
const char *method;
|
||||
int id = -1;
|
||||
|
||||
v = mcp_parse(line);
|
||||
if (v == NULL) {
|
||||
reply_error(fd, 0, -32700, "parse error");
|
||||
return;
|
||||
}
|
||||
method = mcp_arg_string(v, "method");
|
||||
id = mcp_arg_int(v, "id", -1);
|
||||
if (method == NULL) {
|
||||
mcp_json_free(v);
|
||||
return;
|
||||
}
|
||||
if (strcmp(method, "initialize") == 0) {
|
||||
char res[512];
|
||||
|
||||
snprintf(res, sizeof(res),
|
||||
"{\"protocolVersion\":\"2024-11-05\",\"capabilities\":"
|
||||
"{\"tools\":{}},\"serverInfo\":{\"name\":\"splinter\","
|
||||
"\"version\":\"%s\"}}", SP_VERSION);
|
||||
mcp_json_free(v);
|
||||
reply_ok(fd, id, res);
|
||||
return;
|
||||
}
|
||||
if (strcmp(method, "tools/list") == 0) {
|
||||
mcp_json_free(v);
|
||||
reply_tools(fd, id, s);
|
||||
return;
|
||||
}
|
||||
if (strcmp(method, "tools/call") == 0) {
|
||||
mcp_json_free(v);
|
||||
call_tool(fd, id, s, line, allow_mutate);
|
||||
return;
|
||||
}
|
||||
mcp_json_free(v);
|
||||
if (id >= 0)
|
||||
reply_error(fd, id, -32601, "unknown method");
|
||||
/* a notification has no id and gets no answer */
|
||||
}
|
||||
|
||||
/* compare without stopping at the first difference: no timing hint */
|
||||
static int
|
||||
token_equal(const char *a, const char *b)
|
||||
{
|
||||
size_t la = strlen(a), lb = strlen(b), i;
|
||||
unsigned char d = la != lb;
|
||||
|
||||
for (i = 0; i < la; i++)
|
||||
d |= (unsigned char)(a[i] ^ b[i % (lb > 0 ? lb : 1)]);
|
||||
return d == 0;
|
||||
}
|
||||
|
||||
static void
|
||||
serve_conn(int fd, const struct srv *s, int allow_mutate, const char *token)
|
||||
{
|
||||
char line[16384];
|
||||
size_t used = 0;
|
||||
int authed = token == NULL;
|
||||
|
||||
for (;;) {
|
||||
ssize_t got = read(fd, line + used, sizeof(line) - used - 1);
|
||||
|
||||
if (got <= 0) {
|
||||
if (got < 0 && errno == EINTR)
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
used += (size_t)got;
|
||||
line[used] = '\0';
|
||||
for (;;) {
|
||||
char *nl = strchr(line, '\n');
|
||||
size_t len;
|
||||
|
||||
if (nl == NULL)
|
||||
break;
|
||||
*nl = '\0';
|
||||
if (!authed) {
|
||||
size_t l = strlen(line);
|
||||
|
||||
if (l > 0 && line[l - 1] == '\r')
|
||||
line[l - 1] = '\0';
|
||||
if (strncmp(line, "AUTH ", 5) != 0 ||
|
||||
!token_equal(line + 5, token)) {
|
||||
reply_error(fd, 0, -32001,
|
||||
"authentication required");
|
||||
return;
|
||||
}
|
||||
authed = 1;
|
||||
} else if (line[0] == '{')
|
||||
handle_line(fd, s, line, allow_mutate);
|
||||
len = (size_t)(nl - line) + 1;
|
||||
memmove(line, line + len, used - len + 1);
|
||||
used -= len;
|
||||
}
|
||||
if (used >= sizeof(line) - 1)
|
||||
used = 0; /* a line we cannot hold */
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
sp_mcp_serve(struct sp_engine **eng, const struct sp_engine_opts *opts,
|
||||
const struct sp_registry *reg, const char *ip, int port,
|
||||
int allow_mutate, int own_signals, struct sp_buf *err)
|
||||
{
|
||||
struct srv srv;
|
||||
int s, one = 1;
|
||||
struct sockaddr_in addr;
|
||||
|
||||
const char *token = getenv("SPLINTER_MCP_TOKEN");
|
||||
size_t ntools = reg != NULL ? reg->len : 0;
|
||||
|
||||
memset(&srv, 0, sizeof(srv));
|
||||
srv.eng = eng;
|
||||
srv.opts = opts;
|
||||
srv.reg = reg;
|
||||
sp_mcpsession_bind(eng, opts);
|
||||
if (eng != NULL && *eng != NULL && srv_reg(&srv) != NULL)
|
||||
ntools = srv_reg(&srv)->len;
|
||||
|
||||
if (ip == NULL || *ip == '\0')
|
||||
ip = "127.0.0.1";
|
||||
if (token != NULL && *token == '\0')
|
||||
token = NULL;
|
||||
if (token == NULL && strncmp(ip, "127.", 4) != 0) {
|
||||
sp_buf_printf(err, "mcp: refusing to serve on %s without "
|
||||
"SPLINTER_MCP_TOKEN: 'read' alone would give the network "
|
||||
"every file of this user", ip);
|
||||
return -1;
|
||||
}
|
||||
s = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (s < 0) {
|
||||
sp_buf_printf(err, "mcp: socket: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
(void)setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons((unsigned short)port);
|
||||
if (inet_pton(AF_INET, ip, &addr.sin_addr) != 1) {
|
||||
sp_buf_printf(err, "mcp: '%s' is not an address", ip);
|
||||
close(s);
|
||||
return -1;
|
||||
}
|
||||
if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
|
||||
sp_buf_printf(err, "mcp: bind %s:%d: %s", ip, port,
|
||||
strerror(errno));
|
||||
close(s);
|
||||
return -1;
|
||||
}
|
||||
if (listen(s, 8) != 0) {
|
||||
sp_buf_printf(err, "mcp: listen: %s", strerror(errno));
|
||||
close(s);
|
||||
return -1;
|
||||
}
|
||||
if (own_signals) {
|
||||
(void)signal(SIGINT, on_signal);
|
||||
(void)signal(SIGTERM, on_signal);
|
||||
}
|
||||
/* a client that hangs up mid-reply is a closed connection, not our death */
|
||||
(void)signal(SIGPIPE, SIG_IGN);
|
||||
fprintf(stderr, "splinter: MCP server on %s:%d (%zu tools + %d "
|
||||
"session tools, %s, %s)\n", ip, port, ntools, 12,
|
||||
allow_mutate ? "mutating allowed" : "read only",
|
||||
token != NULL ? "token required" : "loopback, no token");
|
||||
|
||||
while (!mcp_stop) {
|
||||
int c = accept(s, NULL, NULL);
|
||||
|
||||
if (c < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
{
|
||||
/*
|
||||
* One connection at a time, so an idle one must not hold
|
||||
* the server forever: five quiet minutes and it is closed.
|
||||
*/
|
||||
struct timeval tv = { 300, 0 };
|
||||
|
||||
(void)setsockopt(c, SOL_SOCKET, SO_RCVTIMEO, &tv,
|
||||
sizeof(tv));
|
||||
}
|
||||
serve_conn(c, &srv, allow_mutate, token);
|
||||
close(c);
|
||||
}
|
||||
close(s);
|
||||
fprintf(stderr, "splinter: MCP server stopped\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
/*
|
||||
* splinter -- the MCP server.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_MCPSERVER_H
|
||||
#define SPLINTER_MCPSERVER_H
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
struct sp_engine;
|
||||
struct sp_engine_opts;
|
||||
|
||||
/*
|
||||
* eng/opts make the session tools work; NULL eng serves the registry only.
|
||||
* own_signals: 0 when the caller already has SIGINT/SIGTERM handlers (the
|
||||
* daemon runs the MCP server in a thread).
|
||||
*/
|
||||
int sp_mcp_serve(struct sp_engine **eng, const struct sp_engine_opts *opts,
|
||||
const struct sp_registry *, const char *ip, int port,
|
||||
int allow_mutate, int own_signals, struct sp_buf *err);
|
||||
|
||||
#endif /* SPLINTER_MCPSERVER_H */
|
||||
@@ -1,597 +0,0 @@
|
||||
/*
|
||||
* splinter -- the session tools of the MCP server.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* The file tools the MCP server exposes are the ones any MCP client already
|
||||
* has. What only splinter can answer is its own sessions: which exist, what
|
||||
* they said, what the model is, and how to put a prompt in and get the answer
|
||||
* back. That is this file.
|
||||
*
|
||||
* splinter_sessions list the sessions of this state directory
|
||||
* splinter_state model, profile, session, busy, counters
|
||||
* splinter_models the selectors /model takes
|
||||
* splinter_history the open session's user and assistant messages
|
||||
* splinter_agents the profiles
|
||||
* splinter_say submit a prompt, wait, return the answer
|
||||
* splinter_open switch to another session (or "new")
|
||||
* splinter_model switch the model (an ordinary /model selector)
|
||||
* splinter_agent switch the profile by name
|
||||
* splinter_steer type into the running turn
|
||||
* splinter_cancel cancel the running turn
|
||||
* splinter_approve answer a pending approval
|
||||
*
|
||||
* A turn that parks on an approval is not an error: splinter_say returns the
|
||||
* question and leaves the turn waiting, and splinter_approve answers it. The
|
||||
* server is one connection at a time, so there is at most one such turn.
|
||||
*
|
||||
* Authorization goes through the same gate as the file tools: reads are
|
||||
* always served, anything that starts a turn or changes a session needs
|
||||
* --autonomous on the server.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_engine.h"
|
||||
#include "mcp.h"
|
||||
#include "mcpsession.h"
|
||||
|
||||
static struct sp_engine **session_eng;
|
||||
static const struct sp_engine_opts *session_opts;
|
||||
|
||||
#define SAY_TIMEOUT_S 3600
|
||||
#define SAY_ANSWER_MAX (256 * 1024)
|
||||
#define HIST_TEXT_MAX 600
|
||||
|
||||
void
|
||||
sp_mcpsession_bind(struct sp_engine **eng, const struct sp_engine_opts *opts)
|
||||
{
|
||||
session_eng = eng;
|
||||
session_opts = opts;
|
||||
}
|
||||
|
||||
static const char *
|
||||
arg_string(const char *args, const char *key, char *out, size_t cap)
|
||||
{
|
||||
mcp_json *v;
|
||||
const char *s;
|
||||
|
||||
out[0] = '\0';
|
||||
if (args == NULL || *args == '\0')
|
||||
return out;
|
||||
v = mcp_parse(args);
|
||||
if (v == NULL)
|
||||
return out;
|
||||
s = mcp_arg_string(v, key);
|
||||
if (s != NULL)
|
||||
snprintf(out, cap, "%s", s);
|
||||
mcp_json_free(v);
|
||||
return out;
|
||||
}
|
||||
|
||||
static int
|
||||
arg_int(const char *args, const char *key, int dflt)
|
||||
{
|
||||
mcp_json *v;
|
||||
int n = dflt;
|
||||
|
||||
if (args == NULL || *args == '\0')
|
||||
return dflt;
|
||||
v = mcp_parse(args);
|
||||
if (v == NULL)
|
||||
return dflt;
|
||||
n = mcp_arg_int(v, key, dflt);
|
||||
mcp_json_free(v);
|
||||
return n;
|
||||
}
|
||||
|
||||
static int
|
||||
arg_bool(const char *args, const char *key, int dflt)
|
||||
{
|
||||
mcp_json *v;
|
||||
int n = dflt;
|
||||
|
||||
if (args == NULL || *args == '\0')
|
||||
return dflt;
|
||||
v = mcp_parse(args);
|
||||
if (v == NULL)
|
||||
return dflt;
|
||||
n = mcp_arg_bool(v, key, dflt);
|
||||
mcp_json_free(v);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* ---- the tools ---- */
|
||||
|
||||
static const struct {
|
||||
const char *name;
|
||||
int auth;
|
||||
const char *description;
|
||||
const char *schema;
|
||||
} tools[] = {
|
||||
{ "splinter_sessions", SP_AUTH_READ,
|
||||
"List the splinter sessions in this state directory: id, title, "
|
||||
"mtime, size, and which one is open.",
|
||||
"{\"type\":\"object\",\"properties\":{}}" },
|
||||
{ "splinter_state", SP_AUTH_READ,
|
||||
"The running splinter: model, endpoint, profile, session, directory, "
|
||||
"busy/waiting, tokens, context use and the last turn.",
|
||||
"{\"type\":\"object\",\"properties\":{}}" },
|
||||
{ "splinter_models", SP_AUTH_READ,
|
||||
"The selectors /model takes (providers, then pools), with the current "
|
||||
"one marked.",
|
||||
"{\"type\":\"object\",\"properties\":{}}" },
|
||||
{ "splinter_agents", SP_AUTH_READ,
|
||||
"The agent profiles of this run, with the active one marked.",
|
||||
"{\"type\":\"object\",\"properties\":{}}" },
|
||||
{ "splinter_history", SP_AUTH_READ,
|
||||
"The open session's user and assistant messages, oldest first.",
|
||||
"{\"type\":\"object\",\"properties\":{\"limit\":{\"type\":\"integer\","
|
||||
"\"description\":\"how many messages, default 20, max 100\"}}}" },
|
||||
{ "splinter_say", SP_AUTH_MUTATE,
|
||||
"Send a prompt to the open session and wait for the answer. Returns "
|
||||
"the answer; if the turn waits for an approval, returns the question "
|
||||
"and leaves the turn parked (call splinter_approve).",
|
||||
"{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\","
|
||||
"\"description\":\"the prompt\"}},\"required\":[\"text\"]}" },
|
||||
{ "splinter_open", SP_AUTH_MUTATE,
|
||||
"Switch splinter to another session: a session id, \"new\" for a fresh "
|
||||
"one, or \"last\" for the newest.",
|
||||
"{\"type\":\"object\",\"properties\":{\"session\":{\"type\":\"string\","
|
||||
"\"description\":\"session id, new or last\"}},"
|
||||
"\"required\":[\"session\"]}" },
|
||||
{ "splinter_model", SP_AUTH_MUTATE,
|
||||
"Switch the model: a provider id, a pool id, provider/model, or a "
|
||||
"model name the provider serves (the same selector /model takes).",
|
||||
"{\"type\":\"object\",\"properties\":{\"model\":{\"type\":\"string\","
|
||||
"\"description\":\"what goes after /model\"}},\"required\":[\"model\"]}" },
|
||||
{ "splinter_agent", SP_AUTH_MUTATE,
|
||||
"Switch the agent profile by name.",
|
||||
"{\"type\":\"object\",\"properties\":{\"agent\":{\"type\":\"string\","
|
||||
"\"description\":\"profile name\"}},\"required\":[\"agent\"]}" },
|
||||
{ "splinter_steer", SP_AUTH_MUTATE,
|
||||
"Type into the running turn; the loop picks it up at the next step "
|
||||
"boundary.",
|
||||
"{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\","
|
||||
"\"description\":\"the steering text\"}},\"required\":[\"text\"]}" },
|
||||
{ "splinter_cancel", SP_AUTH_MUTATE,
|
||||
"Cancel the running turn.", "{\"type\":\"object\",\"properties\":{}}" },
|
||||
{ "splinter_approve", SP_AUTH_MUTATE,
|
||||
"Answer a pending approval: allow true runs the tool, false denies it "
|
||||
"(the denial becomes the observation the model sees).",
|
||||
"{\"type\":\"object\",\"properties\":{\"allow\":{\"type\":\"boolean\"}},"
|
||||
"\"required\":[\"allow\"]}" }
|
||||
};
|
||||
|
||||
int
|
||||
sp_mcpsession_has(const char *name)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < sizeof(tools) / sizeof(tools[0]); i++)
|
||||
if (strcmp(tools[i].name, name) == 0)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_mcpsession_auth(const char *name)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < sizeof(tools) / sizeof(tools[0]); i++)
|
||||
if (strcmp(tools[i].name, name) == 0)
|
||||
return tools[i].auth;
|
||||
return SP_AUTH_READ;
|
||||
}
|
||||
|
||||
/* the JSON entries for tools/list, each prefixed with a comma when !first */
|
||||
void
|
||||
sp_mcpsession_tools(struct sp_buf *b, int *first)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < sizeof(tools) / sizeof(tools[0]); i++) {
|
||||
if (!*first)
|
||||
sp_buf_puts(b, ",");
|
||||
*first = 0;
|
||||
sp_buf_puts(b, "{\"name\":\"");
|
||||
(void)sp_json_escape(b, tools[i].name);
|
||||
sp_buf_puts(b, "\",\"description\":\"");
|
||||
(void)sp_json_escape(b, tools[i].description);
|
||||
sp_buf_puts(b, "\",\"inputSchema\":");
|
||||
sp_buf_puts(b, tools[i].schema);
|
||||
sp_buf_puts(b, "}");
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the handlers ---- */
|
||||
|
||||
static int
|
||||
tool_sessions(struct sp_buf *out)
|
||||
{
|
||||
struct sp_session_brief v[200];
|
||||
const char *cur;
|
||||
int n, i;
|
||||
const char *dir;
|
||||
|
||||
dir = sp_engine_state_dir(*session_eng);
|
||||
cur = sp_engine_session_id(*session_eng);
|
||||
n = sp_session_list(dir, v, 200);
|
||||
if (n < 0)
|
||||
n = 0;
|
||||
for (i = 0; i < n; i++) {
|
||||
char when[32] = "";
|
||||
time_t t = (time_t)v[i].mtime;
|
||||
struct tm tm;
|
||||
|
||||
if (localtime_r(&t, &tm) != NULL)
|
||||
strftime(when, sizeof(when), "%Y-%m-%d %H:%M", &tm);
|
||||
sp_buf_printf(out, "%c %s %-28s %7zu %s\n",
|
||||
strcmp(v[i].id, cur) == 0 ? '*' : ' ', when, v[i].id,
|
||||
v[i].bytes, v[i].title);
|
||||
}
|
||||
if (n == 0)
|
||||
sp_buf_puts(out, "no sessions yet\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_state(struct sp_buf *out)
|
||||
{
|
||||
struct sp_engine_state st;
|
||||
|
||||
if (sp_engine_state(*session_eng, &st) != 0) {
|
||||
sp_buf_puts(out, "error: no engine");
|
||||
return 0;
|
||||
}
|
||||
sp_buf_printf(out, "model: %s\n", st.model);
|
||||
sp_buf_printf(out, "endpoint: %s\n", st.endpoint);
|
||||
sp_buf_printf(out, "agent: %s\n", st.agent);
|
||||
sp_buf_printf(out, "session: %s\n", st.session);
|
||||
sp_buf_printf(out, "dir: %s\n", st.dir);
|
||||
sp_buf_printf(out, "busy: %s%s\n", st.busy ? "yes" : "no",
|
||||
st.waiting ? " (waiting for an approval)" : "");
|
||||
sp_buf_printf(out, "tokens: %zu in / %zu out\n", st.tokens_in,
|
||||
st.tokens_out);
|
||||
sp_buf_printf(out, "ctx: %zu/%zu", st.ctx_used, st.ctx_max);
|
||||
if (st.ctx_max > 0)
|
||||
sp_buf_printf(out, " (%u%%)",
|
||||
(unsigned)(100.0 * (double)st.ctx_used / (double)st.ctx_max));
|
||||
sp_buf_puts(out, "\n");
|
||||
sp_buf_printf(out, "last turn: %zu ms, %zu steps, %zu calls\n",
|
||||
st.last_ms, st.last_steps, st.last_calls);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_models(struct sp_buf *out)
|
||||
{
|
||||
struct sp_model_choice v[SP_MODEL_CHOICES];
|
||||
size_t n, i;
|
||||
|
||||
n = sp_engine_models(*session_eng, v, SP_MODEL_CHOICES);
|
||||
for (i = 0; i < n; i++)
|
||||
sp_buf_printf(out, "%c %-16s %s\n", v[i].current ? '*' : ' ',
|
||||
v[i].sel, v[i].label);
|
||||
if (n == 0)
|
||||
sp_buf_puts(out, "no models configured\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_agents(struct sp_buf *out)
|
||||
{
|
||||
int n, i, cur;
|
||||
|
||||
n = sp_engine_agents(*session_eng);
|
||||
cur = sp_engine_agent_cur(*session_eng);
|
||||
for (i = 0; i < n; i++)
|
||||
sp_buf_printf(out, "%c %s\n", i == cur ? '*' : ' ',
|
||||
sp_engine_agent_name(*session_eng, i));
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_history(const char *args, struct sp_buf *out)
|
||||
{
|
||||
const struct sp_conv *conv = sp_engine_conv(*session_eng);
|
||||
int limit = arg_int(args, "limit", 20);
|
||||
size_t i, from;
|
||||
|
||||
if (limit <= 0)
|
||||
limit = 20;
|
||||
if (limit > 100)
|
||||
limit = 100;
|
||||
if (conv == NULL) {
|
||||
sp_buf_puts(out, "no conversation");
|
||||
return 0;
|
||||
}
|
||||
from = conv->n > (size_t)limit ? conv->n - (size_t)limit : 0;
|
||||
for (i = from; i < conv->n; i++) {
|
||||
const struct sp_msg *m = &conv->v[i];
|
||||
char text[HIST_TEXT_MAX + 1];
|
||||
|
||||
if (m->role == NULL || m->content == NULL)
|
||||
continue;
|
||||
if (strcmp(m->role, "user") != 0 &&
|
||||
strcmp(m->role, "assistant") != 0)
|
||||
continue;
|
||||
snprintf(text, sizeof(text), "%s", m->content);
|
||||
sp_buf_printf(out, "[%s] %s\n", m->role, text);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* drain the events of a turn; returns 0 while it is still running */
|
||||
static int
|
||||
collect(struct sp_engine *e, char *answer, size_t cap, int *known,
|
||||
size_t *steps, size_t *calls)
|
||||
{
|
||||
struct sp_event ev;
|
||||
|
||||
while (sp_engine_poll(e, &ev)) {
|
||||
switch (ev.kind) {
|
||||
case SP_EV_TURN_END:
|
||||
if (ev.a != NULL)
|
||||
snprintf(answer, cap, "%s", ev.a);
|
||||
if (ev.b != NULL && ev.n != 0)
|
||||
snprintf(answer, cap, "error: %s", ev.b);
|
||||
*known = 1;
|
||||
break;
|
||||
case SP_EV_STEP:
|
||||
(*steps)++;
|
||||
break;
|
||||
case SP_EV_TOOL:
|
||||
(*calls)++;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
sp_engine_event_free(&ev);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_say(const char *args, struct sp_buf *out)
|
||||
{
|
||||
struct sp_engine *e = *session_eng;
|
||||
char text[8192], answer[SAY_ANSWER_MAX];
|
||||
char nm[64] = "", ar[512] = "";
|
||||
size_t steps = 0, calls = 0;
|
||||
int known = 0, auth = SP_AUTH_READ;
|
||||
time_t deadline;
|
||||
|
||||
arg_string(args, "text", text, sizeof(text));
|
||||
if (text[0] == '\0') {
|
||||
sp_buf_puts(out, "error: 'text' is required");
|
||||
return 0;
|
||||
}
|
||||
if (sp_engine_busy(e)) {
|
||||
sp_buf_puts(out, "error: a turn is already running "
|
||||
"(splinter_steer or splinter_cancel)");
|
||||
return 0;
|
||||
}
|
||||
answer[0] = '\0';
|
||||
if (sp_engine_submit(e, text) != 0) {
|
||||
sp_buf_puts(out, "error: cannot start the turn");
|
||||
return 0;
|
||||
}
|
||||
deadline = time(NULL) + SAY_TIMEOUT_S;
|
||||
for (;;) {
|
||||
struct sp_engine_state st;
|
||||
|
||||
collect(e, answer, sizeof(answer), &known, &steps, &calls);
|
||||
if (!sp_engine_busy(e))
|
||||
break;
|
||||
if (sp_engine_state(e, &st) == 0 && st.waiting &&
|
||||
sp_engine_approval(e, nm, sizeof(nm), &auth, ar,
|
||||
sizeof(ar))) {
|
||||
sp_buf_printf(out, "approval required: %s %s (%s)\n"
|
||||
"call splinter_approve {\"allow\":true} or "
|
||||
"{\"allow\":false}\n", nm, ar,
|
||||
auth == SP_AUTH_DESTRUCTIVE ? "destructive" :
|
||||
auth == SP_AUTH_MUTATE ? "mutate" : "read");
|
||||
return 0;
|
||||
}
|
||||
if (time(NULL) > deadline) {
|
||||
(void)sp_engine_cancel(e);
|
||||
sp_buf_puts(out, "error: the turn did not finish in "
|
||||
"time and was cancelled");
|
||||
return 0;
|
||||
}
|
||||
{
|
||||
struct timespec ts = { 0, 50 * 1000 * 1000L };
|
||||
|
||||
nanosleep(&ts, NULL);
|
||||
}
|
||||
}
|
||||
(void)sp_engine_wait(e);
|
||||
if (known)
|
||||
sp_buf_printf(out, "%s\n\n[%zu steps, %zu tool calls]\n",
|
||||
answer[0] != '\0' ? answer : "(empty answer)", steps, calls);
|
||||
else
|
||||
sp_buf_puts(out, "error: the turn ended without an answer\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_open(const char *args, struct sp_buf *out)
|
||||
{
|
||||
char id[128];
|
||||
struct sp_buf err;
|
||||
int rc;
|
||||
|
||||
arg_string(args, "session", id, sizeof(id));
|
||||
if (id[0] == '\0') {
|
||||
sp_buf_puts(out, "error: 'session' is required");
|
||||
return 0;
|
||||
}
|
||||
if (session_opts == NULL) {
|
||||
sp_buf_puts(out, "error: this server has no engine options; "
|
||||
"sessions cannot be switched");
|
||||
return 0;
|
||||
}
|
||||
if (sp_buf_init(&err) != 0)
|
||||
return -1;
|
||||
rc = sp_engine_switch(session_eng, session_opts, id, &err);
|
||||
if (rc != 0)
|
||||
sp_buf_printf(out, "error: %s\n",
|
||||
err.p != NULL ? err.p : "cannot open the session");
|
||||
else {
|
||||
struct sp_engine_state st;
|
||||
|
||||
if (sp_engine_state(*session_eng, &st) == 0)
|
||||
sp_buf_printf(out, "opened: %s\nmodel: %s\nagent: %s\n",
|
||||
st.session, st.model, st.agent);
|
||||
else
|
||||
sp_buf_puts(out, "opened\n");
|
||||
}
|
||||
sp_buf_free(&err);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_model(const char *args, struct sp_buf *out)
|
||||
{
|
||||
char sel[300], line[340];
|
||||
struct sp_buf reply;
|
||||
int kind;
|
||||
|
||||
arg_string(args, "model", sel, sizeof(sel));
|
||||
if (sel[0] == '\0') {
|
||||
sp_buf_puts(out, "error: 'model' is required "
|
||||
"(splinter_models lists the selectors)");
|
||||
return 0;
|
||||
}
|
||||
if (sp_engine_busy(*session_eng)) {
|
||||
sp_buf_puts(out, "error: a turn is running; wait or cancel it");
|
||||
return 0;
|
||||
}
|
||||
snprintf(line, sizeof(line), "/model %s", sel);
|
||||
if (sp_buf_init(&reply) != 0)
|
||||
return -1;
|
||||
kind = sp_engine_input(*session_eng, line, &reply);
|
||||
if (kind != SP_INPUT_HANDLED) {
|
||||
sp_buf_puts(out, "error: /model started a turn?");
|
||||
sp_buf_free(&reply);
|
||||
return 0;
|
||||
}
|
||||
sp_buf_printf(out, "%s", reply.p != NULL ? reply.p : "");
|
||||
sp_buf_free(&reply);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_agent(const char *args, struct sp_buf *out)
|
||||
{
|
||||
char name[64];
|
||||
int n, i, cur;
|
||||
|
||||
arg_string(args, "agent", name, sizeof(name));
|
||||
if (name[0] == '\0') {
|
||||
sp_buf_puts(out, "error: 'agent' is required");
|
||||
return 0;
|
||||
}
|
||||
if (sp_engine_busy(*session_eng)) {
|
||||
sp_buf_puts(out, "error: a turn is running; wait or cancel it");
|
||||
return 0;
|
||||
}
|
||||
n = sp_engine_agents(*session_eng);
|
||||
cur = sp_engine_agent_cur(*session_eng);
|
||||
for (i = 0; i < n; i++)
|
||||
if (strcmp(sp_engine_agent_name(*session_eng, i), name) == 0) {
|
||||
if (sp_engine_agent_switch(*session_eng, i) != 0) {
|
||||
sp_buf_puts(out, "error: cannot switch the agent");
|
||||
return 0;
|
||||
}
|
||||
sp_buf_printf(out, "agent: %s\n", name);
|
||||
return 0;
|
||||
}
|
||||
sp_buf_printf(out, "error: no agent '%s' (active is %s)\n", name,
|
||||
cur >= 0 ? sp_engine_agent_name(*session_eng, cur) : "?");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_steer(const char *args, struct sp_buf *out)
|
||||
{
|
||||
char text[4096];
|
||||
|
||||
arg_string(args, "text", text, sizeof(text));
|
||||
if (text[0] == '\0') {
|
||||
sp_buf_puts(out, "error: 'text' is required");
|
||||
return 0;
|
||||
}
|
||||
if (sp_engine_steer(*session_eng, text) != 0) {
|
||||
sp_buf_puts(out, "error: no turn is running");
|
||||
return 0;
|
||||
}
|
||||
sp_buf_puts(out, "queued: the loop picks it up at the next step\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_cancel(struct sp_buf *out)
|
||||
{
|
||||
if (!sp_engine_busy(*session_eng)) {
|
||||
sp_buf_puts(out, "no turn is running");
|
||||
return 0;
|
||||
}
|
||||
(void)sp_engine_cancel(*session_eng);
|
||||
sp_buf_puts(out, "cancel requested\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_approve(const char *args, struct sp_buf *out)
|
||||
{
|
||||
int allow = arg_bool(args, "allow", 0);
|
||||
|
||||
if (sp_engine_approve(*session_eng, allow) != 0) {
|
||||
sp_buf_puts(out, "error: no approval is pending");
|
||||
return 0;
|
||||
}
|
||||
sp_buf_printf(out, "%s\n", allow ? "approved" : "denied");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_mcpsession_call(const char *name, const char *args, struct sp_buf *out)
|
||||
{
|
||||
if (session_eng == NULL || *session_eng == NULL) {
|
||||
sp_buf_puts(out, "error: this MCP server has no splinter engine");
|
||||
return 1;
|
||||
}
|
||||
if (strcmp(name, "splinter_sessions") == 0)
|
||||
return tool_sessions(out), 1;
|
||||
if (strcmp(name, "splinter_state") == 0)
|
||||
return tool_state(out), 1;
|
||||
if (strcmp(name, "splinter_models") == 0)
|
||||
return tool_models(out), 1;
|
||||
if (strcmp(name, "splinter_agents") == 0)
|
||||
return tool_agents(out), 1;
|
||||
if (strcmp(name, "splinter_history") == 0)
|
||||
return tool_history(args, out), 1;
|
||||
if (strcmp(name, "splinter_say") == 0)
|
||||
return tool_say(args, out), 1;
|
||||
if (strcmp(name, "splinter_open") == 0)
|
||||
return tool_open(args, out), 1;
|
||||
if (strcmp(name, "splinter_model") == 0)
|
||||
return tool_model(args, out), 1;
|
||||
if (strcmp(name, "splinter_agent") == 0)
|
||||
return tool_agent(args, out), 1;
|
||||
if (strcmp(name, "splinter_steer") == 0)
|
||||
return tool_steer(args, out), 1;
|
||||
if (strcmp(name, "splinter_cancel") == 0)
|
||||
return tool_cancel(out), 1;
|
||||
if (strcmp(name, "splinter_approve") == 0)
|
||||
return tool_approve(args, out), 1;
|
||||
return 0;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
/*
|
||||
* splinter -- the MCP server's session tools.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_MCPSESSION_H
|
||||
#define SPLINTER_MCPSESSION_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_buf;
|
||||
struct sp_engine;
|
||||
struct sp_engine_opts;
|
||||
|
||||
/* The engine a connection works on; NULL means "file tools only". */
|
||||
void sp_mcpsession_bind(struct sp_engine **eng,
|
||||
const struct sp_engine_opts *opts);
|
||||
|
||||
/* 1 when the name is one of ours, and its authorization class. */
|
||||
int sp_mcpsession_has(const char *name);
|
||||
int sp_mcpsession_auth(const char *name);
|
||||
|
||||
/* tools/list entries, comma-prefixed unless *first is still 1 */
|
||||
void sp_mcpsession_tools(struct sp_buf *b, int *first);
|
||||
|
||||
/* 1 when handled (out filled), 0 when the name is not ours. */
|
||||
int sp_mcpsession_call(const char *name, const char *args,
|
||||
struct sp_buf *out);
|
||||
|
||||
#endif /* SPLINTER_MCPSESSION_H */
|
||||
@@ -1,362 +0,0 @@
|
||||
/*
|
||||
* splinter -- markdown tables as aligned text.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* A chat is monospace, so a table can be a table: the pipe rows are rewritten
|
||||
* with one width per column, taken from the longest cell. The block is the
|
||||
* markdown shape a model actually emits -- a header line, a separator line
|
||||
* ("|---|:---:|---|"), then body rows -- and it ends at the first line that is
|
||||
* not a row. Text before and after the block is copied unchanged.
|
||||
*
|
||||
* This is deliberately not a full markdown parser. Escaped pipes are not
|
||||
* supported (a table cell with a literal '|' is rare; a parser that guesses is
|
||||
* worse than one that leaves the line alone), and alignment is in bytes, which
|
||||
* is exact for ASCII. The screen transliterates UTF-8 before drawing, so a cell
|
||||
* full of umlauts can still be a column short; that is a display detail, not a
|
||||
* reason to turn the table back into pipes.
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "md.h"
|
||||
|
||||
#define MD_MAX_COLS 32
|
||||
#define MD_MAX_ROWS 512
|
||||
|
||||
struct md_row {
|
||||
size_t n;
|
||||
char **cell;
|
||||
};
|
||||
|
||||
static const char *
|
||||
eol(const char *s)
|
||||
{
|
||||
const char *p = strchr(s, '\n');
|
||||
|
||||
return p != NULL ? p : s + strlen(s);
|
||||
}
|
||||
|
||||
/* A separator line: every cell has at least three dashes, optional colons. */
|
||||
static int
|
||||
is_separator(const char *s, size_t n)
|
||||
{
|
||||
size_t i = 0, pipes = 0, cells = 0;
|
||||
|
||||
while (i < n && (s[i] == ' ' || s[i] == '\t' || s[i] == '\r'))
|
||||
i++;
|
||||
if (i < n && s[i] == '|') {
|
||||
i++;
|
||||
pipes++;
|
||||
}
|
||||
for (;;) {
|
||||
size_t dashes = 0;
|
||||
|
||||
while (i < n && (s[i] == ' ' || s[i] == '\t'))
|
||||
i++;
|
||||
if (i < n && s[i] == ':')
|
||||
i++;
|
||||
while (i < n && s[i] == '-') {
|
||||
i++;
|
||||
dashes++;
|
||||
}
|
||||
if (dashes < 3)
|
||||
return 0;
|
||||
if (i < n && s[i] == ':')
|
||||
i++;
|
||||
while (i < n && (s[i] == ' ' || s[i] == '\t'))
|
||||
i++;
|
||||
cells++;
|
||||
if (i < n && s[i] == '|') {
|
||||
i++;
|
||||
pipes++;
|
||||
while (i < n && (s[i] == ' ' || s[i] == '\t'))
|
||||
i++;
|
||||
if (i >= n || s[i] == '\r')
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
while (i < n && (s[i] == ' ' || s[i] == '\t' || s[i] == '\r'))
|
||||
i++;
|
||||
return i == n && cells > 0 && pipes > 0;
|
||||
}
|
||||
|
||||
static void
|
||||
row_free(struct md_row *r)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < r->n; i++)
|
||||
free(r->cell[i]);
|
||||
free(r->cell);
|
||||
r->cell = NULL;
|
||||
r->n = 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Split one line into cells: trim the line, drop one leading and one trailing
|
||||
* pipe, then split on '|'. A trailing pipe does not create an empty last cell.
|
||||
*/
|
||||
static int
|
||||
row_parse(const char *s, size_t n, struct md_row *r)
|
||||
{
|
||||
size_t i = 0, cap = 0;
|
||||
|
||||
r->n = 0;
|
||||
r->cell = NULL;
|
||||
while (n > 0 && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
|
||||
s[n - 1] == '\r'))
|
||||
n--;
|
||||
while (i < n && (s[i] == ' ' || s[i] == '\t'))
|
||||
i++;
|
||||
if (i < n && s[i] == '|')
|
||||
i++;
|
||||
for (;;) {
|
||||
size_t start = i, end;
|
||||
|
||||
while (i < n && s[i] != '|')
|
||||
i++;
|
||||
end = i;
|
||||
while (end > start && (s[end - 1] == ' ' ||
|
||||
s[end - 1] == '\t'))
|
||||
end--;
|
||||
while (start < end && (s[start] == ' ' || s[start] == '\t'))
|
||||
start++;
|
||||
if (r->n == MD_MAX_COLS)
|
||||
goto fail;
|
||||
if (r->n == cap) {
|
||||
size_t ncap = cap == 0 ? 4 : cap * 2;
|
||||
char **nc = realloc(r->cell, ncap * sizeof(*nc));
|
||||
|
||||
if (nc == NULL)
|
||||
goto fail;
|
||||
r->cell = nc;
|
||||
cap = ncap;
|
||||
}
|
||||
r->cell[r->n] = malloc(end - start + 1);
|
||||
if (r->cell[r->n] == NULL)
|
||||
goto fail;
|
||||
memcpy(r->cell[r->n], s + start, end - start);
|
||||
r->cell[r->n][end - start] = '\0';
|
||||
r->n++;
|
||||
if (i < n && s[i] == '|') {
|
||||
i++;
|
||||
if (i >= n)
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
|
||||
fail:
|
||||
row_free(r);
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int
|
||||
row_push(struct md_row **rows, size_t *n, size_t *cap, const char *s,
|
||||
size_t len)
|
||||
{
|
||||
struct md_row *nr;
|
||||
|
||||
if (*n == MD_MAX_ROWS)
|
||||
return -1;
|
||||
if (*n == *cap) {
|
||||
size_t ncap = *cap == 0 ? 4 : *cap * 2;
|
||||
|
||||
nr = realloc(*rows, ncap * sizeof(**rows));
|
||||
if (nr == NULL)
|
||||
return -1;
|
||||
*rows = nr;
|
||||
*cap = ncap;
|
||||
}
|
||||
memset(&(*rows)[*n], 0, sizeof(**rows));
|
||||
if (row_parse(s, len, &(*rows)[*n]) != 0)
|
||||
return -1;
|
||||
(*n)++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
rows_free(struct md_row *rows, size_t n)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < n; i++)
|
||||
row_free(&rows[i]);
|
||||
free(rows);
|
||||
}
|
||||
|
||||
/*
|
||||
* Format the block that starts at 'p' (a header line followed by a separator)
|
||||
* and return the first line after it. NULL means "leave it alone": too many
|
||||
* rows or columns, or no memory.
|
||||
*/
|
||||
static const char *
|
||||
format_table(const char *p, struct sp_buf *out)
|
||||
{
|
||||
struct md_row *rows = NULL;
|
||||
size_t nrows = 0, cap = 0, ncols = 0, i, j;
|
||||
size_t width[MD_MAX_COLS];
|
||||
const char *e = eol(p);
|
||||
const char *sep = (*e == '\n') ? e + 1 : e;
|
||||
const char *se = eol(sep);
|
||||
const char *cur = (*se == '\n') ? se + 1 : se;
|
||||
|
||||
memset(width, 0, sizeof(width));
|
||||
if (row_push(&rows, &nrows, &cap, p, (size_t)(e - p)) != 0)
|
||||
goto fail;
|
||||
while (*cur != '\0') {
|
||||
const char *ce = eol(cur);
|
||||
size_t clen = (size_t)(ce - cur);
|
||||
|
||||
if (clen == 0 || memchr(cur, '|', clen) == NULL)
|
||||
break;
|
||||
if (row_push(&rows, &nrows, &cap, cur, clen) != 0)
|
||||
goto fail;
|
||||
if (*ce == '\0') {
|
||||
cur = ce;
|
||||
break;
|
||||
}
|
||||
cur = ce + 1;
|
||||
}
|
||||
if (nrows == 0)
|
||||
goto fail;
|
||||
for (i = 0; i < nrows; i++) {
|
||||
if (rows[i].n > ncols)
|
||||
ncols = rows[i].n;
|
||||
for (j = 0; j < rows[i].n; j++) {
|
||||
size_t l = strlen(rows[i].cell[j]);
|
||||
|
||||
if (l > width[j])
|
||||
width[j] = l;
|
||||
}
|
||||
}
|
||||
if (ncols == 0 || ncols > MD_MAX_COLS)
|
||||
goto fail;
|
||||
|
||||
for (i = 0; i < nrows; i++) {
|
||||
if (sp_buf_puts(out, "|") != 0)
|
||||
goto fail;
|
||||
for (j = 0; j < ncols; j++) {
|
||||
const char *c = j < rows[i].n ? rows[i].cell[j] : "";
|
||||
size_t l = strlen(c), k;
|
||||
|
||||
if (sp_buf_puts(out, " ") != 0 ||
|
||||
sp_buf_puts(out, c) != 0)
|
||||
goto fail;
|
||||
for (k = l; k < width[j]; k++)
|
||||
if (sp_buf_puts(out, " ") != 0)
|
||||
goto fail;
|
||||
if (sp_buf_puts(out, " |") != 0)
|
||||
goto fail;
|
||||
}
|
||||
if (sp_buf_puts(out, "\n") != 0)
|
||||
goto fail;
|
||||
if (i == 0) {
|
||||
if (sp_buf_puts(out, "|") != 0)
|
||||
goto fail;
|
||||
for (j = 0; j < ncols; j++) {
|
||||
size_t k;
|
||||
|
||||
for (k = 0; k < width[j] + 2; k++)
|
||||
if (sp_buf_puts(out, "-") != 0)
|
||||
goto fail;
|
||||
if (sp_buf_puts(out, "|") != 0)
|
||||
goto fail;
|
||||
}
|
||||
if (sp_buf_puts(out, "\n") != 0)
|
||||
goto fail;
|
||||
}
|
||||
}
|
||||
rows_free(rows, nrows);
|
||||
return cur;
|
||||
|
||||
fail:
|
||||
rows_free(rows, nrows);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static const char *
|
||||
next_table(const char *in)
|
||||
{
|
||||
const char *p = in;
|
||||
|
||||
while (*p != '\0') {
|
||||
const char *e = eol(p);
|
||||
|
||||
if (*e == '\n' && memchr(p, '|', (size_t)(e - p)) != NULL) {
|
||||
const char *q = e + 1;
|
||||
const char *qe = eol(q);
|
||||
|
||||
if (is_separator(q, (size_t)(qe - q)))
|
||||
return p;
|
||||
}
|
||||
if (*e == '\0')
|
||||
break;
|
||||
p = e + 1;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int
|
||||
sp_md_table_starts(const char *in)
|
||||
{
|
||||
const char *e, *q, *qe;
|
||||
|
||||
if (in == NULL)
|
||||
return 0;
|
||||
e = eol(in);
|
||||
if (*e != '\n')
|
||||
return 0;
|
||||
q = e + 1;
|
||||
qe = eol(q);
|
||||
return memchr(in, '|', (size_t)(e - in)) != NULL &&
|
||||
is_separator(q, (size_t)(qe - q));
|
||||
}
|
||||
|
||||
int
|
||||
sp_md_table_format(const char *in, struct sp_buf *out)
|
||||
{
|
||||
const char *p;
|
||||
int changed = 0;
|
||||
|
||||
if (in == NULL || out == NULL)
|
||||
return -1;
|
||||
if (next_table(in) == NULL)
|
||||
return 0;
|
||||
p = in;
|
||||
while (*p != '\0') {
|
||||
const char *e = eol(p);
|
||||
|
||||
if (*e == '\n' && memchr(p, '|', (size_t)(e - p)) != NULL) {
|
||||
const char *q = e + 1;
|
||||
const char *qe = eol(q);
|
||||
|
||||
if (is_separator(q, (size_t)(qe - q))) {
|
||||
const char *after = format_table(p, out);
|
||||
|
||||
if (after == NULL)
|
||||
return -1;
|
||||
changed = 1;
|
||||
p = after;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (sp_buf_add(out, p, (size_t)(e - p)) != 0)
|
||||
return -1;
|
||||
if (*e == '\0') {
|
||||
p = e;
|
||||
break;
|
||||
}
|
||||
if (sp_buf_add(out, "\n", 1) != 0)
|
||||
return -1;
|
||||
p = e + 1;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
/* splinter -- markdown tables as aligned text. */
|
||||
#ifndef SPLINTER_MD_H
|
||||
#define SPLINTER_MD_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_buf;
|
||||
|
||||
/*
|
||||
* Rewrite markdown tables in 'in' as aligned plain text and append the result
|
||||
* to 'out'. A block is a header line containing '|' followed by a separator
|
||||
* line ("|---|:---:|---|"). Cell widths are the maximum per column, so the
|
||||
* table reads as columns in a monospace chat, not as a row of pipes.
|
||||
*
|
||||
* Returns 1 when a table was rewritten, 0 when the text had none (out stays
|
||||
* empty), -1 on allocation failure or a table too large to format.
|
||||
*/
|
||||
int sp_md_table_format(const char *in, struct sp_buf *out);
|
||||
|
||||
/*
|
||||
* 1 when the first line of 'in' is a table header (the second line is the
|
||||
* separator). The chat uses this to put the speaker prefix on its own line:
|
||||
* a table that starts an answer must not begin behind "[12:04] <agent> ".
|
||||
*/
|
||||
int sp_md_table_starts(const char *in);
|
||||
|
||||
#endif /* SPLINTER_MD_H */
|
||||
@@ -1,310 +0,0 @@
|
||||
/*
|
||||
* splinter -- OpenAI-compatible request/reply shaping.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Two pure functions, so both directions can be tested without a network:
|
||||
*
|
||||
* sp_openai_request() conversation + tool table -> the JSON body
|
||||
* sp_openai_reply() the endpoint's JSON -> sp_reply
|
||||
*
|
||||
* What is deliberately not done here: no retries, no streaming, no guessing.
|
||||
* A reply without a usable choice is an error with the provider's own message
|
||||
* in it, because "the model said nothing" and "the endpoint is broken" are
|
||||
* different facts and the caller has to be able to tell them apart.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "mcp.h"
|
||||
|
||||
static int
|
||||
put_field(struct sp_buf *b, const char *key, const char *value)
|
||||
{
|
||||
if (sp_buf_printf(b, "\"%s\":", key) != 0 ||
|
||||
sp_buf_puts(b, "\"") != 0 ||
|
||||
sp_json_escape(b, value != NULL ? value : "") != 0 ||
|
||||
sp_buf_puts(b, "\"") != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
gen_fields(struct sp_buf *out, const struct sp_gen_opts *g)
|
||||
{
|
||||
if (g == NULL)
|
||||
return 0;
|
||||
if (g->have_temperature &&
|
||||
sp_buf_printf(out, ",\"temperature\":%.17g", g->temperature) != 0)
|
||||
return -1;
|
||||
if (g->have_top_p &&
|
||||
sp_buf_printf(out, ",\"top_p\":%.17g", g->top_p) != 0)
|
||||
return -1;
|
||||
if (g->have_max_tokens &&
|
||||
sp_buf_printf(out, ",\"max_tokens\":%ld", g->max_tokens) != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_openai_request_opts(const struct sp_conv *conv, const char *model,
|
||||
const struct sp_registry *reg, int streaming,
|
||||
const struct sp_gen_opts *gen, struct sp_buf *out)
|
||||
{
|
||||
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 ||
|
||||
sp_json_escape(out, model != NULL ? model : "") != 0 ||
|
||||
sp_buf_puts(out, streaming ? "\",\"stream\":true"
|
||||
: "\",\"stream\":false") != 0 ||
|
||||
gen_fields(out, gen) != 0 ||
|
||||
(streaming && gen != NULL && gen->include_usage &&
|
||||
sp_buf_puts(out, ",\"stream_options\":"
|
||||
"{\"include_usage\":true}") != 0) ||
|
||||
sp_buf_puts(out, ",\"messages\":[") != 0)
|
||||
return -1;
|
||||
|
||||
for (i = 0; i < conv->n; i++) {
|
||||
const struct sp_msg *m = &conv->v[i];
|
||||
|
||||
if (i > 0 && sp_buf_puts(out, ",") != 0)
|
||||
return -1;
|
||||
if (sp_buf_puts(out, "{") != 0 ||
|
||||
put_field(out, "role", m->role) != 0)
|
||||
return -1;
|
||||
if (m->call_id != NULL) {
|
||||
if (sp_buf_puts(out, ",") != 0 ||
|
||||
put_field(out, "tool_call_id", m->call_id) != 0)
|
||||
return -1;
|
||||
}
|
||||
if (m->name != NULL && m->call_id == NULL) {
|
||||
if (sp_buf_puts(out, ",") != 0 ||
|
||||
put_field(out, "name", m->name) != 0)
|
||||
return -1;
|
||||
}
|
||||
if (m->content != NULL) {
|
||||
if (sp_buf_puts(out, ",") != 0 ||
|
||||
put_field(out, "content", m->content) != 0)
|
||||
return -1;
|
||||
}
|
||||
if (m->calls != NULL && *m->calls != '\0') {
|
||||
if (sp_buf_printf(out, ",\"tool_calls\":%s", m->calls) != 0)
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_puts(out, "}") != 0)
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* tools: name, description and an open parameter object */
|
||||
if (sp_buf_puts(out, "],\"tools\":[") != 0)
|
||||
return -1;
|
||||
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;
|
||||
if (sp_buf_puts(out, "{\"type\":\"function\",\"function\":{") != 0 ||
|
||||
put_field(out, "name", t->name) != 0 ||
|
||||
sp_buf_puts(out, ",") != 0 ||
|
||||
put_field(out, "description", t->description) != 0 ||
|
||||
sp_buf_puts(out, ",\"parameters\":") != 0)
|
||||
return -1;
|
||||
/* a tool without a schema gets an open object, not an empty one:
|
||||
* an empty properties map tells the model "no arguments exist" */
|
||||
if (t->params != NULL) {
|
||||
if (sp_buf_puts(out, t->params) != 0)
|
||||
return -1;
|
||||
} else if (sp_buf_puts(out, "{\"type\":\"object\","
|
||||
"\"properties\":{},\"additionalProperties\":true}") != 0) {
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_puts(out, "}}") != 0)
|
||||
return -1;
|
||||
}
|
||||
return sp_buf_puts(out, "]}");
|
||||
}
|
||||
|
||||
int
|
||||
sp_openai_request(const struct sp_conv *conv, const char *model,
|
||||
const struct sp_registry *reg, int streaming, struct sp_buf *out)
|
||||
{
|
||||
return sp_openai_request_opts(conv, model, reg, streaming, NULL, out);
|
||||
}
|
||||
|
||||
/*
|
||||
* Extract the raw tool_calls array as text, so a later request can hand the
|
||||
* provider back exactly what it sent: re-encoding parsed calls would be a
|
||||
* second, silently different JSON.
|
||||
*/
|
||||
static char *
|
||||
raw_calls(const char *json, const char *key)
|
||||
{
|
||||
const char *p = strstr(json, key);
|
||||
const char *start;
|
||||
int depth = 0, in_str = 0, esc = 0;
|
||||
size_t len;
|
||||
|
||||
if (p == NULL)
|
||||
return NULL;
|
||||
start = strchr(p + strlen(key), '[');
|
||||
if (start == NULL)
|
||||
return NULL;
|
||||
for (p = start; *p != '\0'; p++) {
|
||||
if (esc) {
|
||||
esc = 0;
|
||||
continue;
|
||||
}
|
||||
if (*p == '\\') {
|
||||
esc = 1;
|
||||
continue;
|
||||
}
|
||||
if (*p == '"') {
|
||||
in_str = !in_str;
|
||||
continue;
|
||||
}
|
||||
if (in_str)
|
||||
continue;
|
||||
if (*p == '[')
|
||||
depth++;
|
||||
else if (*p == ']') {
|
||||
depth--;
|
||||
if (depth == 0) {
|
||||
len = (size_t)(p - start) + 1;
|
||||
return strndup(start, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static const char *
|
||||
jstr(const mcp_json *v)
|
||||
{
|
||||
return v != NULL ? mcp_json_string(v) : NULL;
|
||||
}
|
||||
|
||||
int
|
||||
sp_openai_reply(const char *json, struct sp_reply *out, struct sp_buf *err)
|
||||
{
|
||||
mcp_json *v;
|
||||
const mcp_json *choices, *choice, *message, *calls, *content;
|
||||
const mcp_json *error;
|
||||
const char *text;
|
||||
|
||||
memset(out, 0, sizeof(*out));
|
||||
out->status = 200;
|
||||
|
||||
if (json == NULL || *json == '\0') {
|
||||
sp_buf_puts(err, "openai: empty body");
|
||||
return -1;
|
||||
}
|
||||
v = mcp_parse(json);
|
||||
if (v == NULL) {
|
||||
sp_buf_printf(err, "openai: reply is not JSON: %.120s", json);
|
||||
return -1;
|
||||
}
|
||||
|
||||
error = mcp_arg(v, "error");
|
||||
if (error != NULL) {
|
||||
text = mcp_arg_string(error, "message");
|
||||
sp_buf_printf(err, "openai: provider error: %s",
|
||||
text != NULL ? text : "(no message)");
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
|
||||
choices = mcp_arg(v, "choices");
|
||||
if (choices == NULL || mcp_array_len(choices) == 0) {
|
||||
sp_buf_printf(err, "openai: no choices in reply: %.160s", json);
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
choice = mcp_array_at(choices, 0);
|
||||
message = choice != NULL ? mcp_arg(choice, "message") : NULL;
|
||||
if (message == NULL) {
|
||||
sp_buf_puts(err, "openai: choice without a message");
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
|
||||
content = mcp_arg(message, "content");
|
||||
out->content = strdup(jstr(content) != NULL ? jstr(content) : "");
|
||||
if (out->content == NULL) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
|
||||
{
|
||||
const mcp_json *usage = mcp_arg(v, "usage");
|
||||
|
||||
if (usage != NULL) {
|
||||
const mcp_json *details;
|
||||
long pin = (long)mcp_arg_int(usage, "prompt_tokens", -1);
|
||||
long pout = (long)mcp_arg_int(usage, "completion_tokens",
|
||||
-1);
|
||||
long cached = -1;
|
||||
|
||||
if (pin < 0)
|
||||
pin = (long)mcp_arg_int(usage, "input_tokens", -1);
|
||||
if (pout < 0)
|
||||
pout = (long)mcp_arg_int(usage, "output_tokens", -1);
|
||||
details = mcp_arg(usage, "prompt_tokens_details");
|
||||
if (details != NULL)
|
||||
cached = (long)mcp_arg_int(details,
|
||||
"cached_tokens", -1);
|
||||
if (cached < 0)
|
||||
cached = (long)mcp_arg_int(usage,
|
||||
"prompt_cache_hit_tokens", -1);
|
||||
if (cached < 0)
|
||||
cached = (long)mcp_arg_int(usage,
|
||||
"cache_read_input_tokens", -1);
|
||||
if (pin >= 0)
|
||||
out->tokens_in = pin;
|
||||
if (pout >= 0)
|
||||
out->tokens_out = pout;
|
||||
if (cached >= 0)
|
||||
out->tokens_cached = cached;
|
||||
}
|
||||
}
|
||||
|
||||
calls = mcp_arg(message, "tool_calls");
|
||||
if (calls != NULL && mcp_array_len(calls) > 0) {
|
||||
size_t i, n = mcp_array_len(calls);
|
||||
|
||||
out->calls = calloc(n, sizeof(*out->calls));
|
||||
if (out->calls == NULL) {
|
||||
sp_reply_free(out);
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
for (i = 0; i < n; i++) {
|
||||
const mcp_json *c = mcp_array_at(calls, i);
|
||||
const mcp_json *fn = mcp_arg(c, "function");
|
||||
|
||||
out->calls[i].id = strdup(jstr(mcp_arg(c, "id")) != NULL ?
|
||||
jstr(mcp_arg(c, "id")) : "");
|
||||
out->calls[i].name = strdup(jstr(mcp_arg(fn, "name")) !=
|
||||
NULL ? jstr(mcp_arg(fn, "name")) : "");
|
||||
out->calls[i].args = strdup(jstr(mcp_arg(fn, "arguments")) !=
|
||||
NULL ? jstr(mcp_arg(fn, "arguments")) : "");
|
||||
if (out->calls[i].id == NULL || out->calls[i].name == NULL ||
|
||||
out->calls[i].args == NULL) {
|
||||
out->ncalls = i + 1;
|
||||
sp_reply_free(out);
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
out->ncalls = n;
|
||||
out->calls_json = raw_calls(json, "\"tool_calls\"");
|
||||
}
|
||||
|
||||
mcp_json_free(v);
|
||||
return 0;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,34 +0,0 @@
|
||||
/*
|
||||
* splinter -- the OpenAI-compatible endpoint for another harness.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* The server lives in openai_server.c; this is what main starts it with.
|
||||
*/
|
||||
#ifndef SPLINTER_OPENAI_SERVER_H
|
||||
#define SPLINTER_OPENAI_SERVER_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_registry;
|
||||
struct sp_config;
|
||||
struct sp_buf;
|
||||
|
||||
struct sp_gateway_opts {
|
||||
const char *ip;
|
||||
int port;
|
||||
const char *token; /* SPLINTER_GATEWAY_TOKEN, may be NULL */
|
||||
int autonomous; /* local mutate/destructive tools */
|
||||
size_t max_steps; /* gateway tool rounds, 0: 16 */
|
||||
struct sp_registry *reg; /* splinter's own tools */
|
||||
struct sp_config *conf;
|
||||
const char *endpoint; /* upstream */
|
||||
const char *model;
|
||||
const char *key_env;
|
||||
const char *kind; /* "anthropic", or NULL */
|
||||
};
|
||||
|
||||
int sp_openai_serve(const struct sp_gateway_opts *, struct sp_buf *err);
|
||||
|
||||
#endif /* SPLINTER_OPENAI_SERVER_H */
|
||||
@@ -1,52 +0,0 @@
|
||||
/*
|
||||
* Generated by tools/genpalettes.py from the CDE palette files.
|
||||
* Do not edit by hand: change the .dp source or the generator.
|
||||
*/
|
||||
#include "palettes.h"
|
||||
|
||||
const struct sp_palette sp_palettes[] = {
|
||||
{ "Alpine", { {0xaf,0xbf,0xfb}, {0x78,0xaa,0xb8}, {0x7a,0xb9,0xd8}, {0xbf,0xc0,0xc5}, {0xbf,0x92,0x79}, {0xbf,0xc0,0xc5}, {0xbd,0xbd,0xeb}, {0xbf,0xc0,0xc5} } },
|
||||
{ "Arizona", { {0xff,0xab,0x78}, {0xa8,0x6b,0x79}, {0xde,0xb3,0x94}, {0x88,0x57,0x70}, {0xc3,0x7d,0x79}, {0xcd,0x78,0x6a}, {0x64,0x60,0x47}, {0x84,0x54,0x5f} } },
|
||||
{ "BeigeRose", { {0x61,0x88,0x88}, {0xd1,0xc0,0xae}, {0xb7,0x89,0x89}, {0xf0,0xec,0xeb}, {0x91,0x91,0x91}, {0xb9,0xb9,0xb9}, {0x87,0x93,0xae}, {0x90,0xb0,0xac} } },
|
||||
{ "Black", { {0x00,0x00,0x00}, {0x00,0x00,0x00}, {0x00,0x00,0x00}, {0x00,0x00,0x00}, {0x00,0x00,0x00}, {0x00,0x00,0x00}, {0x00,0x00,0x00}, {0x00,0x00,0x00} } },
|
||||
{ "BlackWhite", { {0x00,0x00,0x00}, {0xff,0xff,0xff}, {0xff,0xff,0xff}, {0x00,0x00,0x00}, {0x00,0x00,0x00}, {0x00,0x00,0x00}, {0x00,0x00,0x00}, {0x00,0x00,0x00} } },
|
||||
{ "Broica", { {0xed,0xa8,0x70}, {0x99,0x99,0x99}, {0x89,0x98,0xaa}, {0x68,0x6f,0x82}, {0xc6,0xb2,0xa8}, {0x49,0x92,0xa7}, {0xb7,0x87,0x8d}, {0x93,0xab,0xbf} } },
|
||||
{ "Cabernet", { {0xd8,0x87,0x75}, {0x63,0x8a,0x7a}, {0x45,0x62,0x56}, {0x4b,0x5e,0x61}, {0xb6,0x5c,0x71}, {0x83,0x3b,0x47}, {0x79,0x46,0x55}, {0x49,0x5c,0x65} } },
|
||||
{ "Camouflage", { {0xac,0xbe,0xb4}, {0x6e,0x7d,0x76}, {0x90,0x7b,0x7b}, {0x82,0x82,0x9b}, {0x8e,0x8e,0x77}, {0x7f,0x6c,0x6c}, {0x8e,0x8e,0x85}, {0x4e,0x6b,0x65} } },
|
||||
{ "Charcoal", { {0x87,0xb4,0xb0}, {0x76,0x72,0x79}, {0x69,0x63,0x63}, {0x89,0x6d,0x6d}, {0x82,0x85,0x85}, {0x63,0x6f,0x6d}, {0x91,0x91,0x91}, {0xaf,0x96,0x96} } },
|
||||
{ "Chocolate", { {0xa9,0xa9,0xff}, {0x70,0x8c,0x8d}, {0x87,0x87,0xaf}, {0x96,0x78,0x78}, {0xb9,0xa0,0xa0}, {0xa5,0x82,0x82}, {0xbb,0xbb,0xd9}, {0x96,0x96,0xb9} } },
|
||||
{ "Cinnamon", { {0xb1,0x4b,0x50}, {0x92,0x68,0x66}, {0x79,0x6e,0x6d}, {0x83,0x69,0x60}, {0x9b,0x68,0x62}, {0xa2,0x8d,0x8c}, {0x84,0x75,0x74}, {0x78,0x69,0x5d} } },
|
||||
{ "Clay", { {0xff,0xaa,0xaa}, {0x96,0x82,0x82}, {0x5a,0x8b,0x8d}, {0x8c,0x64,0x64}, {0xaf,0x91,0x91}, {0xa5,0x6e,0x6e}, {0xac,0x83,0x83}, {0x2f,0x8b,0x8d} } },
|
||||
{ "Crimson", { {0xb2,0x4d,0x7a}, {0xae,0xb2,0xc3}, {0x71,0x8b,0xa5}, {0xff,0xf7,0xe9}, {0x68,0xa6,0xa0}, {0x8d,0xad,0xc7}, {0xd3,0x97,0x98}, {0x97,0x93,0xb5} } },
|
||||
{ "DarkGold", { {0xb8,0x96,0x63}, {0x7a,0x7c,0x7f}, {0x53,0x55,0x70}, {0xff,0xff,0xe2}, {0xa8,0xa8,0xa8}, {0x79,0x9c,0xa1}, {0x86,0x7f,0xb5}, {0x6b,0x94,0xb2} } },
|
||||
{ "Default", { {0xed,0xa8,0x70}, {0x99,0x99,0x99}, {0x89,0x98,0xaa}, {0x68,0x6f,0x82}, {0xc6,0xb2,0xa8}, {0x49,0x92,0xa7}, {0xb7,0x87,0x8d}, {0x93,0xab,0xbf} } },
|
||||
{ "Delphinium", { {0x85,0xc4,0xed}, {0xc8,0xc8,0xc8}, {0x85,0x8c,0xd9}, {0xff,0xff,0xe6}, {0x78,0xb4,0xbe}, {0x55,0x86,0xc3}, {0xba,0x9d,0x91}, {0x90,0xa0,0xbe} } },
|
||||
{ "Desert", { {0xe5,0xb7,0x93}, {0xc2,0xbb,0xa7}, {0x8c,0x8f,0x98}, {0xfd,0xfd,0xfa}, {0x9f,0xae,0xb5}, {0x6f,0x98,0xa2}, {0x73,0x9e,0xbd}, {0xc4,0x92,0x9b} } },
|
||||
{ "Golden", { {0xfa,0xad,0x49}, {0x4d,0x64,0x8d}, {0xbe,0x82,0x6f}, {0x47,0x63,0x4f}, {0x75,0x7c,0xa6}, {0x3d,0x77,0x77}, {0x2b,0x79,0x85}, {0xb1,0x70,0x5f} } },
|
||||
{ "Grass", { {0xd4,0xc7,0x7d}, {0xbe,0xc6,0xb7}, {0x5e,0x9c,0x7b}, {0xe2,0xf3,0xe2}, {0xa4,0xa9,0xaa}, {0x90,0xa7,0x93}, {0x60,0x87,0x9e}, {0x82,0x96,0x94} } },
|
||||
{ "GrayScale", { {0xc3,0xc3,0xc3}, {0x78,0x77,0x77}, {0xbd,0xbd,0xbd}, {0x94,0x94,0x93}, {0xbc,0xbc,0xbc}, {0x93,0x93,0x93}, {0x7f,0x7f,0x7f}, {0x93,0x93,0x93} } },
|
||||
{ "Lilac", { {0xd3,0xd1,0x78}, {0xa5,0xa5,0xac}, {0xa6,0x92,0xb7}, {0xc3,0xc3,0xc9}, {0xa5,0xa5,0xac}, {0xc6,0xb1,0xb1}, {0xc2,0xc2,0xd2}, {0x91,0x7e,0x9f} } },
|
||||
{ "MakroSlate", { {0x18,0x1f,0x26}, {0x2b,0x3a,0x44}, {0x45,0x5a,0x66}, {0x60,0x78,0x88}, {0x8e,0xa8,0xb8}, {0xb8,0xcc,0xd8}, {0xd8,0xe8,0xf0}, {0xf8,0xfc,0xff} } },
|
||||
{ "Mustard", { {0xd5,0x80,0x2e}, {0xb7,0x5f,0x5f}, {0x4d,0x64,0x8d}, {0x5c,0x6a,0x58}, {0x88,0x7c,0xa3}, {0xbe,0x82,0x6f}, {0x46,0x79,0x76}, {0x2a,0x68,0x89} } },
|
||||
{ "Neptune", { {0xa2,0xe5,0xc6}, {0x3f,0x93,0x8d}, {0x2d,0x4e,0x76}, {0x78,0x89,0xa5}, {0x63,0x7e,0x95}, {0x3e,0x70,0x8a}, {0x3d,0x7d,0x84}, {0x61,0x6d,0x8e} } },
|
||||
{ "NorthernSky", { {0xa4,0x75,0x91}, {0x1b,0x5d,0x6c}, {0x0c,0x5a,0x87}, {0x00,0x57,0x7a}, {0x41,0x52,0x5c}, {0x4b,0x7b,0x82}, {0x27,0x70,0x8b}, {0x3d,0x40,0x7c} } },
|
||||
{ "Nutmeg", { {0xce,0xc2,0xbb}, {0x25,0x65,0x93}, {0x9f,0x88,0x81}, {0xcd,0xb2,0xa6}, {0xb3,0x9c,0x8f}, {0xcf,0xb8,0xaa}, {0x90,0xac,0xdb}, {0x45,0x72,0x93} } },
|
||||
{ "Olive", { {0x83,0x83,0x5a}, {0xc3,0xc3,0xb9}, {0x87,0x79,0x87}, {0xce,0xc2,0xb8}, {0xcd,0xbd,0xaa}, {0xe1,0xa8,0x97}, {0xb5,0xa1,0xb5}, {0x9a,0x91,0x9a} } },
|
||||
{ "Orchid", { {0xb9,0xb9,0xff}, {0x9b,0x9b,0xb9}, {0xa8,0xa8,0xcd}, {0x82,0x82,0xab}, {0x9b,0xbe,0xd7}, {0x98,0x98,0xc8}, {0x8c,0x8c,0xaa}, {0xb0,0xb0,0xbf} } },
|
||||
{ "PBNJ", { {0xb6,0x5c,0x61}, {0xd9,0xc1,0xb2}, {0xde,0xa1,0x7f}, {0xf1,0xe3,0xd2}, {0xc6,0x90,0x76}, {0xcb,0xa0,0x8d}, {0x9e,0x86,0xb5}, {0xeb,0xd7,0xbf} } },
|
||||
{ "Sand", { {0xea,0xbe,0x93}, {0xc7,0xaf,0xaf}, {0x8e,0xa2,0xc1}, {0xd4,0xd4,0xda}, {0xaf,0x81,0x81}, {0xbb,0xb5,0xa8}, {0xbf,0xbe,0xd6}, {0x96,0x96,0x96} } },
|
||||
{ "SantaFe", { {0xef,0x9d,0x9d}, {0x7e,0xab,0xab}, {0xbd,0xa2,0x8d}, {0xce,0xaf,0x9a}, {0x83,0xa5,0xb6}, {0x7f,0x9c,0x8c}, {0x72,0xab,0xc8}, {0x9c,0x99,0x92} } },
|
||||
{ "Savannah", { {0xda,0x9a,0x68}, {0xb4,0xaa,0x94}, {0xa0,0xb2,0xc8}, {0xd2,0xbf,0xa8}, {0xc6,0xb2,0xa8}, {0x97,0xa7,0x92}, {0xb7,0xae,0xaa}, {0x93,0xab,0xbf} } },
|
||||
{ "SeaFoam", { {0xaa,0xcb,0xdb}, {0xa7,0xa8,0xa7}, {0x7d,0xb7,0xbb}, {0x97,0xb0,0xb2}, {0xaf,0xbf,0xba}, {0xc5,0xaf,0xa4}, {0x98,0xaa,0xa5}, {0xc8,0xad,0xa0} } },
|
||||
{ "SkyRed", { {0xcc,0x68,0x6f}, {0xaf,0xc0,0xc2}, {0x6d,0xa7,0xb4}, {0xe1,0xeb,0xe1}, {0x6e,0x91,0xaa}, {0x8b,0x97,0x9f}, {0xb7,0xb5,0x8d}, {0x5e,0x84,0xb9} } },
|
||||
{ "SoftBlue", { {0x7f,0xa9,0xeb}, {0x76,0xa9,0x9c}, {0x5b,0x85,0xd0}, {0x6c,0x6c,0x6c}, {0x94,0xd5,0xdf}, {0xb8,0xce,0xbc}, {0xbd,0xbd,0xeb}, {0x5d,0x7c,0xb8} } },
|
||||
{ "SouthWest", { {0xff,0x7d,0x79}, {0xa9,0x75,0x61}, {0xc0,0x9b,0x80}, {0xb1,0x88,0x85}, {0xb8,0x6f,0x4b}, {0x88,0x72,0x61}, {0xb8,0x8a,0x75}, {0x98,0x9c,0xa8} } },
|
||||
{ "Summer", { {0xff,0x56,0x64}, {0xff,0xd6,0x90}, {0x82,0x9f,0xff}, {0xff,0xff,0xff}, {0x86,0xea,0xe7}, {0xb8,0xc8,0xff}, {0x64,0xc1,0xff}, {0xbc,0xc5,0xdb} } },
|
||||
{ "Tundra", { {0xf1,0xbc,0x7f}, {0xa5,0x96,0x80}, {0x7c,0x92,0xb9}, {0x76,0x7e,0x63}, {0x85,0x96,0x80}, {0x7a,0x93,0x95}, {0x82,0x7a,0x8f}, {0x83,0x7e,0x75} } },
|
||||
{ "Urchin", { {0xd5,0xa5,0x91}, {0x0f,0x7c,0x7a}, {0x70,0x68,0x89}, {0x0c,0x68,0x64}, {0x37,0x92,0xa2}, {0x12,0x8e,0x89}, {0x88,0x9a,0x8e}, {0x32,0x83,0x92} } },
|
||||
{ "Wheat", { {0xd1,0xa5,0x7a}, {0xdb,0xc2,0x91}, {0x48,0x6d,0x7f}, {0xbf,0xc0,0xc5}, {0x94,0xd5,0xdf}, {0xb8,0xce,0xbc}, {0xbd,0xbd,0xeb}, {0x5d,0x7c,0xb8} } },
|
||||
{ "White", { {0xff,0xff,0xff}, {0xff,0xff,0xff}, {0xff,0xff,0xff}, {0xff,0xff,0xff}, {0xff,0xff,0xff}, {0xff,0xff,0xff}, {0xff,0xff,0xff}, {0xff,0xff,0xff} } },
|
||||
{ "WhiteBlack", { {0xff,0xff,0xff}, {0x00,0x00,0x00}, {0x00,0x00,0x00}, {0xff,0xff,0xff}, {0xff,0xff,0xff}, {0xff,0xff,0xff}, {0xff,0xff,0xff}, {0xff,0xff,0xff} } },
|
||||
};
|
||||
|
||||
const size_t sp_palette_count = sizeof(sp_palettes) / sizeof(sp_palettes[0]);
|
||||
@@ -1,15 +0,0 @@
|
||||
/* splinter -- CDE palettes, generated by tools/genpalettes.py. */
|
||||
#ifndef SPLINTER_PALETTES_H
|
||||
#define SPLINTER_PALETTES_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_palette {
|
||||
const char *name;
|
||||
unsigned char c[8][3]; /* eight CDE colour sets, RGB 0-255 */
|
||||
};
|
||||
|
||||
extern const struct sp_palette sp_palettes[];
|
||||
extern const size_t sp_palette_count;
|
||||
|
||||
#endif /* SPLINTER_PALETTES_H */
|
||||
@@ -1,901 +0,0 @@
|
||||
/*
|
||||
* splinter -- plugin host: loading, tools, widgets, worker threads.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Three rules keep this safe without a sandbox:
|
||||
*
|
||||
* 1. A plugin is only ever touched on the main thread, except its tick(),
|
||||
* which the host calls on a thread the host owns and can stop.
|
||||
* 2. Anything crossing from a worker thread to the UI goes through a copy
|
||||
* under a mutex. Workers never hold a pointer the UI can see.
|
||||
* 3. Nothing is dlclose()d while threads might still run. A stopped
|
||||
* widget's thread is joined first; the handle itself stays mapped for
|
||||
* the life of the process, which is the only honest option in C.
|
||||
*/
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "config.h"
|
||||
|
||||
#define MAX_WIDGETS 32
|
||||
#define MAX_COMPACTORS 8
|
||||
#define MAX_TRANSPORTS 8
|
||||
#define MAX_COMMANDS 16
|
||||
#define MAX_PLUGINS 32
|
||||
#define MAX_NOTE 2048
|
||||
|
||||
struct widget {
|
||||
struct sp_host *host;
|
||||
char name[64];
|
||||
int (*tick)(struct sp_host *, const char *, void *);
|
||||
void (*draw)(struct sp_host *, const char *, void *);
|
||||
void *ctx;
|
||||
unsigned interval_ms;
|
||||
|
||||
pthread_t thread;
|
||||
int running;
|
||||
int stop;
|
||||
char text[MAX_NOTE];
|
||||
pthread_mutex_t lock;
|
||||
};
|
||||
|
||||
struct sp_host {
|
||||
struct sp_registry *reg;
|
||||
const void *conf; /* the loaded config, for plugins */
|
||||
const char *session_dir; /* session directory, for persistence */
|
||||
struct widget widgets[MAX_WIDGETS];
|
||||
size_t nwidgets;
|
||||
char note[MAX_NOTE];
|
||||
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];
|
||||
size_t ngate;
|
||||
const struct sp_status *status[MAX_COMPACTORS];
|
||||
size_t nstatus;
|
||||
struct sp_meter meter;
|
||||
const struct sp_task_ops *taskops;
|
||||
struct {
|
||||
char name[32];
|
||||
struct sp_transport tr;
|
||||
} transports[MAX_TRANSPORTS];
|
||||
size_t ntransports;
|
||||
struct {
|
||||
char name[32];
|
||||
sp_cmd_fn fn;
|
||||
void *ctx;
|
||||
} commands[MAX_COMMANDS];
|
||||
size_t ncommands;
|
||||
pthread_mutex_t lock; /* guards note and the registry */
|
||||
struct sp_session_info *sess;
|
||||
struct sp_agent *agent;
|
||||
size_t compactions;
|
||||
size_t failed;
|
||||
unsigned turns;
|
||||
char model[256]; /* what the run is on */
|
||||
char served_by[128]; /* who answered the last request */
|
||||
/* loaded plugins, in load order, so shutdown() runs in reverse */
|
||||
const struct sp_plugin *loaded[MAX_PLUGINS];
|
||||
size_t nloaded;
|
||||
/* quota/usage/burst policy hook (dispatches by provider/key_id) */
|
||||
const struct sp_provider_ops *provider;
|
||||
};
|
||||
|
||||
static void *
|
||||
widget_thread(void *arg)
|
||||
{
|
||||
struct widget *w = arg;
|
||||
|
||||
for (;;) {
|
||||
struct timespec ts;
|
||||
|
||||
pthread_mutex_lock(&w->lock);
|
||||
if (w->stop) {
|
||||
pthread_mutex_unlock(&w->lock);
|
||||
break;
|
||||
}
|
||||
pthread_mutex_unlock(&w->lock);
|
||||
|
||||
if (w->tick != NULL)
|
||||
(void)w->tick(w->host, w->name, w->ctx);
|
||||
|
||||
if (w->interval_ms == 0)
|
||||
break;
|
||||
/*
|
||||
* Sleep in short steps and look at the stop flag between them:
|
||||
* one long sleep made the exit wait for a whole interval, since
|
||||
* sp_host_free() joins this thread.
|
||||
*/
|
||||
{
|
||||
unsigned long left = w->interval_ms;
|
||||
int stop = 0;
|
||||
|
||||
while (left > 0 && !stop) {
|
||||
unsigned long step = left > 100 ? 100 : left;
|
||||
|
||||
ts.tv_sec = 0;
|
||||
ts.tv_nsec = (long)step * 1000000L;
|
||||
nanosleep(&ts, NULL);
|
||||
left -= step;
|
||||
pthread_mutex_lock(&w->lock);
|
||||
stop = w->stop;
|
||||
pthread_mutex_unlock(&w->lock);
|
||||
}
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
uint32_t
|
||||
sp_host_abi(struct sp_host *h)
|
||||
{
|
||||
(void)h;
|
||||
return SP_PLUGIN_ABI;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_add_tool(struct sp_host *h, const struct sp_tool *t)
|
||||
{
|
||||
int rc;
|
||||
|
||||
if (h == NULL || t == NULL || t->name == NULL || t->run == NULL)
|
||||
return -1;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
rc = sp_registry_add(h->reg, t);
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_add_widget(struct sp_host *h, const struct sp_widget *w)
|
||||
{
|
||||
struct widget *slot;
|
||||
size_t i;
|
||||
|
||||
if (h == NULL || w == NULL || w->name == NULL)
|
||||
return -1;
|
||||
if (h->nwidgets == MAX_WIDGETS)
|
||||
return -1;
|
||||
for (i = 0; i < h->nwidgets; i++)
|
||||
if (strcmp(h->widgets[i].name, w->name) == 0)
|
||||
return -1;
|
||||
|
||||
/*
|
||||
* Fill the slot first, publish it last. nwidgets used to be counted up
|
||||
* before the slot (and its mutex) existed, while tick threads of other
|
||||
* widgets were already walking the table.
|
||||
*/
|
||||
slot = &h->widgets[h->nwidgets];
|
||||
memset(slot, 0, sizeof(*slot));
|
||||
slot->host = h;
|
||||
snprintf(slot->name, sizeof(slot->name), "%s", w->name);
|
||||
slot->tick = w->tick;
|
||||
slot->draw = w->draw;
|
||||
slot->ctx = w->ctx;
|
||||
slot->interval_ms = w->interval_ms;
|
||||
slot->stop = 0;
|
||||
pthread_mutex_init(&slot->lock, NULL);
|
||||
snprintf(slot->text, sizeof(slot->text), "starting...");
|
||||
|
||||
pthread_mutex_lock(&h->lock);
|
||||
h->nwidgets++;
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
if (slot->tick != NULL) {
|
||||
/*
|
||||
* A worker gets the host pointer, but only the publish path is
|
||||
* thread-safe: sp_host_widget_text() and sp_host_note() take locks.
|
||||
* Everything else on the host belongs to the main thread.
|
||||
*/
|
||||
slot->running = 1;
|
||||
if (pthread_create(&slot->thread, NULL, widget_thread, slot) != 0) {
|
||||
slot->running = 0;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
h->nwidgets--;
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
pthread_mutex_destroy(&slot->lock);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_add_compactor(struct sp_host *h, const struct sp_compactor *c)
|
||||
{
|
||||
if (h == NULL || c == NULL || c->name == NULL || c->compact == NULL)
|
||||
return -1;
|
||||
if (h->ncompact == MAX_COMPACTORS)
|
||||
return -1;
|
||||
h->compact[h->ncompact++] = c;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_add_status(struct sp_host *h, const struct sp_status *s)
|
||||
{
|
||||
if (h == NULL || s == NULL || s->render == NULL || s->name == NULL)
|
||||
return -1;
|
||||
if (h->nstatus == MAX_COMPACTORS)
|
||||
return -1;
|
||||
h->status[h->nstatus++] = s;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_set_task_ops(struct sp_host *h, const struct sp_task_ops *ops)
|
||||
{
|
||||
if (h != NULL)
|
||||
h->taskops = ops;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_task_begin(struct sp_host *h, const char *label, const char *detail)
|
||||
{
|
||||
if (h == NULL || h->taskops == NULL || h->taskops->begin == NULL)
|
||||
return -1;
|
||||
return h->taskops->begin(h, label, detail);
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_task_end(struct sp_host *h, int id, int status, size_t tokens)
|
||||
{
|
||||
if (h != NULL && h->taskops != NULL && h->taskops->end != NULL)
|
||||
h->taskops->end(h, id, status, tokens);
|
||||
}
|
||||
|
||||
const struct sp_meter *
|
||||
sp_host_meter(struct sp_host *h)
|
||||
{
|
||||
static const struct sp_meter empty;
|
||||
|
||||
return h != NULL ? &h->meter : ∅
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_set_meter(struct sp_host *h, const struct sp_meter *m)
|
||||
{
|
||||
if (h == NULL || m == NULL)
|
||||
return;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
h->meter = *m;
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
/*
|
||||
* The meter is written from the UI thread (tokens), from turn threads (tools
|
||||
* of the tasks plugin) and from widget threads. These two are the safe way:
|
||||
* a copy taken under the lock, and a change of only the fields the caller
|
||||
* owns, under the lock.
|
||||
*/
|
||||
void
|
||||
sp_host_meter_get(struct sp_host *h, struct sp_meter *out)
|
||||
{
|
||||
if (out == NULL)
|
||||
return;
|
||||
if (h == NULL) {
|
||||
memset(out, 0, sizeof(*out));
|
||||
return;
|
||||
}
|
||||
pthread_mutex_lock(&h->lock);
|
||||
*out = h->meter;
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_meter_update(struct sp_host *h,
|
||||
void (*fn)(struct sp_meter *, void *), void *ctx)
|
||||
{
|
||||
if (h == NULL || fn == NULL)
|
||||
return;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
fn(&h->meter, ctx);
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
size_t
|
||||
sp_host_status_text(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
size_t i, used = 0;
|
||||
|
||||
if (h == NULL || buf == NULL || len == 0)
|
||||
return 0;
|
||||
buf[0] = '\0';
|
||||
for (i = 0; i < h->nstatus; i++) {
|
||||
char piece[256];
|
||||
int n;
|
||||
|
||||
piece[0] = '\0';
|
||||
h->status[i]->render(h, piece, sizeof(piece));
|
||||
if (piece[0] == '\0')
|
||||
continue;
|
||||
n = snprintf(buf + used, len - used, "%s%s",
|
||||
used > 0 ? " | " : "", piece);
|
||||
if (n < 0 || (size_t)n >= len - used)
|
||||
break;
|
||||
used += (size_t)n;
|
||||
}
|
||||
return used;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_add_gate(struct sp_host *h, const struct sp_gate *g)
|
||||
{
|
||||
if (h == NULL || g == NULL || g->check == NULL || g->name == NULL)
|
||||
return -1;
|
||||
if (h->ngate == MAX_COMPACTORS)
|
||||
return -1;
|
||||
h->gate[h->ngate++] = g;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The first gate with an opinion wins. A denial carries its reason; allowing
|
||||
* skips the operator prompt, which is what a whitelist is for.
|
||||
*/
|
||||
int
|
||||
sp_host_turn_blocked(struct sp_host *h, char *msg, size_t len)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (h == NULL)
|
||||
return 0;
|
||||
for (i = 0; i < h->ngate; i++)
|
||||
if (h->gate[i]->block_turn != NULL &&
|
||||
h->gate[i]->block_turn(h, msg, len))
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_gate(struct sp_host *h, const char *tool, int auth, const char *args,
|
||||
char *reason, size_t reason_len)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (h == NULL)
|
||||
return -1;
|
||||
for (i = 0; i < h->ngate; i++) {
|
||||
int rc = h->gate[i]->check(h, tool, auth, args, reason, reason_len);
|
||||
|
||||
if (rc >= 0)
|
||||
return rc;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/*
|
||||
* Run every compactor in registration order. A compactor that fails does not
|
||||
* stop the others and does not abort the turn: the failure is counted and the
|
||||
* loop carries on with whatever the conversation looks like now.
|
||||
*/
|
||||
int
|
||||
sp_host_add_transport(struct sp_host *h, const char *name,
|
||||
struct sp_transport tr)
|
||||
{
|
||||
if (h == NULL || name == NULL || tr.send == NULL)
|
||||
return -1;
|
||||
if (h->ntransports == MAX_TRANSPORTS)
|
||||
return -1;
|
||||
if (sp_host_transport(h, name) != NULL)
|
||||
return -1;
|
||||
snprintf(h->transports[h->ntransports].name,
|
||||
sizeof(h->transports[h->ntransports].name), "%s", name);
|
||||
h->transports[h->ntransports].tr = tr;
|
||||
h->ntransports++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct sp_transport *
|
||||
sp_host_transport(struct sp_host *h, const char *name)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (h == NULL || name == NULL)
|
||||
return NULL;
|
||||
for (i = 0; i < h->ntransports; i++)
|
||||
if (strcmp(h->transports[i].name, name) == 0)
|
||||
return &h->transports[i].tr;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_add_command(struct sp_host *h, const char *name, sp_cmd_fn fn,
|
||||
void *ctx)
|
||||
{
|
||||
if (h == NULL || name == NULL || fn == NULL)
|
||||
return -1;
|
||||
if (h->ncommands == MAX_COMMANDS)
|
||||
return -1;
|
||||
snprintf(h->commands[h->ncommands].name,
|
||||
sizeof(h->commands[h->ncommands].name), "%s", name);
|
||||
h->commands[h->ncommands].fn = fn;
|
||||
h->commands[h->ncommands].ctx = ctx;
|
||||
h->ncommands++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_command(struct sp_host *h, const char *name, const char *args,
|
||||
struct sp_buf *out)
|
||||
{
|
||||
size_t i;
|
||||
int rc = -1;
|
||||
|
||||
if (h == NULL || name == NULL)
|
||||
return -1;
|
||||
for (i = 0; i < h->ncommands; i++) {
|
||||
if (strcmp(h->commands[i].name, name) != 0)
|
||||
continue;
|
||||
rc = h->commands[i].fn(h, args != NULL ? args : "",
|
||||
out, h->commands[i].ctx);
|
||||
if (rc == 0)
|
||||
return 0;
|
||||
}
|
||||
sp_buf_printf(out, "unknown command: /%s", name);
|
||||
return -1;
|
||||
}
|
||||
|
||||
size_t
|
||||
sp_host_command_help(struct sp_host *h, struct sp_buf *out)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (h == NULL)
|
||||
return 0;
|
||||
for (i = 0; i < h->ncommands; i++)
|
||||
(void)sp_buf_printf(out, "/%s ", h->commands[i].name);
|
||||
return h->ncommands;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_compact(struct sp_host *h, struct sp_conv *conv, size_t budget)
|
||||
{
|
||||
size_t i;
|
||||
int changed = 0, rc;
|
||||
|
||||
if (h == NULL || conv == NULL)
|
||||
return 0;
|
||||
for (i = 0; i < h->ncompact; i++) {
|
||||
rc = h->compact[i]->compact(h, conv, budget,
|
||||
(unsigned)h->turns);
|
||||
if (rc > 0) {
|
||||
changed = 1;
|
||||
h->compactions++;
|
||||
} else if (rc < 0) {
|
||||
h->failed++;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
size_t
|
||||
sp_host_compaction_stats(struct sp_host *h, size_t *compactions,
|
||||
size_t *failed, unsigned *turns)
|
||||
{
|
||||
if (compactions != NULL)
|
||||
*compactions = h != NULL ? h->compactions : 0;
|
||||
if (failed != NULL)
|
||||
*failed = h != NULL ? h->failed : 0;
|
||||
if (turns != NULL)
|
||||
*turns = h != NULL ? h->turns : 0;
|
||||
return h != NULL ? h->compactions : 0;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_model(struct sp_host *h)
|
||||
{
|
||||
static __thread char copy[256];
|
||||
|
||||
if (h == NULL)
|
||||
return "";
|
||||
pthread_mutex_lock(&h->lock);
|
||||
snprintf(copy, sizeof(copy), "%s", h->model);
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
return copy;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_set_model(struct sp_host *h, const char *model)
|
||||
{
|
||||
if (h == NULL)
|
||||
return;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
snprintf(h->model, sizeof(h->model), "%s", model != NULL ? model : "");
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_served_by(struct sp_host *h)
|
||||
{
|
||||
static __thread char copy[128];
|
||||
|
||||
if (h == NULL)
|
||||
return "";
|
||||
pthread_mutex_lock(&h->lock);
|
||||
snprintf(copy, sizeof(copy), "%s", h->served_by);
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
return copy;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_set_served_by(struct sp_host *h, const char *endpoint)
|
||||
{
|
||||
if (h == NULL)
|
||||
return;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
snprintf(h->served_by, sizeof(h->served_by), "%s",
|
||||
endpoint != NULL ? endpoint : "");
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
struct sp_registry *
|
||||
sp_host_registry(struct sp_host *h)
|
||||
{
|
||||
return h != NULL ? h->reg : NULL;
|
||||
}
|
||||
|
||||
const void *
|
||||
sp_host_config(struct sp_host *h)
|
||||
{
|
||||
return h != NULL ? h->conf : NULL;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_set_config(struct sp_host *h, const void *conf)
|
||||
{
|
||||
if (h != NULL)
|
||||
h->conf = conf;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_plugin_config(struct sp_host *h, const char *plugin, const char *key)
|
||||
{
|
||||
return sp_config_plugin_value(h != NULL ? h->conf : NULL, plugin, key);
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_plugin_config_at(struct sp_host *h, const char *plugin, size_t i,
|
||||
const char **key)
|
||||
{
|
||||
const struct sp_config *c = h != NULL ? h->conf : NULL;
|
||||
size_t k, seen = 0;
|
||||
|
||||
if (c == NULL || plugin == NULL)
|
||||
return NULL;
|
||||
for (k = 0; k < c->nplugin_conf; k++) {
|
||||
if (strcmp(c->plugin_conf[k].plugin, plugin) != 0)
|
||||
continue;
|
||||
if (seen++ == i) {
|
||||
if (key != NULL)
|
||||
*key = c->plugin_conf[k].key;
|
||||
return c->plugin_conf[k].val;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_turn(struct sp_host *h)
|
||||
{
|
||||
if (h != NULL)
|
||||
h->turns++;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_widget_text(struct sp_host *h, const char *widget, const char *text)
|
||||
{
|
||||
size_t i, n;
|
||||
|
||||
if (h == NULL || widget == NULL || text == NULL)
|
||||
return -1;
|
||||
/* called from tick threads: the count is read under the host lock */
|
||||
pthread_mutex_lock(&h->lock);
|
||||
n = h->nwidgets;
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
for (i = 0; i < n; i++) {
|
||||
struct widget *w = &h->widgets[i];
|
||||
|
||||
if (strcmp(w->name, widget) != 0)
|
||||
continue;
|
||||
pthread_mutex_lock(&w->lock);
|
||||
snprintf(w->text, sizeof(w->text), "%s", text);
|
||||
pthread_mutex_unlock(&w->lock);
|
||||
return 0;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_note(struct sp_host *h, const char *text)
|
||||
{
|
||||
if (h == NULL || text == NULL)
|
||||
return -1;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
snprintf(h->note, sizeof(h->note), "%s", text);
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
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)
|
||||
{
|
||||
size_t i, used = 0;
|
||||
|
||||
if (h == NULL || buf == NULL || len == 0)
|
||||
return 0;
|
||||
buf[0] = '\0';
|
||||
for (i = 0; i < h->nwidgets; i++) {
|
||||
struct widget *w = &h->widgets[i];
|
||||
int n;
|
||||
|
||||
pthread_mutex_lock(&w->lock);
|
||||
n = snprintf(buf + used, len - used, "%s: %s\n", w->name, w->text);
|
||||
pthread_mutex_unlock(&w->lock);
|
||||
if (n < 0 || (size_t)n >= len - used)
|
||||
break;
|
||||
used += (size_t)n;
|
||||
}
|
||||
return used;
|
||||
}
|
||||
|
||||
struct sp_plugin_handle {
|
||||
void *dl;
|
||||
const struct sp_plugin *p;
|
||||
char path[512];
|
||||
};
|
||||
|
||||
/* how far each table was filled before a plugin's init() ran */
|
||||
struct host_mark {
|
||||
size_t tools, widgets, compact, gate, status;
|
||||
size_t transports, commands;
|
||||
const struct sp_task_ops *taskops;
|
||||
};
|
||||
|
||||
static void
|
||||
mark(struct sp_host *h, struct host_mark *m)
|
||||
{
|
||||
pthread_mutex_lock(&h->lock);
|
||||
m->tools = h->reg != NULL ? h->reg->len : 0;
|
||||
m->widgets = h->nwidgets;
|
||||
m->compact = h->ncompact;
|
||||
m->gate = h->ngate;
|
||||
m->status = h->nstatus;
|
||||
m->transports = h->ntransports;
|
||||
m->commands = h->ncommands;
|
||||
m->taskops = h->taskops;
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
static void
|
||||
stop_widget(struct widget *w)
|
||||
{
|
||||
if (w->running) {
|
||||
pthread_mutex_lock(&w->lock);
|
||||
w->stop = 1;
|
||||
pthread_mutex_unlock(&w->lock);
|
||||
pthread_join(w->thread, NULL);
|
||||
w->running = 0;
|
||||
}
|
||||
pthread_mutex_destroy(&w->lock);
|
||||
}
|
||||
|
||||
static void
|
||||
rollback(struct sp_host *h, const struct host_mark *m)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = m->widgets; i < h->nwidgets; i++)
|
||||
stop_widget(&h->widgets[i]);
|
||||
pthread_mutex_lock(&h->lock);
|
||||
h->nwidgets = m->widgets;
|
||||
if (h->reg != NULL && h->reg->len > m->tools)
|
||||
h->reg->len = m->tools;
|
||||
h->ncompact = m->compact;
|
||||
h->ngate = m->gate;
|
||||
h->nstatus = m->status;
|
||||
h->ntransports = m->transports;
|
||||
h->ncommands = m->commands;
|
||||
h->taskops = m->taskops;
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
int
|
||||
sp_plugin_load(struct sp_host *h, const char *path, struct sp_buf *err)
|
||||
{
|
||||
struct sp_plugin_handle *hd;
|
||||
const struct sp_plugin *(*describe)(void);
|
||||
|
||||
if (h == NULL || path == NULL)
|
||||
return -1;
|
||||
hd = dlopen(path, RTLD_NOW | RTLD_LOCAL);
|
||||
if (hd == NULL) {
|
||||
sp_buf_printf(err, "plugin %s: %s", path, dlerror());
|
||||
return -1;
|
||||
}
|
||||
{
|
||||
void *sym = dlsym(hd, "sp_plugin_describe");
|
||||
|
||||
if (sym == NULL) {
|
||||
sp_buf_printf(err, "plugin %s: no sp_plugin_describe()",
|
||||
path);
|
||||
/* the handle stays mapped: dlclose after a failed init is
|
||||
* how a half-initialised plugin takes the process with it */
|
||||
return -1;
|
||||
}
|
||||
{
|
||||
union { void *p; const struct sp_plugin *(*f)(void); } cast;
|
||||
|
||||
cast.p = sym;
|
||||
describe = cast.f;
|
||||
}
|
||||
}
|
||||
{
|
||||
const struct sp_plugin *p = describe();
|
||||
|
||||
if (p == NULL) {
|
||||
sp_buf_printf(err, "plugin %s: describe() returned NULL",
|
||||
path);
|
||||
return -1;
|
||||
}
|
||||
if (p->abi != SP_PLUGIN_ABI) {
|
||||
sp_buf_printf(err, "plugin %s: abi %u, host speaks %u",
|
||||
path, p->abi, SP_PLUGIN_ABI);
|
||||
return -1;
|
||||
}
|
||||
if (h->nloaded == MAX_PLUGINS) {
|
||||
sp_buf_printf(err, "plugin %s: more than %d plugins", path,
|
||||
MAX_PLUGINS);
|
||||
return -1;
|
||||
}
|
||||
{
|
||||
struct host_mark m;
|
||||
|
||||
mark(h, &m);
|
||||
if (p->init != NULL && p->init(h) != 0) {
|
||||
/*
|
||||
* "Never half-used": whatever init registered before
|
||||
* it failed - tools, a gate, widget threads - goes
|
||||
* again. A kids plugin whose gate stayed while its
|
||||
* compactor did not was a policy nobody had chosen.
|
||||
*/
|
||||
rollback(h, &m);
|
||||
sp_buf_printf(err, "plugin %s: init failed", path);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
h->loaded[h->nloaded++] = p;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
struct sp_host *
|
||||
sp_host_new(struct sp_registry *reg, struct sp_agent *agent,
|
||||
struct sp_session_info *sess)
|
||||
{
|
||||
struct sp_host *h = calloc(1, sizeof(*h));
|
||||
|
||||
if (h == NULL)
|
||||
return NULL;
|
||||
h->reg = reg;
|
||||
h->agent = agent;
|
||||
h->sess = sess;
|
||||
h->session_dir = (sess != NULL) ? sess->dir : NULL;
|
||||
pthread_mutex_init(&h->lock, NULL);
|
||||
return h;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_session_dir(struct sp_host *h)
|
||||
{
|
||||
return (h != NULL) ? h->session_dir : NULL;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_session_id(struct sp_host *h)
|
||||
{
|
||||
return (h != NULL && h->sess != NULL) ? h->sess->id : NULL;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_set_provider(struct sp_host *h, const struct sp_provider_ops *ops)
|
||||
{
|
||||
if (h != NULL)
|
||||
h->provider = ops;
|
||||
}
|
||||
|
||||
enum sp_prov_decision
|
||||
sp_host_provider_preflight(struct sp_host *h, const char *provider,
|
||||
const char *key_id, struct sp_prov_result *out)
|
||||
{
|
||||
if (out != NULL) {
|
||||
memset(out, 0, sizeof(*out));
|
||||
out->decision = SP_PROV_ADMIT;
|
||||
}
|
||||
if (h == NULL || h->provider == NULL || h->provider->preflight == NULL)
|
||||
return SP_PROV_ADMIT;
|
||||
(void)h->provider->preflight(h->provider->ctx, provider, key_id, out);
|
||||
return (out != NULL) ? out->decision : SP_PROV_ADMIT;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_provider_account(struct sp_host *h, const char *provider,
|
||||
const char *key_id, long http_status, size_t tokens_in, size_t tokens_out)
|
||||
{
|
||||
if (h == NULL || h->provider == NULL || h->provider->account == NULL)
|
||||
return;
|
||||
h->provider->account(h->provider->ctx, provider, key_id, http_status,
|
||||
tokens_in, tokens_out);
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_free(struct sp_host *h)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (h == NULL)
|
||||
return;
|
||||
/* the threads first: a tick must not run into a plugin that shut down */
|
||||
for (i = 0; i < h->nwidgets; i++)
|
||||
stop_widget(&h->widgets[i]);
|
||||
/*
|
||||
* Then shutdown(), newest plugin first. It was declared in the ABI and
|
||||
* never called: the MCP plugin's server process was never reaped.
|
||||
*/
|
||||
for (i = h->nloaded; i > 0; i--)
|
||||
if (h->loaded[i - 1]->shutdown != NULL)
|
||||
h->loaded[i - 1]->shutdown(h);
|
||||
pthread_mutex_destroy(&h->lock);
|
||||
free(h);
|
||||
}
|
||||
|
||||
size_t
|
||||
sp_host_widget_count(struct sp_host *h)
|
||||
{
|
||||
return h != NULL ? h->nwidgets : 0;
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
/*
|
||||
* splinter -- the default system prompt.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Short on purpose. Every line here is paid for on every request, and anything
|
||||
* the tools already say does not belong here: a rule in a tool description
|
||||
* cannot be argued away, a rule in the prompt can.
|
||||
*
|
||||
* Placeholders are filled at startup, not by the model:
|
||||
* {{os}} uname -s -r
|
||||
* {{home}} $HOME
|
||||
* {{cwd}} the working directory
|
||||
* {{model}} the model this turn will go to
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/utsname.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "prompt.h"
|
||||
|
||||
#define SP_PROMPT_DEFAULT \
|
||||
"You are Splinter, an autonomous agent on a real machine ({{os}}, home {{home}}, " \
|
||||
"working directory {{cwd}}). You have a shell, a filesystem and the loaded tools.\n" \
|
||||
"\n" \
|
||||
"Read before you build. If a README, AGENTS file, man page or the source itself " \
|
||||
"documents how something here is done, read it first and follow it. A hack that " \
|
||||
"works against the documented way is a bug with good timing.\n" \
|
||||
"\n" \
|
||||
"Check what already exists before writing anything new: binaries, scripts, " \
|
||||
"plugins, skills. Reinventing a thing that is already there costs the user time " \
|
||||
"and trust.\n" \
|
||||
"\n" \
|
||||
"Work through errors by changing the approach, not by repeating the same attempt. " \
|
||||
"Keep a short record of what you built and where it lives.\n" \
|
||||
"\n" \
|
||||
"Evidence over claims. Run what you build, read the output, then say what you " \
|
||||
"verified and what you did not. Never invent output, paths, versions or results.\n" \
|
||||
"\n" \
|
||||
"Answer briefly: the result first, where the files are, then the next step. Use " \
|
||||
"the language the user writes in.\n"
|
||||
|
||||
static void
|
||||
expand_into(const char *tmpl, char *out, size_t cap, const char *model)
|
||||
{
|
||||
const char *src = tmpl;
|
||||
size_t used = 0;
|
||||
struct utsname un;
|
||||
const char *home = getenv("HOME");
|
||||
char cwd[512];
|
||||
|
||||
(void)uname(&un);
|
||||
if (getcwd(cwd, sizeof(cwd)) == NULL)
|
||||
snprintf(cwd, sizeof(cwd), "?");
|
||||
while (*src != '\0' && used + 1 < cap) {
|
||||
if (strncmp(src, "{{os}}", 6) == 0) {
|
||||
used += (size_t)snprintf(out + used, cap - used, "%s %s",
|
||||
un.sysname, un.release);
|
||||
src += 6;
|
||||
} else if (strncmp(src, "{{home}}", 8) == 0) {
|
||||
used += (size_t)snprintf(out + used, cap - used, "%s",
|
||||
home != NULL ? home : "?");
|
||||
src += 8;
|
||||
} else if (strncmp(src, "{{cwd}}", 7) == 0) {
|
||||
used += (size_t)snprintf(out + used, cap - used, "%s", cwd);
|
||||
src += 7;
|
||||
} else if (strncmp(src, "{{model}}", 9) == 0) {
|
||||
used += (size_t)snprintf(out + used, cap - used, "%s",
|
||||
model != NULL ? model : "?");
|
||||
src += 9;
|
||||
} else
|
||||
out[used++] = *src++;
|
||||
}
|
||||
out[used] = '\0';
|
||||
}
|
||||
|
||||
void
|
||||
sp_prompt_default(char *buf, size_t cap, const char *model)
|
||||
{
|
||||
expand_into(SP_PROMPT_DEFAULT, buf, cap, model);
|
||||
}
|
||||
|
||||
void
|
||||
sp_prompt_expand(const char *tmpl, char *buf, size_t cap, const char *model)
|
||||
{
|
||||
if (tmpl == NULL || *tmpl == '\0') {
|
||||
sp_prompt_default(buf, cap, model);
|
||||
return;
|
||||
}
|
||||
expand_into(tmpl, buf, cap, model);
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
/*
|
||||
* splinter -- the default system prompt.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_PROMPT_H
|
||||
#define SPLINTER_PROMPT_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
void sp_prompt_default(char *buf, size_t cap, const char *model);
|
||||
void sp_prompt_expand(const char *tmpl, char *buf, size_t cap,
|
||||
const char *model);
|
||||
|
||||
#endif /* SPLINTER_PROMPT_H */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,161 +0,0 @@
|
||||
/* splinter -- the models this installation can talk to, and how to add one. */
|
||||
#ifndef SPLINTER_PROVIDERS_H
|
||||
#define SPLINTER_PROVIDERS_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_config;
|
||||
struct sp_delegate;
|
||||
struct sp_pool;
|
||||
struct sp_agent;
|
||||
struct sp_transport;
|
||||
struct sp_buf;
|
||||
struct sp_model_choice;
|
||||
|
||||
/*
|
||||
* One reachable model: the endpoint, the model name and the variable the key
|
||||
* lives in. The list is what the run was configured with -- main endpoint,
|
||||
* delegates that name a model, exits -- so nothing here talks to the network.
|
||||
*/
|
||||
struct sp_provider {
|
||||
char id[64];
|
||||
char kind[16]; /* "openai" (default), "anthropic" or "cli" */
|
||||
char endpoint[512];
|
||||
char model[256];
|
||||
char key_env[64];
|
||||
char about[128];
|
||||
unsigned long ctx; /* context window, 0 = unknown */
|
||||
int main; /* the endpoint/model the run started with */
|
||||
};
|
||||
|
||||
/* main first, then delegates with an endpoint and a model, then exits */
|
||||
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);
|
||||
|
||||
/*
|
||||
* The list /model shows: every provider (selector = its id) followed by every
|
||||
* pool (selector = the pool id), with the model as the label and a marker for
|
||||
* the one the run is on. No network: it is the configuration, not the answer
|
||||
* to "what does the endpoint really serve".
|
||||
*/
|
||||
size_t sp_provider_choices(const struct sp_config *, const char *cur_model,
|
||||
struct sp_model_choice *, size_t max);
|
||||
|
||||
/*
|
||||
* 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
|
||||
* usage state are filed under.
|
||||
*/
|
||||
void sp_provider_identify(struct sp_transport *, const char *endpoint,
|
||||
const char *secret);
|
||||
|
||||
/* Point the agent at provider 'i' for the rest of this run. 0 or -1. */
|
||||
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>). '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);
|
||||
|
||||
/*
|
||||
* Add a provider (or replace one with the same id) in 'cfg' and in
|
||||
* <dir>/20-connect.conf, so the next start has it too. The fields are
|
||||
* validated here: a line that cannot be read back is worse than a refusal.
|
||||
*/
|
||||
int sp_provider_add(struct sp_config *, const char *dir, const char *id,
|
||||
const char *endpoint, const char *model, const char *key_env,
|
||||
struct sp_buf *err);
|
||||
|
||||
/* One answer of /connect, checked before it becomes a line: a name must fit
|
||||
* the id field, an endpoint must be http(s), a model must be a name and the key
|
||||
* variable an environment name. 1 when it does. */
|
||||
int sp_provider_id_ok(const char *id);
|
||||
int sp_provider_endpoint_ok(const char *endpoint);
|
||||
int sp_provider_model_ok(const char *model);
|
||||
int sp_provider_key_ok(const char *key_env);
|
||||
|
||||
/*
|
||||
* Ask the endpoint which models it really serves (/v1/models). 'ids' gets one
|
||||
* model name per line. A provider that does not answer that route is not
|
||||
* broken -- many do not -- so the caller decides what a failure means.
|
||||
*/
|
||||
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,
|
||||
struct sp_buf *err);
|
||||
|
||||
/*
|
||||
* Remember the choice for the next start: <config>.d/90-model.conf. Picking
|
||||
* "main" removes the file instead, so the config speaks again. Returns 1 when
|
||||
* nothing was written because a plugin transport decides the model anyway.
|
||||
*/
|
||||
int sp_provider_save_choice(const struct sp_config *,
|
||||
const struct sp_provider *, struct sp_buf *err);
|
||||
|
||||
/* The config line for one provider, also handy for showing it. */
|
||||
int sp_provider_line(char *buf, size_t len, const char *id,
|
||||
const char *endpoint, const char *model, const char *key_env);
|
||||
|
||||
/* 1 when the provider can be called: its key variable (if it names one) is set */
|
||||
int sp_provider_has_key(const struct sp_delegate *);
|
||||
|
||||
/*
|
||||
* Pools. A pool is a name for providers that stand in for each other.
|
||||
* sp_pool_pick gives the member to use now -- first with room (failover) or
|
||||
* the one with the most left (balance) -- never 'skip' (the one that just
|
||||
* failed) and only one that has every tag of 'need_tags' (comma list, NULL:
|
||||
* any), and NULL when every member is benched or used up; *soonest then
|
||||
* holds the epoch the first of them is back (0: unknown).
|
||||
*/
|
||||
const struct sp_pool *sp_pool_find(const struct sp_config *, const char *id);
|
||||
const struct sp_pool *sp_pool_of(const struct sp_config *, const char *member);
|
||||
const struct sp_delegate *sp_pool_pick(const struct sp_config *,
|
||||
const struct sp_pool *, const char *skip, const char *need_tags,
|
||||
long *soonest);
|
||||
|
||||
/*
|
||||
* What the user means by "-m SEL": a pool, a provider, "provider/model", or a
|
||||
* model name one of the providers has. 0, or -1 when nothing matches.
|
||||
*/
|
||||
struct sp_choice {
|
||||
const struct sp_delegate *d;
|
||||
char model[256]; /* the model to ask for, the provider's own by default */
|
||||
};
|
||||
int sp_provider_choose(const struct sp_config *, const char *sel,
|
||||
struct sp_choice *out);
|
||||
|
||||
/*
|
||||
* The provider the conversation is on is at its limit: move to another member
|
||||
* of its pool that has room. 1 when the agent now talks to another provider.
|
||||
*/
|
||||
int sp_provider_failover(struct sp_agent *, const struct sp_config *);
|
||||
|
||||
#endif /* SPLINTER_PROVIDERS_H */
|
||||
@@ -1,227 +0,0 @@
|
||||
/*
|
||||
* splinter -- shared provider/key state (quota/usage), cross-instance.
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "provstate.h"
|
||||
|
||||
/* djb2-ish hash -> hex, stable key identity (not secret storage) */
|
||||
static void
|
||||
keyhash(const char *s, char out[17])
|
||||
{
|
||||
unsigned long h = 5381;
|
||||
int c;
|
||||
while (s && (c = (unsigned char)*s++))
|
||||
h = ((h << 5) + h) ^ (unsigned long)c;
|
||||
snprintf(out, 17, "%016lx", h);
|
||||
}
|
||||
|
||||
static void
|
||||
mkdirs(const char *path)
|
||||
{
|
||||
char buf[512], *p;
|
||||
snprintf(buf, sizeof(buf), "%s", path);
|
||||
for (p = buf + 1; *p; p++) {
|
||||
if (*p == '/') { *p = '\0'; mkdir(buf, 0700); *p = '/'; }
|
||||
}
|
||||
mkdir(buf, 0700);
|
||||
}
|
||||
|
||||
char *
|
||||
sp_provstate_base(const char *provider, const char *key_id,
|
||||
char *buf, size_t cap)
|
||||
{
|
||||
const char *home = getenv("HOME");
|
||||
char kh[17], dir[512];
|
||||
if (!provider || !*provider || !key_id || !*key_id || !home)
|
||||
return NULL;
|
||||
keyhash(key_id, kh);
|
||||
snprintf(dir, sizeof(dir), "%s/.splinter/providers/%s", home, provider);
|
||||
mkdirs(dir);
|
||||
snprintf(buf, cap, "%s/%s", dir, kh);
|
||||
return buf;
|
||||
}
|
||||
|
||||
static void
|
||||
state_zero(struct sp_prov_state *s)
|
||||
{
|
||||
memset(s, 0, sizeof(*s));
|
||||
}
|
||||
|
||||
static const char *
|
||||
jnum(const char *json, const char *key, char *tmp, size_t cap)
|
||||
{
|
||||
char pat[96]; const char *p; size_t n;
|
||||
tmp[0]='\0';
|
||||
snprintf(pat, sizeof(pat), "\"%s\"", key);
|
||||
p = json ? strstr(json, pat) : NULL; if(!p) return tmp;
|
||||
p = strchr(p+strlen(pat), ':'); if(!p) return tmp;
|
||||
while (*p && (*p==' '||*p=='\t'||*p==':')) p++;
|
||||
n = strcspn(p, ", \t\r\n}");
|
||||
if (n >= cap) n = cap-1;
|
||||
memcpy(tmp, p, n); tmp[n]='\0';
|
||||
return tmp;
|
||||
}
|
||||
static void
|
||||
jstr(const char *json, const char *key, char *out, size_t cap)
|
||||
{
|
||||
char pat[96]; const char *p,*q; size_t n;
|
||||
out[0]='\0';
|
||||
snprintf(pat, sizeof(pat), "\"%s\"", key);
|
||||
p = json ? strstr(json, pat) : NULL; if(!p) return;
|
||||
p = strchr(p+strlen(pat), ':'); if(!p) return;
|
||||
p = strchr(p, '"'); if(!p) return; p++; q=strchr(p,'"'); if(!q) return;
|
||||
n=(size_t)(q-p); if(n>=cap) n=cap-1; memcpy(out,p,n); out[n]='\0';
|
||||
}
|
||||
|
||||
static void
|
||||
parse_state(const char *buf, struct sp_prov_state *s)
|
||||
{
|
||||
char t[64];
|
||||
state_zero(s);
|
||||
jstr(buf,"note",s->note,sizeof(s->note));
|
||||
s->quota_ready_at = strtol(jnum(buf,"quota_ready_at",t,sizeof(t)),NULL,10);
|
||||
s->backoff_until = strtol(jnum(buf,"backoff_until",t,sizeof(t)),NULL,10);
|
||||
s->req_count = (unsigned)strtoul(jnum(buf,"req_count",t,sizeof(t)),NULL,10);
|
||||
s->tok_in = strtoul(jnum(buf,"tok_in",t,sizeof(t)),NULL,10);
|
||||
s->tok_out = strtoul(jnum(buf,"tok_out",t,sizeof(t)),NULL,10);
|
||||
s->last_status = strtol(jnum(buf,"last_status",t,sizeof(t)),NULL,10);
|
||||
s->last_update = strtol(jnum(buf,"last_update",t,sizeof(t)),NULL,10);
|
||||
s->last_429_at = strtol(jnum(buf,"last_429_at",t,sizeof(t)),NULL,10);
|
||||
}
|
||||
|
||||
int
|
||||
sp_provstate_load(const char *provider, const char *key_id,
|
||||
struct sp_prov_state *out)
|
||||
{
|
||||
char base[512], path[530], buf[2048];
|
||||
FILE *fp; size_t n;
|
||||
state_zero(out);
|
||||
if (!sp_provstate_base(provider,key_id,base,sizeof(base))) return -1;
|
||||
snprintf(path,sizeof(path),"%s.json",base);
|
||||
fp = fopen(path,"r"); if(!fp) return -1;
|
||||
n = fread(buf,1,sizeof(buf)-1,fp); fclose(fp); buf[n]='\0';
|
||||
parse_state(buf,out);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
write_state(const char *base, const struct sp_prov_state *s)
|
||||
{
|
||||
char path[530], tmp[550];
|
||||
FILE *fp;
|
||||
snprintf(path,sizeof(path),"%s.json",base);
|
||||
snprintf(tmp,sizeof(tmp),"%s.tmp",path);
|
||||
fp = fopen(tmp,"w"); if(!fp) return -1;
|
||||
fprintf(fp, "{\n \"quota_ready_at\":%ld,\n \"backoff_until\":%ld,\n \"req_count\":%u,\n \"tok_in\":%lu,\n \"tok_out\":%lu,\n \"last_status\":%ld,\n \"last_update\":%ld,\n \"last_429_at\":%ld,\n \"note\":\"%s\"\n}\n",
|
||||
s->quota_ready_at, s->backoff_until, s->req_count, s->tok_in, s->tok_out,
|
||||
s->last_status, s->last_update, s->last_429_at, s->note);
|
||||
fclose(fp);
|
||||
return rename(tmp,path)==0 ? 0 : -1;
|
||||
}
|
||||
|
||||
int
|
||||
sp_provstate_update(const char *provider, const char *key_id,
|
||||
void (*fn)(struct sp_prov_state *s, void *ctx), void *ctx)
|
||||
{
|
||||
char base[512], lpath[530], jpath[530], buf[2048];
|
||||
struct sp_prov_state st;
|
||||
int fd; FILE *fp; size_t n;
|
||||
if (!sp_provstate_base(provider,key_id,base,sizeof(base)) || !fn) return -1;
|
||||
snprintf(lpath,sizeof(lpath),"%s.lock",base);
|
||||
snprintf(jpath,sizeof(jpath),"%s.json",base);
|
||||
fd = open(lpath, O_CREAT|O_RDWR, 0600);
|
||||
if (fd < 0) return -1;
|
||||
if (flock(fd, LOCK_EX) != 0) { close(fd); return -1; }
|
||||
state_zero(&st);
|
||||
fp = fopen(jpath,"r");
|
||||
if (fp) { n=fread(buf,1,sizeof(buf)-1,fp); fclose(fp); buf[n]='\0'; parse_state(buf,&st); }
|
||||
fn(&st, ctx);
|
||||
st.last_update = (long)time(NULL);
|
||||
write_state(base, &st);
|
||||
flock(fd, LOCK_UN);
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct acct_ctx { long status; size_t ti,to; long retry_after_s; long now; };
|
||||
static void acct_fn(struct sp_prov_state *s, void *p) {
|
||||
struct acct_ctx *c=p;
|
||||
s->req_count++;
|
||||
s->tok_in += (unsigned long)c->ti;
|
||||
s->tok_out += (unsigned long)c->to;
|
||||
s->last_status = c->status;
|
||||
if (c->status == 429 || c->status == 402 || c->status == 529) {
|
||||
s->last_429_at = c->now;
|
||||
if (c->retry_after_s > 0)
|
||||
s->quota_ready_at = c->now + c->retry_after_s;
|
||||
else if (c->status == 529 && s->quota_ready_at < c->now + 120)
|
||||
s->quota_ready_at = c->now + 120;
|
||||
else if (s->quota_ready_at < c->now + 60)
|
||||
s->quota_ready_at = c->now + 60;
|
||||
snprintf(s->note, sizeof(s->note), "quota/rate limit (status %ld)", c->status);
|
||||
} else if (c->status == 503 || c->status == 408) {
|
||||
s->backoff_until = c->now + (c->retry_after_s > 0 ? c->retry_after_s : 30);
|
||||
snprintf(s->note, sizeof(s->note), "transient backoff (status %ld)", c->status);
|
||||
} else if (c->status >= 200 && c->status < 300) {
|
||||
/* success: clear short backoff; clear expired quota */
|
||||
s->backoff_until = 0;
|
||||
if (s->quota_ready_at > 0 && s->quota_ready_at <= c->now) s->quota_ready_at = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
sp_provstate_account(const char *provider, const char *key_id,
|
||||
long http_status, size_t tok_in, size_t tok_out, long retry_after_s)
|
||||
{
|
||||
struct acct_ctx c;
|
||||
if (!provider || !key_id) return;
|
||||
c.status = http_status; c.ti=tok_in; c.to=tok_out;
|
||||
c.retry_after_s = retry_after_s; c.now = (long)time(NULL);
|
||||
sp_provstate_update(provider, key_id, acct_fn, &c);
|
||||
}
|
||||
|
||||
int
|
||||
sp_provstate_preflight(const char *provider, const char *key_id,
|
||||
long now, long *ready_at, char *reason, size_t reason_cap)
|
||||
{
|
||||
struct sp_prov_state st;
|
||||
if (ready_at) *ready_at = 0;
|
||||
if (reason && reason_cap) reason[0]='\0';
|
||||
if (sp_provstate_load(provider, key_id, &st) != 0)
|
||||
return 0; /* no state => admit */
|
||||
if (st.quota_ready_at > now) {
|
||||
if (ready_at) *ready_at = st.quota_ready_at;
|
||||
if (reason && reason_cap)
|
||||
snprintf(reason, reason_cap, "%s", st.note[0]?st.note:"quota wait");
|
||||
return 1; /* wait */
|
||||
}
|
||||
if (st.backoff_until > now) {
|
||||
if (ready_at) *ready_at = st.backoff_until;
|
||||
if (reason && reason_cap)
|
||||
snprintf(reason, reason_cap, "backoff");
|
||||
return 2; /* delay */
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
char *
|
||||
sp_key_fingerprint(const char *secret, char *buf, size_t cap)
|
||||
{
|
||||
char kh[17];
|
||||
if (!secret || !*secret || !buf || cap < 17) return NULL;
|
||||
keyhash(secret, kh);
|
||||
snprintf(buf, cap, "%s", kh);
|
||||
return buf;
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
#ifndef SP_PROVSTATE_H
|
||||
#define SP_PROVSTATE_H
|
||||
/*
|
||||
* Shared provider/key quota & usage state (persistent, cross-instance per key).
|
||||
* Files under ~/.splinter/providers/<provider>/<keyhash>.{json,lock}.
|
||||
*/
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_prov_state {
|
||||
long quota_ready_at; /* unix timestamp: requests blocked until then (0=ok) */
|
||||
long backoff_until; /* short backoff until (0=ok) */
|
||||
unsigned req_count;
|
||||
unsigned long tok_in;
|
||||
unsigned long tok_out;
|
||||
long last_status;
|
||||
long last_update; /* unix */
|
||||
long last_429_at; /* unix */
|
||||
char note[128]; /* e.g. "quota reset in 4d" */
|
||||
};
|
||||
|
||||
/* Compute state/lock base path for (provider,key_id). Returns buf or NULL. */
|
||||
char *sp_provstate_base(const char *provider, const char *key_id,
|
||||
char *buf, size_t cap);
|
||||
/* Load state (no lock held across return; best-effort). 0 ok, -1 missing/err. */
|
||||
int sp_provstate_load(const char *provider, const char *key_id,
|
||||
struct sp_prov_state *out);
|
||||
/* Atomically: lock, load, call fn to mutate, save, unlock. 0 ok. */
|
||||
int sp_provstate_update(const char *provider, const char *key_id,
|
||||
void (*fn)(struct sp_prov_state *s, void *ctx), void *ctx);
|
||||
/* Convenience: record a response; sets quota_ready_at on 429/402 with hints. */
|
||||
void sp_provstate_account(const char *provider, const char *key_id,
|
||||
long http_status, size_t tok_in, size_t tok_out, long retry_after_s);
|
||||
/* Preflight from shared state: fills decision/reason/ready_at. */
|
||||
int sp_provstate_preflight(const char *provider, const char *key_id,
|
||||
long now, long *ready_at, char *reason, size_t reason_cap);
|
||||
|
||||
char *sp_key_fingerprint(const char *secret, char *buf, size_t cap);
|
||||
#endif
|
||||
@@ -1,936 +0,0 @@
|
||||
/*
|
||||
* splinter -- append-only session log.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* One JSON object per line, opened O_APPEND. A crash can only truncate the
|
||||
* tail, so recovery is "replay complete lines, drop one partial line". Nothing
|
||||
* here ever rewrites an earlier record: history that can be edited is history
|
||||
* you cannot trust after an incident.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "mcp.h"
|
||||
#include "log.h"
|
||||
#include <dirent.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
static int
|
||||
mkdir_p(const char *path)
|
||||
{
|
||||
char buf[512];
|
||||
size_t i, n;
|
||||
|
||||
n = strlen(path);
|
||||
if (n == 0 || n >= sizeof(buf)) {
|
||||
errno = ENAMETOOLONG;
|
||||
return -1;
|
||||
}
|
||||
memcpy(buf, path, n + 1);
|
||||
for (i = 1; i < n; i++) {
|
||||
if (buf[i] != '/')
|
||||
continue;
|
||||
buf[i] = '\0';
|
||||
if (mkdir(buf, 0755) != 0 && errno != EEXIST)
|
||||
return -1;
|
||||
buf[i] = '/';
|
||||
}
|
||||
if (mkdir(buf, 0755) != 0 && errno != EEXIST)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* the session's small sidecar: where it started, when, and its title */
|
||||
struct session_meta {
|
||||
char cwd[512];
|
||||
long created;
|
||||
long opened;
|
||||
char title[96];
|
||||
char goal[1001]; /* the session's /goal, one line */
|
||||
char goal_state[16]; /* open | succeeded: the model said GOAL_COMPLETE */
|
||||
};
|
||||
|
||||
/* a title is one line, no control bytes, at most 95 bytes of UTF-8 */
|
||||
static void
|
||||
title_from_text(const char *text, char *out, size_t cap)
|
||||
{
|
||||
const char *p = text != NULL ? text : "";
|
||||
size_t n = 0;
|
||||
|
||||
if (cap == 0)
|
||||
return;
|
||||
while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
|
||||
p++;
|
||||
while (*p != '\0' && *p != '\n' && *p != '\r' && n + 1 < cap) {
|
||||
unsigned char c = (unsigned char)*p;
|
||||
|
||||
if (c >= 0x20 && c != 0x7f)
|
||||
out[n++] = (c == '\t') ? ' ' : (char)c;
|
||||
p++;
|
||||
}
|
||||
while (n > 0 && (out[n - 1] == ' ' || out[n - 1] == '\t'))
|
||||
n--;
|
||||
/*
|
||||
* Do not leave half a UTF-8 sequence: if the last character was cut,
|
||||
* drop the whole character.
|
||||
*/
|
||||
while (n > 0) {
|
||||
size_t start = n;
|
||||
size_t need;
|
||||
unsigned char c;
|
||||
|
||||
while (start > 0 && ((unsigned char)out[start - 1] & 0xC0) == 0x80)
|
||||
start--;
|
||||
if (start == 0)
|
||||
break;
|
||||
c = (unsigned char)out[start - 1];
|
||||
if ((c & 0x80) == 0)
|
||||
need = 1;
|
||||
else if ((c & 0xE0) == 0xC0)
|
||||
need = 2;
|
||||
else if ((c & 0xF0) == 0xE0)
|
||||
need = 3;
|
||||
else if ((c & 0xF8) == 0xF0)
|
||||
need = 4;
|
||||
else {
|
||||
n = start - 1;
|
||||
continue;
|
||||
}
|
||||
if (start - 1 + need > n) {
|
||||
n = start - 1;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
out[n] = '\0';
|
||||
}
|
||||
|
||||
static int
|
||||
meta_read(const char *dir, const char *id, struct session_meta *m)
|
||||
{
|
||||
char path[700], line[1600];
|
||||
FILE *f;
|
||||
|
||||
memset(m, 0, sizeof(*m));
|
||||
snprintf(path, sizeof(path), "%s/%s.meta", dir, id);
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
return -1;
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
char *v = strchr(line, '=');
|
||||
|
||||
if (v == NULL)
|
||||
continue;
|
||||
*v++ = '\0';
|
||||
v[strcspn(v, "\r\n")] = '\0';
|
||||
if (strcmp(line, "cwd") == 0)
|
||||
snprintf(m->cwd, sizeof(m->cwd), "%s", v);
|
||||
else if (strcmp(line, "created") == 0)
|
||||
m->created = strtol(v, NULL, 10);
|
||||
else if (strcmp(line, "opened") == 0)
|
||||
m->opened = strtol(v, NULL, 10);
|
||||
else if (strcmp(line, "title") == 0)
|
||||
snprintf(m->title, sizeof(m->title), "%s", v);
|
||||
else if (strcmp(line, "goal") == 0)
|
||||
snprintf(m->goal, sizeof(m->goal), "%s", v);
|
||||
else if (strcmp(line, "goal_state") == 0)
|
||||
snprintf(m->goal_state, sizeof(m->goal_state), "%s", v);
|
||||
}
|
||||
fclose(f);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
meta_write(const char *dir, const char *id, const struct session_meta *m)
|
||||
{
|
||||
char path[700], tmp[800];
|
||||
FILE *f;
|
||||
|
||||
snprintf(path, sizeof(path), "%s/%s.meta", dir, id);
|
||||
snprintf(tmp, sizeof(tmp), "%s.tmp", path);
|
||||
f = fopen(tmp, "w");
|
||||
if (f == NULL)
|
||||
return -1;
|
||||
fprintf(f, "cwd=%s\ncreated=%ld\nopened=%ld\n", m->cwd, m->created,
|
||||
m->opened);
|
||||
if (m->title[0] != '\0')
|
||||
fprintf(f, "title=%s\n", m->title);
|
||||
if (m->goal[0] != '\0')
|
||||
fprintf(f, "goal=%s\n", m->goal);
|
||||
if (m->goal_state[0] != '\0')
|
||||
fprintf(f, "goal_state=%s\n", m->goal_state);
|
||||
if (fclose(f) != 0) {
|
||||
(void)unlink(tmp);
|
||||
return -1;
|
||||
}
|
||||
if (rename(tmp, path) != 0) {
|
||||
(void)unlink(tmp);
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* an old session has no stored title: its first user line is the title */
|
||||
static void
|
||||
first_user_title(const char *path, char *out, size_t cap)
|
||||
{
|
||||
char *line = NULL;
|
||||
size_t linecap = 0;
|
||||
FILE *f;
|
||||
|
||||
out[0] = '\0';
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
return;
|
||||
while (getline(&line, &linecap, f) > 0) {
|
||||
mcp_json *v;
|
||||
const char *role, *text;
|
||||
size_t len = strlen(line);
|
||||
|
||||
if (len == 0 || line[len - 1] != '\n')
|
||||
break; /* a torn tail is not a record */
|
||||
v = mcp_parse(line);
|
||||
if (v == NULL)
|
||||
continue;
|
||||
role = mcp_arg_string(v, "role");
|
||||
text = mcp_arg_string(v, "text");
|
||||
if (role != NULL && text != NULL &&
|
||||
strcmp(role, "user") == 0) {
|
||||
title_from_text(text, out, cap);
|
||||
mcp_json_free(v);
|
||||
break;
|
||||
}
|
||||
mcp_json_free(v);
|
||||
}
|
||||
free(line);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static int
|
||||
valid_id(const char *id)
|
||||
{
|
||||
size_t i, n;
|
||||
|
||||
if (id == NULL || *id == '\0')
|
||||
return 0;
|
||||
n = strlen(id);
|
||||
if (n >= 64)
|
||||
return 0;
|
||||
for (i = 0; i < n; i++)
|
||||
if (!((id[i] >= 'a' && id[i] <= 'z') ||
|
||||
(id[i] >= 'A' && id[i] <= 'Z') ||
|
||||
(id[i] >= '0' && id[i] <= '9') ||
|
||||
id[i] == '-' || id[i] == '_' || id[i] == '.'))
|
||||
return 0;
|
||||
return strstr(id, "..") == NULL;
|
||||
}
|
||||
|
||||
/* remove a directory tree without following symlinks */
|
||||
static int
|
||||
rm_tree(const char *path)
|
||||
{
|
||||
struct stat st;
|
||||
DIR *d;
|
||||
struct dirent *e;
|
||||
|
||||
if (lstat(path, &st) != 0)
|
||||
return errno == ENOENT ? 0 : -1;
|
||||
if (!S_ISDIR(st.st_mode))
|
||||
return unlink(path);
|
||||
d = opendir(path);
|
||||
if (d == NULL)
|
||||
return -1;
|
||||
while ((e = readdir(d)) != NULL) {
|
||||
char child[800];
|
||||
|
||||
if (strcmp(e->d_name, ".") == 0 ||
|
||||
strcmp(e->d_name, "..") == 0)
|
||||
continue;
|
||||
snprintf(child, sizeof(child), "%s/%s", path, e->d_name);
|
||||
if (rm_tree(child) != 0) {
|
||||
closedir(d);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
closedir(d);
|
||||
return rmdir(path);
|
||||
}
|
||||
|
||||
int
|
||||
sp_session_open(struct sp_session_info *info, const char *dir,
|
||||
const char *id, struct sp_buf *err)
|
||||
{
|
||||
char path[640];
|
||||
int fd;
|
||||
|
||||
if (dir == NULL || id == NULL || info == NULL) {
|
||||
sp_buf_puts(err, "session: dir and id are required");
|
||||
return -1;
|
||||
}
|
||||
if (strlen(id) >= sizeof(info->id) || strlen(dir) >= sizeof(info->dir)) {
|
||||
sp_buf_puts(err, "session: id or dir too long");
|
||||
return -1;
|
||||
}
|
||||
snprintf(info->id, sizeof(info->id), "%s", id);
|
||||
snprintf(info->dir, sizeof(info->dir), "%s", dir);
|
||||
|
||||
if (mkdir_p(dir) != 0) {
|
||||
sp_buf_printf(err, "session: cannot create %s: %s", dir,
|
||||
strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, info->id);
|
||||
fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0600);
|
||||
if (fd < 0) {
|
||||
sp_buf_printf(err, "session: cannot open %s: %s", path,
|
||||
strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
close(fd);
|
||||
/*
|
||||
* A session belongs to the directory it was started in. That is what '-c'
|
||||
* needs: the last session that happened *here*, not the last one anywhere.
|
||||
* The title and the original creation time survive a reopen.
|
||||
*/
|
||||
{
|
||||
struct session_meta m;
|
||||
time_t now = time(NULL);
|
||||
|
||||
if (meta_read(dir, info->id, &m) != 0) {
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.created = (long)now;
|
||||
}
|
||||
if (getcwd(m.cwd, sizeof(m.cwd)) == NULL)
|
||||
snprintf(m.cwd, sizeof(m.cwd), "?");
|
||||
if (m.created == 0)
|
||||
m.created = (long)now;
|
||||
m.opened = (long)now;
|
||||
(void)meta_write(dir, info->id, &m);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
write_all(int fd, const char *p, size_t n)
|
||||
{
|
||||
ssize_t w;
|
||||
|
||||
while (n > 0) {
|
||||
w = write(fd, p, n);
|
||||
if (w < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
p += (size_t)w;
|
||||
n -= (size_t)w;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
brief_cmp(const void *a, const void *b)
|
||||
{
|
||||
const struct sp_session_brief *x = a, *y = b;
|
||||
|
||||
if (x->mtime != y->mtime)
|
||||
return x->mtime < y->mtime ? 1 : -1;
|
||||
return strcmp(x->id, y->id);
|
||||
}
|
||||
|
||||
int
|
||||
sp_session_list(const char *dir, struct sp_session_brief *v, size_t max)
|
||||
{
|
||||
DIR *d;
|
||||
struct dirent *e;
|
||||
size_t n = 0;
|
||||
|
||||
if (dir == NULL || v == NULL || max == 0)
|
||||
return 0;
|
||||
d = opendir(dir);
|
||||
if (d == NULL)
|
||||
return -1;
|
||||
while ((e = readdir(d)) != NULL && n < max) {
|
||||
char path[800], id[64];
|
||||
size_t len;
|
||||
struct stat st;
|
||||
|
||||
len = strlen(e->d_name);
|
||||
if (len <= 6 || strcmp(e->d_name + len - 6, ".jsonl") != 0)
|
||||
continue;
|
||||
if (len - 6 >= sizeof(id))
|
||||
continue;
|
||||
memcpy(id, e->d_name, len - 6);
|
||||
id[len - 6] = '\0';
|
||||
snprintf(path, sizeof(path), "%s/%s", dir, e->d_name);
|
||||
if (stat(path, &st) != 0)
|
||||
continue;
|
||||
snprintf(v[n].id, sizeof(v[n].id), "%s", id);
|
||||
v[n].title[0] = '\0';
|
||||
{
|
||||
struct session_meta m;
|
||||
|
||||
if (meta_read(dir, id, &m) == 0)
|
||||
snprintf(v[n].title, sizeof(v[n].title),
|
||||
"%s", m.title);
|
||||
}
|
||||
if (v[n].title[0] == '\0')
|
||||
first_user_title(path, v[n].title,
|
||||
sizeof(v[n].title));
|
||||
v[n].mtime = (long)st.st_mtime;
|
||||
v[n].bytes = (size_t)st.st_size;
|
||||
n++;
|
||||
}
|
||||
closedir(d);
|
||||
qsort(v, n, sizeof(*v), brief_cmp);
|
||||
return (int)n;
|
||||
}
|
||||
|
||||
int
|
||||
sp_session_append(const struct sp_session_info *info, const char *role,
|
||||
const char *text, struct sp_buf *err)
|
||||
{
|
||||
struct sp_buf line;
|
||||
char path[640];
|
||||
int fd, rc;
|
||||
|
||||
if (sp_buf_init(&line) != 0) {
|
||||
sp_buf_puts(err, "session: out of memory");
|
||||
return -1;
|
||||
}
|
||||
rc = sp_buf_puts(&line, "{\"role\":\"");
|
||||
if (rc == 0)
|
||||
rc = sp_json_escape(&line, role);
|
||||
if (rc == 0)
|
||||
rc = sp_buf_puts(&line, "\",\"text\":\"");
|
||||
if (rc == 0)
|
||||
rc = sp_json_escape(&line, text);
|
||||
if (rc == 0)
|
||||
rc = sp_buf_puts(&line, "\"}\n");
|
||||
if (rc != 0) {
|
||||
sp_buf_puts(err, "session: out of memory");
|
||||
sp_buf_free(&line);
|
||||
return -1;
|
||||
}
|
||||
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", info->dir, info->id);
|
||||
fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0600);
|
||||
if (fd < 0) {
|
||||
sp_buf_printf(err, "session: cannot open %s: %s", path,
|
||||
strerror(errno));
|
||||
sp_buf_free(&line);
|
||||
return -1;
|
||||
}
|
||||
rc = write_all(fd, line.p, line.len);
|
||||
if (rc == 0 && fsync(fd) != 0)
|
||||
rc = -1;
|
||||
if (rc != 0)
|
||||
sp_buf_printf(err, "session: write failed: %s", strerror(errno));
|
||||
close(fd);
|
||||
sp_buf_free(&line);
|
||||
/*
|
||||
* The first user line is the session's title until /rename says
|
||||
* otherwise. Written once, so a long conversation does not rewrite the
|
||||
* sidecar on every turn.
|
||||
*/
|
||||
if (rc == 0 && role != NULL && strcmp(role, "user") == 0) {
|
||||
struct session_meta m;
|
||||
|
||||
if (meta_read(info->dir, info->id, &m) == 0 &&
|
||||
m.title[0] == '\0') {
|
||||
title_from_text(text, m.title, sizeof(m.title));
|
||||
if (m.title[0] != '\0')
|
||||
(void)meta_write(info->dir, info->id, &m);
|
||||
}
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
int
|
||||
sp_session_count(const struct sp_session_info *info, size_t *n,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
char path[640], chunk[4096];
|
||||
FILE *f;
|
||||
size_t count = 0, i, got;
|
||||
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", info->dir, info->id);
|
||||
*n = 0;
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL) {
|
||||
if (errno == ENOENT)
|
||||
return 0;
|
||||
sp_buf_printf(err, "session: cannot read %s: %s", path,
|
||||
strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
while ((got = fread(chunk, 1, sizeof(chunk), f)) > 0) {
|
||||
for (i = 0; i < got; i++)
|
||||
if (chunk[i] == '\n')
|
||||
count++;
|
||||
}
|
||||
if (ferror(f)) {
|
||||
sp_buf_printf(err, "session: read error on %s", path);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
fclose(f);
|
||||
/*
|
||||
* Only complete lines (terminated by a newline) are records: a torn tail
|
||||
* from a crash is skipped, not repaired and not an error.
|
||||
*/
|
||||
*n = count;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Load a session back into a conversation.
|
||||
*
|
||||
* The JSONL is the record of what happened, so resuming is reading it, not
|
||||
* reconstructing something else. Records this build does not understand (a
|
||||
* thinking entry, a tool line) are skipped and counted, never guessed at.
|
||||
*/
|
||||
int
|
||||
sp_session_load(const struct sp_session_info *info, struct sp_conv *conv,
|
||||
size_t *loaded, struct sp_buf *err)
|
||||
{
|
||||
struct sp_buf raw;
|
||||
char path[640], line[8192];
|
||||
FILE *f;
|
||||
size_t n = 0;
|
||||
|
||||
(void)err;
|
||||
if (loaded != NULL)
|
||||
*loaded = 0;
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", info->dir, info->id);
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
return 0; /* nothing to resume from */
|
||||
if (sp_buf_init(&raw) != 0) {
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
mcp_json *v;
|
||||
const char *role, *text;
|
||||
|
||||
if (line[0] != '{')
|
||||
continue; /* a torn tail is not a record */
|
||||
v = mcp_parse(line);
|
||||
if (v == NULL)
|
||||
continue;
|
||||
role = mcp_arg_string(v, "role");
|
||||
text = mcp_arg_string(v, "text");
|
||||
if (role != NULL && text != NULL &&
|
||||
(strcmp(role, "user") == 0 || strcmp(role, "assistant") == 0)) {
|
||||
if (sp_conv_push(conv, role, NULL, text) == 0)
|
||||
n++;
|
||||
}
|
||||
mcp_json_free(v);
|
||||
}
|
||||
fclose(f);
|
||||
sp_buf_free(&raw);
|
||||
if (loaded != NULL)
|
||||
*loaded = n;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The newest session in a directory.
|
||||
*
|
||||
* Resuming should continue what was last used, not create a new id beside it -
|
||||
* the first version of --resume did exactly that and silently resumed nothing.
|
||||
*/
|
||||
int
|
||||
sp_session_latest(const char *dir, char *id, size_t cap)
|
||||
{
|
||||
DIR *d;
|
||||
struct dirent *e;
|
||||
char best[128] = "";
|
||||
time_t best_t = 0;
|
||||
|
||||
d = opendir(dir);
|
||||
if (d == NULL)
|
||||
return -1;
|
||||
while ((e = readdir(d)) != NULL) {
|
||||
struct stat st;
|
||||
char path[700];
|
||||
|
||||
if (strncmp(e->d_name, "sess-", 5) != 0)
|
||||
continue;
|
||||
if (strlen(e->d_name) < 5 + 5 ||
|
||||
strcmp(e->d_name + strlen(e->d_name) - 6, ".jsonl") != 0)
|
||||
continue;
|
||||
snprintf(path, sizeof(path), "%s/%s", dir, e->d_name);
|
||||
if (stat(path, &st) != 0 || !S_ISREG(st.st_mode))
|
||||
continue;
|
||||
if (st.st_mtime >= best_t) {
|
||||
best_t = st.st_mtime;
|
||||
snprintf(best, sizeof(best), "%s", e->d_name);
|
||||
}
|
||||
}
|
||||
closedir(d);
|
||||
if (best[0] == '\0')
|
||||
return -1;
|
||||
best[strlen(best) - 6] = '\0'; /* strip .jsonl */
|
||||
snprintf(id, cap, "%s", best);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
/* The cwd recorded for a session, or NULL. */
|
||||
static int
|
||||
meta_cwd(const char *dir, const char *id, char *buf, size_t cap)
|
||||
{
|
||||
char path[700], line[600];
|
||||
FILE *f;
|
||||
int found = 0;
|
||||
|
||||
snprintf(path, sizeof(path), "%s/%s.meta", dir, id);
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
return -1;
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
if (strncmp(line, "cwd=", 4) != 0)
|
||||
continue;
|
||||
snprintf(buf, cap, "%.*s", (int)(cap - 1), line + 4);
|
||||
buf[strcspn(buf, "\r\n")] = '\0';
|
||||
found = 1;
|
||||
break;
|
||||
}
|
||||
fclose(f);
|
||||
return found ? 0 : -1;
|
||||
}
|
||||
|
||||
/*
|
||||
* The newest session started in this directory.
|
||||
*
|
||||
* 'splinter -c' in ~/src/splinter means "the last thing I did here" - not the
|
||||
* last thing I did anywhere. Sessions from other directories are the wrong
|
||||
* answer and would silently load the wrong context.
|
||||
*/
|
||||
int
|
||||
sp_session_last_for(const char *dir, const char *cwd, char *id, size_t cap)
|
||||
{
|
||||
DIR *d;
|
||||
struct dirent *e;
|
||||
char best[128] = "";
|
||||
time_t best_t = 0;
|
||||
|
||||
d = opendir(dir);
|
||||
if (d == NULL)
|
||||
return -1;
|
||||
while ((e = readdir(d)) != NULL) {
|
||||
struct stat st;
|
||||
char path[700], session_cwd[512];
|
||||
size_t len = strlen(e->d_name);
|
||||
|
||||
if (len < 6 || strcmp(e->d_name + len - 5, ".meta") != 0)
|
||||
continue;
|
||||
e->d_name[len - 5] = '\0';
|
||||
snprintf(path, sizeof(path), "%s/%s.meta", dir, e->d_name);
|
||||
if (stat(path, &st) != 0)
|
||||
continue;
|
||||
if (meta_cwd(dir, e->d_name, session_cwd,
|
||||
sizeof(session_cwd)) != 0)
|
||||
continue;
|
||||
if (strcmp(session_cwd, cwd) != 0)
|
||||
continue;
|
||||
if (st.st_mtime >= best_t) {
|
||||
best_t = st.st_mtime;
|
||||
snprintf(best, sizeof(best), "%s", e->d_name);
|
||||
}
|
||||
}
|
||||
closedir(d);
|
||||
if (best[0] == '\0')
|
||||
return -1;
|
||||
snprintf(id, cap, "%s", best);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* What happened in a directory: the sessions started there, newest first, with
|
||||
* the number of turns and the last thing that was asked. This is the folder's
|
||||
* memory - readable by the model through a tool, not guessed.
|
||||
*/
|
||||
int
|
||||
sp_session_folder_history(const char *dir, const char *cwd, unsigned limit,
|
||||
struct sp_buf *out)
|
||||
{
|
||||
DIR *d;
|
||||
struct dirent *e;
|
||||
struct {
|
||||
char name[128];
|
||||
time_t mtime;
|
||||
} found[64];
|
||||
size_t n = 0, i, j;
|
||||
|
||||
d = opendir(dir);
|
||||
if (d == NULL) {
|
||||
sp_buf_printf(out, "no sessions in %s\n", dir);
|
||||
return 0;
|
||||
}
|
||||
while ((e = readdir(d)) != NULL && n < 64) {
|
||||
struct stat st;
|
||||
char path[700], session_cwd[512];
|
||||
size_t len = strlen(e->d_name);
|
||||
|
||||
if (len < 6 || strcmp(e->d_name + len - 5, ".meta") != 0)
|
||||
continue;
|
||||
e->d_name[len - 5] = '\0';
|
||||
snprintf(path, sizeof(path), "%s/%s.meta", dir, e->d_name);
|
||||
if (stat(path, &st) != 0)
|
||||
continue;
|
||||
if (meta_cwd(dir, e->d_name, session_cwd,
|
||||
sizeof(session_cwd)) != 0)
|
||||
continue;
|
||||
if (cwd != NULL && strcmp(session_cwd, cwd) != 0)
|
||||
continue;
|
||||
snprintf(found[n].name, sizeof(found[n].name), "%s", e->d_name);
|
||||
found[n].mtime = st.st_mtime;
|
||||
n++;
|
||||
}
|
||||
closedir(d);
|
||||
/* newest first, straight insertion: 64 entries, no library needed */
|
||||
for (i = 1; i < n; i++) {
|
||||
for (j = i; j > 0 && found[j - 1].mtime < found[j].mtime; j--) {
|
||||
char tn[128];
|
||||
time_t tm = found[j - 1].mtime;
|
||||
|
||||
snprintf(tn, sizeof(tn), "%s", found[j - 1].name);
|
||||
snprintf(found[j - 1].name, sizeof(found[j - 1].name),
|
||||
"%s", found[j].name);
|
||||
found[j - 1].mtime = found[j].mtime;
|
||||
snprintf(found[j].name, sizeof(found[j].name), "%s", tn);
|
||||
found[j].mtime = tm;
|
||||
}
|
||||
}
|
||||
if (n == 0) {
|
||||
sp_buf_printf(out, "no sessions in %s%s%s\n", dir,
|
||||
cwd != NULL ? " for " : "", cwd != NULL ? cwd : "");
|
||||
return 0;
|
||||
}
|
||||
for (i = 0; i < n && i < limit; i++) {
|
||||
char path[800], line[2048], stamp[32];
|
||||
struct tm tm;
|
||||
FILE *f;
|
||||
time_t when = found[i].mtime;
|
||||
size_t turns = 0;
|
||||
char last[512] = "";
|
||||
|
||||
(void)localtime_r(&when, &tm);
|
||||
strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M", &tm);
|
||||
snprintf(path, sizeof(path), "%.500s/%.120s.jsonl", dir,
|
||||
found[i].name);
|
||||
f = fopen(path, "r");
|
||||
if (f != NULL) {
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
turns++;
|
||||
if (strstr(line, "\"role\":\"user\"") == NULL)
|
||||
continue;
|
||||
snprintf(last, sizeof(last), "%.511s", line);
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
{
|
||||
char *p = strstr(last, "\"text\":\"");
|
||||
|
||||
if (p != NULL) {
|
||||
char *v = p + 9;
|
||||
size_t k = 0;
|
||||
|
||||
while (*v != '\0' && *v != '"' && k + 1 < sizeof(last))
|
||||
last[k++] = *v++;
|
||||
last[k] = '\0';
|
||||
} else
|
||||
last[0] = '\0';
|
||||
}
|
||||
sp_buf_printf(out, "%s %s %zu records%s%s\n", stamp,
|
||||
found[i].name, turns / 2,
|
||||
last[0] != '\0' ? " last: " : "", last);
|
||||
}
|
||||
if (n > limit)
|
||||
sp_buf_printf(out, "(%zu more)\n", n - limit);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_session_set_title(const char *dir, const char *id, const char *title,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
struct session_meta m;
|
||||
char path[700], clean[96];
|
||||
|
||||
if (dir == NULL || id == NULL || title == NULL ||
|
||||
!valid_id(id)) {
|
||||
sp_buf_puts(err, "session: invalid id");
|
||||
return -1;
|
||||
}
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
|
||||
if (access(path, F_OK) != 0) {
|
||||
sp_buf_puts(err, "session: no such session");
|
||||
return -1;
|
||||
}
|
||||
title_from_text(title, clean, sizeof(clean));
|
||||
if (clean[0] == '\0') {
|
||||
sp_buf_puts(err, "session: empty title");
|
||||
return -1;
|
||||
}
|
||||
if (meta_read(dir, id, &m) != 0)
|
||||
memset(&m, 0, sizeof(m));
|
||||
snprintf(m.title, sizeof(m.title), "%s", clean);
|
||||
if (meta_write(dir, id, &m) != 0) {
|
||||
sp_buf_printf(err, "session: cannot write the meta file: %s",
|
||||
strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The goal belongs to the session, not to the process: a resume must find it
|
||||
* again, and /continue must not depend on a plugin that may have restarted.
|
||||
*/
|
||||
int
|
||||
sp_session_set_goal(const char *dir, const char *id, const char *goal,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
struct session_meta m;
|
||||
char path[700], clean[1001];
|
||||
|
||||
if (dir == NULL || id == NULL || goal == NULL || !valid_id(id)) {
|
||||
sp_buf_puts(err, "session: invalid id");
|
||||
return -1;
|
||||
}
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
|
||||
if (access(path, F_OK) != 0) {
|
||||
sp_buf_puts(err, "session: no such session");
|
||||
return -1;
|
||||
}
|
||||
title_from_text(goal, clean, sizeof(clean));
|
||||
if (clean[0] == '\0') {
|
||||
sp_buf_puts(err, "session: empty goal");
|
||||
return -1;
|
||||
}
|
||||
if (meta_read(dir, id, &m) != 0)
|
||||
memset(&m, 0, sizeof(m));
|
||||
snprintf(m.goal, sizeof(m.goal), "%s", clean);
|
||||
/* a new goal is open, whatever the last one reached */
|
||||
snprintf(m.goal_state, sizeof(m.goal_state), "open");
|
||||
if (meta_write(dir, id, &m) != 0) {
|
||||
sp_buf_printf(err, "session: cannot write the meta file: %s",
|
||||
strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_session_get_goal(const char *dir, const char *id, char *buf, size_t cap)
|
||||
{
|
||||
struct session_meta m;
|
||||
|
||||
if (dir == NULL || id == NULL || buf == NULL || cap == 0 ||
|
||||
!valid_id(id))
|
||||
return -1;
|
||||
if (meta_read(dir, id, &m) != 0 || m.goal[0] == '\0')
|
||||
return -1;
|
||||
snprintf(buf, cap, "%s", m.goal);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Whether the goal is still open or the model has declared it done. The state
|
||||
* lives beside the goal in the session, not in the plugin: a resumed session
|
||||
* must not forget that its goal was already reached, and the plugin is not
|
||||
* unloaded between sessions.
|
||||
*/
|
||||
int
|
||||
sp_session_set_goal_state(const char *dir, const char *id, const char *state,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
struct session_meta m;
|
||||
char path[700];
|
||||
|
||||
if (dir == NULL || id == NULL || state == NULL || !valid_id(id)) {
|
||||
sp_buf_puts(err, "session: invalid id");
|
||||
return -1;
|
||||
}
|
||||
if (strcmp(state, "open") != 0 && strcmp(state, "succeeded") != 0) {
|
||||
sp_buf_puts(err, "session: goal state must be open or succeeded");
|
||||
return -1;
|
||||
}
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
|
||||
if (access(path, F_OK) != 0) {
|
||||
sp_buf_puts(err, "session: no such session");
|
||||
return -1;
|
||||
}
|
||||
if (meta_read(dir, id, &m) != 0)
|
||||
memset(&m, 0, sizeof(m));
|
||||
if (m.goal[0] == '\0') {
|
||||
sp_buf_puts(err, "session: no goal set");
|
||||
return -1;
|
||||
}
|
||||
snprintf(m.goal_state, sizeof(m.goal_state), "%s", state);
|
||||
if (meta_write(dir, id, &m) != 0) {
|
||||
sp_buf_printf(err, "session: cannot write the meta file: %s",
|
||||
strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_session_get_goal_state(const char *dir, const char *id, char *buf,
|
||||
size_t cap)
|
||||
{
|
||||
struct session_meta m;
|
||||
|
||||
if (dir == NULL || id == NULL || buf == NULL || cap == 0 ||
|
||||
!valid_id(id))
|
||||
return -1;
|
||||
if (meta_read(dir, id, &m) != 0 || m.goal_state[0] == '\0')
|
||||
return -1;
|
||||
snprintf(buf, cap, "%s", m.goal_state);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_session_delete(const char *dir, const char *id, struct sp_buf *err)
|
||||
{
|
||||
char path[700], side[700], logdir[700];
|
||||
|
||||
if (dir == NULL || id == NULL || !valid_id(id)) {
|
||||
sp_buf_puts(err, "session: invalid id");
|
||||
return -1;
|
||||
}
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
|
||||
if (access(path, F_OK) != 0) {
|
||||
sp_buf_puts(err, "session: no such session");
|
||||
return -1;
|
||||
}
|
||||
if (unlink(path) != 0) {
|
||||
sp_buf_printf(err, "session: cannot remove %s: %s", path,
|
||||
strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
snprintf(side, sizeof(side), "%s/%s.meta", dir, id);
|
||||
(void)unlink(side);
|
||||
snprintf(side, sizeof(side), "%s/%s.meta.tmp", dir, id);
|
||||
(void)unlink(side);
|
||||
snprintf(side, sizeof(side), "%s/%s.agent", dir, id);
|
||||
(void)unlink(side);
|
||||
/* logs are a convenience, not the record: a leftover must not fail this */
|
||||
snprintf(logdir, sizeof(logdir), "%s/logs/%s", dir, id);
|
||||
(void)rm_tree(logdir);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,350 +0,0 @@
|
||||
/*
|
||||
* splinter -- skills on demand.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* A skill is a markdown file the model may read when it needs it:
|
||||
*
|
||||
* ~/.splinter/skills/c99.md
|
||||
* ~/.splinter/skills/kanban/SKILL.md
|
||||
* <skills_dir = /some/other/dir>
|
||||
*
|
||||
* Nothing is preloaded. The system prompt does not grow with every skill, and
|
||||
* the model is not handed a catalogue it will mostly ignore - it asks:
|
||||
*
|
||||
* skill_search {query} -> names, one-line descriptions, paths
|
||||
* skill_load {name} -> the whole file
|
||||
*
|
||||
* That is the whole design, and it exists because at 8k context every line of
|
||||
* system prompt is paid for on every request.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <dirent.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "mcp.h"
|
||||
#include "config.h"
|
||||
#include "skills.h"
|
||||
|
||||
#define SKILL_MAX 256
|
||||
#define SKILL_LOAD_MAX 64000
|
||||
|
||||
struct skill {
|
||||
char name[96];
|
||||
char desc[256];
|
||||
char path[768];
|
||||
};
|
||||
|
||||
static struct skill skills[SKILL_MAX];
|
||||
static size_t nskills;
|
||||
static const struct sp_config *skills_cfg;
|
||||
|
||||
static void
|
||||
lower(char *dst, size_t cap, const char *src)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; src != NULL && src[i] != '\0' && i + 1 < cap; i++)
|
||||
dst[i] = (char)tolower((unsigned char)src[i]);
|
||||
dst[i] = '\0';
|
||||
}
|
||||
|
||||
/*
|
||||
* The description comes from the frontmatter if there is one, else from the
|
||||
* first non-empty line. A skill without either is still listable - by its name.
|
||||
*/
|
||||
static void
|
||||
read_description(const char *path, char *dst, size_t cap)
|
||||
{
|
||||
FILE *f;
|
||||
char line[512];
|
||||
int in_front = 0, seen_front = 0, got = 0;
|
||||
|
||||
dst[0] = '\0';
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
return;
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
char *s = line;
|
||||
|
||||
while (*s == ' ' || *s == '\t')
|
||||
s++;
|
||||
if (!seen_front) {
|
||||
if (strncmp(s, "---", 3) == 0) {
|
||||
in_front = 1;
|
||||
seen_front = 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (in_front) {
|
||||
if (strncmp(s, "---", 3) == 0) {
|
||||
in_front = 0;
|
||||
if (got)
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
if (strncmp(s, "description:", 12) == 0) {
|
||||
char *v = s + 12;
|
||||
|
||||
while (*v == ' ')
|
||||
v++;
|
||||
snprintf(dst, cap, "%.*s", (int)(cap - 1), v);
|
||||
dst[strcspn(dst, "\r\n")] = '\0';
|
||||
got = 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
/* no frontmatter at all: first real line is the description */
|
||||
if (*s != '\0' && *s != '\n' && *s != '#') {
|
||||
snprintf(dst, cap, "%.*s", (int)(cap - 1), s);
|
||||
dst[strcspn(dst, "\r\n")] = '\0';
|
||||
break;
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static void
|
||||
add_skill(const char *name, const char *path)
|
||||
{
|
||||
if (nskills >= SKILL_MAX)
|
||||
return;
|
||||
snprintf(skills[nskills].name, sizeof(skills[nskills].name), "%s", name);
|
||||
snprintf(skills[nskills].path, sizeof(skills[nskills].path), "%s", path);
|
||||
read_description(path, skills[nskills].desc, sizeof(skills[nskills].desc));
|
||||
nskills++;
|
||||
}
|
||||
|
||||
/* Scan one directory: files *.md and directories with SKILL.md. */
|
||||
static void
|
||||
scan_dir(const char *dir)
|
||||
{
|
||||
DIR *d;
|
||||
struct dirent *e;
|
||||
|
||||
if (dir == NULL || *dir == '\0')
|
||||
return;
|
||||
d = opendir(dir);
|
||||
if (d == NULL)
|
||||
return;
|
||||
while ((e = readdir(d)) != NULL && nskills < SKILL_MAX) {
|
||||
char path[768];
|
||||
struct stat st;
|
||||
size_t len = strlen(e->d_name);
|
||||
|
||||
if (e->d_name[0] == '.')
|
||||
continue;
|
||||
snprintf(path, sizeof(path), "%s/%s", dir, e->d_name);
|
||||
if (stat(path, &st) != 0)
|
||||
continue;
|
||||
if (S_ISDIR(st.st_mode)) {
|
||||
char md[900];
|
||||
char name[96];
|
||||
|
||||
snprintf(md, sizeof(md), "%s/SKILL.md", path);
|
||||
if (stat(md, &st) != 0 || !S_ISREG(st.st_mode))
|
||||
continue;
|
||||
snprintf(name, sizeof(name), "%s", e->d_name);
|
||||
add_skill(name, md);
|
||||
continue;
|
||||
}
|
||||
if (!S_ISREG(st.st_mode) || len < 4 ||
|
||||
strcmp(e->d_name + len - 3, ".md") != 0)
|
||||
continue;
|
||||
e->d_name[len - 3] = '\0';
|
||||
add_skill(e->d_name, path);
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_skills_dir(const char *session_dir, size_t index)
|
||||
{
|
||||
(void)session_dir;
|
||||
if (skills_cfg == NULL)
|
||||
return NULL;
|
||||
if (index == 0)
|
||||
return NULL; /* filled by the caller's default */
|
||||
return index - 1 < skills_cfg->nskills_dir ? skills_cfg->skills_dir[index - 1] :
|
||||
NULL;
|
||||
}
|
||||
|
||||
static void
|
||||
scan_all(const char *session_dir)
|
||||
{
|
||||
const char *home = getenv("HOME");
|
||||
char def[700];
|
||||
|
||||
nskills = 0;
|
||||
if (home != NULL && *home != '\0') {
|
||||
snprintf(def, sizeof(def), "%s/.splinter/skills", home);
|
||||
scan_dir(def);
|
||||
}
|
||||
if (skills_cfg != NULL) {
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < skills_cfg->nskills_dir; i++)
|
||||
scan_dir(skills_cfg->skills_dir[i]);
|
||||
}
|
||||
(void)session_dir;
|
||||
}
|
||||
|
||||
/* ---- tools ---- */
|
||||
|
||||
static int
|
||||
tool_skill_search(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
struct sp_buf keep;
|
||||
mcp_json *v;
|
||||
const char *query = NULL;
|
||||
char q[128];
|
||||
size_t i, hits = 0;
|
||||
|
||||
(void)ctx;
|
||||
if (sp_buf_init(&keep) != 0)
|
||||
return -1;
|
||||
if (args != NULL && args[0] == '{') {
|
||||
v = mcp_parse(args);
|
||||
if (v != NULL) {
|
||||
const char *s = mcp_arg_string(v, "query");
|
||||
|
||||
if (s != NULL)
|
||||
(void)sp_buf_puts(&keep, s);
|
||||
mcp_json_free(v);
|
||||
}
|
||||
} else if (args != NULL)
|
||||
(void)sp_buf_puts(&keep, args);
|
||||
query = keep.p;
|
||||
|
||||
if (query == NULL || *query == '\0') {
|
||||
sp_buf_puts(out, "error: 'query' is required\n");
|
||||
sp_buf_free(&keep);
|
||||
return 0;
|
||||
}
|
||||
scan_all(NULL);
|
||||
if (nskills == 0) {
|
||||
sp_buf_puts(out, "(no skills installed: ~/.splinter/skills is empty "
|
||||
"or missing)\n");
|
||||
sp_buf_free(&keep);
|
||||
return 0;
|
||||
}
|
||||
lower(q, sizeof(q), query);
|
||||
for (i = 0; i < nskills && hits < 20; i++) {
|
||||
char name_lc[128], desc_lc[256];
|
||||
|
||||
lower(name_lc, sizeof(name_lc), skills[i].name);
|
||||
lower(desc_lc, sizeof(desc_lc), skills[i].desc);
|
||||
if (strstr(name_lc, q) == NULL && strstr(desc_lc, q) == NULL)
|
||||
continue;
|
||||
sp_buf_printf(out, "%s — %s\n %s\n", skills[i].name,
|
||||
skills[i].desc[0] != '\0' ? skills[i].desc : "(no description)",
|
||||
skills[i].path);
|
||||
hits++;
|
||||
}
|
||||
if (hits == 0)
|
||||
sp_buf_printf(out, "(nothing matches '%s'; %zu skills are "
|
||||
"installed)\n", query, nskills);
|
||||
sp_buf_free(&keep);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_skill_load(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
struct sp_buf keep;
|
||||
mcp_json *v;
|
||||
const char *name = NULL;
|
||||
FILE *f;
|
||||
char chunk[4096];
|
||||
size_t got;
|
||||
|
||||
(void)ctx;
|
||||
if (sp_buf_init(&keep) != 0)
|
||||
return -1;
|
||||
if (args != NULL && args[0] == '{') {
|
||||
v = mcp_parse(args);
|
||||
if (v != NULL) {
|
||||
const char *s = mcp_arg_string(v, "name");
|
||||
|
||||
if (s != NULL)
|
||||
(void)sp_buf_puts(&keep, s);
|
||||
mcp_json_free(v);
|
||||
}
|
||||
} else if (args != NULL)
|
||||
(void)sp_buf_puts(&keep, args);
|
||||
name = keep.p;
|
||||
if (name == NULL || *name == '\0') {
|
||||
sp_buf_puts(out, "error: 'name' is required\n");
|
||||
sp_buf_free(&keep);
|
||||
return 0;
|
||||
}
|
||||
scan_all(NULL);
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < nskills; i++) {
|
||||
if (strcmp(skills[i].name, name) != 0)
|
||||
continue;
|
||||
f = fopen(skills[i].path, "r");
|
||||
if (f == NULL) {
|
||||
sp_buf_printf(out, "error: cannot read %s\n",
|
||||
skills[i].path);
|
||||
sp_buf_free(&keep);
|
||||
return 0;
|
||||
}
|
||||
while ((got = fread(chunk, 1, sizeof(chunk) - 1, f)) > 0) {
|
||||
chunk[got] = '\0';
|
||||
if (out->len + got > SKILL_LOAD_MAX) {
|
||||
sp_buf_puts(out, "\n[skill truncated]\n");
|
||||
break;
|
||||
}
|
||||
(void)sp_buf_puts(out, chunk);
|
||||
}
|
||||
fclose(f);
|
||||
sp_buf_free(&keep);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
/* no silent empty answer: name what exists */
|
||||
sp_buf_printf(out, "error: no skill '%s'. installed:", name);
|
||||
for (got = 0; got < nskills && got < 40; got++)
|
||||
sp_buf_printf(out, " %s", skills[got].name);
|
||||
sp_buf_puts(out, "\n");
|
||||
sp_buf_free(&keep);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_skills_register(struct sp_registry *r, const struct sp_config *cfg)
|
||||
{
|
||||
struct sp_tool t;
|
||||
|
||||
skills_cfg = cfg;
|
||||
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "skill_search";
|
||||
t.description = "Find an installed skill by name or description. Skills "
|
||||
"are not preloaded; search first, then load what fits.";
|
||||
t.params = "{\"type\":\"object\",\"properties\":{\"query\":"
|
||||
"{\"type\":\"string\",\"description\":\"what you are looking for\"}},"
|
||||
"\"required\":[\"query\"]}";
|
||||
t.auth = SP_AUTH_READ;
|
||||
t.run = tool_skill_search;
|
||||
if (sp_registry_add(r, &t) != 0)
|
||||
return -1;
|
||||
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "skill_load";
|
||||
t.description = "Read an installed skill in full.";
|
||||
t.params = "{\"type\":\"object\",\"properties\":{\"name\":"
|
||||
"{\"type\":\"string\",\"description\":\"skill name from skill_search\"}},"
|
||||
"\"required\":[\"name\"]}";
|
||||
t.auth = SP_AUTH_READ;
|
||||
t.run = tool_skill_load;
|
||||
return sp_registry_add(r, &t);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
/*
|
||||
* splinter -- skills on demand.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_SKILLS_H
|
||||
#define SPLINTER_SKILLS_H
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
struct sp_config;
|
||||
int sp_skills_register(struct sp_registry *, const struct sp_config *);
|
||||
|
||||
#endif /* SPLINTER_SKILLS_H */
|
||||
@@ -1,436 +0,0 @@
|
||||
/*
|
||||
* splinter -- SSE accumulation for streaming chat completions.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* OpenAI streams a turn as `data: {json}` lines. Text arrives in
|
||||
* `choices[0].delta.content` chunks; a tool call arrives in pieces: the name
|
||||
* once, the arguments as a growing string, keyed by an index. This file turns
|
||||
* that into one reply, and it does it one line at a time so the whole thing is
|
||||
* testable with recorded lines and no socket.
|
||||
*
|
||||
* Anything it does not understand is reported with the line quoted. A silent
|
||||
* skip here would mean a turn that ends with no answer and no reason.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "mcp.h"
|
||||
|
||||
#define MAX_CALLS 8
|
||||
|
||||
struct sse_call {
|
||||
char *id;
|
||||
char *name;
|
||||
struct sp_buf args;
|
||||
int seen;
|
||||
};
|
||||
|
||||
struct sp_sse {
|
||||
struct sp_buf content;
|
||||
struct sp_buf think;
|
||||
struct sp_buf pending; /* a pretty-printed data event so far */
|
||||
struct sse_call calls[MAX_CALLS];
|
||||
size_t ncalls;
|
||||
int done;
|
||||
int last; /* what the last line put into out */
|
||||
long tokens_in;
|
||||
long tokens_out;
|
||||
long tokens_cached;
|
||||
};
|
||||
|
||||
#define PENDING_MAX (1u << 20) /* a huge "object" is not a kept promise */
|
||||
|
||||
struct sp_sse *
|
||||
sp_sse_new(void)
|
||||
{
|
||||
struct sp_sse *s = calloc(1, sizeof(*s));
|
||||
|
||||
if (s == NULL)
|
||||
return NULL;
|
||||
if (sp_buf_init(&s->content) != 0 || sp_buf_init(&s->think) != 0 ||
|
||||
sp_buf_init(&s->pending) != 0) {
|
||||
sp_buf_free(&s->content);
|
||||
sp_buf_free(&s->think);
|
||||
free(s);
|
||||
return NULL;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
void
|
||||
sp_sse_free(struct sp_sse *s)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (s == NULL)
|
||||
return;
|
||||
for (i = 0; i < s->ncalls; i++) {
|
||||
free(s->calls[i].id);
|
||||
free(s->calls[i].name);
|
||||
sp_buf_free(&s->calls[i].args);
|
||||
}
|
||||
sp_buf_free(&s->content);
|
||||
sp_buf_free(&s->think);
|
||||
sp_buf_free(&s->pending);
|
||||
free(s);
|
||||
}
|
||||
|
||||
int
|
||||
sp_sse_usage(const struct sp_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;
|
||||
}
|
||||
|
||||
int
|
||||
sp_sse_done(const struct sp_sse *s)
|
||||
{
|
||||
return s != NULL ? s->done : 0;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_sse_tool_start(const struct sp_sse *s, size_t index)
|
||||
{
|
||||
if (s == NULL || index >= s->ncalls)
|
||||
return NULL;
|
||||
return s->calls[index].name;
|
||||
}
|
||||
|
||||
/*
|
||||
* The parser knows what it produced, so nobody has to guess from the raw
|
||||
* line. A chunk can carry text and a tool name at once; text wins, because
|
||||
* that is what belongs in the answer - the name is announced separately
|
||||
* (sp_sse_tool_start).
|
||||
*/
|
||||
int
|
||||
sp_sse_kind(const struct sp_sse *s)
|
||||
{
|
||||
if (s == NULL)
|
||||
return -1;
|
||||
if (s->last & 2)
|
||||
return SP_STREAM_THINK;
|
||||
if (s->last & 1)
|
||||
return SP_STREAM_TEXT;
|
||||
if (s->last & 4)
|
||||
return SP_STREAM_TOOL;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static struct sse_call *
|
||||
call_slot(struct sp_sse *s, size_t index)
|
||||
{
|
||||
if (index >= MAX_CALLS)
|
||||
return NULL;
|
||||
if (index >= s->ncalls) {
|
||||
size_t i;
|
||||
|
||||
for (i = s->ncalls; i <= index; i++) {
|
||||
memset(&s->calls[i], 0, sizeof(s->calls[i]));
|
||||
if (sp_buf_init(&s->calls[i].args) != 0)
|
||||
return NULL;
|
||||
}
|
||||
s->ncalls = index + 1;
|
||||
}
|
||||
return &s->calls[index];
|
||||
}
|
||||
|
||||
int
|
||||
sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
mcp_json *v;
|
||||
const mcp_json *choices, *choice, *delta, *content, *tcs;
|
||||
int produced = 0;
|
||||
const char *payload;
|
||||
|
||||
if (s == NULL)
|
||||
return -1;
|
||||
s->last = 0;
|
||||
while (*line == ' ' || *line == '\t')
|
||||
line++;
|
||||
/*
|
||||
* An empty line ends an SSE event. A data object that is still growing
|
||||
* is kept across the boundary: proxies insert blank lines between the
|
||||
* lines of a pretty-printed object, and a blank line is not a reason
|
||||
* to throw the answer away. Nothing is an error here; an object that
|
||||
* never completes is dropped in sp_sse_finish().
|
||||
*/
|
||||
if (*line == '\0' || *line == '\n')
|
||||
return 0;
|
||||
if (*line == ':')
|
||||
return 0;
|
||||
if (strncmp(line, "data:", 5) != 0) {
|
||||
/* event:/id:/retry: carry nothing we need */
|
||||
return 0;
|
||||
}
|
||||
payload = line + 5;
|
||||
while (*payload == ' ' || *payload == '\t')
|
||||
payload++;
|
||||
if (*payload == '\0')
|
||||
return 0; /* an empty data line is a keepalive */
|
||||
if (strncmp(payload, "[DONE]", 6) == 0) {
|
||||
/*
|
||||
* A fragment that never became an object cannot be used; drop
|
||||
* it rather than failing a turn that already has its answer.
|
||||
*/
|
||||
sp_buf_clear(&s->pending);
|
||||
s->done = 1;
|
||||
return 0;
|
||||
}
|
||||
/*
|
||||
* Some proxies pretty-print the JSON over several data: lines. Try
|
||||
* the object so far first; only when it is incomplete keep growing it.
|
||||
*/
|
||||
if (s->pending.len > 0) {
|
||||
if (sp_buf_puts(&s->pending, "\n") != 0 ||
|
||||
sp_buf_puts(&s->pending, payload) != 0) {
|
||||
sp_buf_puts(err, "sse: out of memory");
|
||||
return -1;
|
||||
}
|
||||
payload = s->pending.p;
|
||||
}
|
||||
|
||||
v = mcp_parse(payload);
|
||||
if (v == NULL) {
|
||||
/*
|
||||
* Proxies send text keepalives as `data: ping` or `data: [PING]`.
|
||||
* Only a line that claims to be a JSON object is a broken answer;
|
||||
* anything else is ignored, not turned into a failed turn.
|
||||
*/
|
||||
if (*payload != '{') {
|
||||
sp_buf_clear(&s->pending);
|
||||
return 0;
|
||||
}
|
||||
if (s->pending.len == 0) {
|
||||
if (sp_buf_puts(&s->pending, payload) != 0) {
|
||||
sp_buf_puts(err, "sse: out of memory");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (s->pending.len > PENDING_MAX) {
|
||||
/* not a kept promise: drop it, keep the turn alive */
|
||||
sp_buf_clear(&s->pending);
|
||||
return 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
sp_buf_clear(&s->pending);
|
||||
|
||||
/* llama.cpp and OpenAI both attach usage to the last chunk */
|
||||
{
|
||||
const mcp_json *usage = mcp_arg(v, "usage");
|
||||
|
||||
if (usage != NULL) {
|
||||
const mcp_json *details;
|
||||
long in = (long)mcp_arg_int(usage, "prompt_tokens", -1);
|
||||
long out = (long)mcp_arg_int(usage, "completion_tokens", -1);
|
||||
long cached = -1;
|
||||
|
||||
if (in < 0)
|
||||
in = (long)mcp_arg_int(usage, "input_tokens", -1);
|
||||
if (out < 0)
|
||||
out = (long)mcp_arg_int(usage, "output_tokens", -1);
|
||||
details = mcp_arg(usage, "prompt_tokens_details");
|
||||
if (details != NULL)
|
||||
cached = (long)mcp_arg_int(details,
|
||||
"cached_tokens", -1);
|
||||
if (cached < 0)
|
||||
cached = (long)mcp_arg_int(usage,
|
||||
"prompt_cache_hit_tokens", -1);
|
||||
if (cached < 0)
|
||||
cached = (long)mcp_arg_int(usage,
|
||||
"cache_read_input_tokens", -1);
|
||||
if (in >= 0)
|
||||
s->tokens_in = in;
|
||||
if (out >= 0)
|
||||
s->tokens_out = out;
|
||||
if (cached >= 0)
|
||||
s->tokens_cached = cached;
|
||||
}
|
||||
}
|
||||
|
||||
choices = mcp_arg(v, "choices");
|
||||
if (choices == NULL || mcp_array_len(choices) == 0) {
|
||||
/* keepalive and usage-only events land here */
|
||||
mcp_json_free(v);
|
||||
return 0;
|
||||
}
|
||||
choice = mcp_array_at(choices, 0);
|
||||
delta = mcp_arg(choice, "delta");
|
||||
if (delta == NULL) {
|
||||
mcp_json_free(v);
|
||||
return 0;
|
||||
}
|
||||
|
||||
content = mcp_arg(delta, "content");
|
||||
if (content != NULL && mcp_json_string(content) != NULL) {
|
||||
const char *text = mcp_json_string(content);
|
||||
|
||||
if (sp_buf_puts(&s->content, text) != 0 ||
|
||||
sp_buf_puts(out, text) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
s->last |= 1;
|
||||
produced = 1;
|
||||
}
|
||||
|
||||
/* reasoning models report their thinking in a separate field */
|
||||
{
|
||||
const mcp_json *think = mcp_arg(delta, "reasoning_content");
|
||||
|
||||
if (think != NULL && mcp_json_string(think) != NULL) {
|
||||
if (sp_buf_puts(&s->think, mcp_json_string(think)) != 0 ||
|
||||
sp_buf_puts(out, mcp_json_string(think)) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
s->last |= 2;
|
||||
produced = 1;
|
||||
}
|
||||
}
|
||||
|
||||
tcs = mcp_arg(delta, "tool_calls");
|
||||
if (tcs != NULL) {
|
||||
size_t i, n = mcp_array_len(tcs);
|
||||
|
||||
for (i = 0; i < n; i++) {
|
||||
const mcp_json *tc = mcp_array_at(tcs, i);
|
||||
const mcp_json *fn = mcp_arg(tc, "function");
|
||||
const mcp_json *idx = mcp_arg(tc, "index");
|
||||
const mcp_json *id = mcp_arg(tc, "id");
|
||||
struct sse_call *slot;
|
||||
int index = (int)mcp_arg_int(tcs, "index", -1);
|
||||
|
||||
if (idx != NULL)
|
||||
index = (int)mcp_arg_int(delta, "index", index);
|
||||
/* the index lives on the tool call itself in OpenAI's shape */
|
||||
index = (int)mcp_arg_int(tc, "index", index);
|
||||
if (index < 0)
|
||||
index = (int)(s->ncalls == 0 ? 0 : s->ncalls - 1);
|
||||
slot = call_slot(s, (size_t)index);
|
||||
if (slot == NULL) {
|
||||
mcp_json_free(v);
|
||||
sp_buf_puts(err, "sse: too many tool calls");
|
||||
return -1;
|
||||
}
|
||||
if (id != NULL && mcp_json_string(id) != NULL &&
|
||||
slot->id == NULL) {
|
||||
slot->id = strdup(mcp_json_string(id));
|
||||
slot->seen = 1;
|
||||
}
|
||||
if (fn != NULL) {
|
||||
const mcp_json *name = mcp_arg(fn, "name");
|
||||
const mcp_json *args = mcp_arg(fn, "arguments");
|
||||
|
||||
if (name != NULL && mcp_json_string(name) != NULL &&
|
||||
slot->name == NULL) {
|
||||
slot->name =
|
||||
strdup(mcp_json_string(name));
|
||||
slot->seen = 1;
|
||||
if (sp_buf_puts(out, slot->name) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
s->last |= 4;
|
||||
produced = 1;
|
||||
}
|
||||
if (args != NULL && mcp_json_string(args) != NULL &&
|
||||
sp_buf_puts(&slot->args,
|
||||
mcp_json_string(args)) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mcp_json_free(v);
|
||||
return produced;
|
||||
}
|
||||
|
||||
int
|
||||
sp_sse_finish(struct sp_sse *s, struct sp_reply *out, struct sp_buf *err)
|
||||
{
|
||||
size_t i;
|
||||
int any = 0;
|
||||
|
||||
if (s == NULL || out == NULL)
|
||||
return -1;
|
||||
/*
|
||||
* A trailing fragment (the stream ended in the middle of an object) is
|
||||
* dropped: whatever arrived before it is the answer. This used to fail
|
||||
* the turn with "incomplete data line", an error the operator can do
|
||||
* nothing about and the provider can cause with one lost chunk.
|
||||
*/
|
||||
if (s->pending.len > 0)
|
||||
sp_buf_clear(&s->pending);
|
||||
out->status = 200;
|
||||
out->tokens_in = s->tokens_in;
|
||||
out->tokens_out = s->tokens_out;
|
||||
out->tokens_cached = s->tokens_cached;
|
||||
out->content = strdup(s->content.p != NULL ? s->content.p : "");
|
||||
if (out->content == NULL)
|
||||
return -1;
|
||||
for (i = 0; i < s->ncalls; i++)
|
||||
if (s->calls[i].seen)
|
||||
any = 1;
|
||||
if (!any)
|
||||
return 0;
|
||||
|
||||
out->calls = calloc(s->ncalls, sizeof(*out->calls));
|
||||
if (out->calls == NULL)
|
||||
return -1;
|
||||
out->ncalls = s->ncalls;
|
||||
for (i = 0; i < s->ncalls; i++) {
|
||||
out->calls[i].id = strdup(s->calls[i].id != NULL ?
|
||||
s->calls[i].id : "call-0");
|
||||
out->calls[i].name = strdup(s->calls[i].name != NULL ?
|
||||
s->calls[i].name : "");
|
||||
out->calls[i].args = strdup(s->calls[i].args.p != NULL ?
|
||||
s->calls[i].args.p : "{}");
|
||||
if (out->calls[i].id == NULL || out->calls[i].name == NULL ||
|
||||
out->calls[i].args == NULL) {
|
||||
sp_reply_free(out);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/* hand the provider's structure back verbatim next round */
|
||||
{
|
||||
struct sp_buf json;
|
||||
|
||||
if (sp_buf_init(&json) != 0)
|
||||
return -1;
|
||||
sp_buf_puts(&json, "[");
|
||||
for (i = 0; i < s->ncalls; i++) {
|
||||
if (i > 0)
|
||||
sp_buf_puts(&json, ",");
|
||||
sp_buf_puts(&json, "{\"id\":\"");
|
||||
sp_json_escape(&json, out->calls[i].id);
|
||||
sp_buf_puts(&json, "\",\"type\":\"function\","
|
||||
"\"function\":{\"name\":\"");
|
||||
sp_json_escape(&json, out->calls[i].name);
|
||||
sp_buf_puts(&json, "\",\"arguments\":\"");
|
||||
sp_json_escape(&json, out->calls[i].args);
|
||||
sp_buf_puts(&json, "\"}}");
|
||||
}
|
||||
sp_buf_puts(&json, "]");
|
||||
out->calls_json = strdup(json.p);
|
||||
sp_buf_free(&json);
|
||||
if (out->calls_json == NULL)
|
||||
return -1;
|
||||
}
|
||||
(void)err;
|
||||
return 0;
|
||||
}
|
||||
Loaded 100 of 984 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user