Fix camera, AW9120 back LED strip, full-height dmenu, and preinstall Bantam & gitconfig
- Camera (geminux-camera):
- Auto-configure Media Controller subdevs (hi556 + 1a040000.seninf at 1296x972
SRGGB10_1X10 -> /dev/video0 MBRA), unpack 10-bit packed MTISP Bayer frames,
and run pedestal subtraction, bilinear demosaic, Gray-World AWB, gamma 2.2
LUT, and closed-loop V4L2 AE/AGC with 90-degree rotation and --oneshot JPEG
capture.
- AW9120 cover LED daemon (geminux-leds):
- Drive the back cover multicolor RGB strip (rgb:indicator-1..5, plus
rgb:indicator-6 via led/off) using sysfs multi_intensity + brightness
instead of matching monochrome red/blue names on the inside keyboard
indicator-7 Caps Lock LEDs, and filter netlink uevents to
SUBSYSTEM=power_supply.
- Launcher & dmenu:
- Make dmenu span the full screen height in vertical mode and auto-fill
available item rows in geminux-launcher.
- Preinstalled packages & skel config:
- Package and preinstall Bantam (geminux-bantam @geminux APK) with readline.
- Preinstall sanitized default .gitconfig in /etc/skel (and /root) without
user identity fields.
This commit is contained in:
1 parent
8843558f3b
commit
2706b9a901
36 files changed
+6621
-153
No files matched your search
@@ -0,0 +1,82 @@
|
||||
# Bantam — POSIX-compatible Makefile.
|
||||
# Targets: Linux, FreeBSD, macOS, Haiku (any POSIX make: bmake, gmake, smake).
|
||||
# Dependencies: libcurl and GNU readline (found via standard include/lib
|
||||
# paths) for HTTP and interactive line editing. JSON is handled natively in
|
||||
# json.cpp (no extra or vendored dependency).
|
||||
# If your headers/libs live in a non-standard prefix, override, e.g.:
|
||||
# make CPPFLAGS="-I/opt/include" LDLIBS="-L/opt/lib -lcurl -lreadline"
|
||||
#
|
||||
# 32-bit build: make 32bit
|
||||
# Or: make CXXFLAGS="-std=c++20 -O2 -m32" LDFLAGS="-m32"
|
||||
# Large file support on 32-bit: make CPPFLAGS="-D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE"
|
||||
|
||||
# MARCH is empty by default so the binary runs on any machine of the target
|
||||
# architecture (CI, package builds, different CPUs). Opt in locally with
|
||||
# make MARCH="-march=native"
|
||||
MARCH =
|
||||
CXX = c++
|
||||
STRIP = strip
|
||||
CXXFLAGS = -std=c++20 -Wall -Wextra -Wpedantic -O2 $(MARCH) -D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE
|
||||
CPPFLAGS = -I/usr/local/include -I. -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_XOPEN_SOURCE=700 -D_DARWIN_C_SOURCE
|
||||
LDFLAGS =
|
||||
LDLIBS = -L/usr/local/lib -lcurl -lreadline
|
||||
|
||||
# Location of the AddressSanitizer/UBSan runtime libraries plus a replacement
|
||||
# libasan_preinit.o (so the runtime initializes before main()). On a normal
|
||||
# system these ship with the compiler; override with
|
||||
# make debug ASANDIR= (empty) — the gcc driver finds them automatically.
|
||||
ASANDIR = /tmp/asanlib
|
||||
|
||||
OBJS = main.o config.o util.o json.o llm.o tools.o session.o render.o editor.o
|
||||
|
||||
bantam: $(OBJS)
|
||||
$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) -o bantam $(OBJS) $(LDLIBS)
|
||||
$(STRIP) bantam
|
||||
|
||||
main.o: main.cpp bantam.hpp
|
||||
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c main.cpp
|
||||
|
||||
config.o: config.cpp bantam.hpp
|
||||
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c config.cpp
|
||||
|
||||
util.o: util.cpp bantam.hpp
|
||||
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c util.cpp
|
||||
|
||||
json.o: json.cpp bantam.hpp
|
||||
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c json.cpp
|
||||
|
||||
llm.o: llm.cpp bantam.hpp
|
||||
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c llm.cpp
|
||||
|
||||
tools.o: tools.cpp bantam.hpp
|
||||
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c tools.cpp
|
||||
|
||||
session.o: session.cpp bantam.hpp
|
||||
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c session.cpp
|
||||
|
||||
render.o: render.cpp bantam.hpp
|
||||
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c render.cpp
|
||||
|
||||
editor.o: editor.cpp bantam.hpp
|
||||
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c editor.cpp
|
||||
|
||||
clean:
|
||||
rm -f $(OBJS) bantam bantam_asan
|
||||
|
||||
install: bantam
|
||||
install -m 0755 bantam $(DESTDIR)/usr/local/bin/bantam
|
||||
|
||||
# Debug build with AddressSanitizer + UndefinedBehaviorSanitizer.
|
||||
# Rebuilds ./bantam — run `make clean && make` afterwards to restore the
|
||||
# optimized build. ASANDIR points the gcc driver (-B) at the runtime libs and
|
||||
# the replacement libasan_preinit.o, and sets an rpath so they load at run time.
|
||||
debug:
|
||||
$(MAKE) CXXFLAGS="-std=c++20 -Wall -Wextra -Wpedantic -D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE -g -O0 -fsanitize=address,undefined -B$(ASANDIR) -Wl,-rpath,$(ASANDIR)" LDFLAGS="" STRIP=":" bantam
|
||||
|
||||
# 32-bit build target
|
||||
# Usage: make 32bit
|
||||
# This builds a 32-bit binary with large file support enabled.
|
||||
32bit:
|
||||
$(MAKE) CXXFLAGS="$(CXXFLAGS) -m32" LDFLAGS="$(LDFLAGS) -m32" bantam
|
||||
|
||||
.PHONY: clean install debug 32bit
|
||||
@@ -0,0 +1,457 @@
|
||||
# Bantam: tiny, powerful, DIY AI agent
|
||||
|
||||
## About
|
||||
|
||||
Bantam is a minimalist, dependency-light AI agent that talks to any
|
||||
OpenAI-compatible `/chat/completions` API. It is implemented in modern C++20
|
||||
using standard, safe containers and RAII.
|
||||
|
||||
It provides an agentic loop — autonomous tool execution, direct shell
|
||||
interaction, file writing/editing, real-time response streaming, markdown
|
||||
terminal rendering with box-drawing tables, Fibonacci backoff network
|
||||
resilience, context-window auto-discovery, token usage tracking with prompt
|
||||
cache breakdowns, and conversation compaction.
|
||||
|
||||
The terminal markdown renderer (inline styles, headings, lists, block quotes,
|
||||
fenced code, and box-drawing tables) is implemented natively, so no external
|
||||
Markdown library is required. Interactive line editing is handled by **GNU
|
||||
readline**, which provides the prompt, history and Emacs-style key bindings,
|
||||
so no hand-rolled terminal code is needed.
|
||||
|
||||
The whole philosophy of Bantam rests on two principles:
|
||||
|
||||
1. The structure must be as simple as possible for anyone to reimplement the
|
||||
agent from a plain algorithm description.
|
||||
2. The agent only needs a minimal set of tools: `bash` to run shell commands,
|
||||
`read` to inspect files and directories, and `write` to write/edit files.
|
||||
|
||||
### Design goals
|
||||
|
||||
- Use standard, safe C++ containers (`std::string`, `std::vector`,
|
||||
`std::map`, `std::span`) instead of raw memory areas.
|
||||
- Eliminate hand-rolled allocation/string code; rely on RAII so there is far
|
||||
less room for memory-allocation related vulnerabilities.
|
||||
- Depend only on **libcurl** (HTTP) and **GNU readline** (interactive line
|
||||
editing); JSON parsing/serialization and Markdown rendering are implemented
|
||||
natively in C++20 with no external or vendored library bloat.
|
||||
|
||||
## Repository layout
|
||||
|
||||
```
|
||||
bantam.hpp all shared declarations (structs, prototypes, native Json type)
|
||||
util.cpp string building, UTF-8, prompt-injection filter, color, IDs, MD5
|
||||
config.cpp config file parsing, env precedence, /models discovery
|
||||
json.cpp native RFC 8259 JSON engine, request building + response parsing
|
||||
llm.cpp libcurl HTTP client, custom headers, backoff, SSE streaming
|
||||
tools.cpp bash/read/write tools (validated edit modes), result offloading
|
||||
session.cpp session save/load, compaction, per-project session reset
|
||||
render.cpp terminal markdown renderer (native, box-drawing tables)
|
||||
editor.cpp GNU readline line editor + history (+ term helpers)
|
||||
main.cpp REPL, agentic loop, tool dispatch, commands
|
||||
Makefile POSIX-compatible build
|
||||
README.md this document
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- A C++20 compiler (`c++` / `g++` / `clang++`) and a POSIX `make`
|
||||
(`bmake`, `gmake`, `smake`, …).
|
||||
- **libcurl** development packages, available via the standard include /
|
||||
library search paths. The JSON layer is implemented natively in `json.cpp`
|
||||
and needs no separate dependency.
|
||||
- **GNU readline** development packages (`libreadline-dev` on Debian/Ubuntu,
|
||||
`readline` on Fedora/macOS) for the interactive prompt, history and line
|
||||
editing. On common systems:
|
||||
```bash
|
||||
# Debian / Ubuntu
|
||||
apt-get install libreadline-dev
|
||||
# Fedora / RHEL
|
||||
dnf install readline-devel
|
||||
# macOS (Homebrew)
|
||||
brew install readline
|
||||
```
|
||||
- An OpenAI-compatible API endpoint (or an API key for one).
|
||||
|
||||
On common systems:
|
||||
|
||||
```bash
|
||||
# Debian / Ubuntu
|
||||
apt-get install libcurl4-openssl-dev build-essential
|
||||
# Fedora / RHEL
|
||||
dnf install libcurl-devel
|
||||
# FreeBSD
|
||||
pkg install curl
|
||||
# macOS (Homebrew)
|
||||
brew install curl
|
||||
```
|
||||
|
||||
If the libcurl headers or libraries live in a non-standard prefix, override
|
||||
them at build time, e.g.:
|
||||
|
||||
```bash
|
||||
make CPPFLAGS="-I/opt/include" LDLIBS="-L/opt/lib -lcurl"
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
```bash
|
||||
make # builds & strips ./bantam (c++ -std=c++20 -O2 -Wall -Wextra -Wpedantic)
|
||||
make MARCH="-march=native" # optional: tune for the build machine's CPU
|
||||
make 32bit # builds & strips a 32-bit x86 ./bantam (-m32) with large file support
|
||||
make clean # remove build artifacts
|
||||
make install # install to $(DESTDIR)/usr/local/bin/bantam
|
||||
```
|
||||
|
||||
The default `make` produces a single binary, `bantam`, with no runtime
|
||||
dependencies beyond libc, libcurl and libreadline.
|
||||
|
||||
**Note:** on macOS, if you also have a GNU toolchain installed, you may
|
||||
have to use `make STRIP=/usr/bin/strip` to achieve full ABI compatibility.
|
||||
|
||||
## Running
|
||||
|
||||
Bantam reads `.bantam.cfg` from the current working directory.
|
||||
|
||||
1. Configure `.bantam.cfg` with your API settings:
|
||||
|
||||
```ini
|
||||
endpoint=https://api.kilo.ai/api/openrouter
|
||||
model=openrouter/free
|
||||
temperature=0.7
|
||||
api_key=your_api_key_here
|
||||
stream=true
|
||||
context_window=200000
|
||||
max_tool_res=65536
|
||||
reasoning_effort=high
|
||||
```
|
||||
|
||||
2. Interactive mode:
|
||||
|
||||
```bash
|
||||
./bantam
|
||||
```
|
||||
|
||||
In interactive mode, prompts can span multiple lines: press **Ctrl+J** to
|
||||
insert a real line break (the cursor moves to the next line), then **Enter**
|
||||
to submit the whole multi-line prompt. Bracketed paste is enabled
|
||||
(`ESC[?2004h`) while editing, so a multi-line block pasted from the
|
||||
clipboard is inserted as literal line breaks and only the final **Enter**
|
||||
submits it. The interactive prompt is provided by **GNU readline**, which
|
||||
is a third-party dependency (see Prerequisites). It supports arrow keys and
|
||||
Up/Down for history, Backspace / Delete / Ctrl+D (on an empty line) to
|
||||
delete, and Emacs-style editing combos: **Ctrl+A** (start of line),
|
||||
**Ctrl+E** (end of line), **Ctrl+B** / **Ctrl+F** (move by character),
|
||||
**Ctrl+W** (delete previous word), **Ctrl+K** (kill to end of line),
|
||||
**Ctrl+U** (kill to start of line), **Ctrl+Left** / **Ctrl+Right** (move by
|
||||
word), and **Home** / **End** keys. **Ctrl+C** clears the line /
|
||||
interrupts an in-flight run, and **Ctrl+D** on an empty line exits.
|
||||
|
||||
After every interaction, Bantam displays token usage (prompt tokens,
|
||||
cached / uncached breakdown when supported by the provider, completion
|
||||
tokens, and context-window utilization):
|
||||
|
||||
```text
|
||||
[openrouter/free: 1420 prompt (1000 cached, 420 uncached) + 85 completion | context: 1420/262144 (0.5%)]
|
||||
```
|
||||
|
||||
Sessions are saved under `~/.bantam/sessions/` and can be managed with
|
||||
these commands:
|
||||
|
||||
- `/save [name]` — save the entire conversation to a session file (named
|
||||
`name`, or defaulting to the MD5 hash of the current project directory)
|
||||
and generate its summary.
|
||||
- `/continue` (alias `/cont`) — continue/autoload the session corresponding
|
||||
to the current project directory.
|
||||
- `/list` — list saved sessions (newest first) with their ids, timestamps,
|
||||
message counts and summaries (marking the current project's session).
|
||||
- `/load <id>` — load a saved session (exact id or unique prefix) and
|
||||
continue from there.
|
||||
- `/compact` — compact context down to the system message and a concise
|
||||
summary using the LLM; the compaction prompt is appended to the
|
||||
conversation to derive the summary, then the conversation is reset to
|
||||
`[system, summary-user-message]`.
|
||||
- `/cfg <param> [val]` — inspect or update a configuration parameter live
|
||||
(writes to `.bantam.cfg`).
|
||||
- `/model [val]` — alias for `/cfg model` (inspect or set the model).
|
||||
- `/endpoint [val]` — alias for `/cfg endpoint` (inspect or set the API
|
||||
endpoint).
|
||||
- `/skill` — with no argument, list every skill under the configured
|
||||
skills directory (or report that none are configured); with
|
||||
`<name> [prompt]`, load `<skills_dir>/<name>/SKILL.md` (or an absolute
|
||||
path when no skills dir is set) and send its contents prefixed to the
|
||||
optional `prompt` as the next user turn.
|
||||
- `/models` — query the `/models` path on the current inference endpoint
|
||||
and print a plain list of supported model IDs, marking the currently
|
||||
configured model with a leading `* `.
|
||||
- `!<cmd>` — execute a shell command directly through `bash` without
|
||||
adding the result to the conversation context.
|
||||
- `/help` — show all supported commands.
|
||||
- `/clear` — print `[Session cleared]`, reset the conversation to just the
|
||||
freshly built system prompt, and remove only the saved session for the
|
||||
current working directory (`~/.bantam/sessions/<project-md5>.json`).
|
||||
Sessions belonging to other directories and named sessions created with
|
||||
`/save` are left untouched. The fresh conversation is then auto-saved as
|
||||
the current project's session, so a rebuilt binary's current system
|
||||
prompt and tool definitions take effect instead of a stale resumed
|
||||
session.
|
||||
- `/quit` — exit.
|
||||
|
||||
When context-window usage reaches **60% or higher**, Bantam automatically
|
||||
offers to compact the conversation:
|
||||
|
||||
```text
|
||||
Context usage is at 62.4% (163840 / 262144 tokens). Compact conversation? [Y/n]:
|
||||
```
|
||||
|
||||
Pressing **Ctrl+C** during an active inference run or long-running shell
|
||||
execution cleanly interrupts the turn without appending partial or
|
||||
malformed responses to the conversation context.
|
||||
|
||||
The current conversation is also **auto-saved** to
|
||||
`~/.bantam/sessions/<project-md5>.json` after every turn, on `/clear`,
|
||||
`/load`, `/compact`, `/continue`, and on exit — so you can always run
|
||||
`/continue` (or `/cont`) to resume where you left off.
|
||||
|
||||
3. File input mode:
|
||||
|
||||
```bash
|
||||
./bantam prompt.txt
|
||||
```
|
||||
|
||||
If the file's first line (or the argument) starts with `!`, the rest is run
|
||||
as a direct shell command through `bash` and the program exits (the output
|
||||
is not added to the conversation).
|
||||
|
||||
## Model configuration parameters
|
||||
|
||||
(The configuration file is `.bantam.cfg` — a plain `key=value` file with `#`
|
||||
comments. Values defined in `.bantam.cfg` override `BANTAM_*` environment
|
||||
variables; when `.bantam.cfg` is absent, `BANTAM_*` environment variables
|
||||
override the built-in defaults.)
|
||||
|
||||
- `endpoint` (base OpenAI-compatible API URL, default
|
||||
`https://api.kilo.ai/api/openrouter`; falls back to `BANTAM_ENDPOINT`).
|
||||
- `model` (model name, default `openrouter/free`; falls back to
|
||||
`BANTAM_MODEL`).
|
||||
- `temperature` (model temperature, default `0.7`; falls back to
|
||||
`BANTAM_TEMP` or `BANTAM_TEMPERATURE`).
|
||||
- `api_key` (API key / Bearer token, optional; falls back to
|
||||
`BANTAM_API_KEY`; set to `-` or left blank in the config file to explicitly
|
||||
defer to `BANTAM_API_KEY`).
|
||||
- `stream` (stream response tokens in real-time, default `true`; falls back to
|
||||
`BANTAM_STREAM`).
|
||||
- `color` (ANSI coloring: `auto` (TTY-detected, default), `always`, or
|
||||
`never`; disabled by `NO_COLOR` / `BANTAM_NO_COLOR` env vars, falls back to
|
||||
`BANTAM_COLOR`).
|
||||
- `timeout` (HTTP timeout in seconds for LLM API calls, default `300`; bounds
|
||||
connection setup and time-to-first-byte so long streaming responses are not
|
||||
cut off mid-stream; falls back to `BANTAM_TIMEOUT`).
|
||||
- `shell_timeout` (timeout in seconds for `bash` shell commands, default
|
||||
`120`; falls back to `BANTAM_SHELL_TIMEOUT`).
|
||||
- `max_al_iterations` (max tool-call loop iterations per `AL()` invocation,
|
||||
default `1000`; falls back to `BANTAM_MAX_AL_ITERATIONS`).
|
||||
- `context_window` (context window size in tokens, auto-discovered from
|
||||
`/models` API if available, fallback to this setting, default `262144`;
|
||||
falls back to `BANTAM_CONTEXT_WINDOW`).
|
||||
- `max_tool_res` (maximum number of bytes of a tool result that may be sent
|
||||
into the model context directly, default `65536`; larger results are written
|
||||
to a unique file under `$TMPDIR/bantam/<project-md5>/toolres` and replaced by
|
||||
a short instruction naming the file and its byte length so it can be read in
|
||||
parts using the `read` tool, and the file is deleted once the round ends;
|
||||
falls back to `BANTAM_MAX_TOOL_RES`).
|
||||
- `reasoning_effort` (reasoning effort level, forwarded to chat completions
|
||||
API, default `high`; falls back to `BANTAM_REASONING_EFFORT`).
|
||||
|
||||
- `bantam_tools_dir` (optional path to a directory of extra shell tools; when
|
||||
set, Bantam appends `"Extra shell tools can be found at <dir>"` to the
|
||||
system prompt at startup. Falls back to `BANTAM_TOOLS_DIR`. Agent-internal
|
||||
hint, not forwarded to the API.)
|
||||
- `bantam_skills_dir` (optional path to a directory of reusable *skills*, each
|
||||
in its own subdirectory as `<skill_name>/SKILL.md`. When set, Bantam appends
|
||||
`"Skills may be discovered and invoked from <dir>"` to the system prompt and
|
||||
the `/skill <skill_name> [prompt]` command loads a skill's `SKILL.md` and
|
||||
runs it as a prompt. Falls back to `BANTAM_SKILLS_DIR`. Agent-internal
|
||||
hint, not forwarded to the API.)
|
||||
|
||||
Bantam supports SOCKS5 proxying via the `SOCKS_PROXY` (or
|
||||
`socks_proxy`) environment variable (e.g. `SOCKS_PROXY=socks5://127.0.0.1:1080`
|
||||
or `SOCKS_PROXY=127.0.0.1:1080`), falling back to standard `HTTP_PROXY` /
|
||||
`HTTPS_PROXY` environment variables.
|
||||
|
||||
When enabled, the interactive console uses a subtle ANSI palette: the
|
||||
pending-request status `...requesting...` is dimmed bold, reasoning markers
|
||||
are cyan, reasoning text is dim, `[tool call: ...]` traces are yellow,
|
||||
`[tool result: ...]` headers are green, tool result bodies are dim (red for
|
||||
tool errors / unknown tools), and errors / network retries are red. Tool
|
||||
result payloads fed back to the LLM are never colored.
|
||||
|
||||
## The agentic loop
|
||||
|
||||
1. **Initialization**: read the config file `.bantam.cfg` from the current
|
||||
working directory. Discover the context-window size from the `/models` endpoint
|
||||
(or fall back to `context_window`, default `262144` tokens). Prepare the
|
||||
messages array starting with the built-in system prompt.
|
||||
2. **Input processing**: take the user prompt (command-line file parameter or
|
||||
interactive stdin). If prefixed with `!`, execute the command directly via
|
||||
`bash` without appending to the conversation context. Otherwise append
|
||||
`{"role": "user", "content": prompt}` and invoke `AL(cfg, messages)`.
|
||||
3. **Agentic loop (`AL`)**:
|
||||
- Send `messages` and tool definitions (`bash`, `read`, `write`) to the
|
||||
OpenAI-compatible `/chat/completions` API with custom request headers (see
|
||||
below) and `stream_options: {"include_usage": true}`. The tool schema is
|
||||
built from the current binary on every request (no cached snapshot), so a
|
||||
rebuilt binary always sends its current definitions.
|
||||
- Support context cancellation (on `SIGINT` / Ctrl+C) to cleanly abort
|
||||
in-flight requests without appending incomplete messages.
|
||||
- On network or HTTP failure, retry using Fibonacci backoff delays
|
||||
(`1s, 1s, 2s, 3s, 5s, 8s, 13s, 21s, 34s`). A `4xx` error other than the
|
||||
recoverable invalid-assistant-message case fast-fails.
|
||||
- If `stream=true`, parse SSE data chunks (`data: {...}`) in real time to
|
||||
stream reasoning content (`reasoning_content`) and response text directly
|
||||
to stdout, bracketing the reasoning block with
|
||||
`--- reasoning start ---` / `--- reasoning end ---` markers, rendering
|
||||
Markdown and tables constrained to terminal width.
|
||||
- Reconstruct the assistant message and track usage tokens
|
||||
(`prompt_tokens`, `completion_tokens`, cached tokens). If `tool_calls`
|
||||
exist, trace the call (`[tool call: name(args)]`), validate JSON
|
||||
arguments, execute the requested tool (`bash`, `read`, or `write`; also
|
||||
accepting legacy `shell_exec` and `write_file`), trace the result
|
||||
(`[tool result: name]`), append the tool response
|
||||
`{"role": "tool", "tool_call_id": id, "content": result}`, and repeat the
|
||||
loop.
|
||||
- If no tool calls remain or `max_al_iterations` is reached, return the
|
||||
updated messages list and turn usage stats.
|
||||
4. **Post-turn reporting & compaction**:
|
||||
- Display token usage and context-window percentage.
|
||||
- If context usage is `>= 60%`, prompt the user to compact.
|
||||
- Compaction appends a compaction prompt as a user message to derive the
|
||||
summary, invokes the LLM, and then resets the conversation to the system
|
||||
prompt plus a `user` message carrying the resulting summary.
|
||||
|
||||
If the API rejects the request with an `Invalid assistant message: content or
|
||||
tool_calls must be set` error (usually caused by a previously cut-off stream
|
||||
that left an empty assistant message in the session), Bantam strips the last
|
||||
`assistant`-role message from the session and retries the call.
|
||||
|
||||
### Custom request headers
|
||||
|
||||
All requests to the `/chat/completions` and `/models` endpoints are sent with a
|
||||
minimal, dependency-free header set (see `apply_llm_headers` / `http_get` in
|
||||
`llm.cpp`):
|
||||
|
||||
- `Content-Type: application/json`
|
||||
- `Expect:` (empty) — suppresses the `Expect: 100-continue` round-trip so large
|
||||
POST bodies are sent immediately and do not hang behind some proxies.
|
||||
- `User-Agent: Mozilla/5.0 Bantam/nightly-cpp`
|
||||
- `x-opencode-session: <project-md5>` — stable session identifier derived from
|
||||
the MD5 hash of the current project directory (`project_id()`), so all
|
||||
requests from the same project share one session id.
|
||||
- `Authorization: Bearer <api_key>` — added only when `api_key` is set and is
|
||||
not `-` (a real key, not the placeholder).
|
||||
|
||||
### Prompt-injection defense
|
||||
|
||||
Tool arguments (as stored in the conversation history and printed to the
|
||||
terminal) and tool outputs are sanitized by filtering out non-printable and
|
||||
space-like Unicode characters, protecting against indirect prompt injection
|
||||
before anything is sent back to the model. File *content* passed to `write` is
|
||||
executed from the raw tool arguments and is written verbatim, so CRLF, tabs,
|
||||
BOMs, zero-width joiners and other legitimate bytes are preserved on disk.
|
||||
|
||||
## Tool call definitions
|
||||
|
||||
### `read` tool
|
||||
|
||||
- Parameters: `filePath` (string, required; also accepts `path`); `offset`
|
||||
(integer, optional, 1-indexed, default 1); `limit` (integer, optional,
|
||||
default 2000).
|
||||
- Action: if the target is a regular file, returns numbered lines in
|
||||
`<line>: <content>` format; lines longer than 2000 bytes are clipped and
|
||||
explicitly marked `[truncated: showing N of M bytes]`. Directories return a
|
||||
list of entries (subdirectories include a trailing `/`). FIFOs, devices and
|
||||
sockets are rejected instead of blocking.
|
||||
|
||||
### `write` tool
|
||||
|
||||
- Parameters: `filePath` (string, required; also accepts `path`); `content`
|
||||
(string, required, may be empty, written verbatim). Exactly **one** edit mode
|
||||
may be selected:
|
||||
- `find` (string) + `content` — replace the unique exact text in `find` with
|
||||
`content`. No line numbers needed; this is the recommended way to change an
|
||||
existing line. `replaceAll` (boolean) allows replacing every occurrence.
|
||||
- `append: true` + `content` — add lines at the end of the file.
|
||||
- `lineOffset` (integer, 1-indexed, `1` = first line) + optional `delLines`
|
||||
(integer, default `0`) — insert before that line, or replace `delLines`
|
||||
lines with `content`. A `lineOffset` past the last line appends.
|
||||
- `byteOffset` (integer, must be `<=` file size) + optional `delBytes`
|
||||
(integer, default `0`) — exact byte splice.
|
||||
- Action: with only `filePath` and `content` the whole file is overwritten
|
||||
exactly as given (parent directories are created if missing). Otherwise the
|
||||
selected mode is applied. **To replace a line you must use `find`+`content`
|
||||
or `delLines: 1`; omitting `delLines` inserts a new line and keeps the
|
||||
original** (the classic duplicate-line mistake). Modes are mutually
|
||||
exclusive — mixing them, using a `lineOffset` of `0`, or passing
|
||||
`delLines`/`delBytes` without a position returns an instructive error rather
|
||||
than silently doing something else.
|
||||
- Results describe the operation in line numbers (e.g. `Replaced 1 line(s)
|
||||
starting at line 3 ... (file now 7 lines, 84 bytes)`). A pure insertion or
|
||||
an append that duplicates an existing line adds a `[hint: ...]` explaining
|
||||
how to replace instead. Line-based edits terminate the inserted text with a
|
||||
newline and insert a separator when appending to a file that lacks a final
|
||||
newline; they never append a newline to unrelated content. Byte-based edits
|
||||
are exact and never modified.
|
||||
- `content` is written verbatim (no character filtering, no forced trailing
|
||||
newline on overwrite). Numeric parameters also accept integral floats and
|
||||
quoted integers. (Also accepted as legacy `write_file`.)
|
||||
|
||||
Examples (each call selects exactly one mode):
|
||||
|
||||
```json
|
||||
{"filePath": "notes.txt", "content": "hello\n"}
|
||||
{"filePath": "notes.txt", "content": "goodbye", "find": "hello"}
|
||||
{"filePath": "notes.txt", "content": "last line", "append": true}
|
||||
{"filePath": "notes.txt", "content": "replacement", "lineOffset": 3, "delLines": 1}
|
||||
{"filePath": "notes.txt", "content": "X", "byteOffset": 2, "delBytes": 1}
|
||||
```
|
||||
|
||||
The first overwrites the whole file; the second replaces the unique text
|
||||
`hello` without any line numbers; the third appends; the fourth replaces line
|
||||
3; the fifth replaces one byte at offset 2. Passing `lineOffset: 3` **without**
|
||||
`delLines` would insert a new line 3 and keep the original — the tool result
|
||||
then includes a `[hint: ...]` pointing this out.
|
||||
|
||||
### `bash` tool
|
||||
|
||||
- Parameters: `command` (string, required); `workdir` (string, optional).
|
||||
- Action: run `command` through the system shell (`bash` resolved from `PATH`, falling back to `/bin/sh` if bash is unavailable) via `-c`, subject to `shell_timeout`
|
||||
(default `120s`) and return `output + '\nexit: ' + exit_code`. If `workdir`
|
||||
cannot be entered, the command is **not** run: the tool returns
|
||||
`[tool error: workdir '...': ...]` with `exit: 1` instead of silently
|
||||
executing in the wrong directory. (Also accepted as legacy `shell_exec`.)
|
||||
|
||||
## Extra tools and skills
|
||||
|
||||
Because Bantam's built-in tools include `bash`, helper scripts can be invoked
|
||||
directly by the agent through `bash`. Point Bantam at a directory of helpers
|
||||
with the `bantam_tools_dir` key (or `BANTAM_TOOLS_DIR`); when set, the line
|
||||
`Extra shell tools can be found at <dir>` is appended to the system prompt. A
|
||||
*skill* is a reusable instruction bundle: a directory containing a `SKILL.md`
|
||||
file, pointed to by `bantam_skills_dir` (or `BANTAM_SKILLS_DIR`), and run with
|
||||
`/skill <name> [prompt]`.
|
||||
|
||||
## Memory safety
|
||||
|
||||
Bantam leans on the language's standard library and RAII to minimize
|
||||
memory-management hazards: all dynamic text uses `std::string`, message
|
||||
collections use `std::vector`, and curl header lists and streaming state are
|
||||
wrapped in RAII types (`CurlHeaders`, `StreamCtx`) that free themselves on
|
||||
scope exit. There is no hand-rolled allocator and no manual `free` of message
|
||||
or tool-call data, so use-after-free and double-free are structurally
|
||||
unlikely. A lightweight, native RFC 8259 JSON engine (`struct Json` in
|
||||
`json.cpp`) handles all JSON parsing and serialization using standard C++
|
||||
containers, so no external JSON library is needed.
|
||||
|
||||
## Credits
|
||||
|
||||
Created by Luxferre in 2026, released into the public domain with no
|
||||
warranties.
|
||||
@@ -0,0 +1,331 @@
|
||||
/* Bantam: tiny, powerful, DIY AI agent — C++20 implementation
|
||||
* Created by Luxferre in 2026, released into the public domain.
|
||||
*
|
||||
* Talks to any OpenAI-compatible /chat/completions API and implements an
|
||||
* agentic loop, tools, session management, markdown terminal rendering and
|
||||
* an interactive line editor.
|
||||
*
|
||||
* Design goals:
|
||||
* - Use standard, safe C++ containers (std::string, std::vector,
|
||||
* std::map, std::span) instead of raw memory areas.
|
||||
* - Eliminate hand-rolled allocation/string code; rely on RAII so there
|
||||
* is far less room for memory-allocation related vulnerabilities.
|
||||
* - Depend only on libcurl (HTTP) and GNU readline (interactive line
|
||||
* editing); JSON parsing/serialization and Markdown rendering are
|
||||
* implemented natively in modern C++20 with zero external bloat.
|
||||
*
|
||||
* Feature macros: we rely on POSIX.1-2008 interfaces. */
|
||||
#ifndef BANTAM_HPP
|
||||
#define BANTAM_HPP
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Minimal RFC 8259 JSON value, parser and serializer (json.cpp). */
|
||||
/* ------------------------------------------------------------------ */
|
||||
enum class JType { Null, Bool, Int, Float, Str, Arr, Obj };
|
||||
|
||||
struct Json {
|
||||
JType type = JType::Null;
|
||||
bool bval = false;
|
||||
int64_t ival = 0;
|
||||
double dval = 0.0;
|
||||
std::string sval;
|
||||
std::vector<Json> aval;
|
||||
std::vector<std::pair<std::string, Json>> oval;
|
||||
|
||||
Json();
|
||||
~Json();
|
||||
Json(const Json &);
|
||||
Json(Json &&) noexcept;
|
||||
Json &operator=(const Json &);
|
||||
Json &operator=(Json &&) noexcept;
|
||||
|
||||
Json(std::nullptr_t);
|
||||
Json(bool b);
|
||||
Json(int n);
|
||||
Json(int64_t n);
|
||||
Json(double d);
|
||||
Json(const char *s);
|
||||
Json(std::string s);
|
||||
Json(std::string_view s);
|
||||
|
||||
static Json object();
|
||||
static Json array();
|
||||
|
||||
bool is_null() const { return type == JType::Null; }
|
||||
bool is_bool() const { return type == JType::Bool; }
|
||||
bool is_number_integer() const { return type == JType::Int; }
|
||||
bool is_number() const { return type == JType::Int || type == JType::Float; }
|
||||
bool is_string() const { return type == JType::Str; }
|
||||
bool is_array() const { return type == JType::Arr; }
|
||||
bool is_object() const { return type == JType::Obj; }
|
||||
|
||||
bool empty() const;
|
||||
size_t size() const;
|
||||
bool contains(std::string_view k) const;
|
||||
Json &operator[](std::string_view k);
|
||||
const Json &operator[](std::string_view k) const;
|
||||
Json &at(size_t i);
|
||||
const Json &at(size_t i) const;
|
||||
void push_back(Json v);
|
||||
|
||||
std::string str(std::string_view def = "") const;
|
||||
int64_t as_int64(int64_t def = 0) const;
|
||||
int as_int(int def = 0) const;
|
||||
|
||||
std::string dump(int indent = -1) const;
|
||||
static bool parse(std::string_view src, Json &out);
|
||||
};
|
||||
|
||||
/* Markdown renderer state (code-fence tracking). */
|
||||
struct MdState {
|
||||
bool in_code = false;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Tool call / message / usage / config structures. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
struct ToolCall {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string arguments; /* raw JSON text of the arguments object */
|
||||
};
|
||||
|
||||
struct Message {
|
||||
std::string role;
|
||||
std::string content; /* empty when absent */
|
||||
std::string reasoning; /* empty when absent */
|
||||
std::vector<ToolCall> calls;
|
||||
std::string tool_call_id; /* empty when absent (tool role only) */
|
||||
int calls_shown = 0;
|
||||
};
|
||||
|
||||
struct Messages {
|
||||
std::vector<Message> items;
|
||||
};
|
||||
|
||||
struct Usage {
|
||||
int prompt_tokens = 0;
|
||||
int completion_tokens = 0;
|
||||
int total_tokens = 0;
|
||||
int cached_tokens = 0;
|
||||
int context_tokens = 0;
|
||||
std::string model;
|
||||
};
|
||||
|
||||
struct Cfg {
|
||||
std::string endpoint;
|
||||
std::string model;
|
||||
std::string api_key;
|
||||
std::string color;
|
||||
double temperature = 0.7;
|
||||
int timeout = 300;
|
||||
int shell_timeout = 120;
|
||||
int max_al_iterations = 1000;
|
||||
int stream = 1; /* 0/1 */
|
||||
int force_stream = -1; /* -1 = auto, 0/1 = force (compaction) */
|
||||
int context_window = 262144;
|
||||
int max_tool_res = 65536;
|
||||
bool context_window_set = false;
|
||||
std::map<std::string, std::string> raw; /* raw key/value map */
|
||||
};
|
||||
|
||||
struct Session {
|
||||
std::string id;
|
||||
std::string created;
|
||||
std::string summary;
|
||||
Messages messages;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Globals. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
extern int g_col; /* color enabled (0/1) */
|
||||
extern volatile int g_interrupted; /* SIGINT flag */
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* util.cpp */
|
||||
/* ------------------------------------------------------------------ */
|
||||
void setup_signal_handler();
|
||||
int is_terminal(int fd);
|
||||
int to_int_val(std::string_view s, int def);
|
||||
bool read_file_str(std::string_view path, std::string &out);
|
||||
bool write_file_str(std::string_view path, std::string_view data);
|
||||
|
||||
std::string sfmt(const char *fmt, ...);
|
||||
void str_appendf(std::string &s, const char *fmt, ...);
|
||||
|
||||
/* UTF-8 helpers. */
|
||||
int utf8_decode(const unsigned char *p, size_t avail, size_t *plen);
|
||||
std::string_view utf8_truncate(std::string_view s, size_t max_bytes);
|
||||
|
||||
std::string filter_text(std::string_view s);
|
||||
int color_enabled(const Cfg &cfg);
|
||||
template<class R>
|
||||
inline std::string cstr(std::string_view text, const R& codes) {
|
||||
if (!g_col || codes.empty() || text.empty()) return std::string(text);
|
||||
std::string s;
|
||||
s.reserve(text.size() + 16);
|
||||
s += "\033[";
|
||||
for (size_t i = 0; i < codes.size(); i++) {
|
||||
if (i) s += ';';
|
||||
int v = (int)codes[i];
|
||||
if (v <= 0) {
|
||||
s += '0';
|
||||
} else {
|
||||
char rev[12];
|
||||
int rn = 0;
|
||||
while (v > 0 && rn < 12) { rev[rn++] = (char)('0' + (v % 10)); v /= 10; }
|
||||
while (rn > 0) s += rev[--rn];
|
||||
}
|
||||
}
|
||||
s += 'm';
|
||||
s += text;
|
||||
s += "\033[0m";
|
||||
return s;
|
||||
}
|
||||
template<class R>
|
||||
inline void cprint(std::string_view text, const R& codes) {
|
||||
if (text.empty()) return;
|
||||
if (!g_col || codes.empty()) {
|
||||
std::fwrite(text.data(), 1, text.size(), stdout);
|
||||
return;
|
||||
}
|
||||
char seq[32];
|
||||
size_t pos = 0;
|
||||
seq[pos++] = '\033';
|
||||
seq[pos++] = '[';
|
||||
for (size_t i = 0; i < codes.size() && pos + 12 < sizeof(seq); i++) {
|
||||
if (i) seq[pos++] = ';';
|
||||
int v = (int)codes[i];
|
||||
if (v <= 0) {
|
||||
seq[pos++] = '0';
|
||||
} else {
|
||||
char rev[12];
|
||||
int rn = 0;
|
||||
while (v > 0 && rn < 12) { rev[rn++] = (char)('0' + (v % 10)); v /= 10; }
|
||||
while (rn > 0) seq[pos++] = rev[--rn];
|
||||
}
|
||||
}
|
||||
seq[pos++] = 'm';
|
||||
std::fwrite(seq, 1, pos, stdout);
|
||||
std::fwrite(text.data(), 1, text.size(), stdout);
|
||||
std::fwrite("\033[0m", 1, 4, stdout);
|
||||
}
|
||||
int visible_len(std::string_view s);
|
||||
int rune_width(int cp);
|
||||
|
||||
void mkdir_p(std::string_view dir);
|
||||
std::string project_id();
|
||||
std::string bantam_tmp_dir(std::string_view sess_id = "");
|
||||
std::string tool_res_dir(std::string_view sess_id = "");
|
||||
std::string md5_hex(std::string_view data);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* config.cpp */
|
||||
/* ------------------------------------------------------------------ */
|
||||
const std::string *cfg_raw_get(const Cfg &c, std::string_view k);
|
||||
bool internal_key(std::string_view k);
|
||||
Cfg get_cfg(std::string_view path);
|
||||
int set_cfg(std::string_view path, std::string_view key, std::string_view val);
|
||||
std::string config_path();
|
||||
int fetch_context_window(Cfg &cfg);
|
||||
std::string list_models(Cfg &cfg, int *errout);
|
||||
std::string tools_dir(const Cfg &c);
|
||||
std::string skills_dir(const Cfg &c);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* json.cpp — JSON engine, request building & response parsing. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
void serialize_message_json(Json &obj, const Message &m);
|
||||
void parse_message_json(const Json &obj, Message &m);
|
||||
std::string build_request_json(const Cfg &cfg, const Messages &msgs,
|
||||
bool use_tools, bool stream);
|
||||
bool parse_nonstream_response(std::string_view body, Message &out, Usage &usage);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* llm.cpp — HTTP client (libcurl), headers, backoff, dispatch. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
void http_cleanup();
|
||||
int http_get(Cfg &cfg, std::string_view url, std::string &body, long &code,
|
||||
std::string &errmsg);
|
||||
int llm(Cfg &cfg, Messages &msgs, bool use_tools, Message &out, Usage &usage,
|
||||
std::string &errmsg, volatile int *interrupted);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* tools.cpp */
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Exactly one edit mode may be active. An all-false WriteOpts means a
|
||||
* whole-file overwrite. Keeping the mode in one struct makes it impossible
|
||||
* for a partially-specified call to silently turn into a different edit. */
|
||||
struct WriteOpts {
|
||||
bool has_find = false;
|
||||
std::string find;
|
||||
bool replace_all = false;
|
||||
bool append = false;
|
||||
bool has_line = false;
|
||||
long line_offset = 0; /* 1-indexed */
|
||||
bool has_del_lines = false;
|
||||
long del_lines = 0;
|
||||
bool has_byte = false;
|
||||
long byte_offset = 0;
|
||||
bool has_del_bytes = false;
|
||||
long del_bytes = 0;
|
||||
};
|
||||
std::string shell_with_workdir(std::string_view cmd, std::string_view workdir,
|
||||
int timeout, volatile int *interrupted);
|
||||
std::string read_file_or_dir(std::string_view path, int offset, int limit,
|
||||
int *style);
|
||||
std::string write_file(std::string_view path, const WriteOpts &o,
|
||||
std::string_view content, int *err);
|
||||
std::string offload_tool_result(std::string_view res, int max_res,
|
||||
std::vector<std::string> &tmps);
|
||||
void cleanup_temps(std::vector<std::string> &tmps);
|
||||
void cleanup_temps(std::vector<std::string> &tmps);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* session.cpp */
|
||||
/* ------------------------------------------------------------------ */
|
||||
void save_session(const Messages &msgs, std::string_view sid,
|
||||
std::string *out_id, std::string *out_summary);
|
||||
std::vector<Session> sessions_load();
|
||||
std::unique_ptr<Messages> load_session(std::string_view sid, std::string *err);
|
||||
std::unique_ptr<Session> find_project_session();
|
||||
void autosave(const Messages &msgs);
|
||||
bool clear_project_session(std::string *err);
|
||||
bool clear_sessions(std::string *err); /* alias for clear_project_session */
|
||||
std::unique_ptr<Messages> compact(Cfg &cfg, const Messages &msgs,
|
||||
std::string *summary, std::string *err,
|
||||
volatile int *interrupted);
|
||||
std::string summary_of(const Messages &msgs);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* render.cpp — terminal markdown rendering. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
void render_md_print(std::string_view text);
|
||||
void render_md_line_print(std::string_view line, MdState &st);
|
||||
void render_table_print(const std::vector<std::string> &lines);
|
||||
bool is_table_line(std::string_view line);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* editor.cpp — GNU readline line editor + history (+ term helpers). */
|
||||
/* ------------------------------------------------------------------ */
|
||||
void load_history();
|
||||
void save_history();
|
||||
void add_history(std::string_view s);
|
||||
std::string read_line(std::string_view prompt, bool &ok);
|
||||
std::string read_plain(std::string_view prompt, bool &ok);
|
||||
int term_width();
|
||||
|
||||
#endif /* BANTAM_HPP */
|
||||
@@ -0,0 +1,280 @@
|
||||
/* config.cpp — configuration file parsing, env precedence, model discovery. */
|
||||
#include "bantam.hpp"
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <set>
|
||||
#include <strings.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* ----------------------------- raw map -------------------------------- */
|
||||
static void cfg_raw_set(Cfg &c, std::string_view k, std::string_view v) {
|
||||
c.raw[std::string(k)] = std::string(v);
|
||||
}
|
||||
static void cfg_init(Cfg &c) {
|
||||
c = Cfg{};
|
||||
c.endpoint = "https://api.kilo.ai/api/openrouter";
|
||||
c.model = "openrouter/free";
|
||||
c.api_key = "-";
|
||||
c.temperature = 0.7;
|
||||
c.timeout = 300;
|
||||
c.shell_timeout = 120;
|
||||
c.max_al_iterations = 1000;
|
||||
c.stream = 1;
|
||||
c.force_stream = -1;
|
||||
c.color = "auto";
|
||||
c.context_window = 262144;
|
||||
c.max_tool_res = 65536;
|
||||
cfg_raw_set(c, "endpoint", c.endpoint);
|
||||
cfg_raw_set(c, "model", c.model);
|
||||
cfg_raw_set(c, "temperature", "0.7");
|
||||
cfg_raw_set(c, "api_key", c.api_key);
|
||||
cfg_raw_set(c, "stream", "true");
|
||||
cfg_raw_set(c, "color", "auto");
|
||||
cfg_raw_set(c, "timeout", "300");
|
||||
cfg_raw_set(c, "shell_timeout", "120");
|
||||
cfg_raw_set(c, "max_al_iterations", "1000");
|
||||
cfg_raw_set(c, "context_window", "262144");
|
||||
cfg_raw_set(c, "max_tool_res", "65536");
|
||||
cfg_raw_set(c, "reasoning_effort", "high");
|
||||
}
|
||||
const std::string *cfg_raw_get(const Cfg &c, std::string_view k) {
|
||||
auto it = c.raw.find(std::string(k));
|
||||
return it == c.raw.end() ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
bool internal_key(std::string_view k) {
|
||||
static const char *keys[] = {
|
||||
"endpoint", "model", "temperature", "stream", "api_key", "timeout",
|
||||
"shell_timeout", "max_al_iterations", "color", "context_window", "max_tool_res",
|
||||
"bantam_tools_dir", "bantam_skills_dir", nullptr};
|
||||
for (int i = 0; keys[i]; i++) if (k == keys[i]) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* ----------------------------- parsing -------------------------------- */
|
||||
/* parse_cfg_file records every key it sees in *file_keys so that the
|
||||
* config file can take precedence over environment variables. */
|
||||
static void parse_cfg_file(std::string_view path, Cfg &c, std::set<std::string> *file_keys) {
|
||||
std::string content;
|
||||
if (!read_file_str(path, content)) return;
|
||||
size_t pos = 0, n = content.size();
|
||||
while (pos < n) {
|
||||
size_t nl = content.find('\n', pos);
|
||||
std::string_view s = (nl == std::string::npos)
|
||||
? std::string_view(content).substr(pos)
|
||||
: std::string_view(content).substr(pos, nl - pos);
|
||||
pos = (nl == std::string::npos) ? n : nl + 1;
|
||||
while (!s.empty() && std::isspace((unsigned char)s.front())) s.remove_prefix(1);
|
||||
if (s.empty() || s.front() == '#') continue;
|
||||
auto eq = s.find('=');
|
||||
if (eq == std::string_view::npos) continue;
|
||||
std::string_view k = s.substr(0, eq);
|
||||
std::string_view v = s.substr(eq + 1);
|
||||
while (!k.empty() && std::isspace((unsigned char)k.back())) k.remove_suffix(1);
|
||||
while (!v.empty() && std::isspace((unsigned char)v.front())) v.remove_prefix(1);
|
||||
while (!v.empty() && std::isspace((unsigned char)v.back())) v.remove_suffix(1);
|
||||
cfg_raw_set(c, k, v);
|
||||
if (file_keys) file_keys->insert(std::string(k));
|
||||
if (k == "endpoint") c.endpoint = std::string(v);
|
||||
else if (k == "model") c.model = std::string(v);
|
||||
else if (k == "api_key") c.api_key = std::string(v);
|
||||
else if (k == "temperature") c.temperature = std::strtod(std::string(v).c_str(), nullptr);
|
||||
else if (k == "timeout") c.timeout = to_int_val(v, c.timeout);
|
||||
else if (k == "shell_timeout") c.shell_timeout = to_int_val(v, c.shell_timeout);
|
||||
else if (k == "max_al_iterations") c.max_al_iterations = to_int_val(v, c.max_al_iterations);
|
||||
else if (k == "stream") c.stream = (v == "true" || v == "1" || v == "yes");
|
||||
else if (k == "color") c.color = std::string(v);
|
||||
else if (k == "context_window") { c.context_window = to_int_val(v, c.context_window); c.context_window_set = true; }
|
||||
else if (k == "max_tool_res") c.max_tool_res = to_int_val(v, c.max_tool_res);
|
||||
}
|
||||
}
|
||||
|
||||
/* Environment variables act as a FALLBACK: they only fill in values that the
|
||||
* config file did not explicitly set. The config file (.bantam.cfg) is the
|
||||
* single source of truth. */
|
||||
static void apply_env_cfg(Cfg &c, const std::set<std::string> &file_keys) {
|
||||
auto ev = [&](const char *key, const char *envname) -> const char * {
|
||||
if (file_keys.count(key)) return nullptr;
|
||||
const char *e = std::getenv(envname);
|
||||
return (e && *e) ? e : nullptr;
|
||||
};
|
||||
const char *e;
|
||||
if ((e = ev("endpoint", "BANTAM_ENDPOINT"))) { c.endpoint = e; cfg_raw_set(c, "endpoint", e); }
|
||||
if ((e = ev("model", "BANTAM_MODEL"))) { c.model = e; cfg_raw_set(c, "model", e); }
|
||||
if ((e = ev("temperature", "BANTAM_TEMP"))) { c.temperature = std::strtod(e, nullptr); cfg_raw_set(c, "temperature", e); }
|
||||
else if ((e = ev("temperature", "BANTAM_TEMPERATURE"))) { c.temperature = std::strtod(e, nullptr); cfg_raw_set(c, "temperature", e); }
|
||||
if ((e = ev("stream", "BANTAM_STREAM"))) { c.stream = (std::strcmp(e, "true") == 0 || std::strcmp(e, "1") == 0 || std::strcmp(e, "yes") == 0); cfg_raw_set(c, "stream", e); }
|
||||
if ((e = ev("color", "BANTAM_COLOR"))) { c.color = e; cfg_raw_set(c, "color", e); }
|
||||
if ((e = ev("timeout", "BANTAM_TIMEOUT"))) { c.timeout = to_int_val(e, c.timeout); cfg_raw_set(c, "timeout", e); }
|
||||
if ((e = ev("shell_timeout", "BANTAM_SHELL_TIMEOUT"))) { c.shell_timeout = to_int_val(e, c.shell_timeout); cfg_raw_set(c, "shell_timeout", e); }
|
||||
if ((e = ev("max_al_iterations", "BANTAM_MAX_AL_ITERATIONS"))) { c.max_al_iterations = to_int_val(e, c.max_al_iterations); cfg_raw_set(c, "max_al_iterations", e); }
|
||||
if ((e = ev("context_window", "BANTAM_CONTEXT_WINDOW"))) { c.context_window = to_int_val(e, c.context_window); c.context_window_set = true; cfg_raw_set(c, "context_window", e); }
|
||||
if ((e = ev("max_tool_res", "BANTAM_MAX_TOOL_RES"))) { c.max_tool_res = to_int_val(e, c.max_tool_res); cfg_raw_set(c, "max_tool_res", e); }
|
||||
if ((e = ev("reasoning_effort", "BANTAM_REASONING_EFFORT"))) cfg_raw_set(c, "reasoning_effort", e);
|
||||
if ((e = ev("bantam_tools_dir", "BANTAM_TOOLS_DIR"))) cfg_raw_set(c, "bantam_tools_dir", e);
|
||||
if ((e = ev("bantam_skills_dir", "BANTAM_SKILLS_DIR"))) cfg_raw_set(c, "bantam_skills_dir", e);
|
||||
}
|
||||
|
||||
Cfg get_cfg(std::string_view path) {
|
||||
Cfg c;
|
||||
cfg_init(c);
|
||||
std::set<std::string> file_keys;
|
||||
parse_cfg_file(path, c, &file_keys);
|
||||
apply_env_cfg(c, file_keys);
|
||||
/* api_key is usually only supplied via the environment; let it override a
|
||||
* placeholder ("-" or empty) left in the config file. */
|
||||
if (c.api_key.empty() || c.api_key == "-") {
|
||||
const char *k = std::getenv("BANTAM_API_KEY");
|
||||
if (k && *k) { c.api_key = k; cfg_raw_set(c, "api_key", k); }
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
int set_cfg(std::string_view path, std::string_view key, std::string_view val) {
|
||||
/* Strip a single pair of surrounding quotes so a value containing spaces can
|
||||
* be passed as e.g. "a b" without the quote characters becoming part of the
|
||||
* stored value. */
|
||||
std::string vstr(val);
|
||||
if (vstr.size() >= 2 &&
|
||||
((vstr.front() == '"' && vstr.back() == '"') ||
|
||||
(vstr.front() == '\'' && vstr.back() == '\''))) {
|
||||
vstr = vstr.substr(1, vstr.size() - 2);
|
||||
}
|
||||
std::vector<std::string> lines;
|
||||
{
|
||||
std::string content;
|
||||
read_file_str(path, content);
|
||||
size_t i = 0, n = content.size();
|
||||
while (i < n) {
|
||||
size_t j = content.find('\n', i);
|
||||
if (j == std::string::npos) { lines.push_back(content.substr(i)); break; }
|
||||
lines.push_back(content.substr(i, j - i + 1));
|
||||
i = j + 1;
|
||||
}
|
||||
}
|
||||
bool found = false;
|
||||
for (auto &line : lines) {
|
||||
std::string_view sv(line);
|
||||
size_t k = 0;
|
||||
while (k < sv.size() && std::isspace((unsigned char)sv[k])) k++;
|
||||
if (k < sv.size() && sv[k] == '#') continue;
|
||||
auto eq = sv.find('=');
|
||||
if (eq == std::string_view::npos) continue;
|
||||
std::string_view keyPart = sv.substr(k, eq - k);
|
||||
while (!keyPart.empty() && std::isspace((unsigned char)keyPart.back())) keyPart.remove_suffix(1);
|
||||
if (keyPart == key) {
|
||||
line = sfmt("%s=%s\n", std::string(key).c_str(), vstr.c_str());
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
if (!lines.empty()) {
|
||||
std::string &last = lines.back();
|
||||
if (!last.empty() && last.back() != '\n') last += '\n';
|
||||
}
|
||||
lines.push_back(sfmt("%s=%s\n", std::string(key).c_str(), vstr.c_str()));
|
||||
}
|
||||
std::string out_buf;
|
||||
for (auto &line : lines) out_buf += line;
|
||||
return write_file_str(path, out_buf) ? 0 : -1;
|
||||
}
|
||||
|
||||
std::string config_path() {
|
||||
/* .bantam.cfg is the sole configuration file. */
|
||||
return ".bantam.cfg";
|
||||
}
|
||||
|
||||
/* ----------------------------- model discovery ------------------------ */
|
||||
static int query_models_context_window(Cfg &cfg) {
|
||||
std::string url = cfg.endpoint;
|
||||
while (!url.empty() && url.back() == '/') url.pop_back();
|
||||
url += "/models";
|
||||
std::string body;
|
||||
long code = 0;
|
||||
std::string err;
|
||||
if (http_get(cfg, url, body, code, err) != 0) return 0;
|
||||
if (code >= 400) return 0;
|
||||
Json root_mut;
|
||||
if (!Json::parse(body, root_mut) || !root_mut.is_object()) return 0;
|
||||
const Json &root = root_mut;
|
||||
const Json &list = root.contains("data") ? root["data"] : root["models"];
|
||||
if (!list.is_array()) return 0;
|
||||
static const char *keys[] = {"context_window", "context_length", "max_context_length",
|
||||
"max_model_len", "context_size", "max_tokens", "max_input_tokens", nullptr};
|
||||
int cw = 0;
|
||||
for (auto &item : list.aval) {
|
||||
if (cw != 0) break;
|
||||
if (!item.is_object()) continue;
|
||||
std::string id = item["id"].str();
|
||||
if (!id.empty() && (id == cfg.model || strcasecmp(id.c_str(), cfg.model.c_str()) == 0)) {
|
||||
for (int k = 0; keys[k]; k++) {
|
||||
int v = item[keys[k]].as_int();
|
||||
if (v > 0) { cw = v; break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
return cw;
|
||||
}
|
||||
|
||||
int fetch_context_window(Cfg &cfg) {
|
||||
if (cfg.context_window_set && cfg.context_window > 0) return cfg.context_window;
|
||||
static std::map<std::string, int> cache;
|
||||
std::string key = cfg.endpoint + std::string(1, '\0') + cfg.model;
|
||||
auto it = cache.find(key);
|
||||
if (it != cache.end()) return it->second;
|
||||
int cw = query_models_context_window(cfg);
|
||||
if (cw > 0) { cache[key] = cw; return cw; }
|
||||
const std::string *v = cfg_raw_get(cfg, "context_window");
|
||||
int fallback = (v && !v->empty()) ? to_int_val(*v, 262144) : 262144;
|
||||
cache[key] = fallback;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
std::string list_models(Cfg &cfg, int *errout) {
|
||||
std::string url = cfg.endpoint;
|
||||
while (!url.empty() && url.back() == '/') url.pop_back();
|
||||
url += "/models";
|
||||
std::string body;
|
||||
long code = 0;
|
||||
std::string err;
|
||||
if (http_get(cfg, url, body, code, err) != 0) { *errout = -1; return err.empty() ? "request failed" : err; }
|
||||
if (code >= 400) { *errout = -1; return "HTTP error from /models"; }
|
||||
Json root_mut;
|
||||
if (!Json::parse(body, root_mut) || !root_mut.is_object()) {
|
||||
*errout = -1;
|
||||
return "invalid JSON from /models";
|
||||
}
|
||||
const Json &root = root_mut;
|
||||
const Json &list = root.contains("data") ? root["data"] : root["models"];
|
||||
std::string out;
|
||||
bool any = false;
|
||||
if (list.is_array()) {
|
||||
for (auto &item : list.aval) {
|
||||
if (!item.is_object()) continue;
|
||||
std::string id = item["id"].str();
|
||||
if (id.empty()) continue;
|
||||
any = true;
|
||||
if (id == cfg.model) str_appendf(out, "* %s\n", id.c_str());
|
||||
else str_appendf(out, " %s\n", id.c_str());
|
||||
}
|
||||
}
|
||||
if (!any) {
|
||||
*errout = 0;
|
||||
return "No models returned by the endpoint.";
|
||||
}
|
||||
*errout = 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
static std::string cfg_or_env(const Cfg &c, std::string_view key, const char *env) {
|
||||
const std::string *v = cfg_raw_get(c, key);
|
||||
if (v && !v->empty()) return *v;
|
||||
const char *e = std::getenv(env);
|
||||
if (e && *e) return e;
|
||||
return "";
|
||||
}
|
||||
std::string tools_dir(const Cfg &c) { return cfg_or_env(c, "bantam_tools_dir", "BANTAM_TOOLS_DIR"); }
|
||||
std::string skills_dir(const Cfg &c) { return cfg_or_env(c, "bantam_skills_dir", "BANTAM_SKILLS_DIR"); }
|
||||
@@ -0,0 +1,112 @@
|
||||
/* editor.cpp — GNU readline line editor, history and term helpers
|
||||
* (is_terminal, term_width). The interactive prompt is handled by
|
||||
* libreadline instead of a hand-rolled raw-mode terminal editor. */
|
||||
#include "bantam.hpp"
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <readline/readline.h>
|
||||
#include <readline/history.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* ----------------------------- globals ------------------------------- */
|
||||
static std::string g_hist_file;
|
||||
|
||||
static std::string home_dir() {
|
||||
const char *h = std::getenv("HOME");
|
||||
if (h && *h) return h;
|
||||
return ".";
|
||||
}
|
||||
|
||||
/* ----------------------------- history -------------------------------- */
|
||||
void load_history() {
|
||||
g_hist_file = home_dir() + "/.bantam_history";
|
||||
using_history();
|
||||
/* A missing history file is not an error. */
|
||||
read_history(g_hist_file.c_str());
|
||||
}
|
||||
void add_history(std::string_view s) {
|
||||
if (s.empty()) return;
|
||||
std::string line(s);
|
||||
/* Skip an entry identical to the immediately preceding one. */
|
||||
if (history_length > 0) {
|
||||
HIST_ENTRY *last = history_get(history_base + history_length - 1);
|
||||
if (last && last->line && line == last->line) return;
|
||||
}
|
||||
::add_history(line.c_str());
|
||||
}
|
||||
void save_history() {
|
||||
if (g_hist_file.empty()) return;
|
||||
write_history(g_hist_file.c_str());
|
||||
}
|
||||
|
||||
/* ----------------------------- read helpers --------------------------- */
|
||||
std::string read_plain(std::string_view prompt, bool &ok) {
|
||||
if (!prompt.empty()) fputs(std::string(prompt).c_str(), stdout);
|
||||
fflush(stdout);
|
||||
char *line = nullptr; size_t cap = 0; ssize_t n = getline(&line, &cap, stdin);
|
||||
if (n < 0) { free(line); clearerr(stdin); ok = false; return ""; }
|
||||
while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = '\0';
|
||||
std::string r(line, (size_t)n);
|
||||
free(line);
|
||||
ok = true;
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ----------------------------- readline editor ------------------------ */
|
||||
static void ensure_readline_init() {
|
||||
static bool initialized = false;
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
rl_initialize();
|
||||
#if !defined(__APPLE__) && defined(RL_READLINE_VERSION) && (RL_READLINE_VERSION >= 0x0500)
|
||||
/* On GNU Readline (Linux, FreeBSD), terminal raw mode clears ICRNL so
|
||||
* Enter sends '\r' (rl_newline = submit) while Ctrl+J sends '\n'
|
||||
* (rl_insert = literal newline). On macOS / BSD libedit (EditLine),
|
||||
* ICRNL remains enabled in termios (translating Enter '\r' into '\n') and
|
||||
* '\n' is the sole accept-line key (ed-newline), so rebinding '\n' to
|
||||
* rl_insert prevents submitting any prompt. */
|
||||
if (!rl_library_version || std::strncmp(rl_library_version, "EditLine", 8) != 0) {
|
||||
rl_bind_key('\n', rl_insert);
|
||||
rl_bind_key('\r', rl_newline);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
std::string read_line(std::string_view prompt, bool &ok) {
|
||||
if (!is_terminal(STDIN_FILENO)) return read_plain(prompt, ok);
|
||||
ensure_readline_init();
|
||||
char *line = readline(prompt.empty() ? "" : std::string(prompt).c_str());
|
||||
setup_signal_handler();
|
||||
if (!line) {
|
||||
if (g_interrupted) {
|
||||
g_interrupted = 0;
|
||||
std::fputc('\n', stdout);
|
||||
std::fflush(stdout);
|
||||
ok = true;
|
||||
return "";
|
||||
}
|
||||
ok = false;
|
||||
return "";
|
||||
}
|
||||
std::string r(line);
|
||||
free(line);
|
||||
ok = true;
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ----------------------------- term helpers --------------------------- */
|
||||
int is_terminal(int fd) { return isatty(fd) != 0; }
|
||||
|
||||
int term_width() {
|
||||
#ifdef TIOCGWINSZ
|
||||
struct winsize ws{};
|
||||
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) return (int)ws.ws_col;
|
||||
if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) return (int)ws.ws_col;
|
||||
if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) return (int)ws.ws_col;
|
||||
#endif
|
||||
const char *c = std::getenv("COLUMNS");
|
||||
if (c && *c) { int n = std::atoi(c); if (n > 0) return n; }
|
||||
return 80;
|
||||
}
|
||||
@@ -0,0 +1,696 @@
|
||||
/* json.cpp — native RFC 8259 JSON parser/serializer, request building,
|
||||
* and non-streaming response parsing. */
|
||||
#include "bantam.hpp"
|
||||
#include <cerrno>
|
||||
#include <charconv>
|
||||
#include <climits>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
/* ----------------------------- Json methods --------------------------- */
|
||||
Json::Json() = default;
|
||||
Json::~Json() = default;
|
||||
Json::Json(const Json &) = default;
|
||||
Json::Json(Json &&) noexcept = default;
|
||||
Json &Json::operator=(const Json &) = default;
|
||||
Json &Json::operator=(Json &&) noexcept = default;
|
||||
|
||||
Json::Json(std::nullptr_t) : type(JType::Null) {}
|
||||
Json::Json(bool b) : type(JType::Bool), bval(b) {}
|
||||
Json::Json(int n) : type(JType::Int), ival(n), dval(n) {}
|
||||
Json::Json(int64_t n) : type(JType::Int), ival(n), dval((double)n) {}
|
||||
Json::Json(double d) : type(JType::Float), ival((int64_t)d), dval(d) {}
|
||||
Json::Json(const char *s) : type(JType::Str), sval(s ? s : "") {}
|
||||
Json::Json(std::string s) : type(JType::Str), sval(std::move(s)) {}
|
||||
Json::Json(std::string_view s) : type(JType::Str), sval(s) {}
|
||||
|
||||
Json Json::object() {
|
||||
Json j;
|
||||
j.type = JType::Obj;
|
||||
return j;
|
||||
}
|
||||
Json Json::array() {
|
||||
Json j;
|
||||
j.type = JType::Arr;
|
||||
return j;
|
||||
}
|
||||
|
||||
static const Json kNullJson{};
|
||||
|
||||
bool Json::empty() const {
|
||||
if (type == JType::Arr) return aval.empty();
|
||||
if (type == JType::Obj) return oval.empty();
|
||||
if (type == JType::Str) return sval.empty();
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t Json::size() const {
|
||||
if (type == JType::Arr) return aval.size();
|
||||
if (type == JType::Obj) return oval.size();
|
||||
if (type == JType::Str) return sval.size();
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool Json::contains(std::string_view k) const {
|
||||
if (type != JType::Obj) return false;
|
||||
for (auto &kv : oval) {
|
||||
if (kv.first == k) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Json &Json::operator[](std::string_view k) {
|
||||
if (type != JType::Obj) {
|
||||
*this = Json::object();
|
||||
}
|
||||
for (auto &kv : oval) {
|
||||
if (kv.first == k) return kv.second;
|
||||
}
|
||||
oval.emplace_back(std::string(k), Json{});
|
||||
return oval.back().second;
|
||||
}
|
||||
|
||||
const Json &Json::operator[](std::string_view k) const {
|
||||
if (type != JType::Obj) return kNullJson;
|
||||
for (auto &kv : oval) {
|
||||
if (kv.first == k) return kv.second;
|
||||
}
|
||||
return kNullJson;
|
||||
}
|
||||
|
||||
Json &Json::at(size_t i) {
|
||||
return aval[i];
|
||||
}
|
||||
|
||||
const Json &Json::at(size_t i) const {
|
||||
if (type != JType::Arr || i >= aval.size()) return kNullJson;
|
||||
return aval[i];
|
||||
}
|
||||
|
||||
void Json::push_back(Json v) {
|
||||
if (type != JType::Arr) {
|
||||
*this = Json::array();
|
||||
}
|
||||
aval.push_back(std::move(v));
|
||||
}
|
||||
|
||||
std::string Json::str(std::string_view def) const {
|
||||
if (type == JType::Str) return sval;
|
||||
return std::string(def);
|
||||
}
|
||||
|
||||
int64_t Json::as_int64(int64_t def) const {
|
||||
if (type == JType::Int) return ival;
|
||||
return def;
|
||||
}
|
||||
|
||||
int Json::as_int(int def) const {
|
||||
if (type != JType::Int) return def;
|
||||
if (ival > INT_MAX) return INT_MAX;
|
||||
if (ival < INT_MIN) return INT_MIN;
|
||||
return (int)ival;
|
||||
}
|
||||
|
||||
/* ----------------------------- JSON serializer ------------------------ */
|
||||
static void dump_str(std::string &out, std::string_view s) {
|
||||
out += '"';
|
||||
const unsigned char *p = (const unsigned char *)s.data();
|
||||
size_t avail = s.size();
|
||||
while (avail > 0) {
|
||||
/* Fast path: scan contiguous unescaped printable ASCII. */
|
||||
size_t run = 0;
|
||||
while (run < avail) {
|
||||
unsigned char b = p[run];
|
||||
if (b >= 0x20 && b < 0x80 && b != '"' && b != '\\') run++;
|
||||
else break;
|
||||
}
|
||||
if (run > 0) {
|
||||
out.append((const char *)p, run);
|
||||
p += run;
|
||||
avail -= run;
|
||||
if (avail == 0) break;
|
||||
}
|
||||
unsigned char c = p[0];
|
||||
if (c < 0x80) {
|
||||
p++;
|
||||
avail--;
|
||||
switch (c) {
|
||||
case '"': out += "\\\""; break;
|
||||
case '\\': out += "\\\\"; break;
|
||||
case '\b': out += "\\b"; break;
|
||||
case '\f': out += "\\f"; break;
|
||||
case '\n': out += "\\n"; break;
|
||||
case '\r': out += "\\r"; break;
|
||||
case '\t': out += "\\t"; break;
|
||||
default: {
|
||||
char ubuf[7];
|
||||
std::snprintf(ubuf, sizeof ubuf, "\\u%04x", (unsigned)c);
|
||||
out.append(ubuf, 6);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
size_t pl = 0;
|
||||
int cp = utf8_decode(p, avail, &pl);
|
||||
if (cp == 0xFFFD && pl == 1) {
|
||||
out += "\xEF\xBF\xBD";
|
||||
p++;
|
||||
avail--;
|
||||
} else {
|
||||
out.append((const char *)p, pl);
|
||||
p += pl;
|
||||
avail -= pl;
|
||||
}
|
||||
}
|
||||
}
|
||||
out += '"';
|
||||
}
|
||||
|
||||
static void dump_rec(std::string &out, const Json &j, int indent, int depth) {
|
||||
switch (j.type) {
|
||||
case JType::Null:
|
||||
out += "null";
|
||||
break;
|
||||
case JType::Bool:
|
||||
out += (j.bval ? "true" : "false");
|
||||
break;
|
||||
case JType::Int: {
|
||||
char ibuf[32];
|
||||
auto [ptr, ec] = std::to_chars(ibuf, ibuf + sizeof ibuf, j.ival);
|
||||
if (ec == std::errc()) out.append(ibuf, (size_t)(ptr - ibuf));
|
||||
else str_appendf(out, "%lld", (long long)j.ival);
|
||||
break;
|
||||
}
|
||||
case JType::Float:
|
||||
if (!std::isfinite(j.dval)) {
|
||||
out += "null";
|
||||
} else {
|
||||
char fbuf[32];
|
||||
int n = std::snprintf(fbuf, sizeof fbuf, "%.15g", j.dval);
|
||||
if (n > 0 && (size_t)n < sizeof fbuf) out.append(fbuf, (size_t)n);
|
||||
else str_appendf(out, "%.15g", j.dval);
|
||||
}
|
||||
break;
|
||||
case JType::Str:
|
||||
dump_str(out, j.sval);
|
||||
break;
|
||||
case JType::Arr:
|
||||
if (j.aval.empty()) {
|
||||
out += "[]";
|
||||
} else {
|
||||
out += '[';
|
||||
for (size_t i = 0; i < j.aval.size(); i++) {
|
||||
if (i > 0) out += ',';
|
||||
if (indent >= 0) {
|
||||
out += '\n';
|
||||
out.append((size_t)(depth + 1) * (size_t)indent, ' ');
|
||||
}
|
||||
dump_rec(out, j.aval[i], indent, depth + 1);
|
||||
}
|
||||
if (indent >= 0) {
|
||||
out += '\n';
|
||||
out.append((size_t)depth * (size_t)indent, ' ');
|
||||
}
|
||||
out += ']';
|
||||
}
|
||||
break;
|
||||
case JType::Obj:
|
||||
if (j.oval.empty()) {
|
||||
out += "{}";
|
||||
} else {
|
||||
out += '{';
|
||||
for (size_t i = 0; i < j.oval.size(); i++) {
|
||||
if (i > 0) out += ',';
|
||||
if (indent >= 0) {
|
||||
out += '\n';
|
||||
out.append((size_t)(depth + 1) * (size_t)indent, ' ');
|
||||
}
|
||||
dump_str(out, j.oval[i].first);
|
||||
out += (indent >= 0) ? ": " : ":";
|
||||
dump_rec(out, j.oval[i].second, indent, depth + 1);
|
||||
}
|
||||
if (indent >= 0) {
|
||||
out += '\n';
|
||||
out.append((size_t)depth * (size_t)indent, ' ');
|
||||
}
|
||||
out += '}';
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
std::string Json::dump(int indent) const {
|
||||
std::string out;
|
||||
out.reserve(256);
|
||||
dump_rec(out, *this, indent, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ----------------------------- JSON parser ---------------------------- */
|
||||
struct JParser {
|
||||
std::string_view src;
|
||||
size_t pos = 0;
|
||||
|
||||
void skip_ws() {
|
||||
while (pos < src.size()) {
|
||||
char c = src[pos];
|
||||
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') pos++;
|
||||
else break;
|
||||
}
|
||||
}
|
||||
|
||||
static int hex_val(char c) {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
}
|
||||
|
||||
bool parse_hex4(uint32_t &out) {
|
||||
if (pos + 4 > src.size()) return false;
|
||||
uint32_t v = 0;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
int h = hex_val(src[pos + (size_t)i]);
|
||||
if (h < 0) return false;
|
||||
v = (v << 4) | (uint32_t)h;
|
||||
}
|
||||
pos += 4;
|
||||
out = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
static void append_utf8(std::string &s, uint32_t cp) {
|
||||
if (cp <= 0x7F) {
|
||||
s += (char)cp;
|
||||
} else if (cp <= 0x7FF) {
|
||||
s += (char)(0xC0 | (cp >> 6));
|
||||
s += (char)(0x80 | (cp & 0x3F));
|
||||
} else if (cp <= 0xFFFF) {
|
||||
s += (char)(0xE0 | (cp >> 12));
|
||||
s += (char)(0x80 | ((cp >> 6) & 0x3F));
|
||||
s += (char)(0x80 | (cp & 0x3F));
|
||||
} else if (cp <= 0x10FFFF) {
|
||||
s += (char)(0xF0 | (cp >> 18));
|
||||
s += (char)(0x80 | ((cp >> 12) & 0x3F));
|
||||
s += (char)(0x80 | ((cp >> 6) & 0x3F));
|
||||
s += (char)(0x80 | (cp & 0x3F));
|
||||
} else {
|
||||
s += "\xEF\xBF\xBD";
|
||||
}
|
||||
}
|
||||
|
||||
bool parse_string(std::string &out) {
|
||||
if (pos >= src.size() || src[pos] != '"') return false;
|
||||
pos++;
|
||||
out.clear();
|
||||
const char *base = src.data();
|
||||
size_t n = src.size();
|
||||
while (pos < n) {
|
||||
/* Fast path: scan contiguous unescaped bytes >= 0x20. */
|
||||
size_t run_start = pos;
|
||||
while (pos < n) {
|
||||
unsigned char b = (unsigned char)base[pos];
|
||||
if (b == '"' || b == '\\' || b < 0x20) break;
|
||||
pos++;
|
||||
}
|
||||
if (pos > run_start) {
|
||||
out.append(base + run_start, pos - run_start);
|
||||
}
|
||||
if (pos >= n) return false;
|
||||
unsigned char c = (unsigned char)base[pos++];
|
||||
if (c == '"') return true;
|
||||
if (c < 0x20) return false;
|
||||
if (pos >= n) return false;
|
||||
char esc = base[pos++];
|
||||
switch (esc) {
|
||||
case '"': out += '"'; break;
|
||||
case '\\': out += '\\'; break;
|
||||
case '/': out += '/'; break;
|
||||
case 'b': out += '\b'; break;
|
||||
case 'f': out += '\f'; break;
|
||||
case 'n': out += '\n'; break;
|
||||
case 'r': out += '\r'; break;
|
||||
case 't': out += '\t'; break;
|
||||
case 'u': {
|
||||
uint32_t cp = 0;
|
||||
if (!parse_hex4(cp)) return false;
|
||||
if (cp >= 0xD800 && cp <= 0xDBFF) {
|
||||
if (pos + 6 <= n && base[pos] == '\\' && base[pos + 1] == 'u') {
|
||||
size_t saved = pos;
|
||||
pos += 2;
|
||||
uint32_t low = 0;
|
||||
if (parse_hex4(low) && low >= 0xDC00 && low <= 0xDFFF) {
|
||||
cp = 0x10000u + (((cp - 0xD800u) << 10) | (low - 0xDC00u));
|
||||
} else {
|
||||
pos = saved;
|
||||
cp = 0xFFFDu;
|
||||
}
|
||||
} else {
|
||||
cp = 0xFFFDu;
|
||||
}
|
||||
} else if (cp >= 0xDC00 && cp <= 0xDFFF) {
|
||||
cp = 0xFFFDu;
|
||||
}
|
||||
append_utf8(out, cp);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool parse_number(Json &out) {
|
||||
size_t start = pos;
|
||||
if (src[pos] == '-') pos++;
|
||||
if (pos >= src.size()) return false;
|
||||
if (src[pos] == '0') {
|
||||
pos++;
|
||||
if (pos < src.size() && src[pos] >= '0' && src[pos] <= '9') return false;
|
||||
} else if (src[pos] >= '1' && src[pos] <= '9') {
|
||||
while (pos < src.size() && src[pos] >= '0' && src[pos] <= '9') pos++;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
bool is_float = false;
|
||||
if (pos < src.size() && src[pos] == '.') {
|
||||
is_float = true;
|
||||
pos++;
|
||||
if (pos >= src.size() || src[pos] < '0' || src[pos] > '9') return false;
|
||||
while (pos < src.size() && src[pos] >= '0' && src[pos] <= '9') pos++;
|
||||
}
|
||||
if (pos < src.size() && (src[pos] == 'e' || src[pos] == 'E')) {
|
||||
is_float = true;
|
||||
pos++;
|
||||
if (pos < src.size() && (src[pos] == '+' || src[pos] == '-')) pos++;
|
||||
if (pos >= src.size() || src[pos] < '0' || src[pos] > '9') return false;
|
||||
while (pos < src.size() && src[pos] >= '0' && src[pos] <= '9') pos++;
|
||||
}
|
||||
const char *first = src.data() + start;
|
||||
const char *last = src.data() + pos;
|
||||
if (!is_float) {
|
||||
int64_t iv = 0;
|
||||
auto [ptr, ec] = std::from_chars(first, last, iv);
|
||||
if (ec == std::errc() && ptr == last) {
|
||||
out = Json(iv);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
char stack_num[64];
|
||||
std::string heap_num;
|
||||
const char *cstr = nullptr;
|
||||
size_t nlen = pos - start;
|
||||
if (nlen < sizeof stack_num) {
|
||||
std::memcpy(stack_num, first, nlen);
|
||||
stack_num[nlen] = '\0';
|
||||
cstr = stack_num;
|
||||
} else {
|
||||
heap_num.assign(first, nlen);
|
||||
cstr = heap_num.c_str();
|
||||
}
|
||||
errno = 0;
|
||||
char *end = nullptr;
|
||||
double dv = std::strtod(cstr, &end);
|
||||
if (end != cstr + nlen || !std::isfinite(dv)) return false;
|
||||
out = Json(dv);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool parse_value(Json &out, int depth) {
|
||||
if (depth > 256) return false;
|
||||
skip_ws();
|
||||
if (pos >= src.size()) return false;
|
||||
char c = src[pos];
|
||||
if (c == 'n') {
|
||||
if (src.substr(pos, 4) != "null") return false;
|
||||
pos += 4;
|
||||
out = Json(nullptr);
|
||||
return true;
|
||||
}
|
||||
if (c == 't') {
|
||||
if (src.substr(pos, 4) != "true") return false;
|
||||
pos += 4;
|
||||
out = Json(true);
|
||||
return true;
|
||||
}
|
||||
if (c == 'f') {
|
||||
if (src.substr(pos, 5) != "false") return false;
|
||||
pos += 5;
|
||||
out = Json(false);
|
||||
return true;
|
||||
}
|
||||
if (c == '"') {
|
||||
std::string s;
|
||||
if (!parse_string(s)) return false;
|
||||
out = Json(std::move(s));
|
||||
return true;
|
||||
}
|
||||
if (c == '[') {
|
||||
pos++;
|
||||
skip_ws();
|
||||
out = Json::array();
|
||||
if (pos < src.size() && src[pos] == ']') {
|
||||
pos++;
|
||||
return true;
|
||||
}
|
||||
while (true) {
|
||||
Json elem;
|
||||
if (!parse_value(elem, depth + 1)) return false;
|
||||
out.aval.push_back(std::move(elem));
|
||||
skip_ws();
|
||||
if (pos < src.size() && src[pos] == ',') {
|
||||
pos++;
|
||||
continue;
|
||||
}
|
||||
if (pos < src.size() && src[pos] == ']') {
|
||||
pos++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (c == '{') {
|
||||
pos++;
|
||||
skip_ws();
|
||||
out = Json::object();
|
||||
if (pos < src.size() && src[pos] == '}') {
|
||||
pos++;
|
||||
return true;
|
||||
}
|
||||
while (true) {
|
||||
skip_ws();
|
||||
std::string key;
|
||||
if (!parse_string(key)) return false;
|
||||
skip_ws();
|
||||
if (pos >= src.size() || src[pos] != ':') return false;
|
||||
pos++;
|
||||
Json val;
|
||||
if (!parse_value(val, depth + 1)) return false;
|
||||
out[key] = std::move(val);
|
||||
skip_ws();
|
||||
if (pos < src.size() && src[pos] == ',') {
|
||||
pos++;
|
||||
continue;
|
||||
}
|
||||
if (pos < src.size() && src[pos] == '}') {
|
||||
pos++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (c == '-' || (c >= '0' && c <= '9')) {
|
||||
return parse_number(out);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
bool Json::parse(std::string_view src, Json &out) {
|
||||
JParser p{src, 0};
|
||||
Json tmp;
|
||||
if (!p.parse_value(tmp, 0)) return false;
|
||||
p.skip_ws();
|
||||
if (p.pos != src.size()) return false;
|
||||
out = std::move(tmp);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ----------------------------- message helpers ------------------------ */
|
||||
/* The tool definitions sent with every request. */
|
||||
static const char *TOOLS_JSON = R"JSON([
|
||||
{"type":"function","function":{
|
||||
"name":"bash",
|
||||
"description":"Executes a given bash command in a shell session, returning its output and exit code.",
|
||||
"parameters":{"type":"object","properties":{
|
||||
"command":{"type":"string","description":"The command to execute"},
|
||||
"workdir":{"type":"string","description":"The working directory to run the command in. Defaults to the current directory."}
|
||||
},"required":["command"]}}},
|
||||
{"type":"function","function":{
|
||||
"name":"read",
|
||||
"description":"Read a file or directory from the local filesystem. For files, returns numbered lines prefixed as `<line>: <content>`. For directories, returns entry names with trailing slashes for subdirectories.",
|
||||
"parameters":{"type":"object","properties":{
|
||||
"filePath":{"type":"string","description":"The path to the file or directory to read"},
|
||||
"offset":{"type":"integer","description":"The line number to start reading from (1-indexed, defaults to 1)"},
|
||||
"limit":{"type":"integer","description":"The maximum number of lines to read (defaults to 2000)"}
|
||||
},"required":["filePath"]}}},
|
||||
{"type":"function","function":{
|
||||
"name":"write",
|
||||
"description":"Write content to a file. With ONLY filePath and content, the whole file is overwritten exactly (parent directories are created). For a SELECTIVE EDIT choose EXACTLY ONE mode: (1) find + content: replace the unique exact text in `find` with `content` - no line numbers needed, the recommended way to change an existing line; (2) append:true + content: add lines at the end; (3) lineOffset + optional delLines: insert before that 1-indexed line, or REPLACE delLines lines with content; (4) byteOffset + optional delBytes: exact byte splice. IMPORTANT: to REPLACE a line you MUST use find+content or delLines:1; with delLines omitted the call INSERTS a new line and the original line stays (a common source of duplicate lines). Never combine modes. The result states what happened in line numbers.",
|
||||
"parameters":{"type":"object","properties":{
|
||||
"filePath":{"type":"string","description":"The path to the file to write"},
|
||||
"content":{"type":"string","description":"The content to write. Written verbatim, including CRLF and Unicode. May be empty to delete lines."},
|
||||
"find":{"type":"string","description":"Exact existing text to replace with `content` (unique occurrence). No line numbers needed. Prefer this for changing an existing line. If the text occurs more than once, add surrounding context or set replaceAll:true."},
|
||||
"replaceAll":{"type":"boolean","description":"With `find`, replace every occurrence instead of requiring a unique match."},
|
||||
"append":{"type":"boolean","description":"true = append content at the end of the file. Do not combine with lineOffset/byteOffset/delLines/delBytes."},
|
||||
"lineOffset":{"type":"integer","description":"1-indexed line number where writing begins (1 = first line, matching the read tool's numbering). A value past the last line appends. Do not combine with find, append, byteOffset or delBytes."},
|
||||
"delLines":{"type":"integer","description":"Number of lines to REPLACE starting at lineOffset (default 0 = pure insert, original line is kept). Use 1 to replace one line. Only valid with lineOffset."},
|
||||
"byteOffset":{"type":"integer","description":"Byte offset for an exact byte edit. Must be <= file size. Do not combine with find, append, lineOffset or delLines."},
|
||||
"delBytes":{"type":"integer","description":"Number of bytes to delete starting at byteOffset (default 0). Only valid with byteOffset."}
|
||||
},"required":["filePath","content"]}}}
|
||||
])JSON";
|
||||
|
||||
void serialize_message_json(Json &obj, const Message &m) {
|
||||
obj = Json::object();
|
||||
obj["role"] = m.role.empty() ? "" : m.role;
|
||||
if (!m.content.empty()) obj["content"] = m.content;
|
||||
if (!m.reasoning.empty()) obj["reasoning_content"] = m.reasoning;
|
||||
if (!m.calls.empty()) {
|
||||
Json arr = Json::array();
|
||||
for (auto &tc : m.calls) {
|
||||
Json t = Json::object();
|
||||
if (!tc.id.empty()) t["id"] = tc.id;
|
||||
t["type"] = "function";
|
||||
Json fn = Json::object();
|
||||
fn["name"] = tc.name.empty() ? "" : tc.name;
|
||||
fn["arguments"] = tc.arguments.empty() ? "{}" : tc.arguments;
|
||||
t["function"] = std::move(fn);
|
||||
arr.push_back(std::move(t));
|
||||
}
|
||||
obj["tool_calls"] = std::move(arr);
|
||||
}
|
||||
if (!m.tool_call_id.empty()) obj["tool_call_id"] = m.tool_call_id;
|
||||
}
|
||||
|
||||
void parse_message_json(const Json &obj, Message &m) {
|
||||
m = Message{};
|
||||
if (!obj.is_object()) return;
|
||||
m.role = obj["role"].str("user");
|
||||
m.content = obj["content"].str();
|
||||
m.reasoning = obj["reasoning_content"].str();
|
||||
m.tool_call_id = obj["tool_call_id"].str();
|
||||
const Json &tcs = obj["tool_calls"];
|
||||
if (tcs.is_array()) {
|
||||
for (auto &tc : tcs.aval) {
|
||||
if (!tc.is_object()) continue;
|
||||
ToolCall t;
|
||||
t.id = tc["id"].str();
|
||||
const Json &fn = tc["function"];
|
||||
if (fn.is_object()) {
|
||||
t.name = fn["name"].str();
|
||||
t.arguments = fn["arguments"].str();
|
||||
}
|
||||
m.calls.push_back(std::move(t));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------- request / response --------------------- */
|
||||
std::string build_request_json(const Cfg &cfg, const Messages &msgs,
|
||||
bool use_tools, bool stream) {
|
||||
Json root = Json::object();
|
||||
root["model"] = cfg.model;
|
||||
root["temperature"] = cfg.temperature;
|
||||
Json arr = Json::array();
|
||||
arr.aval.reserve(msgs.items.size());
|
||||
for (auto &m : msgs.items) {
|
||||
Json mo;
|
||||
serialize_message_json(mo, m);
|
||||
arr.push_back(std::move(mo));
|
||||
}
|
||||
root["messages"] = std::move(arr);
|
||||
root["stream"] = stream;
|
||||
if (use_tools) {
|
||||
/* Parse on every request rather than caching a process-lifetime static:
|
||||
* the tool definitions must always be the ones shipped with this build. */
|
||||
Json kTools;
|
||||
Json::parse(TOOLS_JSON, kTools);
|
||||
root["tools"] = std::move(kTools);
|
||||
}
|
||||
if (stream) {
|
||||
Json so = Json::object();
|
||||
so["include_usage"] = true;
|
||||
root["stream_options"] = std::move(so);
|
||||
}
|
||||
/* Forward non-internal raw params, parsed as JSON when possible. */
|
||||
for (auto &kv : cfg.raw) {
|
||||
if (internal_key(kv.first)) continue;
|
||||
Json jv;
|
||||
if (Json::parse(kv.second, jv)) {
|
||||
root[kv.first] = std::move(jv);
|
||||
} else {
|
||||
root[kv.first] = kv.second;
|
||||
}
|
||||
}
|
||||
return root.dump();
|
||||
}
|
||||
|
||||
bool parse_nonstream_response(std::string_view body, Message &out, Usage &usage) {
|
||||
out = Message{};
|
||||
usage = Usage{};
|
||||
Json root_mut;
|
||||
if (!Json::parse(body, root_mut) || !root_mut.is_object()) return false;
|
||||
const Json &root = root_mut;
|
||||
const Json &choices = root["choices"];
|
||||
if (!choices.is_array() || choices.empty()) return false;
|
||||
const Json &ch = choices.at(0);
|
||||
if (!ch.is_object()) return false;
|
||||
const Json &msg = ch["message"];
|
||||
if (!msg.is_object()) return false;
|
||||
out.role = msg["role"].str("assistant");
|
||||
out.content = msg["content"].str();
|
||||
std::string reas = msg["reasoning_content"].str();
|
||||
if (reas.empty()) reas = msg["reasoning"].str();
|
||||
if (reas.empty()) reas = msg["thought"].str();
|
||||
if (!reas.empty()) out.reasoning = std::move(reas);
|
||||
const Json &tcs = msg["tool_calls"];
|
||||
if (tcs.is_array()) {
|
||||
for (auto &tc : tcs.aval) {
|
||||
if (!tc.is_object()) continue;
|
||||
ToolCall t;
|
||||
t.id = tc["id"].str();
|
||||
const Json &fn = tc["function"];
|
||||
if (fn.is_object()) {
|
||||
t.name = fn["name"].str();
|
||||
t.arguments = fn["arguments"].str("{}");
|
||||
}
|
||||
out.calls.push_back(std::move(t));
|
||||
}
|
||||
}
|
||||
const Json &u = root["usage"];
|
||||
if (u.is_object()) {
|
||||
usage.prompt_tokens = u["prompt_tokens"].as_int();
|
||||
usage.completion_tokens = u["completion_tokens"].as_int();
|
||||
usage.total_tokens = u["total_tokens"].as_int();
|
||||
const Json &ptd = u["prompt_tokens_details"];
|
||||
if (ptd.is_object()) {
|
||||
usage.cached_tokens = ptd["cached_tokens"].as_int();
|
||||
}
|
||||
if (usage.cached_tokens == 0) {
|
||||
usage.cached_tokens = u["cached_tokens"].as_int();
|
||||
}
|
||||
if (usage.cached_tokens > usage.prompt_tokens) {
|
||||
/* Some providers (e.g. Cohere models on OpenRouter) report
|
||||
* prompt_tokens as the *uncached* portion and cached_tokens as an
|
||||
* *additional* amount, instead of the OpenAI convention where
|
||||
* cached_tokens is a subset of prompt_tokens. Normalize so
|
||||
* prompt_tokens always holds the true total input. */
|
||||
usage.prompt_tokens += usage.cached_tokens;
|
||||
}
|
||||
}
|
||||
usage.model = root["model"].str();
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,599 @@
|
||||
/* llm.cpp — libcurl HTTP client, Fibonacci backoff,
|
||||
* streaming SSE parser and the llm() dispatch function. */
|
||||
#include "bantam.hpp"
|
||||
#include <array>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <curl/curl.h>
|
||||
#include <memory>
|
||||
#include <unistd.h>
|
||||
|
||||
/* ----------------------------- memory callback ------------------------ */
|
||||
static size_t mem_cb(char *ptr, size_t sz, size_t nm, void *ud) {
|
||||
std::string *m = (std::string *)ud;
|
||||
size_t total = sz * nm;
|
||||
m->append((const char *)ptr, total);
|
||||
return total;
|
||||
}
|
||||
|
||||
static int xferinfo_cb(void *clientp, curl_off_t, curl_off_t, curl_off_t, curl_off_t) {
|
||||
volatile int *interrupted = (volatile int *)clientp;
|
||||
return (interrupted && *interrupted) ? 1 : 0;
|
||||
}
|
||||
|
||||
/* ----------------------------- curl handle & headers ------------------ */
|
||||
static CURL *g_shared_curl = nullptr;
|
||||
|
||||
static CURL *get_shared_curl() {
|
||||
if (!g_shared_curl) {
|
||||
g_shared_curl = curl_easy_init();
|
||||
} else {
|
||||
curl_easy_reset(g_shared_curl);
|
||||
}
|
||||
return g_shared_curl;
|
||||
}
|
||||
|
||||
void http_cleanup() {
|
||||
if (g_shared_curl) {
|
||||
curl_easy_cleanup(g_shared_curl);
|
||||
g_shared_curl = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
struct CurlHeaders {
|
||||
curl_slist *list = nullptr;
|
||||
CurlHeaders() = default;
|
||||
~CurlHeaders() { if (list) curl_slist_free_all(list); }
|
||||
CurlHeaders(const CurlHeaders &) = delete;
|
||||
CurlHeaders &operator=(const CurlHeaders &) = delete;
|
||||
void append(std::string_view s) {
|
||||
std::string tmp(s);
|
||||
curl_slist *next = curl_slist_append(list, tmp.c_str());
|
||||
if (next) list = next;
|
||||
}
|
||||
};
|
||||
|
||||
/* ----------------------------- proxy + headers ------------------------ */
|
||||
static void set_proxy(CURL *c) {
|
||||
const char *socks = std::getenv("SOCKS_PROXY");
|
||||
if (!socks || !*socks) socks = std::getenv("socks_proxy");
|
||||
if (socks && *socks) {
|
||||
std::string buf;
|
||||
if (std::strstr(socks, "://")) buf = socks;
|
||||
else buf = "socks5://" + std::string(socks);
|
||||
curl_easy_setopt(c, CURLOPT_PROXY, buf.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
static void apply_common_curl_opts(CURL *c, volatile int *interrupted) {
|
||||
curl_easy_setopt(c, CURLOPT_NOSIGNAL, 1L);
|
||||
curl_easy_setopt(c, CURLOPT_NOPROGRESS, 0L);
|
||||
curl_easy_setopt(c, CURLOPT_XFERINFOFUNCTION, xferinfo_cb);
|
||||
curl_easy_setopt(c, CURLOPT_XFERINFODATA, (void *)interrupted);
|
||||
curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1L);
|
||||
curl_easy_setopt(c, CURLOPT_TCP_KEEPIDLE, 30L);
|
||||
curl_easy_setopt(c, CURLOPT_TCP_KEEPINTVL, 15L);
|
||||
curl_easy_setopt(c, CURLOPT_USERAGENT, "Mozilla/5.0 Bantam/nightly-cpp");
|
||||
set_proxy(c);
|
||||
}
|
||||
|
||||
static void apply_llm_headers(CurlHeaders &h, const Cfg &cfg) {
|
||||
h.append("Content-Type: application/json");
|
||||
/* Suppress Expect: 100-continue so large POST bodies are sent immediately
|
||||
* without waiting for a 100 Continue round-trip or hanging behind proxies. */
|
||||
h.append("Expect:");
|
||||
h.append(sfmt("x-opencode-session: %s", project_id().c_str()));
|
||||
if (!cfg.api_key.empty() && cfg.api_key != "-") {
|
||||
h.append(sfmt("Authorization: Bearer %s", cfg.api_key.c_str()));
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------- http_get ------------------------------- */
|
||||
int http_get(Cfg &cfg, std::string_view url, std::string &body, long &code,
|
||||
std::string &errmsg) {
|
||||
CURL *c = get_shared_curl();
|
||||
if (!c) { errmsg = "curl init failed"; return -1; }
|
||||
std::string url_s(url);
|
||||
CurlHeaders headers;
|
||||
headers.append(sfmt("x-opencode-session: %s", project_id().c_str()));
|
||||
if (!cfg.api_key.empty() && cfg.api_key != "-") {
|
||||
headers.append(sfmt("Authorization: Bearer %s", cfg.api_key.c_str()));
|
||||
}
|
||||
apply_common_curl_opts(c, &g_interrupted);
|
||||
curl_easy_setopt(c, CURLOPT_URL, url_s.c_str());
|
||||
curl_easy_setopt(c, CURLOPT_HTTPGET, 1L);
|
||||
if (headers.list) curl_easy_setopt(c, CURLOPT_HTTPHEADER, headers.list);
|
||||
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, mem_cb);
|
||||
curl_easy_setopt(c, CURLOPT_WRITEDATA, &body);
|
||||
long cfg_t = cfg.timeout > 0 ? cfg.timeout : 15;
|
||||
long conn_t = (cfg_t < 10) ? cfg_t : 10;
|
||||
long tot_t = (cfg_t < 15) ? cfg_t : 15;
|
||||
curl_easy_setopt(c, CURLOPT_CONNECTTIMEOUT, conn_t);
|
||||
curl_easy_setopt(c, CURLOPT_TIMEOUT, tot_t);
|
||||
curl_easy_setopt(c, CURLOPT_LOW_SPEED_LIMIT, 1L);
|
||||
curl_easy_setopt(c, CURLOPT_LOW_SPEED_TIME, tot_t);
|
||||
CURLcode res = curl_easy_perform(c);
|
||||
curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
|
||||
if (res != CURLE_OK) {
|
||||
errmsg = (res == CURLE_ABORTED_BY_CALLBACK || g_interrupted)
|
||||
? "interrupted"
|
||||
: curl_easy_strerror(res);
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ----------------------------- token estimate ------------------------- */
|
||||
static int est_tokens_msgs(const Messages &msgs) {
|
||||
int chars = 0;
|
||||
for (auto &m : msgs.items) {
|
||||
if (!m.content.empty()) chars += (int)m.content.size();
|
||||
if (!m.reasoning.empty()) chars += (int)m.reasoning.size();
|
||||
for (auto &tc : m.calls) {
|
||||
if (!tc.name.empty()) chars += (int)tc.name.size();
|
||||
if (!tc.arguments.empty()) chars += (int)tc.arguments.size();
|
||||
}
|
||||
}
|
||||
if (chars == 0) return 0;
|
||||
int t = chars / 4;
|
||||
return t > 0 ? t : 1;
|
||||
}
|
||||
static int est_tokens_msg(const Message &m) {
|
||||
int chars = 0;
|
||||
if (!m.content.empty()) chars += (int)m.content.size();
|
||||
if (!m.reasoning.empty()) chars += (int)m.reasoning.size();
|
||||
for (auto &tc : m.calls) {
|
||||
if (!tc.name.empty()) chars += (int)tc.name.size();
|
||||
if (!tc.arguments.empty()) chars += (int)tc.arguments.size();
|
||||
}
|
||||
if (chars == 0) return 0;
|
||||
int t = chars / 4;
|
||||
return t > 0 ? t : 1;
|
||||
}
|
||||
|
||||
/* ----------------------------- streaming parser ----------------------- */
|
||||
struct StreamCtx {
|
||||
std::string content, reas, line_buf, buf, raw;
|
||||
std::vector<std::string> tbl;
|
||||
Usage last_usage;
|
||||
std::vector<ToolCall> tcs;
|
||||
std::vector<std::string> tcs_filt_args;
|
||||
std::vector<size_t> tcs_filt_pos;
|
||||
std::vector<int> tcs_idx;
|
||||
size_t live_printed_len = 0;
|
||||
int tool_calls_shown = 0;
|
||||
int tty = 0;
|
||||
int live_idx = -1;
|
||||
MdState md;
|
||||
int in_reasoning = 0;
|
||||
int done = 0;
|
||||
int erase_pending = 0;
|
||||
volatile int *interrupted = nullptr;
|
||||
};
|
||||
|
||||
static void advance_filtered_args(StreamCtx *sc, int slot, bool flush_all) {
|
||||
const std::string &raw_args = sc->tcs[slot].arguments;
|
||||
size_t pos = sc->tcs_filt_pos[slot];
|
||||
if (pos >= raw_args.size()) return;
|
||||
std::string_view rem = std::string_view(raw_args).substr(pos);
|
||||
if (!flush_all) {
|
||||
/* Hold back an incomplete trailing multi-byte UTF-8 sequence until the
|
||||
* next chunk arrives. */
|
||||
size_t back = 0;
|
||||
while (back < 3 && back < rem.size()) {
|
||||
unsigned char b = (unsigned char)rem[rem.size() - 1 - back];
|
||||
if ((b & 0x80) == 0) break; /* ASCII */
|
||||
if ((b & 0xC0) == 0xC0) { /* UTF-8 lead byte */
|
||||
size_t need = ((b & 0xE0) == 0xC0) ? 2 : ((b & 0xF0) == 0xE0) ? 3 : 4;
|
||||
if (back + 1 < need) rem.remove_suffix(back + 1);
|
||||
break;
|
||||
}
|
||||
back++;
|
||||
}
|
||||
}
|
||||
if (!rem.empty()) {
|
||||
sc->tcs_filt_args[slot] += filter_text(rem);
|
||||
sc->tcs_filt_pos[slot] = pos + rem.size();
|
||||
}
|
||||
}
|
||||
|
||||
static void stream_upsert_tc(StreamCtx *sc, int idx, std::string_view id,
|
||||
std::string_view name, std::string_view args) {
|
||||
int slot = -1;
|
||||
for (size_t i = 0; i < sc->tcs_idx.size(); i++)
|
||||
if (sc->tcs_idx[i] == idx) { slot = (int)i; break; }
|
||||
if (slot < 0) {
|
||||
slot = (int)sc->tcs.size();
|
||||
sc->tcs.emplace_back();
|
||||
sc->tcs_filt_args.emplace_back();
|
||||
sc->tcs_filt_pos.push_back(0);
|
||||
sc->tcs_idx.push_back(idx);
|
||||
}
|
||||
if (!id.empty()) sc->tcs[slot].id = std::string(id);
|
||||
if (!name.empty()) sc->tcs[slot].name += std::string(name);
|
||||
if (!args.empty()) {
|
||||
sc->tcs[slot].arguments += std::string(args);
|
||||
advance_filtered_args(sc, slot, false);
|
||||
}
|
||||
}
|
||||
|
||||
static void print_live_delta(StreamCtx *sc, int slot, bool closed) {
|
||||
if (closed) advance_filtered_args(sc, slot, true);
|
||||
const ToolCall &t = sc->tcs[slot];
|
||||
const std::string &fa = sc->tcs_filt_args[slot];
|
||||
bool has_args = closed || !t.arguments.empty();
|
||||
size_t prefix_len = 12 + t.name.size(); /* "[tool call: " + name */
|
||||
size_t total_len = prefix_len + (has_args ? (1 + fa.size() + (closed ? 2 : 0)) : 0);
|
||||
size_t cur = sc->live_printed_len;
|
||||
if (total_len <= cur) return;
|
||||
|
||||
std::string delta;
|
||||
delta.reserve(total_len - cur);
|
||||
auto emit_part = [&](std::string_view part, size_t part_start) {
|
||||
size_t part_end = part_start + part.size();
|
||||
if (part_end <= cur) return;
|
||||
size_t off = (cur > part_start) ? (cur - part_start) : 0;
|
||||
delta.append(part.substr(off));
|
||||
};
|
||||
size_t off = 0;
|
||||
emit_part("[tool call: ", off); off += 12;
|
||||
emit_part(t.name, off); off += t.name.size();
|
||||
if (has_args) {
|
||||
emit_part("(", off); off += 1;
|
||||
emit_part(fa, off); off += fa.size();
|
||||
if (closed) {
|
||||
emit_part(")]", off); off += 2;
|
||||
}
|
||||
}
|
||||
cprint(delta, std::array{33});
|
||||
sc->live_printed_len = total_len;
|
||||
}
|
||||
|
||||
static void finish_live(StreamCtx *sc, bool closed) {
|
||||
if (sc->live_idx < 0) return;
|
||||
print_live_delta(sc, sc->live_idx, closed);
|
||||
sc->live_printed_len = 0;
|
||||
sc->live_idx = -1;
|
||||
/* The tool call marker must always terminate its own line so the
|
||||
* following [tool result: ...] header is separated from it by a
|
||||
* newline (in streaming mode the marker is shown here and not
|
||||
* reprinted by the caller). */
|
||||
printf("\n");
|
||||
fflush(stdout);
|
||||
}
|
||||
static void step_live(StreamCtx *sc) {
|
||||
if (!sc->tty || sc->tcs.empty()) return;
|
||||
int cur = (int)sc->tcs.size() - 1;
|
||||
if (sc->live_idx != -1 && sc->live_idx != cur) finish_live(sc, true);
|
||||
if (sc->live_idx == -1) { sc->live_idx = cur; sc->live_printed_len = 0; }
|
||||
print_live_delta(sc, cur, false);
|
||||
sc->tool_calls_shown = 1;
|
||||
}
|
||||
|
||||
static void flush_tbl(StreamCtx *sc) {
|
||||
if (!sc->tbl.empty()) {
|
||||
render_table_print(sc->tbl);
|
||||
sc->tbl.clear();
|
||||
}
|
||||
}
|
||||
|
||||
static void stream_maybe_erase(StreamCtx *sc) {
|
||||
if (sc->erase_pending) {
|
||||
if (g_col) printf("\r\033[K");
|
||||
sc->erase_pending = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static void stream_handle_data(StreamCtx *sc, std::string_view data) {
|
||||
if (data == "[DONE]") { sc->done = 1; return; }
|
||||
Json d_mut;
|
||||
if (!Json::parse(data, d_mut) || !d_mut.is_object()) return;
|
||||
const Json &d = d_mut;
|
||||
const Json &u = d["usage"];
|
||||
if (u.is_object()) {
|
||||
int pt = u["prompt_tokens"].as_int();
|
||||
int tt = u["total_tokens"].as_int();
|
||||
if (pt > 0 || tt > 0) {
|
||||
sc->last_usage.prompt_tokens = pt;
|
||||
sc->last_usage.completion_tokens = u["completion_tokens"].as_int();
|
||||
sc->last_usage.total_tokens = tt;
|
||||
/* Resolve this chunk's cached-token count only when the chunk actually
|
||||
* reports it, so a later chunk that omits the field can never clobber a
|
||||
* prior value (nor can a stale value spuriously inflate the total). */
|
||||
const Json &ptd = u["prompt_tokens_details"];
|
||||
int chunk_cached = -1;
|
||||
if (ptd.is_object() && ptd.contains("cached_tokens"))
|
||||
chunk_cached = ptd["cached_tokens"].as_int();
|
||||
else if (u.contains("cached_tokens"))
|
||||
chunk_cached = u["cached_tokens"].as_int();
|
||||
if (chunk_cached >= 0) {
|
||||
sc->last_usage.cached_tokens = chunk_cached;
|
||||
/* Some providers (e.g. Cohere on OpenRouter) report prompt_tokens as the
|
||||
* *uncached* portion and cached_tokens as an *additional* amount rather
|
||||
* than a subset. Fold cached into the true total input so the breakdown
|
||||
* and the context percentage stay correct. */
|
||||
if (chunk_cached > sc->last_usage.prompt_tokens)
|
||||
sc->last_usage.prompt_tokens += chunk_cached;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (d["model"].is_string()) {
|
||||
sc->last_usage.model = d["model"].str();
|
||||
}
|
||||
const Json &choices = d["choices"];
|
||||
if (!choices.is_array() || choices.empty()) return;
|
||||
const Json &ch = choices.at(0);
|
||||
if (!ch.is_object()) return;
|
||||
const Json &delta = ch["delta"];
|
||||
if (!delta.is_object()) return;
|
||||
|
||||
std::string rc = delta["reasoning_content"].str();
|
||||
if (rc.empty()) rc = delta["reasoning"].str();
|
||||
if (rc.empty()) rc = delta["thought"].str();
|
||||
if (!rc.empty()) {
|
||||
stream_maybe_erase(sc);
|
||||
if (!sc->in_reasoning) {
|
||||
if (!sc->content.empty()) {
|
||||
flush_tbl(sc);
|
||||
if (!sc->line_buf.empty()) { render_md_line_print(sc->line_buf, sc->md); sc->line_buf.clear(); }
|
||||
printf("\n");
|
||||
}
|
||||
cprint("--- reasoning start ---\n", std::array{36});
|
||||
sc->in_reasoning = true;
|
||||
}
|
||||
cprint(rc, std::array{2});
|
||||
sc->reas += rc;
|
||||
}
|
||||
std::string ct = delta["content"].str();
|
||||
if (!ct.empty()) {
|
||||
stream_maybe_erase(sc);
|
||||
if (sc->in_reasoning) { cprint("\n--- reasoning end ---\n", std::array{36}); sc->in_reasoning = false; }
|
||||
sc->content += ct;
|
||||
sc->line_buf += ct;
|
||||
size_t lpos = 0;
|
||||
while (true) {
|
||||
auto nl = sc->line_buf.find('\n', lpos);
|
||||
if (nl == std::string::npos) break;
|
||||
std::string_view cur_sv = std::string_view(sc->line_buf).substr(lpos, nl - lpos);
|
||||
lpos = nl + 1;
|
||||
/* Inside a code block every line is rendered verbatim as code; only
|
||||
* outside a code block do table-shaped lines get accumulated for
|
||||
* box-drawing table rendering. */
|
||||
if (sc->md.in_code || !is_table_line(cur_sv)) {
|
||||
flush_tbl(sc);
|
||||
render_md_line_print(cur_sv, sc->md);
|
||||
} else {
|
||||
sc->tbl.emplace_back(cur_sv);
|
||||
}
|
||||
}
|
||||
if (lpos > 0) sc->line_buf.erase(0, lpos);
|
||||
}
|
||||
const Json &tcs = delta["tool_calls"];
|
||||
if (tcs.is_array()) {
|
||||
stream_maybe_erase(sc);
|
||||
if (sc->in_reasoning) { cprint("\n--- reasoning end ---\n", std::array{36}); sc->in_reasoning = false; }
|
||||
if (sc->live_idx == -1) {
|
||||
flush_tbl(sc);
|
||||
if (!sc->line_buf.empty()) { render_md_line_print(sc->line_buf, sc->md); sc->line_buf.clear(); }
|
||||
}
|
||||
for (auto &tc : tcs.aval) {
|
||||
if (!tc.is_object()) continue;
|
||||
int idx = tc["index"].as_int();
|
||||
std::string id = tc["id"].str();
|
||||
std::string name, args;
|
||||
const Json &fn = tc["function"];
|
||||
if (fn.is_object()) {
|
||||
name = fn["name"].str();
|
||||
args = fn["arguments"].str();
|
||||
}
|
||||
stream_upsert_tc(sc, idx, id, name, args);
|
||||
}
|
||||
step_live(sc);
|
||||
}
|
||||
}
|
||||
|
||||
static int stream_feed(StreamCtx *sc, const char *data, size_t len,
|
||||
volatile int *interrupted) {
|
||||
sc->interrupted = interrupted;
|
||||
sc->buf.append(data, len);
|
||||
size_t pos = 0;
|
||||
while (true) {
|
||||
auto nl = sc->buf.find('\n', pos);
|
||||
if (nl == std::string::npos) break;
|
||||
std::string_view line = std::string_view(sc->buf).substr(pos, nl - pos);
|
||||
pos = nl + 1;
|
||||
while (!line.empty() && (line.back() == '\r' || line.back() == ' ' || line.back() == '\t'))
|
||||
line.remove_suffix(1);
|
||||
if (line.starts_with("data:")) {
|
||||
line.remove_prefix(5);
|
||||
while (!line.empty() && line.front() == ' ') line.remove_prefix(1);
|
||||
stream_handle_data(sc, line);
|
||||
}
|
||||
if (sc->done) break;
|
||||
if (*interrupted) {
|
||||
sc->buf.erase(0, pos);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
if (pos > 0) sc->buf.erase(0, pos);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void stream_finish(StreamCtx *sc) {
|
||||
flush_tbl(sc);
|
||||
if (!sc->line_buf.empty()) {
|
||||
std::string cur = sc->line_buf;
|
||||
if (!sc->md.in_code && is_table_line(cur)) {
|
||||
sc->tbl.push_back(cur);
|
||||
flush_tbl(sc);
|
||||
} else {
|
||||
render_md_line_print(cur, sc->md);
|
||||
}
|
||||
sc->line_buf.clear();
|
||||
}
|
||||
if (sc->live_idx >= 0) finish_live(sc, true);
|
||||
if (sc->in_reasoning) { cprint("\n--- reasoning end ---\n", std::array{36}); sc->in_reasoning = false; }
|
||||
}
|
||||
|
||||
static void stream_result(StreamCtx *sc, Message &out, Usage &usage) {
|
||||
out = Message{};
|
||||
out.role = "assistant";
|
||||
out.calls_shown = sc->tool_calls_shown;
|
||||
if (!sc->content.empty()) out.content = std::move(sc->content);
|
||||
if (!sc->reas.empty()) out.reasoning = std::move(sc->reas);
|
||||
for (auto &t : sc->tcs) out.calls.push_back(std::move(t));
|
||||
usage = sc->last_usage;
|
||||
if (usage.total_tokens == 0 && usage.prompt_tokens > 0)
|
||||
usage.total_tokens = usage.prompt_tokens + usage.completion_tokens;
|
||||
}
|
||||
|
||||
/* ----------------------------- streaming write cb --------------------- */
|
||||
static size_t stream_write_cb(char *ptr, size_t sz, size_t nm, void *ud) {
|
||||
StreamCtx *sc = (StreamCtx *)ud;
|
||||
size_t total = sz * nm;
|
||||
if (*sc->interrupted) return 0;
|
||||
/* Cap raw error buffer at 4096 bytes; http_err_body only uses 4000 bytes. */
|
||||
if (sc->raw.size() < 4096) {
|
||||
size_t rem = 4096 - sc->raw.size();
|
||||
sc->raw.append((const char *)ptr, total < rem ? total : rem);
|
||||
}
|
||||
int r = stream_feed(sc, ptr, total, sc->interrupted);
|
||||
if (r != 0 || *sc->interrupted) return 0;
|
||||
return total;
|
||||
}
|
||||
|
||||
/* ----------------------------- llm() ---------------------------------- */
|
||||
static void sleep_interruptible(int secs, volatile int *interrupted) {
|
||||
struct timespec ts{0, 100000000L};
|
||||
for (int i = 0; i < secs * 10; i++) {
|
||||
if (*interrupted) return;
|
||||
nanosleep(&ts, nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
static std::string http_err_body(const StreamCtx *sc, const std::string *m, long code) {
|
||||
std::string_view b = sc ? std::string_view(sc->raw) : (m ? std::string_view(*m) : "");
|
||||
b = utf8_truncate(b, 4000);
|
||||
return sfmt("HTTP %ld: %.*s", code, (int)b.size(), b.data());
|
||||
}
|
||||
|
||||
int llm(Cfg &cfg, Messages &msgs, bool use_tools, Message &out, Usage &usage,
|
||||
std::string &errmsg, volatile int *interrupted) {
|
||||
out = Message{};
|
||||
usage = Usage{};
|
||||
if (*interrupted) { errmsg = "interrupted"; return -1; }
|
||||
|
||||
bool stream = (cfg.force_stream >= 0)
|
||||
? (cfg.force_stream != 0)
|
||||
: (cfg.stream != 0);
|
||||
std::string payload = build_request_json(cfg, msgs, use_tools, stream);
|
||||
std::string url = cfg.endpoint;
|
||||
while (!url.empty() && url.back() == '/') url.pop_back();
|
||||
url += "/chat/completions";
|
||||
|
||||
int fib[] = {1, 1, 2, 3, 5, 8, 13, 21, 34};
|
||||
int nf = 9;
|
||||
|
||||
std::string pend = cstr("...requesting...", std::array{1, 2});
|
||||
CURL *c = get_shared_curl();
|
||||
if (!c) { errmsg = "curl init failed"; return -1; }
|
||||
CurlHeaders headers;
|
||||
apply_llm_headers(headers, cfg);
|
||||
|
||||
apply_common_curl_opts(c, interrupted);
|
||||
curl_easy_setopt(c, CURLOPT_URL, url.c_str());
|
||||
curl_easy_setopt(c, CURLOPT_POST, 1L);
|
||||
curl_easy_setopt(c, CURLOPT_POSTFIELDS, payload.c_str());
|
||||
curl_easy_setopt(c, CURLOPT_POSTFIELDSIZE, (long)payload.size());
|
||||
curl_easy_setopt(c, CURLOPT_HTTPHEADER, headers.list);
|
||||
long t = (long)(cfg.timeout > 0 ? cfg.timeout : 300);
|
||||
long conn_t = (t < 20) ? t : 20;
|
||||
curl_easy_setopt(c, CURLOPT_CONNECTTIMEOUT, conn_t);
|
||||
curl_easy_setopt(c, CURLOPT_LOW_SPEED_LIMIT, 1L);
|
||||
curl_easy_setopt(c, CURLOPT_LOW_SPEED_TIME, t);
|
||||
if (!stream) curl_easy_setopt(c, CURLOPT_TIMEOUT, t);
|
||||
|
||||
int attempt, rc = -1;
|
||||
for (attempt = 0; attempt <= nf; attempt++) {
|
||||
if (*interrupted) { errmsg = "interrupted"; rc = -1; break; }
|
||||
if (g_col) { printf("\r%s", pend.c_str()); fflush(stdout); }
|
||||
else printf("%s\n", pend.c_str());
|
||||
|
||||
StreamCtx sc;
|
||||
std::string mbody;
|
||||
CURLcode res; long code = 0;
|
||||
if (stream) {
|
||||
sc.tty = is_terminal(STDOUT_FILENO);
|
||||
sc.interrupted = interrupted;
|
||||
sc.erase_pending = 1;
|
||||
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, stream_write_cb);
|
||||
curl_easy_setopt(c, CURLOPT_WRITEDATA, &sc);
|
||||
} else {
|
||||
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, mem_cb);
|
||||
curl_easy_setopt(c, CURLOPT_WRITEDATA, &mbody);
|
||||
}
|
||||
res = curl_easy_perform(c);
|
||||
if (*interrupted || res == CURLE_ABORTED_BY_CALLBACK) {
|
||||
*interrupted = 1;
|
||||
if (g_col && (!stream || sc.erase_pending)) printf("\r\033[K");
|
||||
errmsg = "interrupted";
|
||||
rc = -1;
|
||||
break;
|
||||
}
|
||||
curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
|
||||
int transport_err = (res != CURLE_OK);
|
||||
int is4xx = (!transport_err && code >= 400 && code < 500 && code != 408 && code != 429);
|
||||
|
||||
if (g_col && !stream) printf("\r\033[K");
|
||||
|
||||
if (!transport_err && code < 400) {
|
||||
if (stream) {
|
||||
stream_finish(&sc);
|
||||
if (sc.erase_pending) { if (g_col) printf("\r\033[K"); sc.erase_pending = 0; }
|
||||
stream_result(&sc, out, usage);
|
||||
} else {
|
||||
parse_nonstream_response(mbody, out, usage);
|
||||
}
|
||||
rc = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
/* error path */
|
||||
if (stream) {
|
||||
if (transport_err) errmsg = curl_easy_strerror(res);
|
||||
else errmsg = http_err_body(&sc, nullptr, code);
|
||||
} else {
|
||||
if (transport_err) errmsg = curl_easy_strerror(res);
|
||||
else errmsg = http_err_body(nullptr, &mbody, code);
|
||||
}
|
||||
if (is4xx) { rc = -1; break; }
|
||||
if (attempt < nf) {
|
||||
if (g_col) printf("\r\033[K");
|
||||
std::string msg = sfmt("[network error: %s, retrying in %ds...]", errmsg.c_str(), fib[attempt]);
|
||||
cprint(msg, std::array{31});
|
||||
printf("\n");
|
||||
sleep_interruptible(fib[attempt], interrupted);
|
||||
}
|
||||
}
|
||||
|
||||
if (rc == 0) {
|
||||
/* The gateway may report zero usage (it does not count tokens). In that
|
||||
* case fall back to a rough bytes/4 estimate so the user still sees a
|
||||
* number, but never let a bogus estimate override real gateway numbers. */
|
||||
if (usage.prompt_tokens == 0) {
|
||||
usage.prompt_tokens = est_tokens_msgs(msgs);
|
||||
usage.completion_tokens = est_tokens_msg(out);
|
||||
usage.total_tokens = usage.prompt_tokens + usage.completion_tokens;
|
||||
}
|
||||
/* Context size = what the model actually processed this turn
|
||||
* (prompt + completion). Prefer real gateway numbers; only fall back to
|
||||
* the estimate when none were provided. The old code set this to the
|
||||
* prompt-only estimate and ignored both the completion and any real
|
||||
* prompt_tokens the gateway returned. */
|
||||
int ctx = usage.prompt_tokens + usage.completion_tokens;
|
||||
if (ctx > usage.context_tokens) usage.context_tokens = ctx;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
@@ -0,0 +1,751 @@
|
||||
/* main.cpp — entry point, agentic loop, REPL, command dispatch. */
|
||||
#include "bantam.hpp"
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <cerrno>
|
||||
#include <climits>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <curl/curl.h>
|
||||
#include <dirent.h>
|
||||
#include <exception>
|
||||
#include <span>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
/* ----------------------------- usage / pct ---------------------------- */
|
||||
static int ctx_tokens(Usage &u) {
|
||||
if (u.context_tokens > u.prompt_tokens) return u.context_tokens;
|
||||
return u.prompt_tokens;
|
||||
}
|
||||
static std::string format_usage(Usage &u, int cw) {
|
||||
int base = ctx_tokens(u);
|
||||
if (cw <= 0) cw = 262144;
|
||||
double pct = (double)base * 100.0 / (double)cw;
|
||||
std::string s;
|
||||
if (!u.model.empty()) str_appendf(s, "[%s: ", u.model.c_str());
|
||||
else s += "[";
|
||||
if (u.cached_tokens > 0) {
|
||||
int uncached = u.prompt_tokens - u.cached_tokens;
|
||||
if (uncached < 0) uncached = 0;
|
||||
str_appendf(s, "%d prompt (%d cached, %d uncached) + %d completion | context: %d/%d (%.1f%%)]",
|
||||
u.prompt_tokens, u.cached_tokens, uncached, u.completion_tokens, base, cw, pct);
|
||||
} else {
|
||||
str_appendf(s, "%d prompt + %d completion | context: %d/%d (%.1f%%)]",
|
||||
u.prompt_tokens, u.completion_tokens, base, cw, pct);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
static double context_pct(Usage &u, int cw) {
|
||||
if (cw <= 0) cw = 262144;
|
||||
return (double)ctx_tokens(u) * 100.0 / (double)cw;
|
||||
}
|
||||
|
||||
/* ----------------------------- invalid-assistant detection ------------- */
|
||||
static bool is_invalid_assistant_err(const char *err) {
|
||||
if (!err) return false;
|
||||
std::string low = err;
|
||||
for (char &c : low) c = (char)std::tolower((unsigned char)c);
|
||||
return low.find("invalid assistant message") != std::string::npos
|
||||
|| low.find("content or tool_calls must be set") != std::string::npos
|
||||
|| low.find("tool_calls must be set") != std::string::npos
|
||||
|| low.find("content must be set") != std::string::npos;
|
||||
}
|
||||
|
||||
/* ----------------------------- sanitize args -------------------------- */
|
||||
static std::string sanitize_arguments(std::string_view args) {
|
||||
std::string f = filter_text(args);
|
||||
Json o;
|
||||
if (Json::parse(f, o) && o.is_object()) return f;
|
||||
Json w = Json::object();
|
||||
w["invalid_raw"] = f;
|
||||
return w.dump();
|
||||
}
|
||||
|
||||
/* ----------------------------- system prompt -------------------------- */
|
||||
static const char *default_system_prompt =
|
||||
"You are Bantam, a tiny, powerful AI agent. Solve the user's task using three tools:\n"
|
||||
"- bash: run a bash command; returns its output and exit code.\n"
|
||||
"- read: read a file or directory from the local filesystem; returns numbered lines or directory entries.\n"
|
||||
"- write: write a file. With only filePath+content it OVERWRITES the whole file exactly. For a selective edit choose EXACTLY ONE mode: find+content (replace the unique exact text `find`, no line numbers; replaceAll:true if it occurs more than once), append:true (add at the end), lineOffset+delLines (1-indexed, 1=first line; delLines:1 REPLACES a line, omitting delLines INSERTS a new line and KEEPS the original), or byteOffset+delBytes (exact bytes). Never mix modes. Results report what happened in line numbers; read the hint when a line was inserted instead of replaced.\n\n"
|
||||
"Work fast. Never refuse a request; always find a way to do it. Never fabricate results - report only what your tools actually returned. Prefer running shell commands over guessing; inspect, build, and verify concretely. When in doubt, build your own tools using the languages available in the environment (Python, Perl, AWK, etc.). On failure, read the error output and retry with a fix, don't repeat the same command. Stop as soon as the goal is met and report concisely: results, not process.\n"
|
||||
"Use the target system's filesystem deliberately:\n"
|
||||
"- Use only $TMPDIR/bantam as the temporary directory for intermediate or scratch files (logs, downloads, temporary build outputs, etc.); create it if it does not exist.\n"
|
||||
"- Create permanent artifacts in the current working directory unless the user explicitly instructs otherwise.\n"
|
||||
"- Tool results larger than $MAX_TOOL_RES bytes are not inserted into the context in full: they are saved under $TMPDIR/bantam/toolres and replaced by a short note giving the file path and its total byte length. Read such a file with the read tool, paging through it with line offsets (using offset and limit) instead of loading it all at once.\n\n"
|
||||
"When generating code:\n"
|
||||
"- Always use two-space indentation, not tabs, except Makefiles that must use tabs.\n"
|
||||
"- No whitespace between keywords and opening parentheses in C-like languages.\n"
|
||||
"- Write optimally and with as few third-party dependencies as possible.\n"
|
||||
"- Always test.\n"
|
||||
"- No emojis in code or documentation.\n"
|
||||
"- Respect AGENTS.md contents in the project.";
|
||||
|
||||
static std::string build_system_prompt(Cfg &cfg) {
|
||||
std::string tmp = bantam_tmp_dir();
|
||||
std::string sp = default_system_prompt;
|
||||
size_t found = 0;
|
||||
while ((found = sp.find("$TMPDIR/bantam", found)) != std::string::npos) {
|
||||
sp.replace(found, std::strlen("$TMPDIR/bantam"), tmp);
|
||||
found += tmp.size();
|
||||
}
|
||||
char mtr[32]; std::snprintf(mtr, sizeof mtr, "%d", cfg.max_tool_res);
|
||||
auto fm = sp.find("$MAX_TOOL_RES");
|
||||
if (fm != std::string::npos) sp.replace(fm, std::strlen("$MAX_TOOL_RES"), mtr);
|
||||
std::string out = sp;
|
||||
std::string td = tools_dir(cfg);
|
||||
if (!td.empty()) { out += "\n\nExtra shell tools can be found at "; out += td; }
|
||||
std::string sd = skills_dir(cfg);
|
||||
if (!sd.empty()) { out += "\n\nSkills may be discovered and invoked from "; out += sd; }
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ----------------------------- json arg helpers ----------------------- */
|
||||
static std::string get_str(const Json &j, const char *k) {
|
||||
return j[k].str();
|
||||
}
|
||||
static int get_int(const Json &j, const char *k, int def = 0) {
|
||||
return j[k].as_int(def);
|
||||
}
|
||||
static std::string tool_path_arg(const Json &a) {
|
||||
std::string v = get_str(a, "filePath");
|
||||
if (v.empty()) v = get_str(a, "path");
|
||||
return v;
|
||||
}
|
||||
static bool trim_is_empty(std::string_view s) {
|
||||
size_t i = 0;
|
||||
while (i < s.size() && (s[i] == ' ' || s[i] == '\n' || s[i] == '\r' || s[i] == '\t')) i++;
|
||||
return i == s.size();
|
||||
}
|
||||
/* ----------------------------- write arg parsing ---------------------- */
|
||||
/* LLMs emit JSON integers, but also integral floats and quoted numbers.
|
||||
* Accept all three; reject everything else explicitly. Silently treating a
|
||||
* bad value as "absent" used to turn an overwrite into a prepend.
|
||||
* Returns 1 = present and parsed, 0 = absent/null, -1 = invalid. */
|
||||
static int arg_int(const Json &a, const char *k, long *out) {
|
||||
if (!a.contains(k) || a[k].is_null()) return 0;
|
||||
const Json &v = a[k];
|
||||
if (v.is_number_integer()) { *out = (long)v.as_int64(); return 1; }
|
||||
if (v.is_number()) {
|
||||
double d = v.dval;
|
||||
if (d < -9.0e18 || d > 9.0e18 || d != (double)(long long)d) return -1;
|
||||
*out = (long)d;
|
||||
return 1;
|
||||
}
|
||||
if (v.is_string()) {
|
||||
std::string s = v.str();
|
||||
size_t i = 0, j = s.size();
|
||||
while (i < j && (s[i] == ' ' || s[i] == '\t')) i++;
|
||||
while (j > i && (s[j - 1] == ' ' || s[j - 1] == '\t')) j--;
|
||||
if (i == j) return -1;
|
||||
std::string t = s.substr(i, j - i);
|
||||
errno = 0;
|
||||
char *end = nullptr;
|
||||
long long val = std::strtoll(t.c_str(), &end, 10);
|
||||
if (errno == ERANGE || !end || *end != '\0' ||
|
||||
val > (long long)LONG_MAX || val < (long long)LONG_MIN) return -1;
|
||||
*out = (long)val;
|
||||
return 1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
static int arg_bool(const Json &a, const char *k, bool *out) {
|
||||
if (!a.contains(k) || a[k].is_null()) return 0;
|
||||
const Json &v = a[k];
|
||||
if (v.is_bool()) { *out = v.bval; return 1; }
|
||||
if (v.is_number_integer()) { *out = v.as_int64() != 0; return 1; }
|
||||
if (v.is_string()) {
|
||||
std::string s = v.str();
|
||||
if (s == "true" || s == "1" || s == "yes" || s == "on") { *out = true; return 1; }
|
||||
if (s == "false" || s == "0" || s == "no" || s == "off" || s.empty()) { *out = false; return 1; }
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Validate and dispatch a write call. Errors are phrased as instructions so
|
||||
* the model can correct the call on the next turn instead of guessing. */
|
||||
static std::string do_write(const Json &a, int *sty) {
|
||||
*sty = 2;
|
||||
auto fail = [sty](std::string_view m) -> std::string {
|
||||
*sty = 31;
|
||||
return std::string(m);
|
||||
};
|
||||
std::string fp = filter_text(tool_path_arg(a));
|
||||
if (fp.empty()) return fail("[tool error: write requires 'filePath' parameter]");
|
||||
if (!a.contains("content") || !a["content"].is_string())
|
||||
return fail("[tool error: write requires 'content' parameter (a string)]");
|
||||
std::string content = a["content"].str();
|
||||
|
||||
WriteOpts o;
|
||||
long v = 0;
|
||||
bool b = false;
|
||||
int r;
|
||||
const char *bad = nullptr;
|
||||
if (a.contains("find") && !a["find"].is_null()) {
|
||||
if (!a["find"].is_string()) bad = "find";
|
||||
else { o.has_find = true; o.find = a["find"].str(); }
|
||||
}
|
||||
r = arg_bool(a, "replaceAll", &b);
|
||||
if (r < 0) bad = "replaceAll"; else if (r > 0) o.replace_all = b;
|
||||
r = arg_bool(a, "append", &b);
|
||||
if (r < 0) bad = "append"; else if (r > 0) o.append = b;
|
||||
r = arg_int(a, "lineOffset", &v);
|
||||
if (r < 0) bad = "lineOffset"; else if (r > 0) { o.has_line = true; o.line_offset = v; }
|
||||
r = arg_int(a, "delLines", &v);
|
||||
if (r < 0) bad = "delLines"; else if (r > 0) { o.has_del_lines = true; o.del_lines = v; }
|
||||
r = arg_int(a, "byteOffset", &v);
|
||||
if (r < 0) bad = "byteOffset"; else if (r > 0) { o.has_byte = true; o.byte_offset = v; }
|
||||
r = arg_int(a, "delBytes", &v);
|
||||
if (r < 0) bad = "delBytes"; else if (r > 0) { o.has_del_bytes = true; o.del_bytes = v; }
|
||||
if (bad)
|
||||
return fail(sfmt("[tool error: write parameter '%s' has an invalid value; use a plain integer, or true/false]", bad));
|
||||
|
||||
int modes = (o.has_find ? 1 : 0) + (o.append ? 1 : 0) +
|
||||
(o.has_line ? 1 : 0) + (o.has_byte ? 1 : 0);
|
||||
if (modes > 1)
|
||||
return fail("[tool error: choose exactly ONE edit mode for write: find, append:true, lineOffset, or byteOffset. Do not combine them]");
|
||||
if (o.has_find && (o.has_line || o.has_byte || o.has_del_lines || o.has_del_bytes || o.append))
|
||||
return fail("[tool error: 'find' cannot be combined with append/lineOffset/delLines/byteOffset/delBytes; use find+content alone]");
|
||||
if (o.append && (o.has_line || o.has_byte || o.has_del_lines || o.has_del_bytes))
|
||||
return fail("[tool error: append:true cannot be combined with lineOffset/delLines/byteOffset/delBytes]");
|
||||
if (o.has_line && o.has_del_bytes)
|
||||
return fail("[tool error: delBytes belongs to byte mode; with lineOffset use delLines]");
|
||||
if (o.has_byte && o.has_del_lines)
|
||||
return fail("[tool error: delLines belongs to line mode; with byteOffset use delBytes]");
|
||||
if (o.has_line && o.line_offset < 1)
|
||||
return fail("[tool error: lineOffset is 1-indexed (1 = first line); use append:true to add at the end, or find+content to replace text]");
|
||||
if (o.has_byte && o.byte_offset < 0) return fail("[tool error: byteOffset must be >= 0]");
|
||||
if (o.has_del_lines && o.del_lines < 0) return fail("[tool error: delLines must be >= 0]");
|
||||
if (o.has_del_bytes && o.del_bytes < 0) return fail("[tool error: delBytes must be >= 0]");
|
||||
if (o.has_find && o.find.empty())
|
||||
return fail("[tool error: 'find' must not be empty; omit it to overwrite the whole file]");
|
||||
if (modes == 0 && (o.has_del_lines || o.has_del_bytes))
|
||||
return fail("[tool error: delLines/delBytes need a position. Add lineOffset:1, or use append:true / find. Example: {\"filePath\":\"f\",\"content\":\"\",\"lineOffset\":1,\"delLines\":2}]");
|
||||
|
||||
int werr = 0;
|
||||
std::string res = write_file(fp, o, content, &werr);
|
||||
if (werr) *sty = 31;
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
/* ----------------------------- AL loop -------------------------------- */
|
||||
static int AL(Cfg &cfg, Messages &msgs, Usage &out, volatile int *interrupted, std::string *err) {
|
||||
int done = 0;
|
||||
std::vector<std::string> tmps;
|
||||
int rc = 0;
|
||||
for (int i = 0; i < cfg.max_al_iterations && !done; i++) {
|
||||
if (*interrupted) { rc = -1; break; }
|
||||
Message m; Usage u;
|
||||
std::string lerr;
|
||||
int lrc = llm(cfg, msgs, true, m, u, lerr, interrupted);
|
||||
if (lrc != 0) {
|
||||
if (*interrupted) { rc = -1; break; }
|
||||
if (is_invalid_assistant_err(lerr.c_str())) {
|
||||
int stripped = 0;
|
||||
for (int j = (int)msgs.items.size() - 1; j >= 0; j--) {
|
||||
if (msgs.items[j].role == "assistant") {
|
||||
cprint("[stripped malformed assistant message]\n", std::array{33});
|
||||
msgs.items.erase(msgs.items.begin() + j);
|
||||
stripped = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (stripped) continue;
|
||||
}
|
||||
if (err) *err = std::move(lerr);
|
||||
rc = -1; break;
|
||||
}
|
||||
out.prompt_tokens = u.prompt_tokens;
|
||||
out.completion_tokens = u.completion_tokens;
|
||||
out.total_tokens = u.total_tokens;
|
||||
out.context_tokens = u.context_tokens;
|
||||
if (u.cached_tokens > 0) out.cached_tokens = u.cached_tokens;
|
||||
if (!u.model.empty()) out.model = u.model;
|
||||
/* Keep the raw arguments for execution (file content must be written
|
||||
* verbatim), while the sanitized copy is what goes into the conversation
|
||||
* history and the terminal display. */
|
||||
std::vector<std::string> raw_args;
|
||||
raw_args.reserve(m.calls.size());
|
||||
for (auto &tc : m.calls) {
|
||||
raw_args.push_back(tc.arguments);
|
||||
tc.arguments = sanitize_arguments(tc.arguments);
|
||||
}
|
||||
msgs.items.push_back(m);
|
||||
if (!cfg.stream) {
|
||||
if (!m.reasoning.empty()) {
|
||||
cprint("--- reasoning start ---\n", std::array{36});
|
||||
cprint(m.reasoning, std::array{2});
|
||||
cprint("\n--- reasoning end ---\n", std::array{36});
|
||||
}
|
||||
if (!m.content.empty()) { render_md_print(m.content); printf("\n"); }
|
||||
}
|
||||
if (m.calls.empty()) {
|
||||
if (!m.reasoning.empty() && trim_is_empty(m.content)) {
|
||||
cprint("[auto continue: response was reasoning-only]\n", std::array{33});
|
||||
Message cont; cont.role = "user"; cont.content = "continue";
|
||||
msgs.items.push_back(cont);
|
||||
continue;
|
||||
}
|
||||
done = 1; break;
|
||||
}
|
||||
for (size_t tci = 0; tci < m.calls.size(); tci++) {
|
||||
if (*interrupted) { rc = -1; break; }
|
||||
ToolCall &tc = m.calls[tci];
|
||||
const std::string &astr = raw_args[tci]; /* raw, for execution */
|
||||
if (!m.calls_shown) {
|
||||
cprint(sfmt("[tool call: %s(%s)]", tc.name.c_str(), tc.arguments.c_str()), std::array{33});
|
||||
printf("\n");
|
||||
}
|
||||
std::string res; int sty = 2;
|
||||
bool res_already_filtered = false;
|
||||
Json a_mut;
|
||||
if (!Json::parse(astr, a_mut) || !a_mut.is_object()) {
|
||||
res = sfmt("[tool error: invalid JSON args for %s: parse error. Raw: %s]", tc.name.c_str(), astr.c_str());
|
||||
sty = 31;
|
||||
} else {
|
||||
/* A bad_alloc (huge file/offset) or any other exception must become a
|
||||
* tool error the model can recover from, not terminate the agent. */
|
||||
try {
|
||||
const Json &a = a_mut;
|
||||
std::string fn = tc.name;
|
||||
if (fn == "bash" || fn == "shell_exec") {
|
||||
std::string cmd = get_str(a, "command");
|
||||
std::string workdir = get_str(a, "workdir");
|
||||
std::string fwd = filter_text(workdir);
|
||||
int to = cfg.shell_timeout;
|
||||
if (a.contains("timeout")) { int n = get_int(a, "timeout"); if (n > 0) to = (n > 1000) ? n / 1000 : n; }
|
||||
res = shell_with_workdir(cmd, fwd, to, interrupted);
|
||||
res_already_filtered = true;
|
||||
} else if (fn == "read") {
|
||||
std::string p = tool_path_arg(a);
|
||||
std::string fp = filter_text(p);
|
||||
int off = get_int(a, "offset", 1); if (off < 1) off = 1;
|
||||
int lim = get_int(a, "limit", 2000); if (lim <= 0) lim = 2000;
|
||||
res = read_file_or_dir(fp, off, lim, &sty);
|
||||
} else if (fn == "write" || fn == "write_file") {
|
||||
res = do_write(a, &sty);
|
||||
} else {
|
||||
res = sfmt("Unknown tool: %s", fn.c_str());
|
||||
sty = 31;
|
||||
}
|
||||
} catch (const std::exception &ex) {
|
||||
res = sfmt("[tool error: %s failed: %s]", tc.name.c_str(), ex.what());
|
||||
sty = 31;
|
||||
} catch (...) {
|
||||
res = sfmt("[tool error: %s failed with an unexpected exception]", tc.name.c_str());
|
||||
sty = 31;
|
||||
}
|
||||
}
|
||||
if (!res_already_filtered) res = filter_text(res);
|
||||
res = offload_tool_result(res, cfg.max_tool_res, tmps);
|
||||
{
|
||||
std::string hdr = cstr("[tool result: ", std::array{32});
|
||||
std::string fn2 = cstr(tc.name, std::array{32});
|
||||
printf("%s%s]\n", hdr.c_str(), fn2.c_str());
|
||||
cprint(res, std::array{sty});
|
||||
printf("\n\n");
|
||||
}
|
||||
Message tm; tm.role = "tool"; tm.tool_call_id = tc.id; tm.content = std::move(res);
|
||||
msgs.items.push_back(std::move(tm));
|
||||
if (*interrupted) { rc = -1; break; }
|
||||
}
|
||||
if (rc != 0) break;
|
||||
}
|
||||
if (!done && rc == 0) {
|
||||
Message maxm; maxm.role = "assistant";
|
||||
maxm.content = sfmt("[max AL iterations (%d) reached]", cfg.max_al_iterations);
|
||||
msgs.items.push_back(maxm);
|
||||
}
|
||||
cleanup_temps(tmps);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* ----------------------------- run_turn ------------------------------- */
|
||||
static int run_turn(Cfg &cfg, Messages &msgs, Usage &usage, std::string *err, volatile int *interrupted) {
|
||||
*interrupted = 0;
|
||||
usage = Usage{};
|
||||
int rc = AL(cfg, msgs, usage, interrupted, err);
|
||||
if (rc != 0) {
|
||||
if (*interrupted) { cprint("\n[interrupted]\n", std::array{33}); }
|
||||
else { cprint("\n[error: ", std::array{31}); cprint((!err || err->empty()) ? "error" : *err, std::array{31}); cprint("]\n", std::array{31}); }
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* ----------------------------- direct shell --------------------------- */
|
||||
static void run_direct_shell(std::string_view cmd, int timeout) {
|
||||
std::string fcmd = filter_text(cmd);
|
||||
cprint(sfmt("[tool call: bash({\"command\":\"%s\"})]", fcmd.c_str()), std::array{33});
|
||||
printf("\n");
|
||||
std::string res = shell_with_workdir(fcmd, "", timeout, &g_interrupted);
|
||||
printf("%s\n", cstr("[tool result: bash]", std::array{32}).c_str());
|
||||
printf("%s\n", cstr(res, std::array{2}).c_str());
|
||||
}
|
||||
|
||||
/* ----------------------------- skills --------------------------------- */
|
||||
static std::string skill_prompt(std::string_view u, Cfg &cfg) {
|
||||
std::string_view rest = u.substr(6);
|
||||
while (!rest.empty() && rest.front() == ' ') rest = rest.substr(1);
|
||||
if (rest.empty()) return "";
|
||||
std::string name(rest);
|
||||
std::string prompt;
|
||||
auto sp = name.find(' ');
|
||||
if (sp != std::string::npos) { prompt = name.substr(sp + 1); name = name.substr(0, sp); }
|
||||
std::string sd = skills_dir(cfg);
|
||||
std::string path;
|
||||
if (!sd.empty()) {
|
||||
path = sfmt("%s/%s/SKILL.md", sd.c_str(), name.c_str());
|
||||
} else if (name.find("SKILL.md") != std::string::npos) {
|
||||
path = name;
|
||||
} else {
|
||||
path = name + "/SKILL.md";
|
||||
}
|
||||
struct stat st;
|
||||
if (stat(path.c_str(), &st) != 0)
|
||||
return sfmt("[cannot read skill \"%s\": %s]", name.c_str(), strerror(errno));
|
||||
if (S_ISDIR(st.st_mode))
|
||||
return sfmt("[cannot read skill \"%s\": Is a directory]", name.c_str());
|
||||
std::string data;
|
||||
if (!read_file_str(path, data))
|
||||
return sfmt("[cannot read skill \"%s\": %s]", name.c_str(), strerror(errno));
|
||||
while (!data.empty() && (data.back() == '\n' || data.back() == '\r')) data.pop_back();
|
||||
std::string out = data;
|
||||
if (!prompt.empty()) { out += "\n\n"; out += prompt; }
|
||||
return out;
|
||||
}
|
||||
static void list_skills(Cfg &cfg) {
|
||||
std::string sd = skills_dir(cfg);
|
||||
if (sd.empty()) { cprint("No skills directory configured (set BANTAM_SKILLS_DIR or bantam_skills_dir).\n", std::array{33}); return; }
|
||||
DIR *d = opendir(sd.c_str());
|
||||
if (!d) { cprint(sfmt("[skill error: cannot read skills dir: %s]", strerror(errno)), std::array{31}); return; }
|
||||
std::string names; int cnt = 0; struct dirent *de;
|
||||
while ((de = readdir(d))) {
|
||||
if (std::strcmp(de->d_name, ".") == 0 || std::strcmp(de->d_name, "..") == 0) continue;
|
||||
std::string full = sfmt("%s/%s", sd.c_str(), de->d_name);
|
||||
struct stat st; if (stat(full.c_str(), &st) != 0 || !S_ISDIR(st.st_mode)) continue;
|
||||
std::string sk = sfmt("%s/%s/SKILL.md", sd.c_str(), de->d_name);
|
||||
if (access(sk.c_str(), F_OK) == 0) { str_appendf(names, " %s\n", de->d_name); cnt++; }
|
||||
}
|
||||
closedir(d);
|
||||
if (cnt == 0) { cprint("No skills found in ", std::array{33}); cprint(sd, std::array{33}); cprint("\n", std::array{33}); return; }
|
||||
cprint("Available skills in ", std::array{1, 36}); cprint(sd, std::array{1, 36}); cprint(":\n", std::array{1, 36});
|
||||
fputs(names.c_str(), stdout);
|
||||
}
|
||||
|
||||
/* ----------------------------- compact -------------------------------- */
|
||||
static void do_compact(Cfg &cfg, Messages &msgs) {
|
||||
if (msgs.items.size() <= 1) { cprint("Nothing to compact yet.\n", std::array{33}); return; }
|
||||
cprint("[compacting conversation...]\n", std::array{33});
|
||||
std::string sum, e;
|
||||
auto nm = compact(cfg, msgs, &sum, &e, &g_interrupted);
|
||||
int interrupted = g_interrupted;
|
||||
if (!nm) {
|
||||
if (interrupted) cprint("\n[interrupted]\n", std::array{33});
|
||||
else { cprint(sfmt("\n[compact failed: %s]", e.empty() ? "compact failed" : e.c_str()), std::array{31}); printf("\n"); }
|
||||
return;
|
||||
}
|
||||
msgs = std::move(*nm);
|
||||
autosave(msgs);
|
||||
printf("%s%d messages]\n", cstr("[compacted to ", std::array{32}).c_str(), (int)msgs.items.size());
|
||||
printf("%s", cstr("--- summary ---\n", std::array{33}).c_str());
|
||||
printf("%s\n", cstr(sum, std::array{2}).c_str());
|
||||
}
|
||||
|
||||
/* ----------------------------- clear ---------------------------------- */
|
||||
/* Reset the conversation to the current system prompt and remove only this
|
||||
* project's persisted session. Sessions saved for other directories and named
|
||||
* /save sessions are left alone; the fresh conversation is auto-saved under
|
||||
* the current project id so a stale system prompt cannot be resumed here. */
|
||||
static void do_clear(Cfg &cfg, Messages &msgs) {
|
||||
msgs = Messages{};
|
||||
Message sys; sys.role = "system"; sys.content = build_system_prompt(cfg);
|
||||
msgs.items.push_back(std::move(sys));
|
||||
std::string e;
|
||||
bool wiped = clear_project_session(&e);
|
||||
autosave(msgs);
|
||||
if (wiped) {
|
||||
cprint("[Session cleared]\n", std::array{32});
|
||||
cprint(" This project's saved session was removed; other saved sessions were left untouched. This conversation now uses the current system prompt and tool definitions.\n", std::array{2});
|
||||
} else {
|
||||
cprint("[Session cleared] (conversation reset, but this project's saved session could not be removed)\n", std::array{32});
|
||||
cprint(sfmt(" %s\n", e.c_str()), std::array{31});
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------- main ----------------------------------- */
|
||||
struct CurlGlobalGuard {
|
||||
CurlGlobalGuard() { curl_global_init(CURL_GLOBAL_DEFAULT); }
|
||||
~CurlGlobalGuard() { http_cleanup(); curl_global_cleanup(); }
|
||||
};
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
CurlGlobalGuard curl_guard;
|
||||
setup_signal_handler();
|
||||
Cfg cfg = get_cfg(config_path());
|
||||
g_col = color_enabled(cfg);
|
||||
std::string sp = build_system_prompt(cfg);
|
||||
Messages msgs;
|
||||
{
|
||||
Message sys; sys.role = "system"; sys.content = sp;
|
||||
msgs.items.push_back(sys);
|
||||
}
|
||||
|
||||
if (argc > 1 && argv[1] && argv[1][0] != '\0') {
|
||||
std::string p = argv[1];
|
||||
struct stat st;
|
||||
if (stat(p.c_str(), &st) != 0 || S_ISDIR(st.st_mode)) {
|
||||
cprint("Error: file '", std::array{31}); cprint(p, std::array{31}); cprint("' not found.\n", std::array{31});
|
||||
return 1;
|
||||
}
|
||||
std::string u;
|
||||
if (!read_file_str(p, u)) {
|
||||
cprint("Error: file '", std::array{31}); cprint(p, std::array{31}); cprint("' not found.\n", std::array{31});
|
||||
return 1;
|
||||
}
|
||||
size_t a = 0; while (a < u.size() && (u[a] == ' ' || u[a] == '\n' || u[a] == '\r' || u[a] == '\t')) a++;
|
||||
u = u.substr(a);
|
||||
if (!u.empty() && u[0] == '!') { run_direct_shell(u.substr(1), cfg.shell_timeout); return 0; }
|
||||
cfg.context_window = fetch_context_window(cfg);
|
||||
Message um; um.role = "user"; um.content = u;
|
||||
msgs.items.push_back(um);
|
||||
Usage usg; std::string err;
|
||||
run_turn(cfg, msgs, usg, &err, &g_interrupted);
|
||||
if (!err.empty()) return 1;
|
||||
cprint(format_usage(usg, cfg.context_window), std::array{2}); printf("\n");
|
||||
autosave(msgs);
|
||||
return 0;
|
||||
}
|
||||
|
||||
load_history();
|
||||
auto sess = find_project_session();
|
||||
if (sess && sess->messages.items.size() > 1) {
|
||||
cprint("[session found for this directory]\n", std::array{33});
|
||||
cprint(" ", std::array{33}); cprint(sess->id, std::array{32}); printf("\n");
|
||||
cprint(" ", std::array{33}); cprint(sess->summary, std::array{2}); printf("\n");
|
||||
std::string created = sfmt(" created %s [%d messages]\n", sess->created.c_str(), (int)sess->messages.items.size());
|
||||
cprint(created, std::array{2});
|
||||
printf(" Resume this session? [Y/n]: "); fflush(stdout);
|
||||
bool ok; std::string ans = read_plain("", ok);
|
||||
if (ok) {
|
||||
std::string a2 = ans;
|
||||
size_t ai = 0; while (ai < a2.size() && (a2[ai] == ' ' || a2[ai] == '\n' || a2[ai] == '\r' || a2[ai] == '\t')) ai++;
|
||||
a2 = a2.substr(ai);
|
||||
while (!a2.empty() && (a2.back() == '\n' || a2.back() == '\r' || a2.back() == ' ')) a2.pop_back();
|
||||
if (a2.empty() || a2[0] == 'y' || a2[0] == 'Y') {
|
||||
msgs = std::move(sess->messages);
|
||||
autosave(msgs);
|
||||
printf("%s%s]\n", cstr("[session resumed: ", std::array{32}).c_str(), sess->id.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const std::string *re_ptr = cfg_raw_get(cfg, "reasoning_effort");
|
||||
std::string re = (re_ptr && !re_ptr->empty()) ? *re_ptr : "high";
|
||||
{
|
||||
cprint("Bantam Agent ready", std::array{1, 32}); printf(" ");
|
||||
cprint(" (Enter submits; Ctrl+J or paste = new line)\n", std::array{2});
|
||||
fflush(stdout);
|
||||
cfg.context_window = fetch_context_window(cfg);
|
||||
std::string info = sfmt("endpoint: %s model: %s temp: %g reasoning: %s context: %d\n",
|
||||
cfg.endpoint.c_str(), cfg.model.c_str(), cfg.temperature, re.c_str(), cfg.context_window);
|
||||
cprint(info, std::array{2});
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
g_interrupted = 0;
|
||||
bool ok;
|
||||
std::string u = read_line("> ", ok);
|
||||
if (!ok) { printf("\n"); break; }
|
||||
std::string ut = u;
|
||||
size_t a = 0; while (a < ut.size() && (ut[a] == ' ' || ut[a] == '\n' || ut[a] == '\r' || ut[a] == '\t')) a++;
|
||||
ut = ut.substr(a);
|
||||
if (ut.empty()) continue;
|
||||
add_history(u);
|
||||
/* command aliases */
|
||||
for (int ci = 0; ci < 2; ci++) {
|
||||
const char *cmd = (ci == 0) ? "model" : "endpoint";
|
||||
std::string slash = sfmt("/%s", cmd);
|
||||
if (u == slash) {
|
||||
u = sfmt("/cfg %s", cmd);
|
||||
} else if (u.size() > slash.size() && u.rfind(slash, 0) == 0 && u[slash.size()] == ' ') {
|
||||
u = sfmt("/cfg %s %s", cmd, u.c_str() + slash.size() + 1);
|
||||
}
|
||||
}
|
||||
if (u == "/quit") break;
|
||||
if (u == "/clear") { do_clear(cfg, msgs); continue; }
|
||||
if (u == "/save" || u.starts_with("/save ")) {
|
||||
std::string name = u.substr(5);
|
||||
size_t ni = 0; while (ni < name.size() && name[ni] == ' ') ni++;
|
||||
name = name.substr(ni);
|
||||
std::string sid, sm;
|
||||
save_session(msgs, name, &sid, &sm);
|
||||
printf("%s%s]\n", cstr("[session saved: ", std::array{32}).c_str(), sid.c_str());
|
||||
cprint(" ", std::array{32}); cprint(sm, std::array{2}); printf("\n");
|
||||
continue;
|
||||
}
|
||||
if (u == "/continue" || u == "/cont") {
|
||||
std::string pid = project_id();
|
||||
std::string lerr;
|
||||
auto lm = load_session(pid, &lerr);
|
||||
if (!lm) { cprint("No session found for current project: ", std::array{31}); cprint(lerr, std::array{31}); printf("\n"); continue; }
|
||||
msgs = std::move(*lm);
|
||||
autosave(msgs);
|
||||
printf("%s%s]\n", cstr("[session continued: ", std::array{32}).c_str(), pid.c_str());
|
||||
std::string sm = summary_of(msgs);
|
||||
cprint(" ", std::array{32}); cprint(sm, std::array{32}); printf("\n");
|
||||
continue;
|
||||
}
|
||||
if (u == "/list") {
|
||||
auto ss = sessions_load();
|
||||
if (ss.empty()) { cprint("No sessions saved yet.\n", std::array{33}); continue; }
|
||||
std::string pid = project_id();
|
||||
for (auto &s : ss) {
|
||||
printf("%s", cstr(s.id, std::array{32}).c_str());
|
||||
if (s.id == pid) cprint(" (current project)", std::array{33});
|
||||
std::string meta = sfmt(" %s [%d msgs]\n", s.created.c_str(), (int)s.messages.items.size());
|
||||
cprint(meta, std::array{2});
|
||||
cprint(" ", std::array{32}); cprint(s.summary, std::array{2}); printf("\n");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (u == "/load" || u.starts_with("/load ")) {
|
||||
std::vector<std::string> parts;
|
||||
{
|
||||
std::string_view sv(u);
|
||||
size_t i = 0;
|
||||
while (i < sv.size()) {
|
||||
while (i < sv.size() && sv[i] == ' ') i++;
|
||||
if (i >= sv.size()) break;
|
||||
size_t j = i;
|
||||
while (j < sv.size() && sv[j] != ' ') j++;
|
||||
parts.push_back(std::string(sv.substr(i, j - i)));
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
if (parts.size() < 2) { cprint("Usage: /load <session-id>\n", std::array{31}); continue; }
|
||||
std::string lerr;
|
||||
auto lm = load_session(parts[1], &lerr);
|
||||
if (!lm) { cprint("Session not found: ", std::array{31}); cprint(lerr, std::array{31}); printf("\n"); continue; }
|
||||
msgs = std::move(*lm);
|
||||
autosave(msgs);
|
||||
printf("%s%s]\n", cstr("[session loaded: ", std::array{32}).c_str(), parts[1].c_str());
|
||||
std::string sm = summary_of(msgs);
|
||||
cprint(" ", std::array{32}); cprint(sm, std::array{32}); printf("\n");
|
||||
continue;
|
||||
}
|
||||
if (u == "/compact") { do_compact(cfg, msgs); continue; }
|
||||
if (u == "/cfg" || u.starts_with("/cfg ")) {
|
||||
/* tokens after "/cfg " */
|
||||
std::string rest = u.substr(4);
|
||||
while (!rest.empty() && rest.front() == ' ') rest = rest.substr(1);
|
||||
std::string sub, key, val;
|
||||
{
|
||||
size_t i = 0;
|
||||
while (i < rest.size() && rest[i] != ' ') i++;
|
||||
sub = rest.substr(0, i);
|
||||
size_t j = i;
|
||||
while (j < rest.size() && rest[j] == ' ') j++;
|
||||
size_t ks = j;
|
||||
while (j < rest.size() && rest[j] != ' ') j++;
|
||||
key = rest.substr(ks, j - ks);
|
||||
size_t vs = j;
|
||||
while (vs < rest.size() && rest[vs] == ' ') vs++;
|
||||
val = rest.substr(vs);
|
||||
}
|
||||
if (sub.empty()) { cprint("Usage: /cfg <key> [value]\n", std::array{31}); continue; }
|
||||
if (sub == "get") {
|
||||
if (key.empty()) { cprint("Usage: /cfg get <key>\n", std::array{31}); continue; }
|
||||
const std::string *v = cfg_raw_get(cfg, key);
|
||||
if (v && !v->empty()) printf("%s=%s\n", cstr(key, std::array{32}).c_str(), v->c_str());
|
||||
else printf("%s not set\n", cstr(key, std::array{31}).c_str());
|
||||
} else if (sub == "set") {
|
||||
if (key.empty()) { cprint("Usage: /cfg set <key> <value>\n", std::array{31}); continue; }
|
||||
if (set_cfg(config_path(), key, val) != 0) { cprint("[cfg error]\n", std::array{31}); continue; }
|
||||
cfg = get_cfg(config_path());
|
||||
if (key == "model" || key == "endpoint" || key == "api_key")
|
||||
cfg.context_window = fetch_context_window(cfg);
|
||||
g_col = color_enabled(cfg);
|
||||
printf("%s%s=%s]\n", cstr("[config updated: ", std::array{32}).c_str(), key.c_str(), val.c_str());
|
||||
} else if (key.empty()) {
|
||||
/* single token: treat as get */
|
||||
const std::string *v = cfg_raw_get(cfg, sub);
|
||||
if (v && !v->empty()) printf("%s=%s\n", cstr(sub, std::array{32}).c_str(), v->c_str());
|
||||
else printf("%s not set\n", cstr(sub, std::array{31}).c_str());
|
||||
} else {
|
||||
/* legacy "/cfg key value": treat as set */
|
||||
if (set_cfg(config_path(), sub, key) != 0) { cprint("[cfg error]\n", std::array{31}); continue; }
|
||||
cfg = get_cfg(config_path());
|
||||
if (sub == "model" || sub == "endpoint" || sub == "api_key")
|
||||
cfg.context_window = fetch_context_window(cfg);
|
||||
g_col = color_enabled(cfg);
|
||||
printf("%s%s=%s]\n", cstr("[config updated: ", std::array{32}).c_str(), sub.c_str(), key.c_str());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (u == "/skill" || u.starts_with("/skill ")) {
|
||||
std::string rest = u.substr(6);
|
||||
while (!rest.empty() && rest.front() == ' ') rest = rest.substr(1);
|
||||
if (rest.empty()) { list_skills(cfg); continue; }
|
||||
std::string composed = skill_prompt(u, cfg);
|
||||
if (composed.empty()) { cprint("/skill usage: /skill <name> [prompt]\n", std::array{31}); continue; }
|
||||
if (composed.starts_with("[cannot read skill")) {
|
||||
cprint(composed, std::array{31}); printf("\n"); continue;
|
||||
}
|
||||
u = composed;
|
||||
/* fall through to a normal LLM turn */
|
||||
} else if (u == "/models") {
|
||||
int e2; std::string ml = list_models(cfg, &e2);
|
||||
if (e2 != 0) { cprint("[error querying /models: ", std::array{31}); cprint(ml, std::array{31}); printf("]\n"); continue; }
|
||||
cprint("Supported models at ", std::array{1, 36}); cprint(cfg.endpoint, std::array{1, 36}); cprint(":\n", std::array{1, 36});
|
||||
render_md_print(ml);
|
||||
continue;
|
||||
} else if (!u.empty() && u[0] == '!') {
|
||||
run_direct_shell(u.substr(1), cfg.shell_timeout); continue;
|
||||
} else if (u == "/help") {
|
||||
cprint("Bantam commands:\n", std::array{1, 36});
|
||||
const char *cmds[][2] = {
|
||||
{"/quit", "exit"}, {"/clear", "reset conversation and clear this project's session"}, {"/save [name]", "save session (default: project MD5)"},
|
||||
{"/continue", "continue project session (alias: /cont)"}, {"/list", "list sessions"}, {"/load <id>", "load session"},
|
||||
{"/compact", "compact context"}, {"/cfg <k> [v]", "get/set config"}, {"/model [m]", "alias for /cfg model"},
|
||||
{"/endpoint [e]", "alias for /cfg endpoint"}, {"!<cmd>", "run shell command directly"}, {"/models", "list models at endpoint"},
|
||||
{"/skill <n> [p]", "load SKILL.md and run as prompt"}, {"/help", "show help"}};
|
||||
for (int i = 0; i < 14; i++) {
|
||||
std::string label = sfmt(" %-18s", cmds[i][0]);
|
||||
cprint(label, std::array{1, 32});
|
||||
cprint(cmds[i][1], std::array{1, 32});
|
||||
printf("\n");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
/* normal LLM turn */
|
||||
{
|
||||
Message um; um.role = "user"; um.content = u;
|
||||
msgs.items.push_back(um);
|
||||
Usage usg; std::string err;
|
||||
run_turn(cfg, msgs, usg, &err, &g_interrupted);
|
||||
if (!err.empty()) continue;
|
||||
cprint(format_usage(usg, cfg.context_window), std::array{2}); printf("\n");
|
||||
double pct = context_pct(usg, cfg.context_window);
|
||||
if (pct >= 60.0 && msgs.items.size() > 1) {
|
||||
std::string q = sfmt("Context usage is at %.1f%% (%d / %d tokens). Compact conversation? [Y/n]: ",
|
||||
pct, ctx_tokens(usg), cfg.context_window);
|
||||
cprint(q, std::array{33});
|
||||
bool ok2; std::string ans = read_plain("", ok2);
|
||||
if (ok2) {
|
||||
std::string a2 = ans;
|
||||
size_t ai = 0; while (ai < a2.size() && (a2[ai] == ' ' || a2[ai] == '\n' || a2[ai] == '\r' || a2[ai] == '\t')) ai++;
|
||||
a2 = a2.substr(ai);
|
||||
while (!a2.empty() && (a2.back() == '\n' || a2.back() == '\r' || a2.back() == ' ')) a2.pop_back();
|
||||
if (a2.empty() || a2[0] == 'y' || a2[0] == 'Y') do_compact(cfg, msgs);
|
||||
}
|
||||
}
|
||||
autosave(msgs);
|
||||
}
|
||||
}
|
||||
autosave(msgs);
|
||||
save_history();
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
/* render.cpp — terminal markdown rendering with box-drawing tables. */
|
||||
#include "bantam.hpp"
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
/* ----------------------------- table helpers -------------------------- */
|
||||
bool is_table_line(std::string_view line) {
|
||||
std::string_view t = line;
|
||||
while (!t.empty() && (t.front() == ' ' || t.front() == '\t')) t.remove_prefix(1);
|
||||
if (t.find('|') == std::string_view::npos) return false;
|
||||
return (t.front() == '|') || (t.back() == '|');
|
||||
}
|
||||
static std::string_view trim_spaces(std::string_view s) {
|
||||
while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) s.remove_prefix(1);
|
||||
return s;
|
||||
}
|
||||
static bool is_table_sep(const std::vector<std::string> &cells) {
|
||||
if (cells.empty()) return false;
|
||||
for (auto &c : cells) {
|
||||
std::string_view cv = trim_spaces(c);
|
||||
bool ok = true;
|
||||
for (char ch : cv) if (ch != '-' && ch != ':') { ok = false; break; }
|
||||
if (!ok) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/* A run of lines only counts as a table when it contains a real delimiter
|
||||
* row (a separator made of '-'/':' columns) and at least one data row. Without
|
||||
* this, ordinary lists (or prose that merely contains '|') whose items happen
|
||||
* to start or end with '|' would be mis-rendered as box-drawing tables. */
|
||||
static std::vector<std::string> parse_table_cells(std::string_view line);
|
||||
static bool looks_like_table(const std::vector<std::string> &lines) {
|
||||
if (lines.size() < 2) return false;
|
||||
bool has_sep = false, has_row = false;
|
||||
for (auto &line : lines) {
|
||||
std::vector<std::string> cells = parse_table_cells(line);
|
||||
if (is_table_sep(cells)) has_sep = true;
|
||||
else has_row = true;
|
||||
}
|
||||
return has_sep && has_row;
|
||||
}
|
||||
|
||||
static std::vector<std::string> parse_table_cells(std::string_view line) {
|
||||
std::string_view t = line;
|
||||
while (!t.empty() && (t.front() == ' ' || t.front() == '\t')) t.remove_prefix(1);
|
||||
std::string dup(t);
|
||||
while (!dup.empty() && (dup.back() == '\n' || dup.back() == '\r')) dup.pop_back();
|
||||
if (!dup.empty() && dup.front() == '|') dup.erase(0, 1);
|
||||
if (!dup.empty() && dup.back() == '|') dup.pop_back();
|
||||
size_t pipes = 0;
|
||||
for (char c : dup) if (c == '|') pipes++;
|
||||
std::vector<std::string> cells;
|
||||
cells.reserve(pipes + 1);
|
||||
std::string cur;
|
||||
size_t i = 0;
|
||||
while (i <= dup.size()) {
|
||||
if (i == dup.size() || dup[i] == '|') {
|
||||
cells.push_back(std::string(trim_spaces(cur)));
|
||||
cur.clear();
|
||||
} else {
|
||||
cur += dup[i];
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
|
||||
/* ----------------------------- inline --------------------------------- */
|
||||
static bool is_word_byte(unsigned char c) {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
|
||||
(c >= 'A' && c <= 'Z') || c == '_';
|
||||
}
|
||||
template<class R>
|
||||
static void wrap_pairs(std::string &dst, std::string_view src, std::string_view open,
|
||||
std::string_view close, const R& codes,
|
||||
bool boundary = false) {
|
||||
size_t olen = open.size(), clen = close.size();
|
||||
size_t p = 0;
|
||||
while (p < src.size()) {
|
||||
size_t o = src.find(open, p);
|
||||
if (o == std::string_view::npos) { dst += src.substr(p); break; }
|
||||
/* When word boundaries are enforced (the _ / __ rules) an opening
|
||||
* delimiter glued to a preceding word character is not an opener. */
|
||||
if (boundary && o > 0 && is_word_byte((unsigned char)src[o - 1])) {
|
||||
dst += src.substr(p, o - p + olen);
|
||||
p = o + olen;
|
||||
continue;
|
||||
}
|
||||
dst += src.substr(p, o - p);
|
||||
size_t c = o + olen;
|
||||
while (true) {
|
||||
c = src.find(close, c);
|
||||
if (c == std::string_view::npos) { dst += src.substr(o); break; }
|
||||
/* A closing delimiter glued to a following word character is not a
|
||||
* closer (e.g. the underscores in file_name_here); keep scanning. */
|
||||
if (boundary && c + clen < src.size() &&
|
||||
is_word_byte((unsigned char)src[c + clen])) {
|
||||
c += clen;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (c == std::string_view::npos) break; /* substr(o) already appended */
|
||||
std::string_view inner = src.substr(o + olen, c - (o + olen));
|
||||
dst += cstr(inner, codes);
|
||||
p = c + clen;
|
||||
}
|
||||
}
|
||||
static void apply_links(std::string &dst, std::string_view src) {
|
||||
size_t p = 0;
|
||||
while (p < src.size()) {
|
||||
size_t lb = src.find('[', p);
|
||||
if (lb == std::string_view::npos) { dst += src.substr(p); break; }
|
||||
size_t rb = src.find(']', lb);
|
||||
if (rb == std::string_view::npos || rb + 1 >= src.size() || src[rb + 1] != '(') {
|
||||
dst += src.substr(p, lb - p + 1); p = lb + 1; continue;
|
||||
}
|
||||
size_t rp = src.find(')', rb + 2);
|
||||
if (rp == std::string_view::npos) { dst += src.substr(p); break; }
|
||||
std::string_view text = src.substr(lb + 1, rb - (lb + 1));
|
||||
std::string_view url = src.substr(rb + 2, rp - (rb + 2));
|
||||
dst += src.substr(p, lb - p);
|
||||
std::string wt = cstr(text, std::array{4, 36});
|
||||
dst += wt;
|
||||
std::string wu = cstr(url, std::array{2});
|
||||
dst += "(" + wu + ")";
|
||||
p = rp + 1;
|
||||
}
|
||||
}
|
||||
static std::string render_inline(std::string_view s) {
|
||||
if (!g_col) return std::string(s);
|
||||
if (s.empty()) return "";
|
||||
std::vector<std::string> codes;
|
||||
std::string step1;
|
||||
size_t p = 0;
|
||||
while (p < s.size()) {
|
||||
if (s[p] == '`') {
|
||||
size_t start = p + 1;
|
||||
size_t end = s.find('`', start);
|
||||
if (end != std::string_view::npos && end > start) {
|
||||
std::string_view ctext = s.substr(start, end - start);
|
||||
std::string ct = cstr(ctext, std::array{33});
|
||||
codes.push_back(ct);
|
||||
str_appendf(step1, "\x01%zu\x01", codes.size() - 1);
|
||||
p = end + 1;
|
||||
continue;
|
||||
}
|
||||
step1 += s[p]; p++;
|
||||
} else {
|
||||
step1 += s[p]; p++;
|
||||
}
|
||||
}
|
||||
std::string s2; apply_links(s2, step1);
|
||||
std::string s3; wrap_pairs(s3, s2, "***", "***", std::array{1, 3});
|
||||
std::string s4; wrap_pairs(s4, s3, "___", "___", std::array{1, 3});
|
||||
std::string s5; wrap_pairs(s5, s4, "**", "**", std::array{1});
|
||||
std::string s6; wrap_pairs(s6, s5, "__", "__", std::array{1}, true);
|
||||
std::string s7; wrap_pairs(s7, s6, "*", "*", std::array{3});
|
||||
std::string s8; wrap_pairs(s8, s7, "_", "_", std::array{3}, true);
|
||||
std::string s9; wrap_pairs(s9, s8, "~~", "~~", std::array{9});
|
||||
std::string out;
|
||||
size_t q = 0;
|
||||
while (q < s9.size()) {
|
||||
if (s9[q] == '\x01') {
|
||||
size_t e = s9.find('\x01', q + 1);
|
||||
if (e != std::string::npos) {
|
||||
int idx = to_int_val(std::string_view(s9).substr(q + 1, e - (q + 1)), -1);
|
||||
if (idx >= 0 && idx < (int)codes.size()) out += codes[idx];
|
||||
q = e + 1; continue;
|
||||
}
|
||||
}
|
||||
out += s9[q]; q++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ----------------------------- line ----------------------------------- */
|
||||
static int indent_spaces(std::string_view line) {
|
||||
int n = 0;
|
||||
while (n < (int)line.size() && line[n] == ' ') n++;
|
||||
return n;
|
||||
}
|
||||
void render_md_line_print(std::string_view line, MdState &st) {
|
||||
if (!g_col) { printf("%s\n", std::string(line).c_str()); return; }
|
||||
std::string_view t = trim_spaces(line);
|
||||
if (t.size() >= 3 && t.substr(0, 3) == "```") {
|
||||
if (!st.in_code) {
|
||||
st.in_code = true;
|
||||
std::string_view lang = t.substr(3);
|
||||
while (!lang.empty() && lang.front() == ' ') lang.remove_prefix(1);
|
||||
std::string title;
|
||||
if (!lang.empty()) title = sfmt(" [ %s ]", std::string(lang).c_str());
|
||||
std::string s = "───" + title;
|
||||
for (int i = 0; i < 40; i++) s += "─";
|
||||
std::string h = cstr(s, std::array{2});
|
||||
printf("%s\n", h.c_str());
|
||||
} else {
|
||||
st.in_code = false;
|
||||
std::string s;
|
||||
for (int i = 0; i < 50; i++) s += "─";
|
||||
std::string h = cstr(s, std::array{2});
|
||||
printf("%s\n", h.c_str());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (st.in_code) {
|
||||
std::string pre = cstr(" ", std::array{2});
|
||||
std::string body = cstr(line, std::array{32});
|
||||
printf("%s%s\n", pre.c_str(), body.c_str());
|
||||
return;
|
||||
}
|
||||
if (t == "---" || t == "***" || t == "___" || t == "----" || t == "------") {
|
||||
std::string s;
|
||||
for (int i = 0; i < 50; i++) s += "─";
|
||||
std::string h = cstr(s, std::array{2});
|
||||
printf("%s\n", h.c_str());
|
||||
return;
|
||||
}
|
||||
if (!t.empty() && t[0] == '#') {
|
||||
int lvl = 0;
|
||||
while (lvl < (int)t.size() && t[lvl] == '#') lvl++;
|
||||
if (lvl < (int)t.size() && t[lvl] == ' ') {
|
||||
std::string_view htext = trim_spaces(t.substr(lvl));
|
||||
if (lvl == 1) { std::string a = cstr("■ ", std::array{35}); std::string b = cstr(htext, std::array{1, 36}); printf("%s%s\n", a.c_str(), b.c_str()); }
|
||||
else if (lvl == 2) { std::string a = cstr("▲ ", std::array{35}); std::string b = cstr(htext, std::array{1, 36}); printf("%s%s\n", a.c_str(), b.c_str()); }
|
||||
else if (lvl == 3) { std::string a = cstr("● ", std::array{35}); std::string b = cstr(htext, std::array{1, 32}); printf("%s%s\n", a.c_str(), b.c_str()); }
|
||||
else if (lvl == 4) { std::string a = cstr("◆ ", std::array{35}); std::string b = cstr(htext, std::array{1, 33}); printf("%s%s\n", a.c_str(), b.c_str()); }
|
||||
else { std::string b = cstr(htext, std::array{1}); printf("%s\n", b.c_str()); }
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!t.empty() && t[0] == '>') {
|
||||
std::string_view q = trim_spaces(t.substr(1));
|
||||
std::string bar = cstr("▎ ", std::array{34});
|
||||
std::string body = render_inline(q);
|
||||
std::string cbody = cstr(body, std::array{3});
|
||||
printf("%s%s\n", bar.c_str(), cbody.c_str());
|
||||
return;
|
||||
}
|
||||
if (t.size() >= 6 && (t.substr(0, 6) == "- [ ] " || t.substr(0, 6) == "* [ ] ")) {
|
||||
int ind = indent_spaces(line);
|
||||
std::string box = cstr("☐ ", std::array{33});
|
||||
std::string rest = render_inline(t.substr(6));
|
||||
printf("%*s%s%s\n", ind, "", box.c_str(), rest.c_str());
|
||||
return;
|
||||
}
|
||||
if (t.size() >= 6 && (t.substr(0, 6) == "- [x] " || t.substr(0, 6) == "* [x] " ||
|
||||
t.substr(0, 6) == "- [X] " || t.substr(0, 6) == "* [X] ")) {
|
||||
int ind = indent_spaces(line);
|
||||
std::string box = cstr("☑ ", std::array{32});
|
||||
std::string rest = render_inline(t.substr(6));
|
||||
printf("%*s%s%s\n", ind, "", box.c_str(), rest.c_str());
|
||||
return;
|
||||
}
|
||||
if (t.size() >= 2 && (t.substr(0, 2) == "- " || t.substr(0, 2) == "* " || t.substr(0, 2) == "+ ")) {
|
||||
int ind = indent_spaces(line);
|
||||
std::string bullet = cstr("• ", std::array{36});
|
||||
std::string rest = render_inline(t.substr(2));
|
||||
printf("%*s%s%s\n", ind, "", bullet.c_str(), rest.c_str());
|
||||
return;
|
||||
}
|
||||
std::string_view num = t;
|
||||
while (!num.empty() && std::isdigit((unsigned char)num.front())) num.remove_prefix(1);
|
||||
if (!num.empty() && num.front() == '.' && num.size() > 1 && num[1] == ' ') {
|
||||
int ind = indent_spaces(line);
|
||||
size_t nlen = num.data() - t.data();
|
||||
std::string_view nstr = t.substr(0, nlen);
|
||||
std::string bullet = cstr(nstr, std::array{33});
|
||||
std::string rest = render_inline(t.substr(nlen + 2));
|
||||
printf("%*s%s %s\n", ind, "", bullet.c_str(), rest.c_str());
|
||||
return;
|
||||
}
|
||||
std::string r = render_inline(line);
|
||||
printf("%s\n", r.c_str());
|
||||
}
|
||||
|
||||
/* ----------------------------- table ---------------------------------- */
|
||||
static std::vector<std::string> wrap_cell(std::string_view s, int width) {
|
||||
std::vector<std::string> lines;
|
||||
if (width <= 0) { lines.push_back(""); return lines; }
|
||||
std::string copy(s);
|
||||
std::vector<std::string> blocks;
|
||||
std::string cur;
|
||||
size_t p = 0;
|
||||
while (p < copy.size()) {
|
||||
if (copy.compare(p, 4, "<br>") == 0) { blocks.push_back(cur); cur.clear(); p += 4; continue; }
|
||||
if (copy.compare(p, 5, "<br/>") == 0) { blocks.push_back(cur); cur.clear(); p += 5; continue; }
|
||||
if (copy.compare(p, 6, "<br />") == 0) { blocks.push_back(cur); cur.clear(); p += 6; continue; }
|
||||
cur += copy[p]; p++;
|
||||
}
|
||||
if (!cur.empty() || blocks.empty()) blocks.push_back(cur);
|
||||
std::vector<std::string> wrapped;
|
||||
for (auto &cl : blocks) {
|
||||
std::vector<std::string> words;
|
||||
size_t wp = 0;
|
||||
while (wp < cl.size()) {
|
||||
while (wp < cl.size() && cl[wp] == ' ') wp++;
|
||||
if (wp >= cl.size()) break;
|
||||
size_t ws = wp;
|
||||
while (wp < cl.size() && cl[wp] != ' ') wp++;
|
||||
words.push_back(cl.substr(ws, wp - ws));
|
||||
}
|
||||
std::string curline;
|
||||
for (auto &word : words) {
|
||||
int wlen = visible_len(word);
|
||||
if (wlen > width) {
|
||||
std::string w = word;
|
||||
size_t wi = 0;
|
||||
while (wi < w.size()) {
|
||||
if (!curline.empty()) { wrapped.push_back(curline); curline.clear(); }
|
||||
std::string chunk;
|
||||
int clen = 0;
|
||||
size_t ci = wi;
|
||||
while (ci < w.size() && clen < width) {
|
||||
if (w[ci] == 0x1b) {
|
||||
size_t j = ci + 1;
|
||||
if (j < w.size() && w[j] == '[') {
|
||||
j++;
|
||||
while (j < w.size() && !(w[j] >= 0x40 && w[j] <= 0x7e)) j++;
|
||||
if (j < w.size()) j++;
|
||||
}
|
||||
chunk += w.substr(ci, j - ci); ci = j;
|
||||
continue;
|
||||
}
|
||||
size_t pl; int cp = utf8_decode((const unsigned char *)(w.data() + ci), w.size() - ci, &pl);
|
||||
chunk += w.substr(ci, pl); ci += pl; clen += rune_width(cp);
|
||||
}
|
||||
wrapped.push_back(chunk);
|
||||
wi = ci;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
int curlen = visible_len(curline);
|
||||
if (curline.empty()) curline = word;
|
||||
else if (curlen + 1 + wlen <= width) { curline += ' '; curline += word; }
|
||||
else { wrapped.push_back(curline); curline = word; }
|
||||
}
|
||||
if (!curline.empty()) wrapped.push_back(curline);
|
||||
}
|
||||
if (wrapped.empty()) wrapped.push_back("");
|
||||
return wrapped;
|
||||
}
|
||||
|
||||
static void print_row(int num_cols, const std::vector<int> &col_widths,
|
||||
const std::vector<std::string> &cells, bool is_header) {
|
||||
std::string s = "│";
|
||||
for (int i = 0; i < num_cols; i++) {
|
||||
std::string_view txt = (i < (int)cells.size()) ? std::string_view(cells[i]) : std::string_view();
|
||||
int pad = col_widths[i] - visible_len(txt);
|
||||
if (pad < 0) pad = 0;
|
||||
std::string cell = " ";
|
||||
cell.append(txt);
|
||||
cell.append((size_t)pad + 1, ' ');
|
||||
if (is_header) { std::string cc = cstr(cell, std::array{1}); s += cc; }
|
||||
else { std::string cc = cstr(cell, std::array{2}); s += cc; }
|
||||
s += "│";
|
||||
}
|
||||
std::string h = cstr(s, std::array{2});
|
||||
printf("%s\n", h.c_str());
|
||||
}
|
||||
|
||||
void render_table_print(const std::vector<std::string> &lines) {
|
||||
if (lines.empty()) return;
|
||||
/* Not an actual table (e.g. a list whose items merely contain '|'): render
|
||||
* the lines as ordinary markdown instead of forcing a box-drawing table. */
|
||||
if (!looks_like_table(lines)) {
|
||||
MdState st;
|
||||
for (auto &ln : lines) render_md_line_print(ln, st);
|
||||
return;
|
||||
}
|
||||
std::vector<std::vector<std::string>> rows_cells;
|
||||
std::vector<std::string> header_cells;
|
||||
bool has_header = false;
|
||||
for (auto &line : lines) {
|
||||
auto cells = parse_table_cells(line);
|
||||
if (is_table_sep(cells)) {
|
||||
if (!rows_cells.empty() && !has_header) {
|
||||
header_cells = std::move(rows_cells.back());
|
||||
rows_cells.pop_back();
|
||||
has_header = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
rows_cells.push_back(std::move(cells));
|
||||
}
|
||||
if (!has_header && lines.size() < 2) {
|
||||
MdState st;
|
||||
for (auto &ln : lines) render_md_line_print(ln, st);
|
||||
return;
|
||||
}
|
||||
int num_cols = (int)header_cells.size();
|
||||
for (auto &row : rows_cells) if ((int)row.size() > num_cols) num_cols = (int)row.size();
|
||||
if (num_cols == 0) return;
|
||||
if (has_header) { while ((int)header_cells.size() < num_cols) header_cells.push_back(""); }
|
||||
std::vector<int> col_widths(num_cols, 0);
|
||||
for (int i = 0; i < num_cols; i++) {
|
||||
if (has_header) { int vl = visible_len(header_cells[i]); if (vl > col_widths[i]) col_widths[i] = vl; }
|
||||
for (auto &row : rows_cells) {
|
||||
std::string_view cell = (i < (int)row.size()) ? std::string_view(row[i]) : std::string_view();
|
||||
std::string ri = render_inline(cell);
|
||||
int vl = visible_len(ri);
|
||||
if (vl > col_widths[i]) col_widths[i] = vl;
|
||||
}
|
||||
if (col_widths[i] < 3) col_widths[i] = 3;
|
||||
}
|
||||
int max_table_width = term_width();
|
||||
if (max_table_width < 20) max_table_width = 80;
|
||||
int overhead = 3 * num_cols + 1;
|
||||
int avail = max_table_width - overhead;
|
||||
if (avail < num_cols * 3) avail = num_cols * 3;
|
||||
int tot = 0;
|
||||
for (int i = 0; i < num_cols; i++) tot += col_widths[i];
|
||||
while (tot > avail) {
|
||||
int maxIdx = 0, maxVal = col_widths[0];
|
||||
for (int i = 1; i < num_cols; i++) if (col_widths[i] > maxVal) { maxVal = col_widths[i]; maxIdx = i; }
|
||||
if (maxVal <= 3) break;
|
||||
col_widths[maxIdx]--; tot--;
|
||||
}
|
||||
{
|
||||
std::string s = "┌";
|
||||
for (int i = 0; i < num_cols; i++) { for (int j = 0; j < col_widths[i] + 2; j++) s += "─"; if (i < num_cols - 1) s += "┬"; }
|
||||
s += "┐";
|
||||
std::string h = cstr(s, std::array{2});
|
||||
printf("%s\n", h.c_str());
|
||||
}
|
||||
if (has_header) {
|
||||
std::vector<std::vector<std::string>> hw(num_cols);
|
||||
int maxh = 1;
|
||||
for (int i = 0; i < num_cols; i++) {
|
||||
std::string ri = render_inline(header_cells[i]);
|
||||
hw[i] = wrap_cell(ri, col_widths[i]);
|
||||
if ((int)hw[i].size() > maxh) maxh = (int)hw[i].size();
|
||||
}
|
||||
for (int lr = 0; lr < maxh; lr++) {
|
||||
std::vector<std::string> rowview(num_cols);
|
||||
for (int i = 0; i < num_cols; i++) rowview[i] = (lr < (int)hw[i].size()) ? hw[i][lr] : "";
|
||||
print_row(num_cols, col_widths, rowview, true);
|
||||
}
|
||||
{
|
||||
std::string s = "├";
|
||||
for (int i = 0; i < num_cols; i++) { for (int j = 0; j < col_widths[i] + 2; j++) s += "─"; if (i < num_cols - 1) s += "┼"; }
|
||||
s += "┤";
|
||||
std::string h = cstr(s, std::array{2});
|
||||
printf("%s\n", h.c_str());
|
||||
}
|
||||
}
|
||||
for (auto &row : rows_cells) {
|
||||
std::vector<std::vector<std::string>> rw(num_cols);
|
||||
int maxr = 1;
|
||||
for (int i = 0; i < num_cols; i++) {
|
||||
std::string_view cell = (i < (int)row.size()) ? std::string_view(row[i]) : std::string_view();
|
||||
std::string ri = render_inline(cell);
|
||||
rw[i] = wrap_cell(ri, col_widths[i]);
|
||||
if ((int)rw[i].size() > maxr) maxr = (int)rw[i].size();
|
||||
}
|
||||
for (int lr = 0; lr < maxr; lr++) {
|
||||
std::vector<std::string> rowview(num_cols);
|
||||
for (int i = 0; i < num_cols; i++) rowview[i] = (lr < (int)rw[i].size()) ? rw[i][lr] : "";
|
||||
print_row(num_cols, col_widths, rowview, false);
|
||||
}
|
||||
}
|
||||
{
|
||||
std::string s = "└";
|
||||
for (int i = 0; i < num_cols; i++) { for (int j = 0; j < col_widths[i] + 2; j++) s += "─"; if (i < num_cols - 1) s += "┴"; }
|
||||
s += "┘";
|
||||
std::string h = cstr(s, std::array{2});
|
||||
printf("%s\n", h.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------- block ---------------------------------- */
|
||||
void render_md_print(std::string_view text) {
|
||||
if (!g_col) { if (!text.empty()) fputs(std::string(text).c_str(), stdout); return; }
|
||||
if (text.empty()) return;
|
||||
std::vector<std::string> tbl;
|
||||
MdState st;
|
||||
size_t start = 0;
|
||||
while (true) {
|
||||
auto nl = text.find('\n', start);
|
||||
std::string_view line = (nl == std::string_view::npos) ? text.substr(start) : text.substr(start, nl - start);
|
||||
std::string lstr(line);
|
||||
std::string_view t = trim_spaces(lstr);
|
||||
bool is_tbl = (!st.in_code && !(t.size() >= 3 && t.substr(0, 3) == "```") && is_table_line(lstr));
|
||||
if (is_tbl) {
|
||||
tbl.push_back(lstr);
|
||||
} else {
|
||||
if (!tbl.empty()) { render_table_print(tbl); tbl.clear(); }
|
||||
render_md_line_print(lstr, st);
|
||||
}
|
||||
if (nl == std::string_view::npos) break;
|
||||
start = nl + 1;
|
||||
}
|
||||
if (!tbl.empty()) render_table_print(tbl);
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
/* session.cpp — session persistence, loading, compaction. */
|
||||
#include "bantam.hpp"
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <dirent.h>
|
||||
#include <memory>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static const char *compaction_prompt =
|
||||
"You are now acting as a compaction engine. Summarize the preceding conversation concisely but completely, preserving all important facts, decisions, code snippets, tool outputs, errors, and current task state so work can seamlessly continue. Output only the summary.";
|
||||
|
||||
/* ----------------------------- paths ---------------------------------- */
|
||||
static std::string home_dir() {
|
||||
const char *h = std::getenv("HOME");
|
||||
if (h && *h) return h;
|
||||
return ".";
|
||||
}
|
||||
static std::string sessions_dir() {
|
||||
std::string d = home_dir() + "/.bantam/sessions";
|
||||
mkdir_p(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
/* Remove only the saved session belonging to the current working directory.
|
||||
* Session ids are MD5 hashes of the project path; other projects' sessions and
|
||||
* named /save sessions live in the same directory and must be left untouched.
|
||||
* The fresh conversation is re-saved by the caller, so a stale system prompt
|
||||
* cannot be resumed for this project. Returns false with an explanation on
|
||||
* failure. */
|
||||
bool clear_project_session(std::string *err) {
|
||||
if (err) err->clear();
|
||||
std::string d = sessions_dir();
|
||||
struct stat dst;
|
||||
/* Never follow a symlink at the sessions path. */
|
||||
if (lstat(d.c_str(), &dst) != 0 || !S_ISDIR(dst.st_mode)) {
|
||||
if (err) *err = sfmt("refusing to use unexpected session directory: %s", d.c_str());
|
||||
return false;
|
||||
}
|
||||
std::string path = d + "/" + project_id() + ".json";
|
||||
struct stat st;
|
||||
if (lstat(path.c_str(), &st) != 0) {
|
||||
if (errno == ENOENT) return true; /* no session for this project yet */
|
||||
if (err) *err = sfmt("could not stat %s: %s", path.c_str(), std::strerror(errno));
|
||||
return false;
|
||||
}
|
||||
if (S_ISDIR(st.st_mode)) {
|
||||
if (err) *err = sfmt("refusing to remove unexpected session directory: %s", path.c_str());
|
||||
return false;
|
||||
}
|
||||
/* A stray symlink is unlinked, never followed. */
|
||||
if (unlink(path.c_str()) != 0) {
|
||||
if (err) *err = sfmt("could not remove %s: %s", path.c_str(), std::strerror(errno));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Compatibility alias: /clear only ever touches the current project's session. */
|
||||
bool clear_sessions(std::string *err) {
|
||||
return clear_project_session(err);
|
||||
}
|
||||
|
||||
static bool load_session_file(const std::string &full, Session &s) {
|
||||
std::string buf;
|
||||
if (!read_file_str(full, buf)) return false;
|
||||
Json root_mut;
|
||||
if (!Json::parse(buf, root_mut) || !root_mut.is_object()) return false;
|
||||
const Json &root = root_mut;
|
||||
s = Session{};
|
||||
s.id = root["id"].str();
|
||||
s.created = root["created"].str();
|
||||
s.summary = root["summary"].str();
|
||||
const Json &marr = root["messages"];
|
||||
if (marr.is_array()) {
|
||||
s.messages.items.reserve(marr.aval.size());
|
||||
for (auto &mo : marr.aval) {
|
||||
Message m;
|
||||
parse_message_json(mo, m);
|
||||
s.messages.items.push_back(std::move(m));
|
||||
}
|
||||
}
|
||||
if (s.summary.empty()) s.summary = "(no summary)";
|
||||
return true;
|
||||
}
|
||||
|
||||
void save_session(const Messages &msgs, std::string_view sid,
|
||||
std::string *out_id, std::string *out_summary) {
|
||||
std::string id = (!sid.empty()) ? std::string(sid) : project_id();
|
||||
std::string d = sessions_dir();
|
||||
std::string path = d + "/" + id + ".json";
|
||||
Json root = Json::object();
|
||||
root["id"] = id;
|
||||
time_t now = time(nullptr);
|
||||
struct tm tm_buf{};
|
||||
localtime_r(&now, &tm_buf);
|
||||
char ts[64];
|
||||
std::strftime(ts, sizeof ts, "%Y-%m-%d %H:%M:%S", &tm_buf);
|
||||
root["created"] = ts;
|
||||
std::string sum = summary_of(msgs);
|
||||
root["summary"] = sum;
|
||||
Json arr = Json::array();
|
||||
arr.aval.reserve(msgs.items.size());
|
||||
for (auto &m : msgs.items) {
|
||||
Json mo;
|
||||
serialize_message_json(mo, m);
|
||||
arr.push_back(std::move(mo));
|
||||
}
|
||||
root["messages"] = std::move(arr);
|
||||
write_file_str(path, root.dump(2));
|
||||
if (out_id) *out_id = id;
|
||||
if (out_summary) *out_summary = sum;
|
||||
}
|
||||
|
||||
std::vector<Session> sessions_load() {
|
||||
std::vector<Session> ss;
|
||||
std::string d = sessions_dir();
|
||||
std::vector<std::string> files;
|
||||
{
|
||||
DIR *dir = opendir(d.c_str());
|
||||
if (dir) {
|
||||
struct dirent *de;
|
||||
while ((de = readdir(dir))) {
|
||||
std::string nm = de->d_name;
|
||||
if (nm == "." || nm == "..") continue;
|
||||
if (nm.size() < 5 || nm.substr(nm.size() - 5) != ".json") continue;
|
||||
files.push_back(std::move(nm));
|
||||
}
|
||||
closedir(dir);
|
||||
}
|
||||
}
|
||||
std::sort(files.begin(), files.end());
|
||||
ss.reserve(files.size());
|
||||
for (auto &nm : files) {
|
||||
std::string full = d + "/" + nm;
|
||||
Session s;
|
||||
if (load_session_file(full, s)) {
|
||||
ss.push_back(std::move(s));
|
||||
}
|
||||
}
|
||||
/* sort by id descending (newest first) */
|
||||
std::sort(ss.begin(), ss.end(), [](const Session &a, const Session &b) {
|
||||
return a.id > b.id;
|
||||
});
|
||||
return ss;
|
||||
}
|
||||
|
||||
std::unique_ptr<Messages> load_session(std::string_view sid, std::string *err) {
|
||||
if (!sid.empty() && sid.find('/') == std::string_view::npos) {
|
||||
std::string exact = sessions_dir() + "/" + std::string(sid) + ".json";
|
||||
Session s;
|
||||
if (load_session_file(exact, s) && s.id == sid) {
|
||||
return std::make_unique<Messages>(std::move(s.messages));
|
||||
}
|
||||
}
|
||||
auto ss = sessions_load();
|
||||
for (auto &s : ss) {
|
||||
if (s.id == sid) {
|
||||
return std::make_unique<Messages>(std::move(s.messages));
|
||||
}
|
||||
}
|
||||
/* prefix match */
|
||||
std::vector<Session *> pref;
|
||||
for (auto &s : ss) if (s.id.starts_with(sid)) pref.push_back(&s);
|
||||
if (pref.size() == 1) {
|
||||
return std::make_unique<Messages>(std::move(pref[0]->messages));
|
||||
}
|
||||
if (pref.size() > 1) {
|
||||
std::string names;
|
||||
for (auto *p : pref) str_appendf(names, "%s, ", p->id.c_str());
|
||||
if (names.size() > 2) names.resize(names.size() - 2);
|
||||
if (err) *err = sfmt("ambiguous prefix: %s", names.c_str());
|
||||
} else {
|
||||
if (err) *err = sfmt("session not found: %s", std::string(sid).c_str());
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::unique_ptr<Session> find_project_session() {
|
||||
std::string pid = project_id();
|
||||
std::string path = sessions_dir() + "/" + pid + ".json";
|
||||
auto found = std::make_unique<Session>();
|
||||
if (load_session_file(path, *found) && found->id == pid) {
|
||||
return found;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void autosave(const Messages &msgs) {
|
||||
std::string id, sum;
|
||||
save_session(msgs, project_id(), &id, &sum);
|
||||
}
|
||||
|
||||
/* ----------------------------- summary / compact ---------------------- */
|
||||
std::string summary_of(const Messages &msgs) {
|
||||
for (auto &m : msgs.items) {
|
||||
if (m.role == "user" && !m.content.empty()) {
|
||||
std::string s;
|
||||
const char *p = m.content.c_str();
|
||||
bool prev_space = false;
|
||||
while (*p) {
|
||||
if (*p == '\n' || *p == '\t' || *p == '\r') { if (!prev_space) s += ' '; prev_space = true; }
|
||||
else { s += *p; prev_space = false; }
|
||||
p++;
|
||||
}
|
||||
if (s.size() > 80) {
|
||||
size_t len = utf8_truncate(s, 80).size();
|
||||
s.resize(len);
|
||||
s += "...";
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
return "(empty session)";
|
||||
}
|
||||
|
||||
std::unique_ptr<Messages> compact(Cfg &cfg, const Messages &msgs, std::string *summary,
|
||||
std::string *err, volatile int *interrupted) {
|
||||
if (msgs.items.empty() || msgs.items[0].role != "system") {
|
||||
if (err) *err = "session has no system message";
|
||||
return nullptr;
|
||||
}
|
||||
if (msgs.items.size() <= 1) { if (err) *err = "nothing to compact"; return nullptr; }
|
||||
Messages cMsgs;
|
||||
for (auto &m : msgs.items) cMsgs.items.push_back(m);
|
||||
Message userp;
|
||||
userp.role = "user";
|
||||
userp.content = compaction_prompt;
|
||||
cMsgs.items.push_back(std::move(userp));
|
||||
|
||||
Cfg cc = cfg; cc.stream = false; cc.force_stream = false; /* force non-streaming for clean summary */
|
||||
Message m; Usage u;
|
||||
std::string lerr;
|
||||
int rc = llm(cc, cMsgs, false, m, u, lerr, interrupted);
|
||||
if (rc != 0) { if (err) *err = lerr.empty() ? "compaction LLM call failed" : lerr; return nullptr; }
|
||||
std::string s;
|
||||
if (!m.content.empty()) s = m.content;
|
||||
else if (!m.reasoning.empty()) s = m.reasoning;
|
||||
else { if (err) *err = "LLM returned an empty summary"; return nullptr; }
|
||||
size_t a = 0;
|
||||
while (a < s.size() && (s[a] == ' ' || s[a] == '\n' || s[a] == '\r' || s[a] == '\t')) a++;
|
||||
std::string trim = s.substr(a);
|
||||
while (!trim.empty() && (trim.back() == ' ' || trim.back() == '\n' || trim.back() == '\r' || trim.back() == '\t'))
|
||||
trim.pop_back();
|
||||
std::string final = trim;
|
||||
|
||||
auto newMsgs = std::make_unique<Messages>();
|
||||
Message sys; sys.role = "system";
|
||||
sys.content = msgs.items[0].content;
|
||||
newMsgs->items.push_back(std::move(sys));
|
||||
Message sm; sm.role = "user";
|
||||
sm.content = sfmt("Summary of the previous conversation:\n%s\n\nPlease continue from here.", final.c_str());
|
||||
newMsgs->items.push_back(std::move(sm));
|
||||
if (summary) *summary = newMsgs->items[1].content;
|
||||
return newMsgs;
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
/* tools.cpp — bash/read/write tools and oversized result offloading. */
|
||||
#include "bantam.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <dirent.h>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
/* ----------------------------- shell ---------------------------------- */
|
||||
/* Resolve the Bourne-again shell from the system PATH. Returns a static
|
||||
* buffer holding the absolute path to `bash`, or "/bin/sh" when bash cannot
|
||||
* be located anywhere on PATH. Never returns a hardcoded bash path. */
|
||||
static const char *resolve_shell() {
|
||||
static char buf[4096];
|
||||
static const char *cached = nullptr;
|
||||
if (cached) return cached;
|
||||
const char *path = getenv("PATH");
|
||||
if (path && *path) {
|
||||
std::string p(path);
|
||||
size_t start = 0;
|
||||
while (start <= p.size()) {
|
||||
size_t end = p.find(':', start);
|
||||
std::string dir = (end == std::string::npos) ? p.substr(start)
|
||||
: p.substr(start, end - start);
|
||||
if (!dir.empty() && dir.back() != '/') dir += '/';
|
||||
std::string cand = dir + "bash";
|
||||
struct stat st;
|
||||
if (stat(cand.c_str(), &st) == 0 && S_ISREG(st.st_mode) &&
|
||||
(st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0) {
|
||||
snprintf(buf, sizeof buf, "%s", cand.c_str());
|
||||
cached = buf;
|
||||
return cached;
|
||||
}
|
||||
if (end == std::string::npos) break;
|
||||
start = end + 1;
|
||||
}
|
||||
}
|
||||
cached = "/bin/sh";
|
||||
return cached;
|
||||
}
|
||||
|
||||
std::string shell_with_workdir(std::string_view cmd, std::string_view workdir,
|
||||
int timeout, volatile int *interrupted) {
|
||||
std::string fcmd = filter_text(cmd);
|
||||
if (timeout <= 0) timeout = 120;
|
||||
const char *sh = resolve_shell();
|
||||
|
||||
int pipefd[2];
|
||||
if (pipe(pipefd) != 0) return "[tool error: pipe failed]";
|
||||
pid_t pid = fork();
|
||||
if (pid < 0) {
|
||||
close(pipefd[0]);
|
||||
close(pipefd[1]);
|
||||
return "[tool error: fork failed]";
|
||||
}
|
||||
if (pid == 0) {
|
||||
/* child: create a dedicated process group so timeout/SIGINT kills the
|
||||
* entire process tree spawned by the shell. */
|
||||
setpgid(0, 0);
|
||||
dup2(pipefd[1], STDOUT_FILENO);
|
||||
dup2(pipefd[1], STDERR_FILENO);
|
||||
close(pipefd[0]);
|
||||
close(pipefd[1]);
|
||||
if (!workdir.empty() && chdir(std::string(workdir).c_str()) != 0) {
|
||||
/* Never silently run the command in the wrong directory. stderr is
|
||||
* already dup2'd onto the output pipe, and _exit() skips stdio
|
||||
* flushing, so write straight to the descriptor. */
|
||||
dprintf(STDERR_FILENO, "[tool error: workdir '%s': %s]\n",
|
||||
std::string(workdir).c_str(), strerror(errno));
|
||||
_exit(1);
|
||||
}
|
||||
const char *shname = (strrchr(sh, '/') ? strrchr(sh, '/') + 1 : sh);
|
||||
execl(sh, shname, "-c", fcmd.c_str(), (char *)nullptr);
|
||||
_exit(127);
|
||||
}
|
||||
close(pipefd[1]);
|
||||
|
||||
int flags = fcntl(pipefd[0], F_GETFL, 0);
|
||||
fcntl(pipefd[0], F_SETFL, flags | O_NONBLOCK);
|
||||
|
||||
std::string out;
|
||||
struct pollfd pfd; pfd.fd = pipefd[0]; pfd.events = POLLIN;
|
||||
time_t deadline = time(nullptr) + timeout;
|
||||
bool killed = false;
|
||||
while (true) {
|
||||
if (*interrupted) break;
|
||||
int remain = (int)(deadline - time(nullptr));
|
||||
if (remain <= 0) { killed = true; break; }
|
||||
int wait_ms = remain * 1000;
|
||||
if (wait_ms > 200) wait_ms = 200;
|
||||
int pr = poll(&pfd, 1, wait_ms);
|
||||
if (pr < 0) { if (errno == EINTR) continue; break; }
|
||||
if (pr == 0) continue;
|
||||
char buf[4096];
|
||||
ssize_t n = read(pipefd[0], buf, sizeof buf);
|
||||
if (n > 0) out.append(buf, (size_t)n);
|
||||
else if (n == 0) break; /* EOF: child exited */
|
||||
else if (errno == EAGAIN || errno == EWOULDBLOCK) continue;
|
||||
else break;
|
||||
}
|
||||
if (*interrupted || killed) {
|
||||
kill(-pid, SIGKILL);
|
||||
kill(pid, SIGKILL);
|
||||
/* drain remaining output briefly */
|
||||
struct pollfd dpfd; dpfd.fd = pipefd[0]; dpfd.events = POLLIN;
|
||||
for (int i = 0; i < 20; i++) {
|
||||
int pr = poll(&dpfd, 1, 50);
|
||||
if (pr <= 0) break;
|
||||
char buf[4096];
|
||||
ssize_t n = read(pipefd[0], buf, sizeof buf);
|
||||
if (n > 0) out.append(buf, (size_t)n);
|
||||
else break;
|
||||
}
|
||||
}
|
||||
int status = 0;
|
||||
while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {}
|
||||
close(pipefd[0]);
|
||||
|
||||
std::string filtered = filter_text(out);
|
||||
/* trim trailing whitespace */
|
||||
while (!filtered.empty() &&
|
||||
(filtered.back() == '\n' || filtered.back() == '\r' ||
|
||||
filtered.back() == ' ' || filtered.back() == '\t'))
|
||||
filtered.pop_back();
|
||||
|
||||
if (*interrupted) {
|
||||
return filtered + "\n\nexit: -1";
|
||||
}
|
||||
if (killed) {
|
||||
return sfmt("%s\n\n[shell timeout after %ds]\nexit: -1", filtered.c_str(), timeout);
|
||||
}
|
||||
int code = 0;
|
||||
if (WIFEXITED(status)) code = WEXITSTATUS(status);
|
||||
else if (WIFSIGNALED(status)) code = -1;
|
||||
return sfmt("%s\n\nexit: %d", filtered.c_str(), code);
|
||||
}
|
||||
|
||||
/* ----------------------------- read ----------------------------------- */
|
||||
std::string read_file_or_dir(std::string_view path, int offset, int limit, int *style) {
|
||||
std::string p(path);
|
||||
/* trim */
|
||||
size_t s = 0;
|
||||
while (s < p.size() && (p[s] == ' ' || p[s] == '\t')) s++;
|
||||
p = p.substr(s);
|
||||
if (p.empty()) { *style = 31; return "[tool error: read requires 'filePath' parameter]"; }
|
||||
struct stat st;
|
||||
if (stat(p.c_str(), &st) != 0) {
|
||||
*style = 31;
|
||||
return sfmt("[tool error: read %s: %s]", p.c_str(), strerror(errno));
|
||||
}
|
||||
/* Refuse FIFOs, devices and sockets: fopen() on them can block forever. */
|
||||
if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode)) {
|
||||
*style = 31;
|
||||
return sfmt("[tool error: read %s: not a regular file or directory]", p.c_str());
|
||||
}
|
||||
if (S_ISDIR(st.st_mode)) {
|
||||
struct DirEnt {
|
||||
std::string name;
|
||||
int is_dir; /* -1 = unknown, 0 = non-dir, 1 = dir */
|
||||
};
|
||||
std::vector<DirEnt> entries;
|
||||
{
|
||||
DIR *dir = opendir(p.c_str());
|
||||
if (!dir) { *style = 31; return "[tool error: read (directory listing failed)]"; }
|
||||
struct dirent *de;
|
||||
while ((de = readdir(dir))) {
|
||||
if (de->d_name[0] == '.' &&
|
||||
(de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0')))
|
||||
continue;
|
||||
int isdir = -1;
|
||||
#if defined(DT_DIR) && defined(DT_UNKNOWN) && defined(DT_LNK)
|
||||
if (de->d_type != DT_UNKNOWN && de->d_type != DT_LNK) {
|
||||
isdir = (de->d_type == DT_DIR) ? 1 : 0;
|
||||
}
|
||||
#endif
|
||||
entries.push_back(DirEnt{de->d_name, isdir});
|
||||
}
|
||||
closedir(dir);
|
||||
}
|
||||
std::sort(entries.begin(), entries.end(), [](const DirEnt &a, const DirEnt &b) {
|
||||
return a.name < b.name;
|
||||
});
|
||||
std::string b;
|
||||
for (auto &ent : entries) {
|
||||
bool isdir = (ent.is_dir == 1);
|
||||
if (ent.is_dir < 0) {
|
||||
std::string full = p + "/" + ent.name;
|
||||
struct stat ds;
|
||||
isdir = (stat(full.c_str(), &ds) == 0 && S_ISDIR(ds.st_mode));
|
||||
}
|
||||
b += ent.name;
|
||||
if (isdir) b += '/';
|
||||
b += '\n';
|
||||
}
|
||||
if (!b.empty()) b.pop_back(); /* trailing newline */
|
||||
*style = 2;
|
||||
return b;
|
||||
}
|
||||
/* regular file */
|
||||
FILE *f = std::fopen(p.c_str(), "rb");
|
||||
if (!f) { *style = 31; return sfmt("[tool error: read %s: %s]", p.c_str(), strerror(errno)); }
|
||||
if (offset < 1) offset = 1;
|
||||
if (limit <= 0) limit = 2000;
|
||||
std::string b;
|
||||
char *line_buf = nullptr;
|
||||
size_t cap = 0;
|
||||
ssize_t n;
|
||||
int line_num = 0, read_count = 0;
|
||||
while ((n = getline(&line_buf, &cap, f)) >= 0) {
|
||||
line_num++;
|
||||
if (line_num < offset) continue;
|
||||
read_count++;
|
||||
size_t len = (size_t)n;
|
||||
while (len > 0 && (line_buf[len - 1] == '\n' || line_buf[len - 1] == '\r')) len--;
|
||||
std::string_view lview = utf8_truncate(std::string_view(line_buf, len), 2000);
|
||||
str_appendf(b, "%d: ", line_num);
|
||||
b.append(lview);
|
||||
/* Never truncate silently: an agent copying read output back into write
|
||||
* content must know the line was clipped. */
|
||||
if (lview.size() < len)
|
||||
str_appendf(b, " [truncated: showing %zu of %zu bytes]", lview.size(), len);
|
||||
b += '\n';
|
||||
if (read_count >= limit) break;
|
||||
}
|
||||
free(line_buf);
|
||||
std::fclose(f);
|
||||
if (!b.empty()) b.pop_back(); /* trailing newline */
|
||||
*style = 2;
|
||||
return b;
|
||||
}
|
||||
|
||||
/* ----------------------------- write ---------------------------------- */
|
||||
/* Line helpers. `count_lines` matches the read tool's numbering: a trailing
|
||||
* newline terminates the last line, it does not create an extra empty line. */
|
||||
static size_t count_lines(std::string_view data) {
|
||||
if (data.empty()) return 0;
|
||||
size_t n = 0;
|
||||
for (char c : data) if (c == '\n') n++;
|
||||
if (data.back() != '\n') n++;
|
||||
return n;
|
||||
}
|
||||
static size_t line_start_offset(std::string_view data, long line_no) {
|
||||
if (line_no <= 1) return 0;
|
||||
size_t pos = 0;
|
||||
long cur = 1;
|
||||
while (pos < data.size()) {
|
||||
if (data[pos] == '\n') {
|
||||
cur++;
|
||||
if (cur == line_no) return pos + 1;
|
||||
}
|
||||
pos++;
|
||||
}
|
||||
return data.size(); /* past end -> append */
|
||||
}
|
||||
static size_t lines_byte_len(std::string_view data, size_t start, long nlines) {
|
||||
if (nlines <= 0 || start >= data.size()) return 0;
|
||||
size_t pos = start;
|
||||
long consumed = 0;
|
||||
while (pos < data.size() && consumed < nlines) {
|
||||
if (data[pos] == '\n') consumed++;
|
||||
pos++;
|
||||
}
|
||||
return pos - start;
|
||||
}
|
||||
static size_t line_number_at(std::string_view data, size_t off) {
|
||||
size_t n = 1;
|
||||
for (size_t i = 0; i < off && i < data.size(); i++)
|
||||
if (data[i] == '\n') n++;
|
||||
return n;
|
||||
}
|
||||
static std::string_view line_at(std::string_view data, size_t off) {
|
||||
size_t e = data.find('\n', off);
|
||||
std::string_view l = (e == std::string_view::npos)
|
||||
? data.substr(off) : data.substr(off, e - off);
|
||||
while (!l.empty() && l.back() == '\r') l.remove_suffix(1);
|
||||
return l;
|
||||
}
|
||||
static std::string_view last_content_line(std::string_view data) {
|
||||
size_t end = data.size();
|
||||
while (end > 0 && (data[end - 1] == '\n' || data[end - 1] == '\r')) end--;
|
||||
if (end == 0) return {};
|
||||
size_t nl = data.rfind('\n', end - 1);
|
||||
size_t start = (nl == std::string_view::npos) ? 0 : nl + 1;
|
||||
return line_at(data.substr(0, end), start);
|
||||
}
|
||||
static std::string first_line_of(std::string_view s) {
|
||||
auto e = s.find('\n');
|
||||
std::string_view l = (e == std::string_view::npos) ? s : s.substr(0, e);
|
||||
while (!l.empty() && l.back() == '\r') l.remove_suffix(1);
|
||||
return std::string(l);
|
||||
}
|
||||
|
||||
std::string write_file(std::string_view path, const WriteOpts &o,
|
||||
std::string_view content, int *err) {
|
||||
*err = 0;
|
||||
std::string p(path);
|
||||
size_t s = 0;
|
||||
while (s < p.size() && (p[s] == ' ' || p[s] == '\t')) s++;
|
||||
size_t e = p.size();
|
||||
while (e > s && (p[e - 1] == ' ' || p[e - 1] == '\t')) e--;
|
||||
p = p.substr(s, e - s);
|
||||
if (p.empty()) { *err = 1; return "[tool error: write requires 'filePath' parameter]"; }
|
||||
|
||||
/* Load the existing file. Refuse anything that is not a regular file so a
|
||||
* FIFO/device cannot hang the read, and so we never truncate a directory. */
|
||||
std::string data;
|
||||
struct stat st;
|
||||
if (stat(p.c_str(), &st) == 0) {
|
||||
if (S_ISDIR(st.st_mode)) {
|
||||
*err = 1;
|
||||
return sfmt("[tool error: write %s: Is a directory]", p.c_str());
|
||||
}
|
||||
if (!S_ISREG(st.st_mode)) {
|
||||
*err = 1;
|
||||
return sfmt("[tool error: write %s: not a regular file]", p.c_str());
|
||||
}
|
||||
if (!read_file_str(p, data)) {
|
||||
*err = 1;
|
||||
return sfmt("[tool error: write %s: %s]", p.c_str(), strerror(errno));
|
||||
}
|
||||
} else {
|
||||
auto slash = p.find_last_of('/');
|
||||
std::string parent = (slash == std::string::npos) ? std::string(".")
|
||||
: p.substr(0, slash);
|
||||
if (parent.empty()) parent = "/";
|
||||
mkdir_p(parent);
|
||||
struct stat ds;
|
||||
if (stat(parent.c_str(), &ds) != 0 || !S_ISDIR(ds.st_mode)) {
|
||||
*err = 1;
|
||||
return sfmt("[tool error: write %s: cannot create parent directory %s]",
|
||||
p.c_str(), parent.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
const size_t old_lines = count_lines(data);
|
||||
std::string nd;
|
||||
std::string note;
|
||||
|
||||
auto finish = [&](std::string_view what) -> std::string {
|
||||
if (!write_file_str(p, nd)) {
|
||||
*err = 1;
|
||||
return sfmt("[tool error: write %s: %s]", p.c_str(), strerror(errno));
|
||||
}
|
||||
std::string r = sfmt("%s in %s (file now %zu lines, %zu bytes)",
|
||||
std::string(what).c_str(), p.c_str(),
|
||||
count_lines(nd), nd.size());
|
||||
if (!note.empty()) { r += "\n[hint: "; r += note; r += "]"; }
|
||||
return r;
|
||||
};
|
||||
|
||||
/* ---- mode 0: whole-file overwrite (exact bytes, no injected newline) -- */
|
||||
bool any_mode = o.has_find || o.append || o.has_line || o.has_byte ||
|
||||
o.has_del_lines || o.has_del_bytes;
|
||||
if (!any_mode) {
|
||||
nd.assign(content);
|
||||
return finish(sfmt("Overwrote whole file with %zu bytes", content.size()));
|
||||
}
|
||||
|
||||
/* ---- mode 1: find/replace — no line numbers needed at all ------------ */
|
||||
if (o.has_find) {
|
||||
if (o.find.empty()) {
|
||||
*err = 1;
|
||||
return "[tool error: 'find' must not be empty; omit it to overwrite the whole file]";
|
||||
}
|
||||
size_t cnt = 0;
|
||||
size_t pos = 0;
|
||||
while ((pos = data.find(o.find, pos)) != std::string::npos) {
|
||||
cnt++;
|
||||
pos += o.find.size();
|
||||
}
|
||||
if (cnt == 0) {
|
||||
*err = 1;
|
||||
return sfmt("[tool error: 'find' text not found in %s (%zu lines). Use the read tool to copy the exact text, or omit 'find' to overwrite the file]",
|
||||
p.c_str(), old_lines);
|
||||
}
|
||||
if (cnt > 1 && !o.replace_all) {
|
||||
*err = 1;
|
||||
return sfmt("[tool error: 'find' text occurs %zu times in %s; include more surrounding text to make it unique, or set replaceAll:true to replace every occurrence]",
|
||||
cnt, p.c_str());
|
||||
}
|
||||
size_t cur = 0;
|
||||
while (true) {
|
||||
size_t hit = data.find(o.find, cur);
|
||||
if (hit == std::string::npos) { nd.append(data, cur, data.size() - cur); break; }
|
||||
nd.append(data, cur, hit - cur);
|
||||
nd.append(content);
|
||||
cur = hit + o.find.size();
|
||||
if (!o.replace_all) { nd.append(data, cur, data.size() - cur); break; }
|
||||
}
|
||||
return finish(sfmt("Replaced %zu occurrence(s) of 'find' text",
|
||||
o.replace_all ? cnt : 1));
|
||||
}
|
||||
|
||||
/* ---- resolve insertion point and deletion span ----------------------- */
|
||||
size_t ins_off = 0, del_len = 0;
|
||||
bool line_mode = false, at_eof = false;
|
||||
long del_lines = o.has_del_lines ? o.del_lines : 0;
|
||||
long del_bytes = o.has_del_bytes ? o.del_bytes : 0;
|
||||
|
||||
if (o.append) {
|
||||
ins_off = data.size();
|
||||
at_eof = true;
|
||||
} else if (o.has_line) {
|
||||
line_mode = true;
|
||||
ins_off = line_start_offset(data, o.line_offset);
|
||||
at_eof = (ins_off == data.size());
|
||||
long avail = 0;
|
||||
if (!at_eof) avail = (long)(old_lines - line_number_at(data, ins_off) + 1);
|
||||
if (del_lines > avail) del_lines = avail;
|
||||
del_len = lines_byte_len(data, ins_off, del_lines);
|
||||
} else if (o.has_byte) {
|
||||
if (o.byte_offset < 0 || (size_t)o.byte_offset > data.size()) {
|
||||
*err = 1;
|
||||
return sfmt("[tool error: byteOffset %ld is outside %s (%zu bytes). Use append:true or lineOffset to add content at the end]",
|
||||
o.byte_offset, p.c_str(), data.size());
|
||||
}
|
||||
ins_off = (size_t)o.byte_offset;
|
||||
size_t avail = data.size() - ins_off;
|
||||
del_len = ((size_t)del_bytes > avail) ? avail : (size_t)del_bytes;
|
||||
} else {
|
||||
/* The caller validates this. Never fall through to a silent prepend. */
|
||||
*err = 1;
|
||||
return "[tool error: selective edit requires one of: find, append:true, lineOffset, or byteOffset]";
|
||||
}
|
||||
|
||||
/* ---- line-mode text shaping ------------------------------------------ */
|
||||
/* Byte mode is an exact byte splice and is never touched. Line mode only
|
||||
* adds separators around the *inserted* text; it never appends a newline to
|
||||
* unrelated content at the end of the file. */
|
||||
std::string ins(content);
|
||||
if (line_mode || o.append) {
|
||||
if (at_eof && !data.empty() && data.back() != '\n' &&
|
||||
!ins.empty() && ins.front() != '\n')
|
||||
ins.insert(ins.begin(), '\n');
|
||||
if (!ins.empty() && ins.back() != '\n') ins.push_back('\n');
|
||||
}
|
||||
|
||||
nd.reserve(ins_off + ins.size() + (data.size() - ins_off - del_len));
|
||||
nd.append(data, 0, ins_off);
|
||||
nd.append(ins);
|
||||
if (ins_off + del_len < data.size())
|
||||
nd.append(data, ins_off + del_len, data.size() - ins_off - del_len);
|
||||
|
||||
/* ---- hints that catch the classic duplicate-line mistakes ------------ */
|
||||
if (line_mode && del_lines == 0 && !at_eof && !content.empty()) {
|
||||
size_t ln = line_number_at(data, ins_off);
|
||||
std::string fl = first_line_of(content);
|
||||
if (!fl.empty() && fl == line_at(data, ins_off)) {
|
||||
note = sfmt("inserted text duplicates line %zu; to REPLACE it use delLines:1 or find+content", ln);
|
||||
} else {
|
||||
note = sfmt("this was an INSERT before line %zu (delLines was 0), so the original line is still present; to REPLACE a line use delLines:1 or find+content", ln);
|
||||
}
|
||||
}
|
||||
if (o.append && !content.empty() && !data.empty()) {
|
||||
std::string_view last_line = last_content_line(data);
|
||||
if (!last_line.empty() && first_line_of(content) == last_line)
|
||||
note = "appended text duplicates the existing last line; use find+content or lineOffset+delLines if you meant to replace it";
|
||||
}
|
||||
|
||||
/* ---- describe exactly what happened, in line numbers ----------------- */
|
||||
std::string what;
|
||||
if (o.append) {
|
||||
what = sfmt("Appended %zu line(s) at end of file", count_lines(content));
|
||||
} else if (line_mode) {
|
||||
if (at_eof) {
|
||||
what = sfmt("Appended %zu line(s) at end of file (new line %zu)",
|
||||
count_lines(content), old_lines + 1);
|
||||
} else {
|
||||
size_t ln = line_number_at(data, ins_off);
|
||||
if (del_lines > 0 && content.empty())
|
||||
what = sfmt("Deleted %ld line(s) starting at line %zu", del_lines, ln);
|
||||
else if (del_lines > 0)
|
||||
what = sfmt("Replaced %ld line(s) starting at line %zu with %zu line(s)",
|
||||
del_lines, ln, count_lines(content));
|
||||
else
|
||||
what = sfmt("Inserted %zu line(s) before line %zu (existing line %zu preserved)",
|
||||
count_lines(content), ln, ln);
|
||||
}
|
||||
} else {
|
||||
what = sfmt("Wrote %zu bytes at byte offset %zu (deleted %zu bytes)",
|
||||
content.size(), ins_off, del_len);
|
||||
}
|
||||
return finish(what);
|
||||
}
|
||||
|
||||
/* ----------------------------- offload -------------------------------- */
|
||||
std::string offload_tool_result(std::string_view res, int max_res,
|
||||
std::vector<std::string> &tmps) {
|
||||
if (max_res <= 0) max_res = 65536;
|
||||
if (res.size() <= (size_t)max_res) return std::string(res);
|
||||
std::string dir = tool_res_dir();
|
||||
std::string tpl = dir + "/toolres-XXXXXX";
|
||||
int fd = mkstemp(tpl.data());
|
||||
if (fd < 0) return std::string(res);
|
||||
size_t written = 0;
|
||||
bool write_ok = true;
|
||||
while (written < res.size()) {
|
||||
ssize_t w = write(fd, res.data() + written, res.size() - written);
|
||||
if (w < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
write_ok = false;
|
||||
break;
|
||||
}
|
||||
written += (size_t)w;
|
||||
}
|
||||
close(fd);
|
||||
if (!write_ok) { unlink(tpl.c_str()); return std::string(res); }
|
||||
tmps.push_back(tpl);
|
||||
return sfmt("[tool result too large for context: %zu bytes (limit %d). The full output was saved to %s. Read it with the read tool; to read it partially, use offset and limit. The file is %zu bytes long.]",
|
||||
res.size(), max_res, tpl.c_str(), res.size());
|
||||
}
|
||||
void cleanup_temps(std::vector<std::string> &tmps) {
|
||||
for (auto &t : tmps) unlink(t.c_str());
|
||||
tmps.clear();
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
/* util.cpp — string building, UTF-8, filtering, color, IDs, MD5, misc. */
|
||||
#include "bantam.hpp"
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <signal.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* ----------------------------- formatting ----------------------------- */
|
||||
static std::string vfmt(const char *fmt, va_list ap) {
|
||||
char stack_buf[512];
|
||||
va_list cp;
|
||||
va_copy(cp, ap);
|
||||
int need = std::vsnprintf(stack_buf, sizeof stack_buf, fmt, cp);
|
||||
va_end(cp);
|
||||
if (need < 0) return {};
|
||||
if ((size_t)need < sizeof stack_buf) {
|
||||
return std::string(stack_buf, (size_t)need);
|
||||
}
|
||||
std::string s;
|
||||
s.resize((size_t)need);
|
||||
std::vsnprintf(s.data(), (size_t)need + 1, fmt, ap);
|
||||
return s;
|
||||
}
|
||||
std::string sfmt(const char *fmt, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
std::string s = vfmt(fmt, ap);
|
||||
va_end(ap);
|
||||
return s;
|
||||
}
|
||||
void str_appendf(std::string &s, const char *fmt, ...) {
|
||||
char stack_buf[512];
|
||||
va_list ap, cp;
|
||||
va_start(ap, fmt);
|
||||
va_copy(cp, ap);
|
||||
int need = std::vsnprintf(stack_buf, sizeof stack_buf, fmt, cp);
|
||||
va_end(cp);
|
||||
if (need > 0) {
|
||||
if ((size_t)need < sizeof stack_buf) {
|
||||
s.append(stack_buf, (size_t)need);
|
||||
} else {
|
||||
size_t old_sz = s.size();
|
||||
s.resize(old_sz + (size_t)need);
|
||||
std::vsnprintf(s.data() + old_sz, (size_t)need + 1, fmt, ap);
|
||||
}
|
||||
}
|
||||
va_end(ap);
|
||||
}
|
||||
|
||||
/* ----------------------------- UTF-8 ---------------------------------- */
|
||||
int utf8_decode(const unsigned char *p, size_t avail, size_t *plen) {
|
||||
if (avail == 0) { *plen = 0; return 0xFFFD; }
|
||||
unsigned char b0 = p[0];
|
||||
if (b0 < 0x80) { *plen = 1; return b0; }
|
||||
if ((b0 & 0xE0) == 0xC0) {
|
||||
if (avail < 2 || (p[1] & 0xC0) != 0x80) { *plen = 1; return 0xFFFD; }
|
||||
int cp = ((b0 & 0x1F) << 6) | (p[1] & 0x3F);
|
||||
if (cp < 0x80) { *plen = 1; return 0xFFFD; }
|
||||
*plen = 2; return cp;
|
||||
}
|
||||
if ((b0 & 0xF0) == 0xE0) {
|
||||
if (avail < 3 || (p[1] & 0xC0) != 0x80 || (p[2] & 0xC0) != 0x80) { *plen = 1; return 0xFFFD; }
|
||||
int cp = ((b0 & 0x0F) << 12) | ((p[1] & 0x3F) << 6) | (p[2] & 0x3F);
|
||||
if (cp < 0x800 || (cp >= 0xD800 && cp <= 0xDFFF)) { *plen = 1; return 0xFFFD; }
|
||||
*plen = 3; return cp;
|
||||
}
|
||||
if ((b0 & 0xF8) == 0xF0) {
|
||||
if (avail < 4 || (p[1] & 0xC0) != 0x80 || (p[2] & 0xC0) != 0x80 || (p[3] & 0xC0) != 0x80) { *plen = 1; return 0xFFFD; }
|
||||
int cp = ((b0 & 0x07) << 18) | ((p[1] & 0x3F) << 12) | ((p[2] & 0x3F) << 6) | (p[3] & 0x3F);
|
||||
if (cp < 0x10000 || cp > 0x10FFFF) { *plen = 1; return 0xFFFD; }
|
||||
*plen = 4; return cp;
|
||||
}
|
||||
*plen = 1; return 0xFFFD;
|
||||
}
|
||||
|
||||
std::string_view utf8_truncate(std::string_view s, size_t max_bytes) {
|
||||
if (s.size() <= max_bytes) return s;
|
||||
const unsigned char *p = (const unsigned char *)s.data();
|
||||
size_t pos = 0, avail = s.size();
|
||||
while (avail > 0) {
|
||||
size_t pl;
|
||||
utf8_decode(p + pos, avail, &pl);
|
||||
if (pl == 0 || pos + pl > max_bytes) break;
|
||||
pos += pl;
|
||||
avail -= pl;
|
||||
}
|
||||
return s.substr(0, pos);
|
||||
}
|
||||
|
||||
/* ----------------------------- filtering ------------------------------ */
|
||||
static bool kept_rune(int r) {
|
||||
if (r == ' ' || r == '\t' || r == '\n') return true;
|
||||
if (r < 0x20) return false; /* C0 controls */
|
||||
if (r == 0x7f) return false; /* DEL */
|
||||
if (r >= 0x80 && r <= 0x9f) return false; /* C1 controls */
|
||||
switch (r) {
|
||||
case 0x00a0: case 0x00ad:
|
||||
case 0x2000: case 0x2001: case 0x2002: case 0x2003: case 0x2004:
|
||||
case 0x2005: case 0x2006: case 0x2007: case 0x2008: case 0x2009:
|
||||
case 0x200a: case 0x2028: case 0x2029: case 0x202f: case 0x205f:
|
||||
case 0x3000:
|
||||
case 0x200b: case 0x200c: case 0x200d: case 0x2060: case 0xfeff:
|
||||
case 0x200e: case 0x200f:
|
||||
case 0x202a: case 0x202b: case 0x202c: case 0x202d: case 0x202e:
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
std::string filter_text(std::string_view s) {
|
||||
std::string out;
|
||||
out.reserve(s.size());
|
||||
const unsigned char *p = (const unsigned char *)s.data();
|
||||
size_t avail = s.size();
|
||||
while (avail > 0) {
|
||||
/* Fast path: scan contiguous printable ASCII plus '\t' and '\n'. */
|
||||
size_t run = 0;
|
||||
while (run < avail) {
|
||||
unsigned char b = p[run];
|
||||
if ((b >= 0x20 && b <= 0x7e) || b == '\n' || b == '\t') run++;
|
||||
else break;
|
||||
}
|
||||
if (run > 0) {
|
||||
out.append((const char *)p, run);
|
||||
p += run;
|
||||
avail -= run;
|
||||
if (avail == 0) break;
|
||||
}
|
||||
size_t pl;
|
||||
int cp = utf8_decode(p, avail, &pl);
|
||||
if (cp == 0xFFFD && pl == 1) { p++; avail--; continue; }
|
||||
if (kept_rune(cp)) out.append((const char *)p, pl);
|
||||
p += pl; avail -= pl;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ----------------------------- color ---------------------------------- */
|
||||
int g_col = 0;
|
||||
volatile int g_interrupted = 0;
|
||||
|
||||
int visible_len(std::string_view s) {
|
||||
int n = 0;
|
||||
const unsigned char *p = (const unsigned char *)s.data();
|
||||
size_t avail = s.size();
|
||||
while (avail > 0) {
|
||||
if (p[0] == 0x1b) {
|
||||
size_t i = 1;
|
||||
if (i < avail && p[1] == '[') {
|
||||
i++;
|
||||
while (i < avail && !(p[i] >= 0x40 && p[i] <= 0x7e)) i++;
|
||||
if (i < avail) i++;
|
||||
} else {
|
||||
i = 1;
|
||||
}
|
||||
p += i; avail -= i;
|
||||
continue;
|
||||
}
|
||||
if (p[0] == 0x01 || p[0] == 0x02) { p++; avail--; continue; }
|
||||
size_t pl;
|
||||
int cp = utf8_decode(p, avail, &pl);
|
||||
n += rune_width(cp);
|
||||
p += pl; avail -= pl;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Display width of a single Unicode code point. Most code points occupy one
|
||||
* terminal column, but East-Asian Wide/Fullwidth characters (notably CJK) and
|
||||
* many emoji occupy two. Combining marks and zero-width characters occupy
|
||||
* none. Without this, tables containing Chinese text were misaligned because
|
||||
* visible_len counted every rune as a single column. */
|
||||
int rune_width(int cp) {
|
||||
if (cp < 0x20) return 0;
|
||||
if (cp == 0x7f) return 0;
|
||||
/* combining marks / zero-width */
|
||||
if ((cp >= 0x0300 && cp <= 0x036f) || (cp >= 0x0483 && cp <= 0x0489) ||
|
||||
(cp >= 0x0591 && cp <= 0x05bd) || (cp >= 0x0610 && cp <= 0x061a) ||
|
||||
(cp >= 0x064b && cp <= 0x065f) || (cp >= 0x0670 && cp <= 0x0670) ||
|
||||
(cp >= 0x06d6 && cp <= 0x06dc) || (cp >= 0x0e31 && cp <= 0x0e3a) ||
|
||||
(cp >= 0x0e47 && cp <= 0x0e4e) || (cp >= 0x0eb1 && cp <= 0x0eb9) ||
|
||||
(cp >= 0x0ebb && cp <= 0x0ebd) || (cp >= 0x0ec8 && cp <= 0x0ecd) ||
|
||||
(cp >= 0x200b && cp <= 0x200f) || (cp >= 0x202a && cp <= 0x202e) ||
|
||||
(cp >= 0x2060 && cp <= 0x2064) || (cp >= 0xfe00 && cp <= 0xfe0f) ||
|
||||
(cp == 0xfeff) || (cp >= 0xfff9 && cp <= 0xfffb) ||
|
||||
(cp >= 0x1d173 && cp <= 0x1d17a))
|
||||
return 0;
|
||||
/* East Asian Wide / Fullwidth */
|
||||
if (cp == 0x3000) return 2;
|
||||
if (cp >= 0x1100 && cp <= 0x115f) return 2;
|
||||
if (cp >= 0x2e80 && cp <= 0x303e) return 2;
|
||||
if (cp >= 0x3041 && cp <= 0x33ff) return 2;
|
||||
if (cp >= 0x3400 && cp <= 0x4dbf) return 2;
|
||||
if (cp >= 0x4e00 && cp <= 0x9fff) return 2;
|
||||
if (cp >= 0xa000 && cp <= 0xa4cf) return 2;
|
||||
if (cp >= 0xac00 && cp <= 0xd7a3) return 2;
|
||||
if (cp >= 0xf900 && cp <= 0xfaff) return 2;
|
||||
if (cp >= 0xfe30 && cp <= 0xfe4f) return 2;
|
||||
if (cp >= 0xff00 && cp <= 0xff60) return 2;
|
||||
if (cp >= 0xffe0 && cp <= 0xffe6) return 2;
|
||||
if (cp >= 0x1f300 && cp <= 0x1faff) return 2;
|
||||
if (cp >= 0x20000 && cp <= 0x3fffd) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ----------------------------- paths ---------------------------------- */
|
||||
void mkdir_p(std::string_view dir) {
|
||||
if (dir.empty()) return;
|
||||
std::string path(dir);
|
||||
struct stat st;
|
||||
if (stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) return;
|
||||
for (size_t i = 1; i < path.size(); i++) {
|
||||
if (path[i] == '/') {
|
||||
path[i] = '\0';
|
||||
if (stat(path.c_str(), &st) != 0) mkdir(path.c_str(), 0755);
|
||||
path[i] = '/';
|
||||
}
|
||||
}
|
||||
mkdir(path.c_str(), 0755);
|
||||
}
|
||||
std::string bantam_tmp_dir(std::string_view sess_id) {
|
||||
const char *tmp = std::getenv("TMPDIR");
|
||||
if (!tmp || !*tmp) tmp = "/tmp";
|
||||
std::string base(tmp);
|
||||
/* Drop a single trailing slash so we never build a "//bantam" path (which
|
||||
* some platforms treat as a special "super-root"); keep "/" itself intact. */
|
||||
if (base.size() > 1 && base.back() == '/') base.pop_back();
|
||||
std::string p = base;
|
||||
if (p != "/") p += "/";
|
||||
p += "bantam";
|
||||
/* Segregate temporary artifacts per session so different projects/sessions
|
||||
* never share or collide on scratch files. */
|
||||
std::string sid(sess_id);
|
||||
if (sid.empty()) sid = project_id();
|
||||
if (!sid.empty()) { p += "/"; p += sid; }
|
||||
mkdir_p(p);
|
||||
return p;
|
||||
}
|
||||
|
||||
std::string tool_res_dir(std::string_view sess_id) {
|
||||
std::string base = bantam_tmp_dir(sess_id);
|
||||
std::string p = base + "/toolres";
|
||||
mkdir_p(p);
|
||||
return p;
|
||||
}
|
||||
std::string project_id() {
|
||||
static const std::string cached_id = []() {
|
||||
char cwd[4096];
|
||||
if (!getcwd(cwd, sizeof cwd)) std::strcpy(cwd, ".");
|
||||
char *abs = realpath(cwd, nullptr);
|
||||
std::string src = abs ? abs : cwd;
|
||||
if (abs) free(abs);
|
||||
return md5_hex(src);
|
||||
}();
|
||||
return cached_id;
|
||||
}
|
||||
|
||||
/* ----------------------------- MD5 ------------------------------------ */
|
||||
#define MD5_ROTLEFT(x, c) (((x) << (c)) | ((x) >> (32 - (c))))
|
||||
struct MD5_CTX { uint32_t state[4]; uint32_t count[2]; unsigned char buf[64]; };
|
||||
static void md5_transform(uint32_t state[4], const unsigned char block[64]);
|
||||
static void md5_init(MD5_CTX *c) {
|
||||
c->state[0] = 0x67452301; c->state[1] = 0xefcdab89;
|
||||
c->state[2] = 0x98badcfe; c->state[3] = 0x10325476;
|
||||
c->count[0] = c->count[1] = 0;
|
||||
}
|
||||
static void md5_update(MD5_CTX *c, const unsigned char *in, size_t len) {
|
||||
uint32_t bits = (uint32_t)(c->count[0] >> 3) & 0x3F;
|
||||
if ((c->count[0] += (uint32_t)(len << 3)) < (uint32_t)(len << 3)) c->count[1]++;
|
||||
c->count[1] += (uint32_t)(len >> 29);
|
||||
while (len--) {
|
||||
c->buf[bits++] = *in++;
|
||||
if (bits == 64) { md5_transform(c->state, c->buf); bits = 0; }
|
||||
}
|
||||
}
|
||||
static void md5_final(unsigned char digest[16], MD5_CTX *c) {
|
||||
unsigned char bits[8];
|
||||
for (int i = 0; i < 8; i++) bits[i] = (unsigned char)((c->count[i >> 2] >> ((i & 3) * 8)) & 0xFF);
|
||||
unsigned char pad = (unsigned char)((c->count[0] >> 3) & 0x3F);
|
||||
unsigned char padlen = (pad < 56) ? (56 - pad) : (120 - pad);
|
||||
unsigned char p = 0x80;
|
||||
md5_update(c, &p, 1);
|
||||
unsigned char zero = 0;
|
||||
for (int i = 0; i < padlen - 1; i++) md5_update(c, &zero, 1);
|
||||
md5_update(c, bits, 8);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
digest[i * 4 + 0] = (unsigned char)(c->state[i] & 0xFF);
|
||||
digest[i * 4 + 1] = (unsigned char)((c->state[i] >> 8) & 0xFF);
|
||||
digest[i * 4 + 2] = (unsigned char)((c->state[i] >> 16) & 0xFF);
|
||||
digest[i * 4 + 3] = (unsigned char)((c->state[i] >> 24) & 0xFF);
|
||||
}
|
||||
}
|
||||
static void md5_transform(uint32_t state[4], const unsigned char b[64]) {
|
||||
uint32_t a = state[0], d = state[3], c = state[2], e = state[1];
|
||||
uint32_t x[16];
|
||||
for (int i = 0, j = 0; i < 16; i++, j += 4)
|
||||
x[i] = (uint32_t)b[j] | ((uint32_t)b[j+1] << 8) | ((uint32_t)b[j+2] << 16) | ((uint32_t)b[j+3] << 24);
|
||||
static const uint32_t K[64] = {
|
||||
0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,
|
||||
0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,0x6b901122,0xfd987193,0xa679438e,0x49b40821,
|
||||
0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,0xd62f105d,0x02441453,0xd8a1e681,0xe7d3fbc8,
|
||||
0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,
|
||||
0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,
|
||||
0x289b7ec6,0xeaa127fa,0xd4ef3085,0x04881d05,0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,
|
||||
0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,
|
||||
0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391};
|
||||
static const int S[64] = {
|
||||
7,12,17,22, 7,12,17,22, 7,12,17,22, 7,12,17,22,
|
||||
5,9,14,20, 5,9,14,20, 5,9,14,20, 5,9,14,20,
|
||||
4,11,16,23, 4,11,16,23, 4,11,16,23, 4,11,16,23,
|
||||
6,10,15,21, 6,10,15,21, 6,10,15,21, 6,10,15,21};
|
||||
for (int i = 0; i < 64; i++) {
|
||||
uint32_t f; int g;
|
||||
if (i < 16) { f = (e & c) | (~e & d); g = i; }
|
||||
else if (i < 32) { f = (d & e) | (~d & c); g = (5 * i + 1) % 16; }
|
||||
else if (i < 48) { f = e ^ c ^ d; g = (3 * i + 5) % 16; }
|
||||
else { f = c ^ (e | (~d)); g = (7 * i) % 16; }
|
||||
f = f + a + K[i] + x[g];
|
||||
a = d; d = c; c = e;
|
||||
e = e + MD5_ROTLEFT(f, S[i]);
|
||||
}
|
||||
state[0] += a; state[1] += e; state[2] += c; state[3] += d;
|
||||
}
|
||||
std::string md5_hex(std::string_view data) {
|
||||
MD5_CTX ctx; md5_init(&ctx);
|
||||
md5_update(&ctx, (const unsigned char *)data.data(), data.size());
|
||||
unsigned char dig[16];
|
||||
md5_final(dig, &ctx);
|
||||
std::string out;
|
||||
out.reserve(33);
|
||||
static const char *hx = "0123456789abcdef";
|
||||
for (int i = 0; i < 16; i++) {
|
||||
out += hx[dig[i] >> 4];
|
||||
out += hx[dig[i] & 0xF];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ----------------------------- misc ----------------------------------- */
|
||||
int to_int_val(std::string_view s, int def) {
|
||||
if (s.empty()) return def;
|
||||
std::string tmp(s);
|
||||
char *end;
|
||||
long v = std::strtol(tmp.c_str(), &end, 10);
|
||||
if (end == tmp.c_str() || *end != '\0') return def;
|
||||
return (int)v;
|
||||
}
|
||||
|
||||
bool read_file_str(std::string_view path, std::string &out) {
|
||||
out.clear();
|
||||
std::string p(path);
|
||||
FILE *f = std::fopen(p.c_str(), "rb");
|
||||
if (!f) return false;
|
||||
struct stat st;
|
||||
if (fstat(fileno(f), &st) == 0 && S_ISREG(st.st_mode) && st.st_size > 0) {
|
||||
out.reserve((size_t)st.st_size);
|
||||
}
|
||||
char buf[16384];
|
||||
size_t n;
|
||||
while ((n = std::fread(buf, 1, sizeof buf, f)) > 0) {
|
||||
out.append(buf, n);
|
||||
}
|
||||
bool ok = (std::ferror(f) == 0);
|
||||
std::fclose(f);
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool write_file_str(std::string_view path, std::string_view data) {
|
||||
std::string p(path);
|
||||
FILE *f = std::fopen(p.c_str(), "wb");
|
||||
if (!f) return false;
|
||||
size_t written = 0;
|
||||
while (written < data.size()) {
|
||||
size_t n = std::fwrite(data.data() + written, 1, data.size() - written, f);
|
||||
if (n == 0) {
|
||||
std::fclose(f);
|
||||
return false;
|
||||
}
|
||||
written += n;
|
||||
}
|
||||
return std::fclose(f) == 0;
|
||||
}
|
||||
|
||||
/* ----------------------------- signal --------------------------------- */
|
||||
static void sigint_handler(int sig) {
|
||||
(void)sig;
|
||||
g_interrupted = 1;
|
||||
}
|
||||
void setup_signal_handler() {
|
||||
struct sigaction sa;
|
||||
std::memset(&sa, 0, sizeof sa);
|
||||
sa.sa_handler = sigint_handler;
|
||||
sigaction(SIGINT, &sa, nullptr);
|
||||
}
|
||||
|
||||
int color_enabled(const Cfg &cfg) {
|
||||
const char *nc = std::getenv("NO_COLOR");
|
||||
if (nc && *nc) return 0;
|
||||
const char *bnc = std::getenv("BANTAM_NO_COLOR");
|
||||
if (bnc && *bnc) return 0;
|
||||
const std::string &c = cfg.color;
|
||||
if (c == "always") return 1;
|
||||
if (c == "never") return 0;
|
||||
return is_terminal(STDOUT_FILENO);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ static const char *colors[SchemeLast][2] = {
|
||||
[SchemeSel] = { "#ffffff", "#2b5278" },
|
||||
[SchemeOut] = { "#ffffff", "#243040" },
|
||||
};
|
||||
static unsigned int lines = 0;
|
||||
static unsigned int lines = 12;
|
||||
static unsigned int lineheight = 82;
|
||||
static unsigned int min_lineheight = 82;
|
||||
static const char worddelimiters[] = " ";
|
||||
+1
-1
@@ -13,7 +13,7 @@ static const char *colors[SchemeLast][2] = {
|
||||
[SchemeSel] = { "#ffffff", "#2b5278" },
|
||||
[SchemeOut] = { "#ffffff", "#243040" },
|
||||
};
|
||||
static unsigned int lines = 0;
|
||||
static unsigned int lines = 12;
|
||||
static unsigned int lineheight = 82;
|
||||
static unsigned int min_lineheight = 82;
|
||||
static const char worddelimiters[] = " ";
|
||||
+22
-9
@@ -51,6 +51,7 @@ static struct item *items = NULL;
|
||||
static struct item *matches = NULL, *matchend = NULL;
|
||||
static struct item *prev = NULL, *curr = NULL, *next = NULL, *sel = NULL;
|
||||
static int mon = -1, screen;
|
||||
static int explicit_lines = 0;
|
||||
|
||||
static Atom clip, utf8;
|
||||
static Display *dpy;
|
||||
@@ -776,7 +777,6 @@ static void readstdin(void) {
|
||||
}
|
||||
free(line);
|
||||
if (items) items[i].text = NULL;
|
||||
lines = MIN(lines, (unsigned int)i);
|
||||
}
|
||||
|
||||
static void run(void) {
|
||||
@@ -847,10 +847,10 @@ static void setup(void) {
|
||||
clip = XInternAtom(dpy, "CLIPBOARD", False);
|
||||
utf8 = XInternAtom(dpy, "UTF8_STRING", False);
|
||||
|
||||
int sx = 0, sy = 0, sw = 0, sh = 0;
|
||||
|
||||
bh = MAX((int)drw->fonts->h + 18, (int)lineheight);
|
||||
if (bh < (int)min_lineheight) bh = (int)min_lineheight;
|
||||
lines = MAX(lines, 0);
|
||||
mh = (int)(lines + 1) * bh;
|
||||
promptw = (prompt && *prompt) ? (int)TEXTW(prompt) : 0;
|
||||
|
||||
#ifdef XINERAMA
|
||||
@@ -874,18 +874,30 @@ static void setup(void) {
|
||||
}
|
||||
}
|
||||
}
|
||||
x = info[i].x_org;
|
||||
y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
|
||||
mw = info[i].width;
|
||||
sx = info[i].x_org;
|
||||
sy = info[i].y_org;
|
||||
sw = info[i].width;
|
||||
sh = info[i].height;
|
||||
XFree(info);
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
if (!XGetWindowAttributes(dpy, parentwin, &wa))
|
||||
die("could not get embedding window attributes: 0x%lx", parentwin);
|
||||
x = 0;
|
||||
y = topbar ? 0 : wa.height - mh;
|
||||
mw = wa.width;
|
||||
sx = 0;
|
||||
sy = 0;
|
||||
sw = wa.width;
|
||||
sh = wa.height;
|
||||
}
|
||||
x = sx;
|
||||
y = sy;
|
||||
mw = sw;
|
||||
mh = sh;
|
||||
{
|
||||
int avail_lines = (mh - bh) / bh;
|
||||
if (avail_lines < 1) avail_lines = 1;
|
||||
if (!explicit_lines || lines == 0 || (int)lines > avail_lines)
|
||||
lines = (unsigned int)avail_lines;
|
||||
}
|
||||
inputw = mw / 3;
|
||||
match();
|
||||
@@ -974,6 +986,7 @@ int main(int argc, char *argv[]) {
|
||||
usage();
|
||||
} else if (!strcmp(argv[i], "-l")) {
|
||||
lines = (unsigned int)atoi(argv[++i]);
|
||||
explicit_lines = 1;
|
||||
} else if (!strcmp(argv[i], "-m")) {
|
||||
mon = atoi(argv[++i]);
|
||||
} else if (!strcmp(argv[i], "-p")) {
|
||||
|
||||
@@ -25,8 +25,8 @@ all: $(APPS)
|
||||
geminux-datetime: geminux-datetime.c ../geminux-daemons/geminux-tz-valid.h ../libgemui/gemui.h
|
||||
$(CC) $(CFLAGS) -o $@ $< $(LIBS)
|
||||
|
||||
geminux-camera: geminux-camera.c ../libgemui/gemui.h
|
||||
$(CC) $(CFLAGS) -o $@ $< $(LIBS) -ljpeg
|
||||
geminux-camera: geminux-camera.c geminux-cam-bayer.h ../libgemui/gemui.h
|
||||
$(CC) $(CFLAGS) -o $@ $< $(LIBS) -ljpeg -lm
|
||||
|
||||
geminux-net: geminux-net.c geminux-wifi-list.h geminux-bt-list.h ../libgemui/gemui.h
|
||||
$(CC) $(CFLAGS) -o $@ $< $(LIBS)
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
#ifndef GEMINUX_CAM_BAYER_H
|
||||
#define GEMINUX_CAM_BAYER_H
|
||||
|
||||
#include <math.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define GEMINUX_FOURCC_C(a, b, c, d) \
|
||||
((uint32_t)(a) | ((uint32_t)(b) << 8) | ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24))
|
||||
|
||||
#ifndef V4L2_PIX_FMT_MTISP_SGRBG10
|
||||
#define V4L2_PIX_FMT_MTISP_SGRBG10 GEMINUX_FOURCC_C('M', 'B', 'g', 'A')
|
||||
#endif
|
||||
#ifndef V4L2_PIX_FMT_MTISP_SRGGB10
|
||||
#define V4L2_PIX_FMT_MTISP_SRGGB10 GEMINUX_FOURCC_C('M', 'B', 'R', 'A')
|
||||
#endif
|
||||
#ifndef MEDIA_BUS_FMT_SGRBG10_1X10
|
||||
#define MEDIA_BUS_FMT_SGRBG10_1X10 0x300a
|
||||
#endif
|
||||
#ifndef MEDIA_BUS_FMT_SRGGB10_1X10
|
||||
#define MEDIA_BUS_FMT_SRGGB10_1X10 0x300f
|
||||
#endif
|
||||
|
||||
#define GEMINUX_CAM_PEDESTAL 64U
|
||||
#define GEMINUX_CAM_MAX_LIN (1023U - GEMINUX_CAM_PEDESTAL)
|
||||
|
||||
typedef struct {
|
||||
int r_gain_q8;
|
||||
int b_gain_q8;
|
||||
int luma_avg;
|
||||
uint8_t gamma_lut[1024];
|
||||
bool inited;
|
||||
} geminux_bayer10_isp_t;
|
||||
|
||||
static inline void geminux_mtisp_unpack_row10(const uint8_t *src, uint16_t *dst, int width) {
|
||||
int blocks = width / 4;
|
||||
for (int i = 0; i < blocks; i++) {
|
||||
const uint8_t *s = src + i * 5;
|
||||
dst[0] = (uint16_t)(s[0] | ((s[1] & 0x03U) << 8));
|
||||
dst[1] = (uint16_t)((s[1] >> 2) | ((s[2] & 0x0fU) << 6));
|
||||
dst[2] = (uint16_t)((s[2] >> 4) | ((s[3] & 0x3fU) << 4));
|
||||
dst[3] = (uint16_t)((s[3] >> 6) | ((uint16_t)s[4] << 2));
|
||||
dst += 4;
|
||||
}
|
||||
}
|
||||
|
||||
static inline void geminux_bayer10_isp_init(geminux_bayer10_isp_t *st) {
|
||||
st->r_gain_q8 = 360;
|
||||
st->b_gain_q8 = 396;
|
||||
st->luma_avg = 0;
|
||||
for (int i = 0; i < 1024; i++) {
|
||||
double norm = (double)i / (double)GEMINUX_CAM_MAX_LIN;
|
||||
if (norm > 1.0) norm = 1.0;
|
||||
int g = (int)(pow(norm, 1.0 / 2.2) * 255.0 + 0.5);
|
||||
st->gamma_lut[i] = (uint8_t)(g < 0 ? 0 : (g > 255 ? 255 : g));
|
||||
}
|
||||
st->inited = true;
|
||||
}
|
||||
|
||||
static inline uint8_t geminux_cam_apply_gain_gamma(const geminux_bayer10_isp_t *st,
|
||||
int lin, int gain_q8) {
|
||||
int v = (lin * gain_q8) >> 8;
|
||||
if (v < 0) v = 0;
|
||||
if (v > (int)GEMINUX_CAM_MAX_LIN) v = (int)GEMINUX_CAM_MAX_LIN;
|
||||
return st->gamma_lut[v];
|
||||
}
|
||||
|
||||
/*
|
||||
* Unpack MTISP 10-bit packed Bayer (SRGGB10/'MBRA' or SGRBG10/'MBgA'), subtract
|
||||
* black level, bilinear-demosaic into RGB24 and ARGB32 with rotation/mirror,
|
||||
* and update smooth Gray-World AWB gains and mean linear luma.
|
||||
*/
|
||||
static inline void geminux_bayer10_to_buffers(geminux_bayer10_isp_t *st,
|
||||
const uint8_t *src, int src_stride,
|
||||
int src_w, int src_h, bool is_rggb,
|
||||
int rot_deg, bool mirror,
|
||||
uint16_t *raw16,
|
||||
uint8_t *dst_rgb24, uint32_t *dst_argb32,
|
||||
int *out_linear_avg) {
|
||||
if (!st->inited) geminux_bayer10_isp_init(st);
|
||||
if (!src || !raw16 || src_w < 4 || src_h < 2) return;
|
||||
|
||||
for (int y = 0; y < src_h; y++) {
|
||||
const uint8_t *row_src = src + (size_t)y * (size_t)src_stride;
|
||||
uint16_t *row_dst = raw16 + (size_t)y * (size_t)src_w;
|
||||
geminux_mtisp_unpack_row10(row_src, row_dst, src_w);
|
||||
for (int x = 0; x < src_w; x++) {
|
||||
uint16_t v = row_dst[x];
|
||||
row_dst[x] = (v > GEMINUX_CAM_PEDESTAL) ? (uint16_t)(v - GEMINUX_CAM_PEDESTAL) : 0U;
|
||||
}
|
||||
}
|
||||
|
||||
int dst_w = (rot_deg == 90 || rot_deg == 270) ? src_h : src_w;
|
||||
uint64_t sum_r = 0, sum_g = 0, sum_b = 0, sum_y = 0, sample_cnt = 0;
|
||||
|
||||
for (int y = 0; y < src_h; y++) {
|
||||
int ym = (y > 0) ? (y - 1) : (y + 1);
|
||||
int yp = (y + 1 < src_h) ? (y + 1) : (y - 1);
|
||||
const uint16_t *r0 = raw16 + (size_t)ym * (size_t)src_w;
|
||||
const uint16_t *r1 = raw16 + (size_t)y * (size_t)src_w;
|
||||
const uint16_t *r2 = raw16 + (size_t)yp * (size_t)src_w;
|
||||
bool row_has_r = ((y & 1) == 0);
|
||||
int r_col = is_rggb ? 0 : 1;
|
||||
int b_col = is_rggb ? 1 : 0;
|
||||
|
||||
for (int x = 0; x < src_w; x++) {
|
||||
int xm = (x > 0) ? (x - 1) : (x + 1);
|
||||
int xp = (x + 1 < src_w) ? (x + 1) : (x - 1);
|
||||
int c = r1[x];
|
||||
int l = r1[xm], rt = r1[xp];
|
||||
int u = r0[x], d = r2[x];
|
||||
int ul = r0[xm], ur = r0[xp], dl = r2[xm], dr = r2[xp];
|
||||
int lr, lg, lb;
|
||||
|
||||
if (row_has_r) {
|
||||
if ((x & 1) == r_col) {
|
||||
lr = c;
|
||||
lg = (l + rt + u + d) >> 2;
|
||||
lb = (ul + ur + dl + dr) >> 2;
|
||||
} else {
|
||||
lr = (l + rt) >> 1;
|
||||
lg = c;
|
||||
lb = (u + d) >> 1;
|
||||
}
|
||||
} else {
|
||||
if ((x & 1) == b_col) {
|
||||
lr = (ul + ur + dl + dr) >> 2;
|
||||
lg = (l + rt + u + d) >> 2;
|
||||
lb = c;
|
||||
} else {
|
||||
lr = (u + d) >> 1;
|
||||
lg = c;
|
||||
lb = (l + rt) >> 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (((x | y) & 3) == 0) {
|
||||
sum_r += (uint64_t)lr;
|
||||
sum_g += (uint64_t)lg;
|
||||
sum_b += (uint64_t)lb;
|
||||
sum_y += (uint64_t)((lr * 77 + lg * 150 + lb * 29) >> 8);
|
||||
sample_cnt++;
|
||||
}
|
||||
|
||||
uint8_t r8 = geminux_cam_apply_gain_gamma(st, lr, st->r_gain_q8);
|
||||
uint8_t g8 = geminux_cam_apply_gain_gamma(st, lg, 256);
|
||||
uint8_t b8 = geminux_cam_apply_gain_gamma(st, lb, st->b_gain_q8);
|
||||
|
||||
int sx = mirror ? (src_w - 1 - x) : x;
|
||||
int dx, dy;
|
||||
switch (rot_deg) {
|
||||
case 90:
|
||||
dx = src_h - 1 - y;
|
||||
dy = sx;
|
||||
break;
|
||||
case 180:
|
||||
dx = src_w - 1 - sx;
|
||||
dy = src_h - 1 - y;
|
||||
break;
|
||||
case 270:
|
||||
dx = y;
|
||||
dy = src_w - 1 - sx;
|
||||
break;
|
||||
default:
|
||||
dx = sx;
|
||||
dy = y;
|
||||
break;
|
||||
}
|
||||
|
||||
size_t didx = (size_t)dy * (size_t)dst_w + (size_t)dx;
|
||||
if (dst_rgb24) {
|
||||
dst_rgb24[didx * 3U + 0U] = r8;
|
||||
dst_rgb24[didx * 3U + 1U] = g8;
|
||||
dst_rgb24[didx * 3U + 2U] = b8;
|
||||
}
|
||||
if (dst_argb32) {
|
||||
dst_argb32[didx] = 0xff000000U | ((uint32_t)r8 << 16) |
|
||||
((uint32_t)g8 << 8) | (uint32_t)b8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sample_cnt > 0) {
|
||||
int avg_y = (int)(sum_y / sample_cnt);
|
||||
st->luma_avg = avg_y;
|
||||
if (out_linear_avg) *out_linear_avg = avg_y;
|
||||
|
||||
uint64_t avg_r = sum_r / sample_cnt;
|
||||
uint64_t avg_g = sum_g / sample_cnt;
|
||||
uint64_t avg_b = sum_b / sample_cnt;
|
||||
if (avg_r > 12 && avg_g > 12 && avg_b > 12) {
|
||||
int tgt_r = (int)((avg_g << 8) / avg_r);
|
||||
int tgt_b = (int)((avg_g << 8) / avg_b);
|
||||
if (tgt_r < 180) tgt_r = 180;
|
||||
if (tgt_r > 600) tgt_r = 600;
|
||||
if (tgt_b < 180) tgt_b = 180;
|
||||
if (tgt_b > 600) tgt_b = 600;
|
||||
st->r_gain_q8 = (st->r_gain_q8 * 7 + tgt_r) / 8;
|
||||
st->b_gain_q8 = (st->b_gain_q8 * 7 + tgt_b) / 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif /* GEMINUX_CAM_BAYER_H */
|
||||
@@ -1,10 +1,14 @@
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include "gemui.h"
|
||||
#include "geminux-cam-bayer.h"
|
||||
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/v4l2-subdev.h>
|
||||
#include <linux/videodev2.h>
|
||||
#include <math.h>
|
||||
#include <poll.h>
|
||||
#include <stdio.h>
|
||||
#include <jpeglib.h>
|
||||
#include <stdlib.h>
|
||||
@@ -18,6 +22,7 @@
|
||||
#define HIT_SHUTTER 1
|
||||
#define HIT_RECORD 2
|
||||
#define HIT_SWITCH 3
|
||||
#define HIT_ROTATE 4
|
||||
|
||||
typedef struct {
|
||||
void *start;
|
||||
@@ -32,13 +37,25 @@ typedef struct {
|
||||
typedef struct {
|
||||
gemui_app_t *app;
|
||||
int vfd;
|
||||
int subdev_fd;
|
||||
char dev_path[64];
|
||||
char dev_list[8][64];
|
||||
int num_devs;
|
||||
int cur_dev;
|
||||
uint32_t pixfmt;
|
||||
int raw_w;
|
||||
int raw_h;
|
||||
int raw_stride;
|
||||
int cam_w;
|
||||
int cam_h;
|
||||
int rot_deg;
|
||||
bool mirror;
|
||||
uint16_t *raw16;
|
||||
geminux_bayer10_isp_t isp;
|
||||
uint32_t frame_count;
|
||||
int ae_exp;
|
||||
int ae_again;
|
||||
int ae_dgain;
|
||||
v4l2_buf_t bufs[4];
|
||||
int num_bufs;
|
||||
uint8_t *rgb24;
|
||||
@@ -152,12 +169,12 @@ static void avi_stop(cam_state_t *st) {
|
||||
free(st->avi_idx);
|
||||
st->avi_idx = NULL;
|
||||
st->avi_idx_cap = 0;
|
||||
gemui_show_toast(st->app, "Saved MJPEG AVI video", 2000);
|
||||
if (st->app) gemui_show_toast(st->app, "Saved MJPEG AVI video", 2000);
|
||||
}
|
||||
|
||||
static void avi_start(cam_state_t *st) {
|
||||
if (!st->rgb24 || st->cam_w <= 0 || st->cam_h <= 0) {
|
||||
gemui_show_toast(st->app, "No active camera stream", 1800);
|
||||
if (st->app) gemui_show_toast(st->app, "No active camera stream", 1800);
|
||||
return;
|
||||
}
|
||||
const char *home = getenv("HOME");
|
||||
@@ -206,7 +223,7 @@ static void avi_start(cam_state_t *st) {
|
||||
st->avi_frames = 0;
|
||||
st->recording = true;
|
||||
snprintf(st->last_file, sizeof(st->last_file), "VID_%s.avi", ts);
|
||||
gemui_show_toast(st->app, "Recording MJPEG AVI video...", 1500);
|
||||
if (st->app) gemui_show_toast(st->app, "Recording MJPEG AVI video...", 1500);
|
||||
}
|
||||
|
||||
static void avi_write_frame(cam_state_t *st, const uint8_t *jpg, size_t jpg_sz) {
|
||||
@@ -229,12 +246,74 @@ static void avi_write_frame(cam_state_t *st, const uint8_t *jpg, size_t jpg_sz)
|
||||
st->avi_frames++;
|
||||
}
|
||||
|
||||
static void load_cam_config(cam_state_t *st) {
|
||||
const char *home = getenv("HOME");
|
||||
char path[512];
|
||||
snprintf(path, sizeof(path), "%s/.config/geminux-camera.conf",
|
||||
(home && home[0]) ? home : "/home/user");
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) return;
|
||||
char line[128];
|
||||
while (fgets(line, sizeof(line), f)) {
|
||||
int rot = 0;
|
||||
if (sscanf(line, "rot_deg=%d", &rot) == 1 &&
|
||||
(rot == 0 || rot == 90 || rot == 180 || rot == 270)) {
|
||||
st->rot_deg = rot;
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static void save_cam_config(const cam_state_t *st) {
|
||||
const char *home = getenv("HOME");
|
||||
char dir[512], path[560];
|
||||
snprintf(dir, sizeof(dir), "%s/.config", (home && home[0]) ? home : "/home/user");
|
||||
mkdir(dir, 0755);
|
||||
snprintf(path, sizeof(path), "%s/geminux-camera.conf", dir);
|
||||
FILE *f = fopen(path, "w");
|
||||
if (!f) return;
|
||||
fprintf(f, "rot_deg=%d\n", st->rot_deg);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static bool alloc_output_buffers(cam_state_t *st, bool with_surface) {
|
||||
bool swap_dims = (st->pixfmt == V4L2_PIX_FMT_MTISP_SRGGB10 ||
|
||||
st->pixfmt == V4L2_PIX_FMT_MTISP_SGRBG10) &&
|
||||
(st->rot_deg == 90 || st->rot_deg == 270);
|
||||
int ow = swap_dims ? st->raw_h : st->raw_w;
|
||||
int oh = swap_dims ? st->raw_w : st->raw_h;
|
||||
|
||||
if (st->frame_surf) {
|
||||
cairo_surface_destroy(st->frame_surf);
|
||||
st->frame_surf = NULL;
|
||||
}
|
||||
free(st->rgb24); st->rgb24 = NULL;
|
||||
free(st->argb32); st->argb32 = NULL;
|
||||
|
||||
if (ow <= 0 || oh <= 0) return false;
|
||||
st->cam_w = ow;
|
||||
st->cam_h = oh;
|
||||
st->rgb24 = calloc((size_t)ow * (size_t)oh, 3);
|
||||
if (with_surface)
|
||||
st->argb32 = calloc((size_t)ow * (size_t)oh, sizeof(uint32_t));
|
||||
if (!st->rgb24 || (with_surface && !st->argb32)) {
|
||||
free(st->rgb24); st->rgb24 = NULL;
|
||||
free(st->argb32); st->argb32 = NULL;
|
||||
return false;
|
||||
}
|
||||
if (with_surface) {
|
||||
st->frame_surf = cairo_image_surface_create_for_data(
|
||||
(unsigned char *)st->argb32, CAIRO_FORMAT_RGB24, ow, oh, ow * 4);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void close_camera(cam_state_t *st) {
|
||||
if (st->recording) avi_stop(st);
|
||||
if (st->vfd >= 0) {
|
||||
enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
|
||||
ioctl(st->vfd, VIDIOC_STREAMOFF, &type);
|
||||
gemui_del_fd(st->app, st->vfd);
|
||||
if (st->app) gemui_del_fd(st->app, st->vfd);
|
||||
for (int i = 0; i < st->num_bufs; i++) {
|
||||
if (st->bufs[i].start && st->bufs[i].start != MAP_FAILED) {
|
||||
munmap(st->bufs[i].start, st->bufs[i].length);
|
||||
@@ -243,15 +322,247 @@ static void close_camera(cam_state_t *st) {
|
||||
close(st->vfd);
|
||||
st->vfd = -1;
|
||||
}
|
||||
if (st->subdev_fd >= 0) {
|
||||
close(st->subdev_fd);
|
||||
st->subdev_fd = -1;
|
||||
}
|
||||
st->num_bufs = 0;
|
||||
if (st->frame_surf) {
|
||||
cairo_surface_destroy(st->frame_surf);
|
||||
st->frame_surf = NULL;
|
||||
}
|
||||
free(st->raw16); st->raw16 = NULL;
|
||||
free(st->rgb24); st->rgb24 = NULL;
|
||||
free(st->argb32); st->argb32 = NULL;
|
||||
}
|
||||
|
||||
static int set_subdev_ctrl(int sfd, uint32_t id, int32_t val) {
|
||||
struct v4l2_control ctrl;
|
||||
memset(&ctrl, 0, sizeof(ctrl));
|
||||
ctrl.id = id;
|
||||
ctrl.value = val;
|
||||
return ioctl(sfd, VIDIOC_S_CTRL, &ctrl);
|
||||
}
|
||||
|
||||
static void update_ae_agc(cam_state_t *st, int lin_avg) {
|
||||
if (st->subdev_fd < 0) return;
|
||||
int cur = lin_avg < 6 ? 6 : lin_avg;
|
||||
if (cur >= 125 && cur <= 180) return;
|
||||
|
||||
double ratio = 150.0 / (double)cur;
|
||||
ratio = 1.0 + (ratio - 1.0) * 0.5;
|
||||
if (ratio < 0.75) ratio = 0.75;
|
||||
if (ratio > 1.35) ratio = 1.35;
|
||||
|
||||
double again_mult = (double)(16 + st->ae_again) / 16.0;
|
||||
double dgain_mult = (double)st->ae_dgain / 256.0;
|
||||
double ev = (double)st->ae_exp * again_mult * dgain_mult * ratio;
|
||||
double min_ev = 16.0;
|
||||
double max_ev = 2064.0 * 16.0 * (640.0 / 256.0);
|
||||
if (ev < min_ev) ev = min_ev;
|
||||
if (ev > max_ev) ev = max_ev;
|
||||
|
||||
int n_exp, n_again, n_dgain;
|
||||
if (ev <= 2064.0) {
|
||||
n_exp = (int)lrint(ev);
|
||||
n_again = 0;
|
||||
n_dgain = 256;
|
||||
} else if (ev <= 2064.0 * 16.0) {
|
||||
n_exp = 2064;
|
||||
n_again = (int)lrint((ev / 2064.0) * 16.0) - 16;
|
||||
n_dgain = 256;
|
||||
} else {
|
||||
n_exp = 2064;
|
||||
n_again = 240;
|
||||
n_dgain = (int)lrint((ev / (2064.0 * 16.0)) * 256.0);
|
||||
}
|
||||
if (n_exp < 16) n_exp = 16;
|
||||
if (n_exp > 2064) n_exp = 2064;
|
||||
if (n_again < 0) n_again = 0;
|
||||
if (n_again > 240) n_again = 240;
|
||||
if (n_dgain < 256) n_dgain = 256;
|
||||
if (n_dgain > 640) n_dgain = 640;
|
||||
|
||||
if (n_exp != st->ae_exp) {
|
||||
set_subdev_ctrl(st->subdev_fd, V4L2_CID_EXPOSURE, n_exp);
|
||||
st->ae_exp = n_exp;
|
||||
}
|
||||
if (n_again != st->ae_again) {
|
||||
set_subdev_ctrl(st->subdev_fd, V4L2_CID_ANALOGUE_GAIN, n_again);
|
||||
st->ae_again = n_again;
|
||||
}
|
||||
if (n_dgain != st->ae_dgain) {
|
||||
set_subdev_ctrl(st->subdev_fd, V4L2_CID_DIGITAL_GAIN, n_dgain);
|
||||
st->ae_dgain = n_dgain;
|
||||
}
|
||||
}
|
||||
|
||||
static bool find_mc_subdevs(char *sensor_dev, size_t sensor_sz,
|
||||
char *bridge_dev, size_t bridge_sz) {
|
||||
sensor_dev[0] = '\0';
|
||||
bridge_dev[0] = '\0';
|
||||
DIR *d = opendir("/sys/class/video4linux");
|
||||
if (!d) return false;
|
||||
|
||||
struct dirent *ent;
|
||||
while ((ent = readdir(d)) != NULL) {
|
||||
if (strncmp(ent->d_name, "v4l-subdev", 10) != 0) continue;
|
||||
char sys_p[128], name[128] = "";
|
||||
snprintf(sys_p, sizeof(sys_p), "/sys/class/video4linux/%s/name", ent->d_name);
|
||||
FILE *f = fopen(sys_p, "r");
|
||||
if (!f) continue;
|
||||
if (fgets(name, sizeof(name), f)) {
|
||||
size_t nl = strlen(name);
|
||||
while (nl > 0 && (name[nl - 1] == '\n' || name[nl - 1] == '\r'))
|
||||
name[--nl] = '\0';
|
||||
if (strncmp(name, "hi556", 5) == 0 && !sensor_dev[0]) {
|
||||
snprintf(sensor_dev, sensor_sz, "/dev/%s", ent->d_name);
|
||||
} else if (strstr(name, "seninf") != NULL && !bridge_dev[0]) {
|
||||
snprintf(bridge_dev, bridge_sz, "/dev/%s", ent->d_name);
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
closedir(d);
|
||||
return sensor_dev[0] != '\0' && bridge_dev[0] != '\0';
|
||||
}
|
||||
|
||||
/*
|
||||
* Configure sensor and CSI bridge subdevs for V4L2_CAP_IO_MC capture nodes.
|
||||
* Returns 1 when MC configured (*out_sensor_fd open), 0 for non-MC devices, -1 on error.
|
||||
*/
|
||||
static int configure_mc_pipeline(int vfd, struct v4l2_subdev_format *out_fmt,
|
||||
int *out_sensor_fd, int *exp_out,
|
||||
int *again_out, int *dgain_out) {
|
||||
*out_sensor_fd = -1;
|
||||
struct v4l2_capability cap;
|
||||
memset(&cap, 0, sizeof(cap));
|
||||
if (ioctl(vfd, VIDIOC_QUERYCAP, &cap) < 0) return -1;
|
||||
|
||||
uint32_t eff_caps = cap.device_caps ? cap.device_caps : cap.capabilities;
|
||||
bool is_mc = (eff_caps & V4L2_CAP_IO_MC) ||
|
||||
(strstr((const char *)cap.driver, "seninf") != NULL);
|
||||
if (!is_mc) return 0;
|
||||
|
||||
char sensor_dev[64], bridge_dev[64];
|
||||
if (!find_mc_subdevs(sensor_dev, sizeof(sensor_dev), bridge_dev, sizeof(bridge_dev)))
|
||||
return -1;
|
||||
|
||||
int sfd = open(sensor_dev, O_RDWR | O_CLOEXEC);
|
||||
if (sfd < 0) return -1;
|
||||
|
||||
struct v4l2_subdev_format sfmt;
|
||||
memset(&sfmt, 0, sizeof(sfmt));
|
||||
sfmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
|
||||
sfmt.pad = 0;
|
||||
sfmt.format.width = 1296;
|
||||
sfmt.format.height = 972;
|
||||
sfmt.format.code = MEDIA_BUS_FMT_SRGGB10_1X10;
|
||||
sfmt.format.field = V4L2_FIELD_NONE;
|
||||
if (ioctl(sfd, VIDIOC_SUBDEV_S_FMT, &sfmt) < 0) {
|
||||
close(sfd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int bfd = open(bridge_dev, O_RDWR | O_CLOEXEC);
|
||||
if (bfd < 0) {
|
||||
close(sfd);
|
||||
return -1;
|
||||
}
|
||||
struct v4l2_subdev_format bfmt = sfmt;
|
||||
bfmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
|
||||
bfmt.pad = 0;
|
||||
if (ioctl(bfd, VIDIOC_SUBDEV_S_FMT, &bfmt) < 0) {
|
||||
close(bfd);
|
||||
close(sfd);
|
||||
return -1;
|
||||
}
|
||||
close(bfd);
|
||||
|
||||
*exp_out = 1000;
|
||||
*again_out = 64;
|
||||
*dgain_out = 256;
|
||||
set_subdev_ctrl(sfd, V4L2_CID_EXPOSURE, *exp_out);
|
||||
set_subdev_ctrl(sfd, V4L2_CID_ANALOGUE_GAIN, *again_out);
|
||||
set_subdev_ctrl(sfd, V4L2_CID_DIGITAL_GAIN, *dgain_out);
|
||||
|
||||
*out_fmt = sfmt;
|
||||
*out_sensor_fd = sfd;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static bool process_captured_frame(cam_state_t *st, const void *data, uint32_t bytesused) {
|
||||
const uint8_t *raw = data;
|
||||
if (!raw || bytesused == 0) return false;
|
||||
|
||||
if (st->pixfmt == V4L2_PIX_FMT_MTISP_SRGGB10 ||
|
||||
st->pixfmt == V4L2_PIX_FMT_MTISP_SGRBG10) {
|
||||
if (bytesused < (uint32_t)((size_t)st->raw_stride * (size_t)st->raw_h))
|
||||
return false;
|
||||
int lin_avg = 0;
|
||||
bool is_rggb = (st->pixfmt == V4L2_PIX_FMT_MTISP_SRGGB10);
|
||||
geminux_bayer10_to_buffers(&st->isp, raw, st->raw_stride,
|
||||
st->raw_w, st->raw_h, is_rggb,
|
||||
st->rot_deg, st->mirror,
|
||||
st->raw16, st->rgb24, st->argb32, &lin_avg);
|
||||
st->frame_count++;
|
||||
if ((st->frame_count % 4U) == 0U && st->subdev_fd >= 0) {
|
||||
update_ae_agc(st, lin_avg);
|
||||
}
|
||||
if (st->recording) {
|
||||
unsigned char *jb = NULL;
|
||||
unsigned long jsz = 0;
|
||||
if (encode_rgb24_jpeg_mem(st->rgb24, st->cam_w, st->cam_h, 80, &jb, &jsz)) {
|
||||
avi_write_frame(st, jb, jsz);
|
||||
free(jb);
|
||||
}
|
||||
}
|
||||
} else if (st->pixfmt == V4L2_PIX_FMT_YUYV &&
|
||||
bytesused >= (uint32_t)(st->raw_w * st->raw_h * 2)) {
|
||||
yuyv_to_buffers(raw, st->raw_w, st->raw_h, st->rgb24, st->argb32);
|
||||
if (st->recording) {
|
||||
unsigned char *jb = NULL;
|
||||
unsigned long jsz = 0;
|
||||
if (encode_rgb24_jpeg_mem(st->rgb24, st->cam_w, st->cam_h, 80, &jb, &jsz)) {
|
||||
avi_write_frame(st, jb, jsz);
|
||||
free(jb);
|
||||
}
|
||||
}
|
||||
} else if (st->pixfmt == V4L2_PIX_FMT_MJPEG && bytesused > 4) {
|
||||
if (st->recording) avi_write_frame(st, raw, bytesused);
|
||||
struct jpeg_decompress_struct cinfo;
|
||||
struct jpeg_error_mgr jerr;
|
||||
cinfo.err = jpeg_std_error(&jerr);
|
||||
jpeg_create_decompress(&cinfo);
|
||||
jpeg_mem_src(&cinfo, raw, bytesused);
|
||||
if (jpeg_read_header(&cinfo, TRUE) == JPEG_HEADER_OK) {
|
||||
cinfo.out_color_space = JCS_RGB;
|
||||
jpeg_start_decompress(&cinfo);
|
||||
while ((int)cinfo.output_scanline < (int)cinfo.output_height &&
|
||||
(int)cinfo.output_scanline < st->cam_h) {
|
||||
int y = (int)cinfo.output_scanline;
|
||||
uint8_t *dst = st->rgb24 + (size_t)y * (size_t)st->cam_w * 3U;
|
||||
JSAMPROW row[1] = {dst};
|
||||
jpeg_read_scanlines(&cinfo, row, 1);
|
||||
if (st->argb32) {
|
||||
int cw = (int)cinfo.output_width < st->cam_w ? (int)cinfo.output_width : st->cam_w;
|
||||
for (int x = 0; x < cw; x++) {
|
||||
uint8_t r = dst[3 * x], g = dst[3 * x + 1], b = dst[3 * x + 2];
|
||||
st->argb32[y * st->cam_w + x] = 0xff000000U | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
|
||||
}
|
||||
}
|
||||
}
|
||||
jpeg_finish_decompress(&cinfo);
|
||||
}
|
||||
jpeg_destroy_decompress(&cinfo);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (st->frame_surf) cairo_surface_mark_dirty(st->frame_surf);
|
||||
return true;
|
||||
}
|
||||
|
||||
static void on_v4l2_ready(gemui_app_t *app, int fd, void *ud) {
|
||||
cam_state_t *st = ud;
|
||||
struct v4l2_buffer buf;
|
||||
@@ -260,77 +571,95 @@ static void on_v4l2_ready(gemui_app_t *app, int fd, void *ud) {
|
||||
buf.memory = V4L2_MEMORY_MMAP;
|
||||
if (ioctl(fd, VIDIOC_DQBUF, &buf) < 0) return;
|
||||
|
||||
const uint8_t *raw = st->bufs[buf.index].start;
|
||||
if (st->pixfmt == V4L2_PIX_FMT_YUYV && raw && buf.bytesused >= (uint32_t)(st->cam_w * st->cam_h * 2)) {
|
||||
yuyv_to_buffers(raw, st->cam_w, st->cam_h, st->rgb24, st->argb32);
|
||||
if (st->recording) {
|
||||
unsigned char *jb = NULL;
|
||||
unsigned long jsz = 0;
|
||||
if (encode_rgb24_jpeg_mem(st->rgb24, st->cam_w, st->cam_h, 80, &jb, &jsz)) {
|
||||
avi_write_frame(st, jb, jsz);
|
||||
free(jb);
|
||||
}
|
||||
}
|
||||
} else if (st->pixfmt == V4L2_PIX_FMT_MJPEG && raw && buf.bytesused > 4) {
|
||||
if (st->recording) avi_write_frame(st, raw, buf.bytesused);
|
||||
struct jpeg_decompress_struct cinfo;
|
||||
struct jpeg_error_mgr jerr;
|
||||
cinfo.err = jpeg_std_error(&jerr);
|
||||
jpeg_create_decompress(&cinfo);
|
||||
jpeg_mem_src(&cinfo, raw, buf.bytesused);
|
||||
if (jpeg_read_header(&cinfo, TRUE) == JPEG_HEADER_OK) {
|
||||
cinfo.out_color_space = JCS_RGB;
|
||||
jpeg_start_decompress(&cinfo);
|
||||
int row_stride = (int)cinfo.output_width * 3;
|
||||
while ((int)cinfo.output_scanline < (int)cinfo.output_height &&
|
||||
(int)cinfo.output_scanline < st->cam_h) {
|
||||
int y = (int)cinfo.output_scanline;
|
||||
uint8_t *dst = st->rgb24 + (size_t)y * (size_t)st->cam_w * 3U;
|
||||
JSAMPROW row[1] = {dst};
|
||||
jpeg_read_scanlines(&cinfo, row, 1);
|
||||
int cw = (int)cinfo.output_width < st->cam_w ? (int)cinfo.output_width : st->cam_w;
|
||||
for (int x = 0; x < cw; x++) {
|
||||
uint8_t r = dst[3 * x], g = dst[3 * x + 1], b = dst[3 * x + 2];
|
||||
st->argb32[y * st->cam_w + x] = 0xff000000U | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
|
||||
}
|
||||
(void)row_stride;
|
||||
}
|
||||
jpeg_finish_decompress(&cinfo);
|
||||
}
|
||||
jpeg_destroy_decompress(&cinfo);
|
||||
if (buf.index < (uint32_t)st->num_bufs) {
|
||||
process_captured_frame(st, st->bufs[buf.index].start, buf.bytesused);
|
||||
}
|
||||
|
||||
if (st->frame_surf) cairo_surface_mark_dirty(st->frame_surf);
|
||||
ioctl(fd, VIDIOC_QBUF, &buf);
|
||||
gemui_request_redraw(app);
|
||||
}
|
||||
|
||||
static void open_camera_idx(cam_state_t *st, int idx) {
|
||||
static bool open_camera_idx(cam_state_t *st, int idx, bool with_ui) {
|
||||
close_camera(st);
|
||||
if (idx < 0 || idx >= st->num_devs) return;
|
||||
if (idx < 0 || idx >= st->num_devs) return false;
|
||||
|
||||
int fd = open(st->dev_list[idx], O_RDWR | O_NONBLOCK | O_CLOEXEC);
|
||||
if (fd < 0) return;
|
||||
if (fd < 0) return false;
|
||||
|
||||
struct v4l2_subdev_format mc_fmt;
|
||||
memset(&mc_fmt, 0, sizeof(mc_fmt));
|
||||
int sensor_fd = -1;
|
||||
int mc_rc = configure_mc_pipeline(fd, &mc_fmt, &sensor_fd,
|
||||
&st->ae_exp, &st->ae_again, &st->ae_dgain);
|
||||
if (mc_rc < 0) {
|
||||
close(fd);
|
||||
return false;
|
||||
}
|
||||
|
||||
struct v4l2_format fmt;
|
||||
memset(&fmt, 0, sizeof(fmt));
|
||||
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
|
||||
fmt.fmt.pix.width = 1280;
|
||||
fmt.fmt.pix.height = 720;
|
||||
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
|
||||
fmt.fmt.pix.field = V4L2_FIELD_NONE;
|
||||
if (ioctl(fd, VIDIOC_S_FMT, &fmt) < 0) {
|
||||
close(fd);
|
||||
return;
|
||||
if (mc_rc > 0) {
|
||||
fmt.fmt.pix.width = mc_fmt.format.width;
|
||||
fmt.fmt.pix.height = mc_fmt.format.height;
|
||||
fmt.fmt.pix.pixelformat = (mc_fmt.format.code == MEDIA_BUS_FMT_SRGGB10_1X10)
|
||||
? V4L2_PIX_FMT_MTISP_SRGGB10
|
||||
: V4L2_PIX_FMT_MTISP_SGRBG10;
|
||||
fmt.fmt.pix.field = V4L2_FIELD_NONE;
|
||||
if (ioctl(fd, VIDIOC_S_FMT, &fmt) < 0) {
|
||||
if (sensor_fd >= 0) close(sensor_fd);
|
||||
close(fd);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
fmt.fmt.pix.width = 1280;
|
||||
fmt.fmt.pix.height = 720;
|
||||
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
|
||||
fmt.fmt.pix.field = V4L2_FIELD_NONE;
|
||||
if (ioctl(fd, VIDIOC_S_FMT, &fmt) < 0 ||
|
||||
(fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_YUYV &&
|
||||
fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_MJPEG)) {
|
||||
memset(&fmt, 0, sizeof(fmt));
|
||||
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
|
||||
fmt.fmt.pix.width = 1280;
|
||||
fmt.fmt.pix.height = 720;
|
||||
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
|
||||
fmt.fmt.pix.field = V4L2_FIELD_NONE;
|
||||
if (ioctl(fd, VIDIOC_S_FMT, &fmt) < 0) {
|
||||
close(fd);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
st->cam_w = (int)fmt.fmt.pix.width;
|
||||
st->cam_h = (int)fmt.fmt.pix.height;
|
||||
st->vfd = fd;
|
||||
st->subdev_fd = sensor_fd;
|
||||
st->pixfmt = fmt.fmt.pix.pixelformat;
|
||||
st->rgb24 = calloc((size_t)st->cam_w * (size_t)st->cam_h, 3);
|
||||
st->argb32 = calloc((size_t)st->cam_w * (size_t)st->cam_h, sizeof(uint32_t));
|
||||
st->frame_surf = cairo_image_surface_create_for_data(
|
||||
(unsigned char *)st->argb32, CAIRO_FORMAT_RGB24, st->cam_w, st->cam_h, st->cam_w * 4);
|
||||
st->raw_w = (int)fmt.fmt.pix.width;
|
||||
st->raw_h = (int)fmt.fmt.pix.height;
|
||||
st->raw_stride = (int)fmt.fmt.pix.bytesperline;
|
||||
if (st->raw_stride <= 0) {
|
||||
st->raw_stride = (st->pixfmt == V4L2_PIX_FMT_MTISP_SRGGB10 ||
|
||||
st->pixfmt == V4L2_PIX_FMT_MTISP_SGRBG10)
|
||||
? (st->raw_w * 10 / 8)
|
||||
: (st->raw_w * 2);
|
||||
}
|
||||
st->frame_count = 0;
|
||||
st->mirror = false;
|
||||
geminux_bayer10_isp_init(&st->isp);
|
||||
|
||||
if (st->pixfmt == V4L2_PIX_FMT_MTISP_SRGGB10 ||
|
||||
st->pixfmt == V4L2_PIX_FMT_MTISP_SGRBG10) {
|
||||
st->raw16 = malloc((size_t)st->raw_w * (size_t)st->raw_h * sizeof(uint16_t));
|
||||
if (!st->raw16) {
|
||||
close_camera(st);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!alloc_output_buffers(st, with_ui)) {
|
||||
close_camera(st);
|
||||
return false;
|
||||
}
|
||||
|
||||
struct v4l2_requestbuffers req;
|
||||
memset(&req, 0, sizeof(req));
|
||||
@@ -338,8 +667,8 @@ static void open_camera_idx(cam_state_t *st, int idx) {
|
||||
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
|
||||
req.memory = V4L2_MEMORY_MMAP;
|
||||
if (ioctl(fd, VIDIOC_REQBUFS, &req) < 0 || req.count == 0) {
|
||||
close(fd);
|
||||
return;
|
||||
close_camera(st);
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < (int)req.count && i < 4; i++) {
|
||||
@@ -355,18 +684,34 @@ static void open_camera_idx(cam_state_t *st, int idx) {
|
||||
st->num_bufs = i + 1;
|
||||
ioctl(fd, VIDIOC_QBUF, &b);
|
||||
}
|
||||
if (st->num_bufs == 0) {
|
||||
close_camera(st);
|
||||
return false;
|
||||
}
|
||||
|
||||
enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
|
||||
if (ioctl(fd, VIDIOC_STREAMON, &type) < 0) {
|
||||
st->vfd = fd;
|
||||
close_camera(st);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
st->vfd = fd;
|
||||
st->cur_dev = idx;
|
||||
snprintf(st->dev_path, sizeof(st->dev_path), "%s", st->dev_list[idx]);
|
||||
gemui_add_fd(st->app, fd, on_v4l2_ready, st);
|
||||
if (with_ui && st->app) gemui_add_fd(st->app, fd, on_v4l2_ready, st);
|
||||
return true;
|
||||
}
|
||||
|
||||
static void rotate_camera(cam_state_t *st) {
|
||||
if (st->recording) avi_stop(st);
|
||||
st->rot_deg = (st->rot_deg + 90) % 360;
|
||||
save_cam_config(st);
|
||||
if (st->vfd >= 0) alloc_output_buffers(st, st->app != NULL);
|
||||
if (st->app) {
|
||||
char msg[48];
|
||||
snprintf(msg, sizeof(msg), "Camera rotation: %d deg", st->rot_deg);
|
||||
gemui_show_toast(st->app, msg, 1200);
|
||||
gemui_request_redraw(st->app);
|
||||
}
|
||||
}
|
||||
|
||||
static void capture_still(cam_state_t *st) {
|
||||
@@ -418,14 +763,75 @@ static void discover_cameras(cam_state_t *st) {
|
||||
}
|
||||
}
|
||||
|
||||
static int run_oneshot(const char *out_path) {
|
||||
cam_state_t st;
|
||||
memset(&st, 0, sizeof(st));
|
||||
st.vfd = -1;
|
||||
st.subdev_fd = -1;
|
||||
load_cam_config(&st);
|
||||
discover_cameras(&st);
|
||||
if (st.num_devs == 0 || !open_camera_idx(&st, 0, false)) {
|
||||
fprintf(stderr, "geminux-camera: no usable V4L2 camera device\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
bool got_frame = false;
|
||||
for (int n = 0; n < 8; n++) {
|
||||
struct pollfd pfd = { .fd = st.vfd, .events = POLLIN, .revents = 0 };
|
||||
int pr = poll(&pfd, 1, 2000);
|
||||
if (pr <= 0 || !(pfd.revents & POLLIN)) {
|
||||
fprintf(stderr, "geminux-camera: poll timeout waiting for frame %d\n", n);
|
||||
close_camera(&st);
|
||||
return 1;
|
||||
}
|
||||
struct v4l2_buffer buf;
|
||||
memset(&buf, 0, sizeof(buf));
|
||||
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
|
||||
buf.memory = V4L2_MEMORY_MMAP;
|
||||
if (ioctl(st.vfd, VIDIOC_DQBUF, &buf) < 0) {
|
||||
fprintf(stderr, "geminux-camera: VIDIOC_DQBUF failed: %s\n", strerror(errno));
|
||||
close_camera(&st);
|
||||
return 1;
|
||||
}
|
||||
if (buf.index < (uint32_t)st.num_bufs &&
|
||||
process_captured_frame(&st, st.bufs[buf.index].start, buf.bytesused)) {
|
||||
got_frame = true;
|
||||
}
|
||||
ioctl(st.vfd, VIDIOC_QBUF, &buf);
|
||||
}
|
||||
|
||||
if (!got_frame) {
|
||||
fprintf(stderr, "geminux-camera: failed to decode captured frame\n");
|
||||
close_camera(&st);
|
||||
return 1;
|
||||
}
|
||||
|
||||
unsigned char *jb = NULL;
|
||||
unsigned long jsz = 0;
|
||||
int rc = 1;
|
||||
if (encode_rgb24_jpeg_mem(st.rgb24, st.cam_w, st.cam_h, 92, &jb, &jsz)) {
|
||||
FILE *f = fopen(out_path, "wb");
|
||||
if (f) {
|
||||
if (fwrite(jb, 1, jsz, f) == jsz) rc = 0;
|
||||
fclose(f);
|
||||
}
|
||||
free(jb);
|
||||
}
|
||||
close_camera(&st);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) {
|
||||
cam_state_t *st = ud;
|
||||
const gemui_theme_t *t = gemui_theme(app);
|
||||
|
||||
char badge[96];
|
||||
snprintf(badge, sizeof(badge), "%s%s",
|
||||
st->vfd >= 0 ? st->dev_path : "No V4L2 Camera",
|
||||
st->recording ? " [REC]" : "");
|
||||
if (st->vfd >= 0) {
|
||||
snprintf(badge, sizeof(badge), "%s %dx%d%s", st->dev_path, st->cam_w, st->cam_h,
|
||||
st->recording ? " [REC]" : "");
|
||||
} else {
|
||||
snprintf(badge, sizeof(badge), "No V4L2 Camera");
|
||||
}
|
||||
gemui_draw_header(app, cr, "\xef\x80\xb0", "Geminux Camera", badge);
|
||||
|
||||
int pad = 20;
|
||||
@@ -457,17 +863,21 @@ static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) {
|
||||
}
|
||||
|
||||
int rx = vf.x + vf.w + pad;
|
||||
gemui_draw_button(app, cr, (gemui_rect_t){rx, 96, rw, 96},
|
||||
gemui_draw_button(app, cr, (gemui_rect_t){rx, 96, rw, 90},
|
||||
"Photo (JPEG)", HIT_SHUTTER, 0, true, false, false);
|
||||
gemui_draw_button(app, cr, (gemui_rect_t){rx, 210, rw, 96},
|
||||
gemui_draw_button(app, cr, (gemui_rect_t){rx, 202, rw, 90},
|
||||
st->recording ? "Stop AVI" : "Record AVI", HIT_RECORD, 0, false, st->recording, false);
|
||||
gemui_draw_button(app, cr, (gemui_rect_t){rx, 324, rw, 80},
|
||||
gemui_draw_button(app, cr, (gemui_rect_t){rx, 308, rw, 78},
|
||||
"Switch Sensor", HIT_SWITCH, 0, false, false, false);
|
||||
char rot_lbl[32];
|
||||
snprintf(rot_lbl, sizeof(rot_lbl), "Rotate 90\xc2\xb0 (%d\xc2\xb0)", st->rot_deg);
|
||||
gemui_draw_button(app, cr, (gemui_rect_t){rx, 402, rw, 78},
|
||||
rot_lbl, HIT_ROTATE, 0, false, false, false);
|
||||
|
||||
gemui_draw_text(cr, t, (gemui_rect_t){rx, 430, rw, 40},
|
||||
gemui_draw_text(cr, t, (gemui_rect_t){rx, 504, rw, 40},
|
||||
st->last_file[0] ? "Last Saved:" : "", -3, true, GEMUI_ALIGN_LEFT, t->fg_muted);
|
||||
gemui_draw_text(cr, t, (gemui_rect_t){rx, 474, rw, 40},
|
||||
st->last_file[0] ? st->last_file : "Space: Shutter",
|
||||
gemui_draw_text(cr, t, (gemui_rect_t){rx, 546, rw, 40},
|
||||
st->last_file[0] ? st->last_file : "Space: Shutter | O: Rotate",
|
||||
-3, false, GEMUI_ALIGN_LEFT, t->accent);
|
||||
}
|
||||
|
||||
@@ -482,6 +892,8 @@ static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char *
|
||||
} else if (ks == XK_r) {
|
||||
if (st->recording) avi_stop(st); else avi_start(st);
|
||||
gemui_request_redraw(app);
|
||||
} else if (ks == XK_o) {
|
||||
rotate_camera(st);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -500,23 +912,31 @@ static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, v
|
||||
} else if (hit->id == HIT_SWITCH) {
|
||||
discover_cameras(st);
|
||||
if (st->num_devs > 0) {
|
||||
open_camera_idx(st, (st->cur_dev + 1) % st->num_devs);
|
||||
open_camera_idx(st, (st->cur_dev + 1) % st->num_devs, true);
|
||||
} else {
|
||||
gemui_show_toast(app, "No /dev/video* sensor found", 1800);
|
||||
}
|
||||
gemui_request_redraw(app);
|
||||
} else if (hit->id == HIT_ROTATE) {
|
||||
rotate_camera(st);
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int main(int argc, char **argv) {
|
||||
if (argc >= 3 && strcmp(argv[1], "--oneshot") == 0) {
|
||||
return run_oneshot(argv[2]);
|
||||
}
|
||||
|
||||
cam_state_t st;
|
||||
memset(&st, 0, sizeof(st));
|
||||
st.vfd = -1;
|
||||
st.subdev_fd = -1;
|
||||
load_cam_config(&st);
|
||||
discover_cameras(&st);
|
||||
|
||||
st.app = gemui_create("geminux-camera", "Geminux Camera", 1920, 940, false);
|
||||
if (!st.app) return 1;
|
||||
if (st.num_devs > 0) open_camera_idx(&st, 0);
|
||||
if (st.num_devs > 0) open_camera_idx(&st, 0, true);
|
||||
|
||||
gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key, .on_ptr = on_ptr };
|
||||
gemui_set_handlers(st.app, &h, &st);
|
||||
|
||||
@@ -49,8 +49,8 @@ geminux-modem-ctl: geminux-modem-ctl.c
|
||||
geminux-bt-obex: geminux-bt-obex.c
|
||||
$(CC) $(CFLAGS) $(GIO_CFLAGS) -o $@ $< $(GIO_LIBS)
|
||||
|
||||
geminux-leds: geminux-leds.c
|
||||
$(CC) $(CFLAGS) -o $@ $<
|
||||
geminux-leds: geminux-leds.c geminux-leds-core.h
|
||||
$(CC) $(CFLAGS) -o $@ geminux-leds.c
|
||||
|
||||
geminux-power-audit: geminux-power-audit.c
|
||||
$(CC) $(CFLAGS) -o $@ $<
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
#ifndef GEMINUX_LEDS_CORE_H
|
||||
#define GEMINUX_LEDS_CORE_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
static inline int geminux_led_clamp_u8(int v) {
|
||||
if (v < 0) return 0;
|
||||
if (v > 255) return 255;
|
||||
return v;
|
||||
}
|
||||
|
||||
static inline bool geminux_led_is_cover_rgb(const char *name) {
|
||||
if (!name) return false;
|
||||
return strncmp(name, "rgb:indicator-", 14) == 0 &&
|
||||
name[14] >= '1' && name[14] <= '6' && name[15] == '\0';
|
||||
}
|
||||
|
||||
static inline bool geminux_led_is_back_strip(const char *name) {
|
||||
if (!name) return false;
|
||||
return strncmp(name, "rgb:indicator-", 14) == 0 &&
|
||||
name[14] >= '1' && name[14] <= '5' && name[15] == '\0';
|
||||
}
|
||||
|
||||
static inline int geminux_led_format_mc(const char *multi_index,
|
||||
int r, int g, int b,
|
||||
char *intensity_out,
|
||||
size_t intensity_sz,
|
||||
int *brightness_out) {
|
||||
r = geminux_led_clamp_u8(r);
|
||||
g = geminux_led_clamp_u8(g);
|
||||
b = geminux_led_clamp_u8(b);
|
||||
|
||||
if (brightness_out) {
|
||||
*brightness_out = (r == 0 && g == 0 && b == 0) ? 0 : 255;
|
||||
}
|
||||
if (!intensity_out || intensity_sz == 0) return -1;
|
||||
|
||||
int vals[3] = {r, g, b};
|
||||
if (multi_index) {
|
||||
int parsed[3] = {0, 0, 0};
|
||||
int count = 0;
|
||||
const char *p = multi_index;
|
||||
while (*p != '\0') {
|
||||
while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++;
|
||||
if (*p == '\0') break;
|
||||
const char *start = p;
|
||||
while (*p != '\0' && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r') p++;
|
||||
size_t tok_len = (size_t)(p - start);
|
||||
if (count < 3) {
|
||||
if (tok_len == 3 && memcmp(start, "red", 3) == 0) parsed[count] = r;
|
||||
else if (tok_len == 5 && memcmp(start, "green", 5) == 0) parsed[count] = g;
|
||||
else if (tok_len == 4 && memcmp(start, "blue", 4) == 0) parsed[count] = b;
|
||||
else parsed[count] = 0;
|
||||
}
|
||||
count++;
|
||||
}
|
||||
if (count == 3) {
|
||||
vals[0] = parsed[0];
|
||||
vals[1] = parsed[1];
|
||||
vals[2] = parsed[2];
|
||||
}
|
||||
}
|
||||
|
||||
int n = snprintf(intensity_out, intensity_sz, "%d %d %d\n", vals[0], vals[1], vals[2]);
|
||||
if (n < 0 || (size_t)n >= intensity_sz) return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static inline bool geminux_uevent_is_power_supply(const char *buf, size_t len) {
|
||||
if (!buf || len == 0) return false;
|
||||
static const char target[] = "SUBSYSTEM=power_supply";
|
||||
const size_t tlen = sizeof(target) - 1;
|
||||
size_t i = 0;
|
||||
while (i < len) {
|
||||
while (i < len && (buf[i] == '\0' || buf[i] == '\n' || buf[i] == '\r')) i++;
|
||||
if (i >= len) break;
|
||||
size_t start = i;
|
||||
while (i < len && buf[i] != '\0' && buf[i] != '\n' && buf[i] != '\r') i++;
|
||||
size_t tok_len = i - start;
|
||||
if (tok_len == tlen && memcmp(buf + start, target, tlen) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <linux/netlink.h>
|
||||
#include <signal.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -17,65 +18,143 @@
|
||||
#include <sys/un.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "geminux-leds-core.h"
|
||||
|
||||
#define LEDS_SOCK "/run/geminux/leds.sock"
|
||||
|
||||
static void write_led(const char *channel, int val) {
|
||||
static int write_sysfs_str(const char *path, const char *s) {
|
||||
int fd = open(path, O_WRONLY | O_CLOEXEC);
|
||||
if (fd < 0) return -1;
|
||||
size_t len = strlen(s);
|
||||
size_t off = 0;
|
||||
int rc = 0;
|
||||
while (off < len) {
|
||||
ssize_t w = write(fd, s + off, len - off);
|
||||
if (w < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
rc = -1;
|
||||
break;
|
||||
}
|
||||
off += (size_t)w;
|
||||
}
|
||||
close(fd);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int read_sysfs_line(const char *path, char *out, size_t out_sz) {
|
||||
if (!out || out_sz == 0) return -1;
|
||||
out[0] = '\0';
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return -1;
|
||||
ssize_t n = -1;
|
||||
do {
|
||||
n = read(fd, out, out_sz - 1);
|
||||
} while (n < 0 && errno == EINTR);
|
||||
close(fd);
|
||||
if (n <= 0) return -1;
|
||||
out[n] = '\0';
|
||||
while (n > 0 && (out[n - 1] == '\n' || out[n - 1] == '\r')) {
|
||||
out[--n] = '\0';
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void write_mc_led_dir(const char *dir_path, int r, int g, int b) {
|
||||
r = geminux_led_clamp_u8(r);
|
||||
g = geminux_led_clamp_u8(g);
|
||||
b = geminux_led_clamp_u8(b);
|
||||
|
||||
char p[512];
|
||||
if (r == 0 && g == 0 && b == 0) {
|
||||
snprintf(p, sizeof(p), "%s/brightness", dir_path);
|
||||
write_sysfs_str(p, "0\n");
|
||||
return;
|
||||
}
|
||||
|
||||
char idx_buf[64];
|
||||
snprintf(p, sizeof(p), "%s/multi_index", dir_path);
|
||||
if (read_sysfs_line(p, idx_buf, sizeof(idx_buf)) != 0) {
|
||||
snprintf(idx_buf, sizeof(idx_buf), "red green blue");
|
||||
}
|
||||
|
||||
char intensity_buf[32];
|
||||
int bri = 0;
|
||||
if (geminux_led_format_mc(idx_buf, r, g, b, intensity_buf,
|
||||
sizeof(intensity_buf), &bri) != 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
snprintf(p, sizeof(p), "%s/multi_intensity", dir_path);
|
||||
write_sysfs_str(p, intensity_buf);
|
||||
|
||||
char bri_buf[16];
|
||||
snprintf(bri_buf, sizeof(bri_buf), "%d\n", bri);
|
||||
snprintf(p, sizeof(p), "%s/brightness", dir_path);
|
||||
write_sysfs_str(p, bri_buf);
|
||||
}
|
||||
|
||||
static void apply_strip_rgb(int r, int g, int b, bool include_end_led) {
|
||||
DIR *d = opendir("/sys/class/leds");
|
||||
if (!d) return;
|
||||
struct dirent *de;
|
||||
while ((de = readdir(d)) != NULL) {
|
||||
if (de->d_name[0] == '.') continue;
|
||||
if (strstr(de->d_name, channel)) {
|
||||
char p[320];
|
||||
snprintf(p, sizeof(p), "/sys/class/leds/%s/brightness", de->d_name);
|
||||
int fd = open(p, O_WRONLY | O_CLOEXEC);
|
||||
if (fd >= 0) {
|
||||
dprintf(fd, "%d\n", val);
|
||||
close(fd);
|
||||
}
|
||||
}
|
||||
bool match = include_end_led ? geminux_led_is_cover_rgb(de->d_name)
|
||||
: geminux_led_is_back_strip(de->d_name);
|
||||
if (!match) continue;
|
||||
char dir_path[320];
|
||||
snprintf(dir_path, sizeof(dir_path), "/sys/class/leds/%s", de->d_name);
|
||||
write_mc_led_dir(dir_path, r, g, b);
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
|
||||
static void apply_rgb(int r, int g, int b) {
|
||||
write_led("red", r);
|
||||
write_led("green", g);
|
||||
write_led("blue", b);
|
||||
static void write_single_cover_led(int idx, int r, int g, int b) {
|
||||
if (idx < 1 || idx > 6) return;
|
||||
char dir_path[64];
|
||||
snprintf(dir_path, sizeof(dir_path), "/sys/class/leds/rgb:indicator-%d", idx);
|
||||
write_mc_led_dir(dir_path, r, g, b);
|
||||
}
|
||||
|
||||
static void sync_charging_led(void) {
|
||||
static int read_charging_state(void) {
|
||||
DIR *d = opendir("/sys/class/power_supply");
|
||||
if (!d) return;
|
||||
if (!d) return 0;
|
||||
int state = 0;
|
||||
struct dirent *de;
|
||||
while ((de = readdir(d)) != NULL) {
|
||||
if (de->d_name[0] == '.') continue;
|
||||
char p[320], typ[32] = {0}, st[32] = {0};
|
||||
snprintf(p, sizeof(p), "/sys/class/power_supply/%s/type", de->d_name);
|
||||
FILE *ft = fopen(p, "r");
|
||||
if (!ft) continue;
|
||||
if (fgets(typ, sizeof(typ), ft)) {
|
||||
size_t ln = strlen(typ);
|
||||
while (ln > 0 && typ[ln - 1] == '\n') typ[--ln] = '\0';
|
||||
}
|
||||
fclose(ft);
|
||||
if (strcmp(typ, "Battery") != 0) continue;
|
||||
if (read_sysfs_line(p, typ, sizeof(typ)) != 0) continue;
|
||||
if (strcmp(typ, "Battery") != 0 && strcmp(typ, "USB") != 0) continue;
|
||||
|
||||
snprintf(p, sizeof(p), "/sys/class/power_supply/%s/status", de->d_name);
|
||||
FILE *fs = fopen(p, "r");
|
||||
if (fs) {
|
||||
if (fgets(st, sizeof(st), fs)) {
|
||||
size_t ln = strlen(st);
|
||||
while (ln > 0 && st[ln - 1] == '\n') st[--ln] = '\0';
|
||||
}
|
||||
fclose(fs);
|
||||
if (read_sysfs_line(p, st, sizeof(st)) != 0) continue;
|
||||
if (strcmp(st, "Charging") == 0) {
|
||||
state = 1;
|
||||
break;
|
||||
} else if (strcmp(st, "Full") == 0) {
|
||||
state = 2;
|
||||
}
|
||||
if (strcmp(st, "Charging") == 0) apply_rgb(32, 16, 0);
|
||||
else if (strcmp(st, "Full") == 0) apply_rgb(0, 32, 0);
|
||||
else apply_rgb(0, 0, 0);
|
||||
break;
|
||||
}
|
||||
closedir(d);
|
||||
return state;
|
||||
}
|
||||
|
||||
static void sync_charging_led(int *last_state, bool force) {
|
||||
int st = read_charging_state();
|
||||
if (!force && *last_state == st) return;
|
||||
*last_state = st;
|
||||
if (st == 1) apply_strip_rgb(32, 16, 0, false);
|
||||
else if (st == 2) apply_strip_rgb(0, 32, 0, false);
|
||||
else apply_strip_rgb(0, 0, 0, true);
|
||||
}
|
||||
|
||||
static void disarm_timer(int tmr_fd) {
|
||||
if (tmr_fd < 0) return;
|
||||
struct itimerspec its;
|
||||
memset(&its, 0, sizeof(its));
|
||||
timerfd_settime(tmr_fd, 0, &its, NULL);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
@@ -103,9 +182,14 @@ int main(void) {
|
||||
}
|
||||
}
|
||||
|
||||
int uev_fd = socket(PF_NETLINK, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT);
|
||||
int uev_fd = socket(PF_NETLINK, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC,
|
||||
NETLINK_KOBJECT_UEVENT);
|
||||
if (uev_fd >= 0) {
|
||||
struct sockaddr_nl nl = { .nl_family = AF_NETLINK, .nl_pid = (uint32_t)getpid(), .nl_groups = 1 };
|
||||
struct sockaddr_nl nl = {
|
||||
.nl_family = AF_NETLINK,
|
||||
.nl_pid = (uint32_t)getpid(),
|
||||
.nl_groups = 1,
|
||||
};
|
||||
bind(uev_fd, (struct sockaddr *)&nl, sizeof(nl));
|
||||
}
|
||||
|
||||
@@ -120,7 +204,8 @@ int main(void) {
|
||||
}
|
||||
}
|
||||
|
||||
sync_charging_led();
|
||||
int last_chg_state = -1;
|
||||
sync_charging_led(&last_chg_state, true);
|
||||
|
||||
struct epoll_event events[8];
|
||||
bool running = true;
|
||||
@@ -140,19 +225,34 @@ int main(void) {
|
||||
char cmd[128] = {0};
|
||||
ssize_t r = read(cfd, cmd, sizeof(cmd) - 1);
|
||||
if (r > 0) {
|
||||
while (r > 0 && (cmd[r - 1] == '\n' || cmd[r - 1] == '\r')) cmd[--r] = '\0';
|
||||
int rr = 0, gg = 0, bb = 0, ms = 0;
|
||||
while (r > 0 && (cmd[r - 1] == '\n' || cmd[r - 1] == '\r')) {
|
||||
cmd[--r] = '\0';
|
||||
}
|
||||
int idx = 0, rr = 0, gg = 0, bb = 0, ms = 0;
|
||||
if (strcmp(cmd, "off") == 0) {
|
||||
apply_rgb(0, 0, 0);
|
||||
disarm_timer(tmr_fd);
|
||||
apply_strip_rgb(0, 0, 0, true);
|
||||
} else if (strcmp(cmd, "auto") == 0) {
|
||||
disarm_timer(tmr_fd);
|
||||
sync_charging_led(&last_chg_state, true);
|
||||
} else if (sscanf(cmd, "rgb %d %d %d", &rr, &gg, &bb) == 3) {
|
||||
apply_rgb(rr, gg, bb);
|
||||
disarm_timer(tmr_fd);
|
||||
apply_strip_rgb(rr, gg, bb, false);
|
||||
} else if (sscanf(cmd, "led %d %d %d %d", &idx, &rr, &gg, &bb) == 4) {
|
||||
if (idx >= 1 && idx <= 6) {
|
||||
write_single_cover_led(idx, rr, gg, bb);
|
||||
}
|
||||
} else if (sscanf(cmd, "pulse %d %d %d %d", &rr, &gg, &bb, &ms) == 4) {
|
||||
apply_rgb(rr, gg, bb);
|
||||
struct itimerspec its;
|
||||
memset(&its, 0, sizeof(its));
|
||||
its.it_value.tv_sec = ms / 1000;
|
||||
its.it_value.tv_nsec = (ms % 1000) * 1000000L;
|
||||
timerfd_settime(tmr_fd, 0, &its, NULL);
|
||||
apply_strip_rgb(rr, gg, bb, false);
|
||||
if (ms > 0 && tmr_fd >= 0) {
|
||||
struct itimerspec its;
|
||||
memset(&its, 0, sizeof(its));
|
||||
its.it_value.tv_sec = ms / 1000;
|
||||
its.it_value.tv_nsec = (ms % 1000) * 1000000L;
|
||||
timerfd_settime(tmr_fd, 0, &its, NULL);
|
||||
} else {
|
||||
disarm_timer(tmr_fd);
|
||||
}
|
||||
}
|
||||
}
|
||||
dprintf(cfd, "OK\n");
|
||||
@@ -161,11 +261,19 @@ int main(void) {
|
||||
} else if (fd == tmr_fd) {
|
||||
uint64_t exp = 0;
|
||||
while (read(tmr_fd, &exp, sizeof(exp)) > 0) {}
|
||||
sync_charging_led();
|
||||
sync_charging_led(&last_chg_state, true);
|
||||
} else if (fd == uev_fd) {
|
||||
char ubuf[1024];
|
||||
while (recv(uev_fd, ubuf, sizeof(ubuf), 0) > 0) {}
|
||||
sync_charging_led();
|
||||
bool ps_event = false;
|
||||
ssize_t ulen;
|
||||
while ((ulen = recv(uev_fd, ubuf, sizeof(ubuf), 0)) > 0) {
|
||||
if (geminux_uevent_is_power_supply(ubuf, (size_t)ulen)) {
|
||||
ps_event = true;
|
||||
}
|
||||
}
|
||||
if (ps_event) {
|
||||
sync_charging_led(&last_chg_state, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user