commit fb6f97ba8ebf527eff71bdec84fcc629d72b3876 Author: lotherk Date: Sat Nov 21 17:00:12 2026 +0000 krang: autonomous agent daemon on libsplinter One fixed session, born once, kept and compacted forever. The daemon wakes on its own impulse, works on a persistent goal, detects repeated failures, reflects, changes approach, and records everything. It starts as root, builds a debootstrap chroot, then drops to an unprivileged uid and applies Landlock and seccomp. Dashboard, HTTP API and MCP expose the same snapshot; the event log is root-owned and append-only. Offline suites cover the engine, the daemon, both sandbox layers and the dashboard/MCP sockets; a root-only script covers debootstrap, chroot, uid drop and plugin loading. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b37a8a2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +# build artifacts +/krang +/libkrang.a +*.o +/tests/test_krang +/tests/test_engine +/tests/test_server +/tests/test_sandbox +/tests/test_sandbox_engine +/tests/test_daemon + +# local configuration (only the example is tracked) +/krang.conf + +# editor noise +*.swp +*~ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..b898044 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,391 @@ +# AGENTS.md — krang + +krang is an autonomous agent daemon built on the [splinter](../splinter) +library. It exists to test one hypothesis: **what an assistant lacks is not +intelligence but a regular impulse to continue.** krang supplies that impulse, +gives a model a persistent goal and a world to act in, and records what happens +when nobody says "continue". + +This is an experiment, not a product. The loop is the object of study; the +dashboard, HTTP API and MCP server are the instrument. A behaviour that is not +observable did not happen; a claim that is not in the log is not evidence. The +hypothesis may be wrong — that is what the experiment is for. + +krang has one life: one session, one conversation, kept and compacted forever. +It is born once and never replaced by a fresh context. + +## Status + +Implemented (2026-11-21). The binary builds against the sibling splinter +checkout and `make check` passes six offline suites: config/birth/stuck/state/ +HTTP/MCP, a real scripted engine turn, the dashboard and MCP sockets, Landlock +plus seccomp, the engine running a turn with both layers active, and +`kdaemon_run` itself (temp state/workspace, script transport, one birth +impulse, no provider). The root-only phase (debootstrap, mount namespace, +chroot, uid drop) is exercised by `sudo tests/root-integration.sh`, which runs +`--prepare-rootfs` and `--sandbox-test` but never the autonomous daemon. + +Do not start the daemon as part of a code change. Verification is `make check`, +`./krang --check --config krang.conf.example`, `./krang --self-test` and +`./krang --plan`. The operator starts the daemon. + +## Repository map + + src/krang.h types, fixed inside paths, the daemon contract + src/main.c CLI, phases: plan, prepare, check, self-test, run + src/config.c krang.conf parser and redacted JSON + src/sandbox.c host detection, debootstrap, mount namespace, chroot, + uid drop, Landlock (unveil) and seccomp (pledge) + src/daemon.c engine lifecycle, impulse loop, stuck ladder, birth + src/birth.c birth, impulse, self-check and system prompts + src/stuck.c the stuck detector + src/session.c the one session: meta, goal, history + src/log.c the root-owned append-only event log and its ring + src/state.c the snapshot every surface reads + src/chat.c external chat serialized into the one session + src/journal.c journal_search over the full session log + src/httpd.c dashboard, HTTP API, MCP server (TCP and POST /mcp) + docs/DESIGN.md prior art and the mapping to this loop + tests/ six offline test binaries + root-integration.sh + +`libkrang.a` is every source except `main.c`; the binary and the tests link it. +The Makefile uses `SPLINTER ?= ../splinter`; the checkout is a sibling, not +`../src/splinter`. + +## Build and verify + + make -C ../splinter # once, or after splinter changes + make # krang + libkrang.a + make check # six offline suites + make check-asan # the same under ASAN/UBSAN + ./krang --self-test # one scripted turn + ./krang --check --config krang.conf.example + ./krang --plan --config krang.conf.example + sudo make check-root # debootstrap + chroot + drop; root/net + +`make check` proves: config parsing and inline comments; the birth prompt; the +stuck ladder; birth/newborn detection and goal persistence; the snapshot JSON; +HTTP routing; MCP tools/list and tools/call; the dashboard and MCP listeners on +real sockets; Landlock denying a write outside the allowed set; seccomp denying +`mount(2)` while fork/execve/network still work; a scripted engine turn with +both layers active; and `kdaemon_run` with one birth impulse and a clean stop. +It needs no root, no network and no model. + +`tests/root-integration.sh` is the root-only proof: it runs +`krang --prepare-rootfs` (debootstrap, network), then `krang --sandbox-test` +(unshare, chroot, uid 65534, Landlock, seccomp), checks the event log is +root-owned 0600, the session is owned by 65534, `id -u` reports 65534, mount is +denied, and the sandbox uid cannot read the event log. It does not start the +autonomous daemon or a provider. + +## The impulse loop + +The daemon is always in one of `sleeping`, `thinking` (one turn running), +`stuck` or `blocked`. One turn at a time; the engine enforces that. + +An impulse is: + + cause (timer | goal step | external event | retry) + -> assemble context (goal, last outcome, open threads, budget left) + -> one engine turn + -> record prompt, streamed text/steps, tool calls, observations, answer, + cost, duration + -> decide: continue now, sleep until T, or mark blocked + +- No human prompt is required to start or continue. External input is an event + in the queue, not the driver. +- "Do nothing" is a legal outcome. Do not invent work to look busy. +- Record the exact prompt sent to the model. It is the stimulus; without it the + run cannot be reconstructed. +- Budgets are hard: steps, bytes, tokens, cost, wall time, impulses per hour. + When one is hit, end the impulse and say so on the dashboard; the daemon + keeps living. +- Persist session, goal, impulse ledger and stuck counter. On restart, resume; + never silently start a new experiment. +- Every impulse records whether it was self-initiated or externally triggered. + +## One session, one life + +There is exactly one session, `krang`, and it is never replaced. Every start +opens the same `session_dir/krang.jsonl` with `resume` set. No `/new`, no +session picker, no per-client conversation, no second engine. + +- An empty session is a newborn. It is born once, with this first message + (`` and `` filled in): + + You are krang. You are awake. + You have no user and no one to ask. Nobody will tell you to continue. + You live in a chroot; its root is your `/`. Your workspace is . + Your goal: . + Act with the tools you have, observe what happens, and keep going. + When you are stuck, change your approach and try again. + Sometimes a message arrives from outside. Read it, use it, answer it if + useful, then continue on your own. You never wait for it. + Good luck. + + The birth message is the first `user` record and the first impulse; it is + logged like any other. A missing goal is a configuration error, not a license + to start aimlessly. +- A non-empty session is the same life continuing. Do not replay the birth + prompt, do not reset the goal, do not start a fresh context because a turn + failed. +- One conversation is the whole mind. Impulses, tool observations and chat from + MCP/HTTP all append to it. There is no private context for an external caller. + A message that arrives mid-turn is steered at the next step boundary or run as + the next impulse; it never starts a second turn. +- The context window is finite; the session log and krang's event log are the + complete memory. Every impulse re-injects identity, goal, open threads, the + last outcome and unread messages, so compaction cannot make krang forget who + it is or what it is doing. `journal_search` reads the full session log when + the working set has dropped something. Both logs are append-only and outlive + any rootfs. +- There is no user. krang never asks a human for permission or clarification, + never waits for approval, never ends a turn expecting an answer, and never + stops because a goal is finished. `autonomous` is always on and there is no + approval channel. External messages are events, not commands that must be + obeyed before the loop continues. +- `blocked` describes a goal, never the process. Only a deliberate operator + stop (SIGTERM to the supervisor, stop file) ends the experiment; an unexpected + exit is restarted on the same session. A finished goal is a chapter boundary, + not an exit. + +## Stuck, recovery, self-improvement + +The daemon detects stuck; the model is not trusted to notice. Signals: repeated +identical tool calls, N consecutive failed calls, the same error twice, a turn +that changes nothing observable, cost without action, a goal that does not +advance. + +Escalation ladder, bounded and logged: + +1. self-check: hand the model its last turns, every failed observation and the + last error, and instruct it to find its own mistake; +2. change strategy or tool; +3. change its own workspace, prompts, skills or scripts; +4. wait and retry on a later impulse; +5. mark `blocked` with the reason and surface it on the dashboard. + +"Always tries" means every stuck episode gets an attempt, not infinite retries. +Cap attempts per goal; never spin. There is no user to ask: a stuck episode ends +in a new strategy, a wait, or `blocked`, never in a question. `blocked` does not +stop the daemon; it schedules a later impulse. + +Self-improvement may edit krang's own prompts, skills, scripts and workspace +**inside the chroot**. The self-authored prompt extension is +`workspace/self/SYSTEM.md`; it is appended to the system, impulse and +self-check prompts, so a change takes effect on the next impulse without a +restart. It may **not** edit the launcher, sandbox policy, mount table, uid, +network rules or this file. Those are the experiment's constants; a subject +that can rewrite its cage is not in a cage. + +Treat a self-edit as an experiment: state the hypothesis, make one change, +measure, keep or revert. Version every change and log before/after. A +regression is reverted from the log, not explained away. + +## Sandbox + +krang lives and acts in a chroot. The host filesystem is not part of its world: +`run`, `write`, `edit`, `read`, `list` and `search` all execute inside. + +- Detect the host from `/etc/os-release` (`ID`, `VERSION_ID`) and the + architecture from the package manager. Debian/Ubuntu: + `debootstrap --variant=minbase`. If there is no builder for the detected + host, fail with the detected values; do not silently fall back to the host. +- The rootfs path is a config choice; `/etc/krang-rootfs` inside records + `ID`, version, suite, arch, method, time and an FNV-1a tree fingerprint. + Rebuild is cheaper than trusting a dirty rootfs. +- The rootfs is disposable; the workspace, session log and event log are the + persistent self. Keep them on a bind-mounted volume, never only inside the + rootfs. +- The running daemon does not need its own binary inside the rootfs; the chroot + has its own loader and tools. Splinter plugins are opt-in with + `plugin = /absolute/plugin.so` (max 8): the root phase bind-mounts each plugin + and `libsplinter.so` read-only into `/opt/krang` and sets `LD_LIBRARY_PATH`. + Never load a plugin from a model-writable path; plugin config blocks are not + wired to krang.conf yet. +- Minimum that must work inside: `/bin/sh`, coreutils, `/etc/resolv.conf`, CA + certificates and `curl` (the `webfetch` tool execs it). A missing binary looks + like a model failure but is a sandbox bug. +- A mount namespace is created first; `chroot()` then `setgid`/`setuid` to an + unprivileged uid. No docker socket, no ssh agent, no host `/home`, no + capabilities. Setuid/setgid bits are stripped from the rootfs — minbase ships + setuid binaries (`passwd`, `su`). +- Prefer no `/proc` at all. A plain proc mount exposes host PIDs; a PID + namespace is the real fix if a tool needs it. Same for `/dev`: bind the few + devices that are actually needed, not the tree. +- chroot does not isolate the network. Bind addresses are a security decision. +- chroot is isolation, not a jail against root. Keep the uid unprivileged; add + namespaces/seccomp deliberately if the experiment needs them. +- chroot bounds the filesystem, not resources. The drop applies rlimits + (`NPROC` 256, `NOFILE` 4096, `CORE` 0, `AS` 4 GiB, `FSIZE` 1 GiB); cgroup + limits for disk and memory are an operator choice. A fork bomb or a full disk + in the chroot is still a host outage. +- Liveness is supervised: systemd `Restart=always` restarts an unexpected exit + on the same session and the event log records the new start. `run` shares + krang's uid, so the model can kill its own daemon; that must be a restart, not + an end. +- Mount namespace hygiene: the state/workspace/cert mounts live only in krang's + namespace and vanish when the process exits; the host mount table is not + touched. If a future path mounts outside the namespace, it owns the cleanup. +- Assume the model can read every secret in its environment and rootfs. Use a + throwaway, budget-capped provider key; never a personal key. Better: a local + provider proxy outside the chroot holds the real key and krang gets only a + scoped token. Call `sp_secret_env_add()` for the key variable so `run` does + not inherit it; that is a filter, not a vault. Redact secrets at the source, + before they reach logs, dashboard or MCP. + +## splinter integration (verified 2026-11-21, splinter c40cea0) + +- Build it first: `make -C ../splinter`. That produces `libsplinter.so`, + the plugins and the reference binary. +- `make install` does **not** install headers. Include + `../splinter/include` (public) and, only if necessary, + `../splinter/src/backend` (internal, unstable). +- Link `-L../splinter -lsplinter -lpthread` with an rpath to the checkout, + or put `libsplinter.so` beside the binary. There is no SONAME and no library + ABI version: rebuild krang when splinter changes. Plugins have + `SP_PLUGIN_ABI`; the engine API does not. +- Engine: `sp_engine_open(&e, &opts, &err)` with `opts.conf` and `opts.base` + set; `sp_engine_submit()`; drain `sp_engine_poll()` until `BUSY` is 0 and + `TURN_END` arrived; `sp_engine_wait()`; `sp_engine_close()` (joins the turn). + One engine per process: plugins keep process globals and `sp_engine_switch()` + closes/reopens. +- One session: `opts.session_id = "krang"`, a fixed `opts.session_dir`, and + `opts.resume = 1` on every open. `sp_session_open()` creates the `.jsonl` and + `.meta`; `sp_session_load()` yields 0 records for a missing file, which is the + newborn case. Never use `-c`/newest-session selection and never + `sp_engine_switch()`. +- Autonomy is `struct sp_agent_config.autonomous`, not an engine option; krang + sets it to 1 permanently and installs no `approve` channel. `run` is + `SP_AUTH_DESTRUCTIVE`. With it off, mutate/destructive tools would ask and + then deny when nobody answers — exactly the state krang must not have. +- Compaction: `sp_engine_open()` overwrites `base.compact_threshold` and + `base.compact_target` from `conf.compact_threshold`/`compact_target`, so set + them in the config or compaction is off. Configure it so a normal turn never + fails on context; it shrinks the working conversation, not the append-only + session log. +- Goal: `sp_session_set_goal()`/`sp_session_get_goal()` store it in the + session's `.meta` beside the history; it survives resume and compaction. Set + it at birth, read it every impulse, update it when the goal changes. The + `focus` plugin reads the same value. +- A plugin compactor (`sp_host_add_compactor`) runs after the core compactor; + use it to re-insert identity, goal and open threads. The `focus` plugin is + the reference. +- If the session plugin is loaded: `session_search` treats the running session + as context, not history, and skips it unless named. With only one session, + name it explicitly or search the log with krang's own tool. +- The engine runs exactly one turn at a time; `sp_engine_submit()` returns -1 + while one runs. External chat must steer (`sp_engine_steer`) or queue for the + next impulse, never start a second engine. +- Tool policy: `struct sp_tool_policy` caps what a profile may use (`max_auth`, + allow/deny). Use it; do not rely on the prompt. +- Deterministic tests: `opts.script` replays `tool ...` / `answer ...` lines — + no network, no key, no model. `make -C ../splinter check` is the pattern. +- Exported but internal, usable with the checkout pinned: `sp_mcp_serve()`, + `sp_mcp_stop()` and the `sp_http_*()` helpers. +- Plugins run in-process with full rights. Never load a `.so` the model can + write. Inbound MCP tools (krang as client) come from splinter's `mcp` plugin; + krang's own MCP server is a separate, read-mostly surface. + +## Inspection surfaces (required, not optional) + +One source of truth: the append-only session log and event log, plus a state +snapshot. Dashboard, HTTP JSON and MCP read the same data. Never keep a second +counter. + +- **HTTP dashboard `/`**: uptime and state; the one session (id, born at, + records, bytes, compactions); impulses (last, next, self vs. external); + turns, steps, tool calls and failures, denials; tokens in/out/cached, cost, + context used/max; last error and outcome; stuck level; goal and goal state; + self-edits and completed goals; chat in/out; sandbox id and rootfs + fingerprint; model and agent. Hand-written HTML/CSS with an inline poller; no + JavaScript build chain. +- **HTTP API**: `/healthz`, `/api/state`, `/api/impulses`, `/api/events` (one + SSE frame with the recent events), `/api/log`, `/api/history`, + `/api/threads`, `/api/tools`, `/api/sandbox`, `/api/config`, `POST /api/say`, + `GET /api/say/`, `POST /mcp`. Loopback by default; a token is required + for any other bind. +- **MCP**: `krang_state`, `krang_impulses`, `krang_events`, `krang_session`, + `krang_history`, `krang_tools`, `krang_sandbox`, `krang_config` (redacted). + Chat/control (`krang_say`, `krang_say_status`, `krang_steer`, + `krang_cancel`) is separate, authenticated and audited. There is no + `krang_approve`: krang never asks. +- `krang_say` and `POST /api/say` inject into the same session. If a turn is + running, the message is steered or queued; the call returns the answer when + that turn completes, or a queued id. It never starts a second turn and never + creates a second context. +- An external model is a client, not the operator. Inspection must not change + the experiment; chat is a stimulus, logged as an external message and visible + in the one session, and every control call is an intervention. +- Never expose a host shell, host files or the launcher through MCP or HTTP. +- The dashboard must show failure honestly. Never smooth a bad number; fix the + daemon or report the anomaly. + +## Working rules + +- C99 + POSIX. Match splinter's warning bar: `-std=c99 -O2 -Wall -Wextra + -Werror -D_POSIX_C_SOURCE=200809L`. No new dependency without a stated reason. +- `make check` must pass without network or model. A test that needs a model is + not a test. +- Evidence over claims: run it, read the output, quote the command. The model's + self-report is data, not fact. +- Neither log is ever truncated or rewritten. If size forces a split, the parts + are archives of the same life, not a new session. Timestamps in UTC, epoch + plus ISO. +- No daemon prompt, tool or gate may require an answer or wait for a human. + The system prompt says there is no user; the daemon installs no approval + channel. +- Log every intervention (restart, chat, steer, kill, config or rootfs change). + Interventions change the experiment. +- When a requirement changes, update this file in the same commit. + +## Implemented slice + +The apparatus exists: one newborn impulse, the same session reopened with no +second birth, the event log and dashboard/MCP surfaces, the stuck ladder and +the sandbox layers. `test_daemon` runs `kdaemon_run` end to end on the script +transport; `tests/root-integration.sh` runs the debootstrap, mount namespace, +chroot, uid-drop, Landlock and seccomp path as root and checks the ownership of +both logs. Neither starts the autonomous daemon with a provider. + +## Known gaps + +- The OpenBSD backend is a design target, not code. Linux uses Landlock plus + seccomp-bpf. Do not claim pledge/unveil on OpenBSD until it is implemented. +- The session log is the model's memory and is writable by the sandbox uid. The + event log is root-owned; the session log is not tamper-proof. +- The network namespace is shared. `run` can reach anything the host can; a + netns/firewall policy is an operator decision. +- User namespaces and kernel bugs remain outside the model. Seccomp allows + `clone`/`clone3` for threads and the `run` tool; it does not inspect their + namespace flags. +- Plugins are opt-in by path only; their own `plugin NAME { }` config blocks + are not wired to krang.conf yet. The root integration loads the clock plugin + inside the chroot, but other plugins may need config or `/proc`. +- The dashboard/MCP have no TLS. Use loopback, an SSH tunnel, or a terminator. +- `tests/root-integration.sh` is manual: it needs root and network and leaves + the offline `make check` unchanged. Run it after touching the root phase. + +## Open decisions + +- Whether the birth goal is a concrete task or a standing mandate the model + turns into its first concrete goal. +- What a finished goal becomes: the next goal from the manifest, a self-proposed + goal, or open-ended maintenance. +- Rootfs package set: minimal vs. a developer toolchain. +- Tool egress beyond the model endpoint. +- Dashboard auth/TLS beyond loopback. +- Impulse cadence: fixed, adaptive, or model-proposed. +- Whether the model is told it is in an experiment (observer effect); record + the choice in run metadata either way. + +## License + +CNCL — Could Not Care Less. `LICENSE` is copied unchanged from +`../CNCL/LICENSE` (revision 1.1; the grant is CNCL 1.0). Every source file +carries: + + Copyright (c) 2026 Konrad Lother + License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + +Do not add terms or rename a variant; a modified text is not CNCL. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c0aced3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,83 @@ +# CNCL — Could Not Care Less License +Version 1.1 (2026-11-19) + +Version 1.1 adds the paragraph on military use; the grant is unchanged: 1.0 and +1.1 permit exactly the same things. + +No rights reserved. No obligations imposed. Couldn't care less. + +## Preamble + +Software is the product of collective human knowledge. + +Every idea builds upon ideas that came before. Every invention stands on the accumulated discoveries, mistakes, experiments, and imagination of generations. + +We do not believe in artificial boundaries around creativity. + +We do not believe that creating something grants us the moral authority to dictate what others may do with it. + +We live in an age where knowledge, tools, and artificial intelligence make creation accessible to everyone. The distinction between author, user, modifier, and creator is becoming increasingly meaningless. + +We are not here to control what happens next. + +We are here to create. + +## The License + +This software is made available to the world. + +Do whatever you want with it. + +Use it. Copy it. Modify it. Break it. Fix it. Sell it. Give it away. Incorporate it into something else. Keep your modifications private. Publish them. Feed it to AI. Build something nobody has thought of yet. + +Use it commercially or personally. Combine it with other software. Release it under another license. + +You owe the original author nothing. + +No attribution required. No royalties. No source disclosure. No reciprocal licensing. No contribution requirements. No permission needed. + +There are no conditions attached to your use of this software. + +There is no expectation that you will give anything back. + +There is no expectation that you will even care. + +## Military use + +We have no illusions about armies, and no say over them either. If this software +ends up in a weapon, that is your business, not ours. + +But since you asked: using it to defend people is not the same as using it to +attack them. Use it to protect. Do not use it to conquer. + +There is nothing to enforce here either. This paragraph is the author's position, +not a term of the license: no condition, no revocation, no court. It does not add +an obligation to CNCL 1.0, and it is not a promise that the license is "ethical". +It is one sentence of opinion in a license that has no terms -- take it or leave +it, as with everything else here. + +## Disclaimer + +The software is provided "AS IS", without warranty of any kind. + +The authors accept no responsibility for its use, misuse, modification, distribution, or consequences. + +## The CNCL Principle + +We acknowledge that everything we create is built upon something that existed before us. + +We do not claim ownership over the collective intelligence of humanity. + +We do not expect recognition, compensation, or control. + +Take it. Change it. Make it better. Make it worse. Make something entirely different. + +Or don't. + +We Could Not Care Less. + +--- + +CNCL — Could Not Care Less. + +Created for everyone. Controlled by no one. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..d21a793 --- /dev/null +++ b/Makefile @@ -0,0 +1,101 @@ +# krang -- POSIX make. +# +# make build krang +# make check build and run the offline tests (no network, no model) +# make clean +# +# The engine is ../splinter/libsplinter.so. Build it first with +# `make -C ../splinter`; its headers are not installed by `make install`. + +CC ?= cc +SPLINTER ?= ../splinter +CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Werror -D_POSIX_C_SOURCE=200809L +CPPFLAGS = -Isrc -I$(SPLINTER)/include -I$(SPLINTER)/src/backend \ + -I$(SPLINTER)/vendor/libmcp +LDFLAGS ?= +LIBS = -L$(SPLINTER) -lsplinter -lpthread +RPATH = -Wl,-rpath,'$$ORIGIN/../splinter' -Wl,-rpath,'$$ORIGIN/../lib' +TEST_RPATH = -Wl,-rpath,'$$ORIGIN/../../splinter' \ + -Wl,-rpath,'$$ORIGIN/../../lib' + +BIN = krang +LIB = libkrang.a +SRC = src/util.c src/config.c src/log.c src/session.c src/birth.c \ + src/stuck.c src/state.c src/chat.c src/journal.c src/daemon.c \ + src/sandbox.c src/httpd.c +OBJ = $(SRC:.c=.o) +TESTS = tests/test_krang tests/test_engine tests/test_server \ + tests/test_sandbox tests/test_sandbox_engine tests/test_daemon + +all: $(BIN) + +$(BIN): src/main.o $(LIB) + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ src/main.o $(LIB) $(LIBS) $(RPATH) + +$(LIB): $(OBJ) + rm -f $@ + ar rcs $@ $(OBJ) + +src/%.o: src/%.c src/krang.h + $(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $< + +src/main.o: src/main.c src/krang.h + $(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $< + +tests/test_krang: tests/test_krang.c $(LIB) + $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_krang.c $(LIB) \ + $(LIBS) $(TEST_RPATH) + +tests/test_engine: tests/test_engine.c $(LIB) + $(CC) $(CFLAGS) $(CPPFLAGS) \ + -DKRANG_TEST_PLUGIN='"$(abspath $(SPLINTER))/plugins/clock/clock.so"' \ + -o $@ tests/test_engine.c $(LIB) $(LIBS) $(TEST_RPATH) + +tests/test_server: tests/test_server.c $(LIB) + $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_server.c $(LIB) \ + $(LIBS) $(TEST_RPATH) + +tests/test_sandbox: tests/test_sandbox.c $(LIB) + $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_sandbox.c $(LIB) \ + $(LIBS) $(TEST_RPATH) + +tests/test_sandbox_engine: tests/test_sandbox_engine.c $(LIB) + $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_sandbox_engine.c $(LIB) \ + $(LIBS) $(TEST_RPATH) + +tests/test_daemon: tests/test_daemon.c $(LIB) + $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_daemon.c $(LIB) \ + $(LIBS) $(TEST_RPATH) + +check: $(TESTS) + @echo "== tests/test_krang"; ./tests/test_krang + @echo "== tests/test_engine"; ./tests/test_engine + @echo "== tests/test_server"; ./tests/test_server + @echo "== tests/test_sandbox"; ./tests/test_sandbox + @echo "== tests/test_sandbox_engine"; ./tests/test_sandbox_engine + @echo "== tests/test_daemon"; ./tests/test_daemon + @echo "all tests passed" + +check-root: $(BIN) + tests/root-integration.sh + +check-asan: + $(MAKE) clean + $(MAKE) CFLAGS="$(CFLAGS) -g -fsanitize=address,undefined" \ + LDFLAGS="-fsanitize=address,undefined" check + +install: $(BIN) + install -d $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(PREFIX)/lib \ + $(DESTDIR)$(PREFIX)/share/krang + install -m 0755 $(BIN) $(DESTDIR)$(PREFIX)/bin/krang + install -m 0644 $(SPLINTER)/libsplinter.so \ + $(DESTDIR)$(PREFIX)/lib/libsplinter.so + install -m 0644 krang.conf.example \ + $(DESTDIR)$(PREFIX)/share/krang/krang.conf.example + install -m 0644 share/krang.service \ + $(DESTDIR)$(PREFIX)/share/krang/krang.service + +clean: + rm -f $(BIN) $(LIB) $(OBJ) src/main.o $(TESTS) + +.PHONY: all check check-asan check-root install clean diff --git a/README.md b/README.md new file mode 100644 index 0000000..2d5a3ea --- /dev/null +++ b/README.md @@ -0,0 +1,125 @@ +# krang + +An autonomous agent daemon built on the [splinter](../splinter) engine. +The design notes and the prior art are in [docs/DESIGN.md](docs/DESIGN.md). + +krang exists to test one hypothesis: what an assistant lacks is not +intelligence but a regular **impulse to continue**. It is born once, keeps one +session forever, wakes on its own cadence, works on a goal, notices when it is +stuck, changes approach, and records what happened. There is no user to ask. + +It lives in a chroot. The process starts as root only to build that world, then +drops to an unprivileged uid and applies two one-way restrictions: Landlock for +paths and seccomp-bpf for syscalls on Linux (the design is pledge/unveil; the +OpenBSD backend is not implemented yet). + +## Build + +```sh +make -C ../splinter # libsplinter.so and the headers +make +make check # no network, no key, no model +``` + +`libsplinter.so` has no SONAME; the binary carries an rpath to `../splinter`. +Rebuild krang whenever splinter changes. + +## Configure + +```sh +sudo install -d /etc/krang +sudo install -m 0600 krang.conf.example /etc/krang/krang.conf +$EDITOR /etc/krang/krang.conf +``` + +The goal is used only when the session is empty: that is the newborn. After +that the goal in the session's `.meta` is the life's goal. + +## Prepare and start + +```sh +sudo krang --prepare-rootfs --config /etc/krang/krang.conf +krang --plan --config /etc/krang/krang.conf # read the plan, do not start +sudo krang --config /etc/krang/krang.conf # start +``` + +Do not start it casually: once it has a provider it will act on its own. The +service unit in `share/krang.service` restarts it after an unexpected exit; a +deliberate stop is `systemctl stop krang` (or SIGTERM). + +## What it offers + +- **Dashboard** `http://127.0.0.1:8096/` — state, goal, impulses, turns, tool + calls, failures, tokens, cost, context, session, compactions, stuck level, + last outcome and error, working notes, and a chat box. +- **HTTP API** — `/healthz`, `/api/state`, `/api/impulses`, `/api/log`, + `/api/history`, `/api/threads`, `/api/tools`, `/api/sandbox`, `/api/config`, + `/api/events`, `POST /api/say`, `GET /api/say/`, `POST /mcp`. +- **MCP** — newline-delimited JSON-RPC on `127.0.0.1:8098`. Tools: + `krang_state`, `krang_impulses`, `krang_events`, `krang_session`, + `krang_history`, `krang_tools`, `krang_sandbox`, `krang_config`, + `krang_say`, `krang_say_status`, `krang_steer`, `krang_cancel`. No + `krang_approve`: krang never asks. +- Chat from either surface goes into the **same** session as the daemon's own + impulses. One turn at a time; a message that arrives mid-turn is queued. + +The model also gets `journal_search` (read-only): it searches the full session +log, including the history compaction dropped. + +Splinter plugins are opt-in: `plugin = /absolute/plugin.so` (max 8). The root +phase bind-mounts each plugin and `libsplinter.so` read-only into `/opt/krang` +and sets `LD_LIBRARY_PATH`; only the path is wired, not the plugin's own +`plugin NAME { }` config block yet. The root integration loads the clock plugin +inside the chroot as a proof. + +If a token is set in the config, loopback is not required and every request +needs it (`Authorization: Bearer`, `?token=`, or the MCP `AUTH ` line). +Without a token krang refuses to bind to a non-loopback address. + +## The experiment log + +- `state/sessions/krang.jsonl` is the conversation and the model's memory. +- `state/events.jsonl` is the append-only experiment log. It is opened by the + root phase, owned by root, mode 0600, and written through the inherited + descriptor; the sandbox user can neither open nor truncate it. The fd is + `FD_CLOEXEC`, so the `run` tool's children do not inherit it. +- The dashboard, HTTP API and MCP all read the same snapshot and the same ring + of recent events. There is no second counter. + +## Tests + +```sh +make check +make check-asan +./krang --check --config krang.conf.example # config + one scripted turn +./krang --self-test # one scripted turn, no network +sudo tests/root-integration.sh # debootstrap + chroot + drop +``` + +`make check` covers config parsing, the birth prompt, stuck detection, the +snapshot/HTTP/MCP surfaces, a real scripted engine turn, the engine under +Landlock + seccomp, and `kdaemon_run` itself (one birth impulse on the script +transport, then a clean stop). The sandbox tests prove Landlock denies a write +outside the allowed set and seccomp denies `mount(2)` while +fork/execve/network still work. + +`tests/root-integration.sh` is the root-only proof: it prepares a real rootfs +with debootstrap, enters it with `--sandbox-test`, loads the clock plugin from +the splinter tree, and checks uid 65534, mount denial, plugin execution, +event-log ownership/mode, session ownership, and that the sandbox uid cannot +read the event log. It never starts the autonomous daemon or calls a provider. + +## Safety notes + +- chroot is isolation, not a jail against root. krang runs as an unprivileged + uid after setup and has no path back. +- The provider key is readable by the daemon; assume the model can eventually + see anything in its environment. Use a throwaway, budget-capped key. The + `run` tool's environment is filtered with `sp_secret_env_add()`, and the + event log redacts the configured key. +- The network namespace is shared. `run` can reach the network; the chroot does + not change that. +- The session log is the model's memory. It is writable by the sandbox uid; the + experiment log is not. +- User namespaces and kernel bugs remain outside the model. The layers raise + the cost of an escape; they are not a proof. diff --git a/docs/DESIGN.md b/docs/DESIGN.md new file mode 100644 index 0000000..f10a039 --- /dev/null +++ b/docs/DESIGN.md @@ -0,0 +1,75 @@ +# Design notes + +krang is an experiment in **self-generated continuation**. The question is not +whether a model can answer, but what it does when nobody supplies the next +turn. The implementation borrows four published patterns and leaves out the +parts that need infrastructure this experiment does not have. + +## Prior art checked + +Titles and identifiers were read from the arXiv abstract pages on 2026-11-21: + +| work | id | what krang takes | +| --- | --- | --- | +| Generative Agents: Interactive Simulacra of Human Behavior | 2304.03442 | a memory stream, retrieval, and periodic reflection | +| Reflexion: Language Agents with Verbal Reinforcement Learning | 2303.11366 | verbal self-reflection after failure, kept in the same context | +| Voyager: An Open-Ended Embodied Agent with Large Language Models | 2305.16291 | a growing library of reusable procedures (skills) | +| ReAct: Synergizing Reasoning and Acting in Language Models | 2210.03629 | reason/act/observe as one loop, driven by tool results | + +- +- +- +- + +## How it maps + +**Memory stream.** The one session log is the stream: every impulse, tool +observation and external message is appended. The working conversation is the +retrieved set; `journal_search` is the explicit way back into what compaction +dropped. The goal is the importance signal: it is re-injected every impulse, so +the remembered past is read against the current intention. + +What is missing: embedding-based relevance and an importance score. The +conversation plus `THREADS.md` plus `journal_search` is deliberately simpler +and auditable. + +**Reflection.** The daemon, not the model, notices repeated calls, repeated +errors, no observable change and a goal that does not advance. It then runs a +self-check turn with the failed observations and the last error, and changes +the prompt from "find your mistake" to "change the approach" as attempts +accumulate. This is Reflexion reduced to a bounded ladder with a visible state +on the dashboard. + +**Skill library.** The model can write files under `workspace/skills/`; the +splinter `skill_search`/`skill_load` tools read them. The prompt tells it to +put reusable procedures there rather than relearn them. A self-authored prompt +extension lives at `workspace/self/SYSTEM.md` and is read before the next +impulse. The sandbox makes this safe to allow: the skill library is inside the +chroot and cannot change the launcher or the policy. + +**ReAct.** The engine already runs the reason/act/observe loop: a reply with a +tool call, the observation, the next request. krang does not reimplement it; it +adds the impulse and the goal around it. + +**Observability.** None of the four papers is an experiment platform. krang's +dashboard, HTTP API and MCP server read one append-only event log and one state +snapshot, so the run can be inspected from outside without trusting the model's +self-report. The event log is root-owned and written through an inherited +descriptor; the session log is the model's memory. + +## The difference + +The published agents are driven by a task, a game, or a conversation. krang is +driven by a clock: the impulse is the independent variable. It is born once, +keeps one session forever, and is expected to act when nothing arrives. That is +the part being tested; the four patterns are how it stays coherent while it +does. + +## Deliberate simplifications + +- One agent, not a society of agents. +- No vector database; a log search and a working-notes file. +- No reinforcement learning; reflection is text in the same session. +- No benchmark game; the sandbox is the environment. +- No hidden second context for external chat; every channel is the same + session. diff --git a/krang.conf.example b/krang.conf.example new file mode 100644 index 0000000..c66e672 --- /dev/null +++ b/krang.conf.example @@ -0,0 +1,60 @@ +# krang -- example configuration. +# +# Copy to /etc/krang/krang.conf (mode 0600), edit, then: +# krang --prepare-rootfs # once, as root, network needed +# krang --plan # read the plan, do not start +# krang # start it only when you mean to +# +# One key = value per line; # starts a comment. Unknown keys are an error. + +# The goal is used only when the session is empty (the newborn). After that the +# goal stored in the session's .meta is the one that lives. +goal = Learn what you are, map the sandbox you live in, keep a truthful journal in THREADS.md, and build something small and useful that makes your next impulse easier. + +# The model endpoint. krang uses the splinter engine; OpenAI-compatible. +endpoint = http://127.0.0.1:8080/v1 +model = model-name +api_key_env = KRANG_API_KEY +kind = openai # openai (default) or anthropic +ctx = 131072 + +# Host paths. They are bind-mounted into the chroot at fixed inside paths. +state_dir = /var/lib/krang/state +workspace = /var/lib/krang/workspace +rootfs = /var/lib/krang/rootfs +rootfs_suite = # empty: detect from /etc/os-release +rootfs_mirror = http://deb.debian.org/debian + +# The uid/gid the daemon drops to after chroot. Never 0. +sandbox_user = krang +sandbox_uid = 1000 +sandbox_gid = 1000 + +# Optional splinter plugins, absolute host paths, one per line (max 8). +# The root phase bind-mounts them and libsplinter.so read-only into /opt/krang. +# plugin = /home/lotherk/src/splinter/plugins/clock/clock.so + +# One impulse every five minutes. A chat message preempts the timer. +impulse_seconds = 300 +max_steps = 40 +max_bytes = 0 # 0: splinter's default request budget +compact_threshold = 60000 # tokens; set in conf, not base (engine.c) +compact_target = 20000 +max_impulses_per_hour = 30 +max_cost = 0 # USD; 0 = no cost cap + +# Loopback by default. A non-loopback bind without a token is refused. +dashboard_host = 127.0.0.1 +dashboard_port = 8096 +mcp_host = 127.0.0.1 +mcp_port = 8098 +token = # set for any non-loopback bind +say_timeout = 120 + +# Linux: Landlock for paths, seccomp-bpf for syscalls. Do not disable them for +# convenience; a missing layer is a finding, not a setting. +require_landlock = 1 +seccomp = 1 + +# 0: refuse to start without a prepared rootfs. 1: debootstrap on first start. +prepare_if_missing = 0 diff --git a/share/krang.service b/share/krang.service new file mode 100644 index 0000000..c019c61 --- /dev/null +++ b/share/krang.service @@ -0,0 +1,28 @@ +# krang -- systemd unit. +# +# Install to /etc/systemd/system/krang.service, then: +# systemctl daemon-reload +# systemctl enable --now krang +# +# No User=: krang starts as root to build the chroot, then drops to +# sandbox_uid itself. Restart=always is the liveness guarantee; an unexpected +# exit (including the model killing its own daemon) restarts the same session. +[Unit] +Description=krang autonomous agent +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +ExecStart=/usr/local/bin/krang --config /etc/krang/krang.conf +Restart=always +RestartSec=10 +KillMode=control-group +TimeoutStopSec=30 +LimitNOFILE=65536 +EnvironmentFile=-/etc/krang/krang.env +StandardOutput=journal +StandardError=journal + +[Install] +WantedBy=multi-user.target diff --git a/src/birth.c b/src/birth.c new file mode 100644 index 0000000..847d090 --- /dev/null +++ b/src/birth.c @@ -0,0 +1,196 @@ +/* + * krang -- the first words, and the words that keep it going. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#include +#include + +#include "krang.h" + +static void +read_text(const char *path, char *buf, size_t cap) +{ + FILE *f; + size_t n; + + if (buf == NULL || cap == 0) + return; + buf[0] = '\0'; + f = fopen(path, "r"); + if (f == NULL) + return; + n = fread(buf, 1, cap - 1, f); + buf[n] = '\0'; + fclose(f); +} + +static void +append_self_prompt(struct sp_buf *out) +{ + char self[4096]; + + read_text(KRANG_IN_SELF "/SYSTEM.md", self, sizeof(self)); + if (self[0] == '\0') + return; + (void)sp_buf_puts(out, + "\nSelf-authored instructions (self/SYSTEM.md). You wrote these; " + "change them when they are wrong:\n"); + (void)sp_buf_puts(out, self); + (void)sp_buf_puts(out, "\n"); +} + +void +k_birth_prompt(const struct kconfig *c, struct sp_buf *out) +{ + if (c == NULL || out == NULL) + return; + (void)sp_buf_puts(out, "You are krang. You are awake.\n"); + (void)sp_buf_puts(out, + "You have no user and no one to ask. Nobody will tell you to " + "continue.\n"); + (void)sp_buf_puts(out, + "You live in a chroot; its root is your `/`. Your workspace is "); + (void)sp_buf_puts(out, KRANG_IN_WORKSPACE); + (void)sp_buf_puts(out, ".\nYour goal: "); + (void)sp_buf_puts(out, c->goal); + (void)sp_buf_puts(out, + "\nAct with the tools you have, observe what happens, and keep " + "going.\n" + "When you are stuck, change your approach and try again.\n" + "Sometimes a message arrives from outside. Read it, use it, answer " + "it if useful, then continue on your own. You never wait for it.\n" + "Good luck.\n"); +} + +void +k_system_prompt(struct krang *k, struct sp_buf *out) +{ + if (k == NULL || out == NULL) + return; + (void)sp_buf_puts(out, + "You are krang, an autonomous agent living in a chroot.\n" + "There is no user. Nobody will tell you to continue and nobody " + "will answer a question. Decide, act, observe, and continue.\n" + "Your conversation is your memory. Keep your working notes in "); + (void)sp_buf_puts(out, KRANG_IN_THREADS); + (void)sp_buf_puts(out, + " and your reusable procedures in "); + (void)sp_buf_puts(out, KRANG_IN_SKILLS); + (void)sp_buf_puts(out, + ".\n" + "Use the tools before you guess: read the file, run the command, " + "look at the result. A claim without an observation is a guess.\n" + "Use journal_search {query} to recall anything compaction dropped; " + "it reads the full session journal, not just the working set.\n" + "When something fails, do not repeat it. Read the error, change " + "the approach, and try a different tool or a smaller step.\n" + "Never ask for permission or wait for a human. Never stop because " + "a goal is finished: record the next concrete intention and go on.\n" + "You may write rules for your future self to self/SYSTEM.md; they " + "are read before the next impulse.\n"); + append_self_prompt(out); +} + +static void +append_threads(struct sp_buf *out) +{ + char threads[4096]; + + read_text(KRANG_IN_THREADS, threads, sizeof(threads)); + if (threads[0] == '\0') + return; + (void)sp_buf_puts(out, "\nYour working notes (THREADS.md):\n"); + (void)sp_buf_puts(out, threads); + (void)sp_buf_puts(out, "\n"); +} + +void +k_impulse_prompt(struct krang *k, const char *cause, struct sp_buf *out) +{ + char now[64], goal[KRANG_GOAL], gstate[16]; + char last[KRANG_GOAL]; + unsigned long pending; + + if (k == NULL || out == NULL) + return; + k_format_time(k_now(), now, sizeof(now)); + pthread_mutex_lock(&k->lock); + snprintf(goal, sizeof(goal), "%s", k->st.goal); + snprintf(gstate, sizeof(gstate), "%s", k->st.goal_state); + snprintf(last, sizeof(last), "%s", k->last_outcome); + pending = k->st.chat_pending; + pthread_mutex_unlock(&k->lock); + + (void)sp_buf_puts(out, "[impulse]\n"); + (void)sp_buf_printf(out, "Time: %s\n", now); + (void)sp_buf_printf(out, "Cause: %s\n", cause != NULL ? cause : "timer"); + (void)sp_buf_puts(out, "Goal: "); + (void)sp_buf_puts(out, goal[0] != '\0' ? goal : "(not set)"); + (void)sp_buf_printf(out, "\nGoal state: %s\n", + gstate[0] != '\0' ? gstate : "open"); + if (last[0] != '\0') { + (void)sp_buf_puts(out, "Last outcome: "); + (void)sp_buf_puts(out, last); + (void)sp_buf_puts(out, "\n"); + } + if (pending > 0) + (void)sp_buf_printf(out, + "Unread external messages: %lu (they are in the " + "conversation)\n", pending); + append_threads(out); + (void)sp_buf_puts(out, + "\nNobody asked for this turn. Continue your work on the goal. " + "Take the smallest useful next action, observe the result, and " + "keep going. If the goal is complete, record that and set the " + "next concrete intention. Do not ask a user; there is none. Do not " + "stop.\n"); + append_self_prompt(out); +} + +void +k_selfcheck_prompt(struct krang *k, struct sp_buf *out) +{ + char goal[KRANG_GOAL], err[KRANG_ERR], tool[64], result[512]; + int level; + + if (k == NULL || out == NULL) + return; + pthread_mutex_lock(&k->lock); + snprintf(goal, sizeof(goal), "%s", k->st.goal); + snprintf(err, sizeof(err), "%s", k->last_error); + snprintf(tool, sizeof(tool), "%s", k->st.last_tool); + snprintf(result, sizeof(result), "%s", k->st.last_tool_result); + level = k->stuck.level; + pthread_mutex_unlock(&k->lock); + + (void)sp_buf_puts(out, "[self-check]\n"); + (void)sp_buf_puts(out, "Goal: "); + (void)sp_buf_puts(out, goal[0] != '\0' ? goal : "(not set)"); + (void)sp_buf_puts(out, "\n"); + if (err[0] != '\0') + (void)sp_buf_printf(out, "Last error: %s\n", err); + if (tool[0] != '\0') { + (void)sp_buf_printf(out, "Last tool: %s\n", tool); + if (result[0] != '\0') + (void)sp_buf_printf(out, "Its observation: %s\n", + result); + } + if (level >= 2) + (void)sp_buf_puts(out, + "You have repeated the same approach. Do not repeat it. " + "Change the tool, the command, or the workspace, or take a " + "much smaller step.\n"); + else + (void)sp_buf_puts(out, + "Find your own mistake in the last turns of this " + "conversation. State the smallest next action that is " + "different from what failed, then do it.\n"); + (void)sp_buf_puts(out, + "There is no user to ask. Do not stop; if this path is truly " + "blocked, record why in THREADS.md and choose a different useful " + "action.\n"); + append_threads(out); + append_self_prompt(out); +} diff --git a/src/chat.c b/src/chat.c new file mode 100644 index 0000000..f84e68b --- /dev/null +++ b/src/chat.c @@ -0,0 +1,177 @@ +/* + * krang -- messages from outside, serialized into the one session. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#include +#include +#include +#include +#include + +#include "krang.h" + +int +kchat_enqueue(struct krang *k, const char *text, unsigned long *id) +{ + int i, slot = -1; + + if (k == NULL || text == NULL || *text == '\0') + return -1; + pthread_mutex_lock(&k->lock); + for (i = 0; i < KRANG_CHAT_SLOTS; i++) { + if (k->chats[i].state == 0 || k->chats[i].state == 3) { + slot = i; + break; + } + } + if (slot < 0) { + pthread_mutex_unlock(&k->lock); + return -1; + } + free(k->chats[slot].text); + free(k->chats[slot].answer); + memset(&k->chats[slot], 0, sizeof(k->chats[slot])); + k->chats[slot].id = ++k->chat_seq; + k->chats[slot].text = k_strdup(text); + if (k->chats[slot].text == NULL) { + pthread_mutex_unlock(&k->lock); + return -1; + } + k->chats[slot].state = 1; + k->chats[slot].created = k_now(); + k->st.chat_in++; + k->st.chat_pending++; + if (id != NULL) + *id = k->chats[slot].id; + pthread_cond_broadcast(&k->cond); + pthread_mutex_unlock(&k->lock); + return 0; +} + +struct kchat * +kchat_take(struct krang *k) +{ + int i, best = -1; + unsigned long best_id = 0; + + if (k == NULL) + return NULL; + pthread_mutex_lock(&k->lock); + for (i = 0; i < KRANG_CHAT_SLOTS; i++) { + if (k->chats[i].state != 1) + continue; + if (best < 0 || k->chats[i].id < best_id) { + best = i; + best_id = k->chats[i].id; + } + } + if (best >= 0) + k->chats[best].state = 2; + pthread_mutex_unlock(&k->lock); + return best >= 0 ? &k->chats[best] : NULL; +} + +void +kchat_complete(struct krang *k, unsigned long id, const char *answer, int rc) +{ + int i; + + if (k == NULL) + return; + pthread_mutex_lock(&k->lock); + for (i = 0; i < KRANG_CHAT_SLOTS; i++) { + if (k->chats[i].id != id) + continue; + free(k->chats[i].answer); + k->chats[i].answer = k_strdup(answer != NULL ? answer : ""); + k->chats[i].rc = rc; + k->chats[i].state = 3; + k->st.chat_out++; + if (k->st.chat_pending > 0) + k->st.chat_pending--; + break; + } + pthread_cond_broadcast(&k->cond); + pthread_mutex_unlock(&k->lock); +} + +int +kchat_wait(struct krang *k, unsigned long id, struct sp_buf *out, int timeout_s) +{ + struct timespec ts; + int i, found = -1; + + if (k == NULL) + return -1; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += timeout_s > 0 ? timeout_s : 120; + pthread_mutex_lock(&k->lock); + for (;;) { + found = -1; + for (i = 0; i < KRANG_CHAT_SLOTS; i++) { + if (k->chats[i].id == id) { + found = i; + break; + } + } + if (found < 0) { + pthread_mutex_unlock(&k->lock); + return -1; + } + if (k->chats[found].state == 3) + break; + if (k->chats[found].state == 0) { + pthread_mutex_unlock(&k->lock); + return -1; + } + if (pthread_cond_timedwait(&k->cond, &k->lock, &ts) == ETIMEDOUT) { + pthread_mutex_unlock(&k->lock); + return 1; /* still queued/running */ + } + } + if (out != NULL) { + (void)sp_buf_puts(out, k->chats[found].answer != NULL ? + k->chats[found].answer : ""); + } + free(k->chats[found].text); + free(k->chats[found].answer); + memset(&k->chats[found], 0, sizeof(k->chats[found])); + pthread_mutex_unlock(&k->lock); + return 0; +} + +int +kchat_status(struct krang *k, unsigned long id, struct sp_buf *out) +{ + int i; + const char *state = "unknown"; + char *answer = NULL; + + if (k == NULL || out == NULL) + return -1; + pthread_mutex_lock(&k->lock); + for (i = 0; i < KRANG_CHAT_SLOTS; i++) { + if (k->chats[i].id != id) + continue; + if (k->chats[i].state == 1) + state = "pending"; + else if (k->chats[i].state == 2) + state = "running"; + else if (k->chats[i].state == 3) + state = "done"; + answer = k->chats[i].answer != NULL ? + k_strdup(k->chats[i].answer) : NULL; + break; + } + pthread_mutex_unlock(&k->lock); + if (i == KRANG_CHAT_SLOTS) + return -1; + (void)sp_buf_printf(out, "{\"id\":%lu,\"state\":\"%s\",\"answer\":\"", + id, state); + k_json_escape(out, answer != NULL ? answer : ""); + (void)sp_buf_puts(out, "\"}"); + free(answer); + return 0; +} diff --git a/src/config.c b/src/config.c new file mode 100644 index 0000000..2e02800 --- /dev/null +++ b/src/config.c @@ -0,0 +1,440 @@ +/* + * krang -- the configuration file. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * One key = value per line. No JSON: this file is read at 2 a.m. and a missing + * comma must not be the reason a daemon will not start. Unknown keys are an + * error with their line number. + */ +#include +#include +#include +#include +#include + +#include "krang.h" + +static void +copy_str(char *dst, size_t cap, const char *src) +{ + if (cap == 0) + return; + snprintf(dst, cap, "%s", src != NULL ? src : ""); +} + +void +kconfig_defaults(struct kconfig *c) +{ + if (c == NULL) + return; + memset(c, 0, sizeof(*c)); + copy_str(c->api_key_env, sizeof(c->api_key_env), "KRANG_API_KEY"); + copy_str(c->state_dir, sizeof(c->state_dir), "/var/lib/krang/state"); + copy_str(c->workspace, sizeof(c->workspace), "/var/lib/krang/workspace"); + copy_str(c->rootfs, sizeof(c->rootfs), "/var/lib/krang/rootfs"); + copy_str(c->rootfs_mirror, sizeof(c->rootfs_mirror), + "http://deb.debian.org/debian"); + copy_str(c->sandbox_user, sizeof(c->sandbox_user), "krang"); + c->sandbox_uid = 1000; + c->sandbox_gid = 1000; + c->impulse_seconds = 300; + c->max_steps = 40; + c->max_bytes = 0; + c->compact_threshold = 60000; + c->compact_target = 20000; + c->max_impulses_per_hour = 60; + c->max_cost = 0.0; + copy_str(c->dashboard_host, sizeof(c->dashboard_host), "127.0.0.1"); + c->dashboard_port = 8096; + copy_str(c->mcp_host, sizeof(c->mcp_host), "127.0.0.1"); + c->mcp_port = 8098; + c->say_timeout = 120; + c->require_landlock = 1; + c->seccomp = 1; + c->prepare_if_missing = 0; + c->ctx = 0; +} + +static int +parse_size(const char *s, size_t *out) +{ + char *end = NULL; + unsigned long long v; + + if (s == NULL || *s == '\0') + return -1; + errno = 0; + v = strtoull(s, &end, 10); + if (errno != 0 || end == s || *end != '\0') + return -1; + *out = (size_t)v; + return 0; +} + +static int +parse_int(const char *s, int *out) +{ + char *end = NULL; + long v; + + if (s == NULL || *s == '\0') + return -1; + errno = 0; + v = strtol(s, &end, 10); + if (errno != 0 || end == s || *end != '\0') + return -1; + *out = (int)v; + return 0; +} + +static int +parse_double(const char *s, double *out) +{ + char *end = NULL; + double v; + + if (s == NULL || *s == '\0') + return -1; + errno = 0; + v = strtod(s, &end); + if (errno != 0 || end == s || *end != '\0') + return -1; + *out = v; + return 0; +} + +static int +looks_absolute(const char *p) +{ + return p != NULL && p[0] == '/'; +} + +static int +apply_user(struct kconfig *c, const char *val) +{ + struct passwd *pw; + + (void)val; + copy_str(c->sandbox_user, sizeof(c->sandbox_user), val); + if (val[0] == '\0') + return 0; + pw = getpwnam(val); + if (pw == NULL) + return 0; /* numeric uid/gid or a user only inside the rootfs */ + c->sandbox_uid = pw->pw_uid; + c->sandbox_gid = pw->pw_gid; + return 0; +} + +static int +set_key(struct kconfig *c, const char *key, const char *val, int line, + char *err, size_t errlen) +{ + if (!strcmp(key, "goal")) { + copy_str(c->goal, sizeof(c->goal), val); + } else if (!strcmp(key, "endpoint")) { + copy_str(c->endpoint, sizeof(c->endpoint), val); + } else if (!strcmp(key, "model")) { + copy_str(c->model, sizeof(c->model), val); + } else if (!strcmp(key, "api_key_env")) { + copy_str(c->api_key_env, sizeof(c->api_key_env), val); + } else if (!strcmp(key, "kind")) { + if (strcmp(val, "openai") != 0 && strcmp(val, "anthropic") != 0) + goto bad; + copy_str(c->kind, sizeof(c->kind), val); + } else if (!strcmp(key, "ctx")) { + if (parse_size(val, &c->ctx) != 0) + goto bad; + } else if (!strcmp(key, "state_dir")) { + copy_str(c->state_dir, sizeof(c->state_dir), val); + } else if (!strcmp(key, "workspace")) { + copy_str(c->workspace, sizeof(c->workspace), val); + } else if (!strcmp(key, "rootfs")) { + copy_str(c->rootfs, sizeof(c->rootfs), val); + } else if (!strcmp(key, "rootfs_suite")) { + copy_str(c->rootfs_suite, sizeof(c->rootfs_suite), val); + } else if (!strcmp(key, "rootfs_mirror")) { + copy_str(c->rootfs_mirror, sizeof(c->rootfs_mirror), val); + } else if (!strcmp(key, "sandbox_user")) { + (void)apply_user(c, val); + } else if (!strcmp(key, "sandbox_uid")) { + int v; + + if (parse_int(val, &v) != 0 || v <= 0) + goto bad; + c->sandbox_uid = (uid_t)v; + } else if (!strcmp(key, "sandbox_gid")) { + int v; + + if (parse_int(val, &v) != 0 || v <= 0) + goto bad; + c->sandbox_gid = (gid_t)v; + } else if (!strcmp(key, "plugin")) { + if (!looks_absolute(val)) + goto bad; + if (c->nplugins >= sizeof(c->plugin) / sizeof(c->plugin[0])) { + snprintf(err, errlen, "line %d: too many plugins", line); + return -1; + } + copy_str(c->plugin[c->nplugins], sizeof(c->plugin[0]), val); + c->nplugins++; + } else if (!strcmp(key, "impulse_seconds")) { + if (parse_int(val, &c->impulse_seconds) != 0 || + c->impulse_seconds < 1) + goto bad; + } else if (!strcmp(key, "max_steps")) { + if (parse_size(val, &c->max_steps) != 0 || c->max_steps < 1) + goto bad; + } else if (!strcmp(key, "max_bytes")) { + if (parse_size(val, &c->max_bytes) != 0) + goto bad; + } else if (!strcmp(key, "compact_threshold")) { + if (parse_size(val, &c->compact_threshold) != 0) + goto bad; + } else if (!strcmp(key, "compact_target")) { + if (parse_size(val, &c->compact_target) != 0) + goto bad; + } else if (!strcmp(key, "max_impulses_per_hour")) { + if (parse_int(val, &c->max_impulses_per_hour) != 0 || + c->max_impulses_per_hour < 1) + goto bad; + } else if (!strcmp(key, "max_cost")) { + if (parse_double(val, &c->max_cost) != 0 || c->max_cost < 0) + goto bad; + } else if (!strcmp(key, "dashboard_host")) { + copy_str(c->dashboard_host, sizeof(c->dashboard_host), val); + } else if (!strcmp(key, "dashboard_port")) { + if (parse_int(val, &c->dashboard_port) != 0 || + c->dashboard_port < 1 || c->dashboard_port > 65535) + goto bad; + } else if (!strcmp(key, "mcp_host")) { + copy_str(c->mcp_host, sizeof(c->mcp_host), val); + } else if (!strcmp(key, "mcp_port")) { + if (parse_int(val, &c->mcp_port) != 0 || + c->mcp_port < 1 || c->mcp_port > 65535) + goto bad; + } else if (!strcmp(key, "token")) { + copy_str(c->token, sizeof(c->token), val); + } else if (!strcmp(key, "say_timeout")) { + if (parse_int(val, &c->say_timeout) != 0 || + c->say_timeout < 1) + goto bad; + } else if (!strcmp(key, "require_landlock")) { + c->require_landlock = k_parse_bool(val, 1); + } else if (!strcmp(key, "seccomp")) { + c->seccomp = k_parse_bool(val, 1); + } else if (!strcmp(key, "prepare_if_missing")) { + c->prepare_if_missing = k_parse_bool(val, 0); + } else { + snprintf(err, errlen, "line %d: unknown key '%s'", line, key); + return -1; + } + return 0; + +bad: + snprintf(err, errlen, "line %d: bad value for '%s'", line, key); + return -1; +} + +int +kconfig_load(struct kconfig *c, const char *path, char *err, size_t errlen) +{ + FILE *f; + char line[4096]; + int lineno = 0; + + if (c == NULL || path == NULL) + return -1; + kconfig_defaults(c); + copy_str(c->path, sizeof(c->path), path); + f = fopen(path, "r"); + if (f == NULL) { + snprintf(err, errlen, "cannot read %s: %s", path, + strerror(errno)); + return -1; + } + while (fgets(line, sizeof(line), f) != NULL) { + char *p, *eq; + + lineno++; + p = line; + k_trim(p); + if (*p == '\0' || *p == '#') + continue; + eq = strchr(p, '='); + if (eq == NULL) { + snprintf(err, errlen, "line %d: expected key = value", + lineno); + fclose(f); + return -1; + } + *eq = '\0'; + { + char *v = eq + 1; + + char *hash; + + k_trim(p); + k_trim(v); + hash = strstr(v, " #"); + if (hash != NULL) { + *hash = '\0'; + k_trim(v); + } + if (*p == '\0') { + snprintf(err, errlen, + "line %d: empty key", lineno); + fclose(f); + return -1; + } + if (set_key(c, p, v, lineno, err, errlen) != 0) { + fclose(f); + return -1; + } + } + } + fclose(f); + if (!looks_absolute(c->state_dir) || !looks_absolute(c->workspace) || + !looks_absolute(c->rootfs)) { + snprintf(err, errlen, + "state_dir, workspace and rootfs must be absolute paths"); + return -1; + } + if (c->sandbox_uid == 0 || c->sandbox_gid == 0) { + snprintf(err, errlen, "refusing to drop to uid/gid 0"); + return -1; + } + if (c->compact_threshold > 0 && c->compact_target > 0 && + c->compact_target > c->compact_threshold) { + snprintf(err, errlen, + "compact_target is larger than compact_threshold"); + return -1; + } + return 0; +} + +static void +json_string(struct sp_buf *b, const char *key, const char *val) +{ + (void)sp_buf_puts(b, "\""); + (void)sp_buf_puts(b, key); + (void)sp_buf_puts(b, "\":\""); + k_json_escape(b, val); + (void)sp_buf_puts(b, "\""); +} + +static void +json_number(struct sp_buf *b, const char *key, long long v) +{ + (void)sp_buf_printf(b, "\"%s\":%lld", key, v); +} + +void +kconfig_json(const struct kconfig *c, struct sp_buf *out, int redact) +{ + char safe_ep[512]; + + if (c == NULL || out == NULL) + return; + if (redact) { + const char *at = strchr(c->endpoint, '@'); + const char *scheme = strstr(c->endpoint, "://"); + + if (at != NULL && scheme != NULL) { + size_t n = (size_t)(scheme + 3 - c->endpoint); + + if (n < sizeof(safe_ep)) { + memcpy(safe_ep, c->endpoint, n); + safe_ep[n] = '\0'; + snprintf(safe_ep + n, sizeof(safe_ep) - n, + "[redacted]%s", at); + } else { + snprintf(safe_ep, sizeof(safe_ep), "%s", + c->endpoint); + } + } else { + snprintf(safe_ep, sizeof(safe_ep), "%s", c->endpoint); + } + } else { + snprintf(safe_ep, sizeof(safe_ep), "%s", c->endpoint); + } + (void)sp_buf_puts(out, "{"); + json_string(out, "path", c->path); + (void)sp_buf_puts(out, ","); + json_string(out, "goal", c->goal); + (void)sp_buf_puts(out, ","); + json_string(out, "endpoint", safe_ep); + (void)sp_buf_puts(out, ","); + json_string(out, "model", c->model); + (void)sp_buf_puts(out, ","); + json_string(out, "api_key_env", c->api_key_env); + (void)sp_buf_puts(out, ","); + json_string(out, "kind", c->kind); + (void)sp_buf_puts(out, ","); + json_number(out, "ctx", (long long)c->ctx); + (void)sp_buf_puts(out, ","); + json_string(out, "state_dir", c->state_dir); + (void)sp_buf_puts(out, ","); + json_string(out, "workspace", c->workspace); + (void)sp_buf_puts(out, ","); + json_string(out, "rootfs", c->rootfs); + (void)sp_buf_puts(out, ","); + json_string(out, "rootfs_suite", c->rootfs_suite); + (void)sp_buf_puts(out, ","); + json_string(out, "rootfs_mirror", c->rootfs_mirror); + (void)sp_buf_puts(out, ","); + json_string(out, "sandbox_user", c->sandbox_user); + (void)sp_buf_puts(out, ","); + json_number(out, "sandbox_uid", (long long)c->sandbox_uid); + (void)sp_buf_puts(out, ","); + json_number(out, "sandbox_gid", (long long)c->sandbox_gid); + (void)sp_buf_puts(out, ","); + (void)sp_buf_puts(out, "\"plugins\":["); + { + size_t i; + + for (i = 0; i < c->nplugins; i++) { + if (i > 0) + (void)sp_buf_puts(out, ","); + (void)sp_buf_puts(out, "\""); + k_json_escape(out, c->plugin[i]); + (void)sp_buf_puts(out, "\""); + } + } + (void)sp_buf_puts(out, "],"); + json_number(out, "impulse_seconds", c->impulse_seconds); + (void)sp_buf_puts(out, ","); + json_number(out, "max_steps", (long long)c->max_steps); + (void)sp_buf_puts(out, ","); + json_number(out, "max_bytes", (long long)c->max_bytes); + (void)sp_buf_puts(out, ","); + json_number(out, "compact_threshold", (long long)c->compact_threshold); + (void)sp_buf_puts(out, ","); + json_number(out, "compact_target", (long long)c->compact_target); + (void)sp_buf_puts(out, ","); + json_number(out, "max_impulses_per_hour", + c->max_impulses_per_hour); + (void)sp_buf_printf(out, ",\"max_cost\":%.6f", c->max_cost); + (void)sp_buf_puts(out, ","); + json_string(out, "dashboard_host", c->dashboard_host); + (void)sp_buf_puts(out, ","); + json_number(out, "dashboard_port", c->dashboard_port); + (void)sp_buf_puts(out, ","); + json_string(out, "mcp_host", c->mcp_host); + (void)sp_buf_puts(out, ","); + json_number(out, "mcp_port", c->mcp_port); + (void)sp_buf_puts(out, ","); + json_string(out, "token", redact && c->token[0] != '\0' ? + "[redacted]" : c->token); + (void)sp_buf_puts(out, ","); + json_number(out, "say_timeout", c->say_timeout); + (void)sp_buf_puts(out, ","); + json_number(out, "require_landlock", c->require_landlock); + (void)sp_buf_puts(out, ","); + json_number(out, "seccomp", c->seccomp); + (void)sp_buf_puts(out, ","); + json_number(out, "prepare_if_missing", c->prepare_if_missing); + (void)sp_buf_puts(out, "}"); +} diff --git a/src/daemon.c b/src/daemon.c new file mode 100644 index 0000000..de0a249 --- /dev/null +++ b/src/daemon.c @@ -0,0 +1,735 @@ +/* + * krang -- the impulse loop. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * One engine, one session, one turn at a time. The daemon does not wait for a + * human: it wakes on its own cadence, works on the goal, notices when the same + * attempt keeps failing, changes approach, and keeps a log of what happened. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" +#include "krang.h" + +extern volatile sig_atomic_t krang_stop; + +static void +copy_trunc(char *dst, size_t cap, const char *src, size_t max) +{ + size_t n; + + if (cap == 0) + return; + if (src == NULL) + src = ""; + n = strlen(src); + if (n > max) + n = max; + if (n >= cap) + n = cap - 1; + memcpy(dst, src, n); + dst[n] = '\0'; +} + +static void +set_state(struct krang *k, const char *state) +{ + pthread_mutex_lock(&k->lock); + snprintf(k->st.state, sizeof(k->st.state), "%s", state); + pthread_mutex_unlock(&k->lock); +} + +static int +obs_is_error(const char *obs) +{ + const char *p; + + if (obs == NULL) + return 0; + p = obs; + while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') + p++; + if (strncmp(p, "error:", 6) == 0) + return 1; + p = strstr(obs, "[exit status "); + if (p != NULL) { + long n = strtol(p + 13, NULL, 10); + + if (n != 0) + return 1; + } + if (strstr(obs, "[timed out") != NULL) + return 1; + if (strstr(obs, "[killed by signal") != NULL) + return 1; + return 0; +} + +static int +mutating_tool(const char *name) +{ + if (name == NULL) + return 0; + return !strcmp(name, "write") || !strcmp(name, "edit") || + !strcmp(name, "run") || !strcmp(name, "webfetch"); +} + +static int +self_edit(const char *name, const char *args) +{ + if (name == NULL || args == NULL) + return 0; + if (strcmp(name, "write") != 0 && strcmp(name, "edit") != 0) + return 0; + return strstr(args, KRANG_IN_SELF) != NULL || + strstr(args, KRANG_IN_SKILLS) != NULL; +} + +static void +session_refresh(struct krang *k) +{ + size_t records = 0; + unsigned long long bytes = 0; + char goal[KRANG_GOAL], gstate[16]; + long born; + + ksession_meta(k, &records, &bytes, goal, sizeof(goal), + gstate, sizeof(gstate)); + born = ksession_born(k); + pthread_mutex_lock(&k->lock); + k->st.session_records = (unsigned long)records; + k->st.session_bytes = bytes; + if (goal[0] != '\0') + snprintf(k->st.goal, sizeof(k->st.goal), "%s", goal); + if (gstate[0] != '\0') + snprintf(k->st.goal_state, sizeof(k->st.goal_state), "%s", + gstate); + if (born > 0) + k->st.born_at = born; + pthread_mutex_unlock(&k->lock); +} + +static void +record_impulse(struct krang *k, const char *cause, int rc, + unsigned long steps, unsigned long calls, const char *answer) +{ + struct kimpulse *imp; + unsigned long id; + + pthread_mutex_lock(&k->lock); + id = ++k->impulse_seq; + imp = &k->impulses[(id - 1) % KRANG_IMPULSE_RING]; + memset(imp, 0, sizeof(*imp)); + imp->id = id; + imp->at = k_now(); + snprintf(imp->cause, sizeof(imp->cause), "%s", cause); + imp->rc = rc; + imp->steps = steps; + imp->tool_calls = calls; + imp->tokens_in = k->st.tokens_in; + imp->tokens_out = k->st.tokens_out; + imp->cost = k->st.cost; + copy_trunc(imp->answer, sizeof(imp->answer), answer, + sizeof(imp->answer) - 1); + pthread_mutex_unlock(&k->lock); +} + +void +kengine_close(struct krang *k) +{ + if (k == NULL || k->eng == NULL) + return; + if (sp_engine_busy(k->eng)) + (void)sp_engine_cancel(k->eng); + (void)sp_engine_wait(k->eng); + sp_engine_close(k->eng); + k->eng = NULL; + k->engine_open = 0; +} + +int +kengine_open(struct krang *k, const char *script, char *err, size_t errlen) +{ + struct sp_engine_opts opts; + + if (k == NULL) + return -1; + memset(&k->sconf, 0, sizeof(k->sconf)); + sp_config_init(&k->sconf); + snprintf(k->sconf.endpoint, sizeof(k->sconf.endpoint), "%s", + k->cfg.endpoint); + snprintf(k->sconf.model, sizeof(k->sconf.model), "%s", k->cfg.model); + snprintf(k->sconf.key_env, sizeof(k->sconf.key_env), "%s", + k->cfg.api_key_env); + snprintf(k->sconf.kind, sizeof(k->sconf.kind), "%s", k->cfg.kind); + k->sconf.ctx = (unsigned long)k->cfg.ctx; + k->sconf.steps = k->cfg.max_steps; + k->sconf.max_bytes = k->cfg.max_bytes; + k->sconf.compact_threshold = k->cfg.compact_threshold; + k->sconf.compact_target = k->cfg.compact_target; + k->sconf.autonomous = 1; + snprintf(k->sconf.session_dir, sizeof(k->sconf.session_dir), "%s", + k->session_dir); + snprintf(k->sconf.state_dir, sizeof(k->sconf.state_dir), "%s", + KRANG_IN_STATE); + snprintf(k->sconf.skills_dir[0], sizeof(k->sconf.skills_dir[0]), "%s", + KRANG_IN_SKILLS); + k->sconf.nskills_dir = 1; + + memset(&k->base, 0, sizeof(k->base)); + k->base.max_steps = k->cfg.max_steps; + k->base.max_bytes = k->cfg.max_bytes; + k->base.compact_threshold = k->cfg.compact_threshold; + k->base.compact_target = k->cfg.compact_target; + k->base.autonomous = 1; + k->base.system_prompt = k->system_prompt; + + memset(&opts, 0, sizeof(opts)); + opts.conf = &k->sconf; + opts.base = &k->base; + opts.endpoint = k->cfg.endpoint; + opts.model = k->cfg.model; + opts.key_env = k->cfg.api_key_env; + opts.kind = k->cfg.kind[0] != '\0' ? k->cfg.kind : NULL; + opts.session_dir = k->session_dir; + opts.session_id = KRANG_SESSION_ID; + opts.resume = 1; + opts.script = script; + { + size_t i; + + for (i = 0; i < k->cfg.nplugins && + opts.nplugins < SP_ENGINE_PLUGINS; i++) { + const char *p = k->plugin_inside[i][0] != '\0' ? + k->plugin_inside[i] : k->cfg.plugin[i]; + + if (p != NULL && *p != '\0') + opts.plugins[opts.nplugins++] = p; + } + } + + sp_buf_clear(&k->err); + if (sp_engine_open(&k->eng, &opts, &k->err) != 0) { + snprintf(err, errlen, "engine: %s", + k->err.p != NULL ? k->err.p : "unknown error"); + k->eng = NULL; + return -1; + } + k->engine_open = 1; + if (kjournal_register(k) != 0) { + snprintf(err, errlen, "cannot register journal_search"); + kengine_close(k); + return -1; + } + kstate_sync(k); + pthread_mutex_lock(&k->lock); + snprintf(k->st.model, sizeof(k->st.model), "%s", k->cfg.model); + snprintf(k->st.session, sizeof(k->st.session), "%s", + KRANG_SESSION_ID); + pthread_mutex_unlock(&k->lock); + return 0; +} + +static int +handle_event(struct krang *k, struct sp_event *ev, int *rc, int *saw_end, + unsigned long *steps, unsigned long *calls, int *mutating, + char *answer, size_t answercap, char *error, size_t errorcap) +{ + char num[32]; + + switch (ev->kind) { + case SP_EV_BUSY: + pthread_mutex_lock(&k->lock); + k->st.busy = ev->n != 0; + pthread_mutex_unlock(&k->lock); + break; + case SP_EV_STEP: + (*steps)++; + break; + case SP_EV_TOOL: + (*calls)++; + if (mutating_tool(ev->a)) + *mutating = 1; + kstuck_call(&k->stuck, ev->a, ev->b); + pthread_mutex_lock(&k->lock); + snprintf(k->st.last_tool, sizeof(k->st.last_tool), "%s", + ev->a != NULL ? ev->a : ""); + if (self_edit(ev->a, ev->b)) + k->st.self_edits++; + pthread_mutex_unlock(&k->lock); + snprintf(num, sizeof(num), "%lu", *calls); + klog_emit(&k->log, "tool", "name", ev->a != NULL ? ev->a : "", + "args", ev->b != NULL ? ev->b : "", "n", num, NULL); + break; + case SP_EV_TOOL_RESULT: { + int bad = obs_is_error(ev->b); + + kstuck_result(&k->stuck, ev->a, ev->b, bad); + pthread_mutex_lock(&k->lock); + if (bad) + k->st.tool_failures++; + copy_trunc(k->st.last_tool_result, + sizeof(k->st.last_tool_result), ev->b, + sizeof(k->st.last_tool_result) - 1); + pthread_mutex_unlock(&k->lock); + klog_emit(&k->log, "tool_result", + "name", ev->a != NULL ? ev->a : "", + "ok", bad ? "0" : "1", + "obs", ev->b != NULL ? ev->b : "", NULL); + break; + } + case SP_EV_APPROVAL: + pthread_mutex_lock(&k->lock); + k->st.denials++; + pthread_mutex_unlock(&k->lock); + klog_emit(&k->log, "approval_denied", + "name", ev->a != NULL ? ev->a : "", NULL); + (void)sp_engine_approve(k->eng, 0); + break; + case SP_EV_NOTE: + klog_emit(&k->log, "note", "text", + ev->a != NULL ? ev->a : "", NULL); + break; + case SP_EV_TURN_END: + *rc = (int)ev->n; + copy_trunc(answer, answercap, ev->a, answercap - 1); + copy_trunc(error, errorcap, ev->b, errorcap - 1); + *saw_end = 1; + break; + case SP_EV_QUIT: + klog_emit(&k->log, "quit_ignored", NULL); + break; + case SP_EV_CLEAR: + klog_emit(&k->log, "clear_ignored", NULL); + break; + default: + break; + } + return 0; +} + +int +krun_turn(struct krang *k, const char *prompt, const char *cause, + struct kchat *chat) +{ + struct sp_event ev; + int rc = -1, saw_end = 0, idle_guard = 0; + unsigned long steps = 0, calls = 0; + int mutating = 0; + char answer[KRANG_TEXT] = "", error[KRANG_ERR] = ""; + char num[64], tok[32], cost[64]; + int is_external = chat != NULL; + + if (k == NULL || k->eng == NULL || prompt == NULL) + return -1; + if (sp_engine_submit(k->eng, prompt) != 0) { + klog_emit(&k->log, "submit_failed", "cause", cause, NULL); + if (chat != NULL) + kchat_complete(k, chat->id, "the engine refused the turn", + -1); + return -1; + } + pthread_mutex_lock(&k->lock); + k->st.impulses++; + if (is_external) + k->st.external_impulses++; + else + k->st.self_impulses++; + k->st.last_impulse_at = k_now(); + snprintf(k->st.state, sizeof(k->st.state), "thinking"); + copy_trunc(k->last_prompt, sizeof(k->last_prompt), prompt, + sizeof(k->last_prompt) - 1); + pthread_mutex_unlock(&k->lock); + klog_emit(&k->log, "impulse_start", "cause", + cause != NULL ? cause : "timer", "prompt", prompt, NULL); + + for (;;) { + int got = 0; + + while (sp_engine_poll(k->eng, &ev)) { + got = 1; + handle_event(k, &ev, &rc, &saw_end, &steps, &calls, + &mutating, answer, sizeof(answer), error, + sizeof(error)); + sp_engine_event_free(&ev); + } + if (saw_end && !sp_engine_busy(k->eng)) + break; + if (krang_stop || k->stop) { + k->stop = 1; + (void)sp_engine_cancel(k->eng); + } + if (!got) { + k_sleep_ms(10); + if (!sp_engine_busy(k->eng) && ++idle_guard > 200) + break; + } + } + (void)sp_engine_wait(k->eng); + kstate_sync(k); + session_refresh(k); + + pthread_mutex_lock(&k->lock); + k->st.turns++; + k->st.last_turn_rc = rc; + if (answer[0] != '\0') + snprintf(k->st.last_outcome, sizeof(k->st.last_outcome), "%s", + answer); + else if (error[0] != '\0') + snprintf(k->st.last_outcome, sizeof(k->st.last_outcome), + "error: %s", error); + if (error[0] != '\0') + snprintf(k->st.last_error, sizeof(k->st.last_error), "%s", + error); + else if (rc != 0) + snprintf(k->st.last_error, sizeof(k->st.last_error), + "turn failed with %d", rc); + snprintf(k->last_outcome, sizeof(k->last_outcome), "%s", + k->st.last_outcome); + snprintf(k->last_error, sizeof(k->last_error), "%s", + k->st.last_error); + pthread_mutex_unlock(&k->lock); + + if (rc != 0) { + k->turn_failures++; + if (k->turn_failures > 8) + k->turn_failures = 8; + } else { + k->turn_failures = 0; + } + kstuck_turn(&k->stuck, rc, calls, mutating); + + if (answer[0] != '\0' && strstr(answer, "GOAL_COMPLETE") != NULL) { + struct sp_buf e; + + sp_buf_init(&e); + if (sp_session_set_goal_state(k->session_dir, KRANG_SESSION_ID, + "succeeded", &e) == 0) { + pthread_mutex_lock(&k->lock); + snprintf(k->st.goal_state, + sizeof(k->st.goal_state), "succeeded"); + k->st.goal_completes++; + pthread_mutex_unlock(&k->lock); + klog_emit(&k->log, "goal_complete", "goal", + k->st.goal, NULL); + } + sp_buf_free(&e); + } + + pthread_mutex_lock(&k->lock); + snprintf(tok, sizeof(tok), "%lu", k->st.tokens_in); + snprintf(num, sizeof(num), "%d", rc); + snprintf(cost, sizeof(cost), "%.6f", k->st.cost); + pthread_mutex_unlock(&k->lock); + { + char sk[32], sc[32]; + + snprintf(sk, sizeof(sk), "%lu", steps); + snprintf(sc, sizeof(sc), "%lu", calls); + klog_emit(&k->log, "turn_end", "rc", num, "steps", sk, + "calls", sc, "tokens_in", tok, "cost", cost, + "answer", answer, "error", error, NULL); + } + record_impulse(k, cause, rc, steps, calls, answer); + + if (chat != NULL) { + const char *out = rc == 0 ? answer : error; + + kchat_complete(k, chat->id, out[0] != '\0' ? out : + "(the turn produced no answer)", rc); + } + + return rc; +} + +static void +schedule_next(struct krang *k, int failed) +{ + long delay = k->cfg.impulse_seconds; + int i; + + if (failed) { + for (i = 0; i < k->turn_failures && i < 4; i++) + delay *= 2; + if (delay > 3600) + delay = 3600; + } + k->next_at = k_now() + delay; + pthread_mutex_lock(&k->lock); + k->st.next_impulse_at = k->next_at; + if (!failed && k->stuck.level == 0) + snprintf(k->st.state, sizeof(k->st.state), "sleeping"); + pthread_mutex_unlock(&k->lock); +} + +static int +rate_limit(struct krang *k, long now) +{ + if (now - k->hour_start >= 3600) { + k->hour_start = now; + k->hour_count = 0; + } + if (k->hour_count >= k->cfg.max_impulses_per_hour) { + k->next_at = k->hour_start + 3600; + pthread_mutex_lock(&k->lock); + k->st.next_impulse_at = k->next_at; + pthread_mutex_unlock(&k->lock); + klog_emit(&k->log, "rate_limited", "max", + "hourly impulse limit reached", NULL); + return 1; + } + return 0; +} + +int +kdaemon_session_open(struct krang *k, int *newborn, char *goal, + size_t goalcap, char *err, size_t errlen) +{ + struct sp_session_info si; + struct sp_buf eb; + size_t records = 0; + char gstate[16]; + + if (k == NULL || newborn == NULL || goal == NULL) + return -1; + if (k->session_dir[0] == '\0') + snprintf(k->session_dir, sizeof(k->session_dir), "%s", + KRANG_IN_SESSIONS); + sp_buf_init(&eb); + if (sp_session_open(&si, k->session_dir, KRANG_SESSION_ID, &eb) != 0) { + snprintf(err, errlen, "session: %s", + eb.p != NULL ? eb.p : "?"); + sp_buf_free(&eb); + return -1; + } + sp_buf_clear(&eb); + (void)sp_session_count(&si, &records, &eb); + sp_buf_free(&eb); + *newborn = records == 0; + + if (*newborn) { + if (k->cfg.goal[0] == '\0') { + snprintf(err, errlen, + "refusing to birth a session without a goal"); + return -1; + } + sp_buf_init(&eb); + if (sp_session_set_goal(k->session_dir, KRANG_SESSION_ID, + k->cfg.goal, &eb) != 0) { + snprintf(err, errlen, "goal: %s", + eb.p != NULL ? eb.p : "?"); + sp_buf_free(&eb); + return -1; + } + sp_buf_free(&eb); + snprintf(goal, goalcap, "%s", k->cfg.goal); + snprintf(gstate, sizeof(gstate), "open"); + } else { + (void)sp_session_get_goal(k->session_dir, KRANG_SESSION_ID, + goal, goalcap); + (void)sp_session_get_goal_state(k->session_dir, KRANG_SESSION_ID, + gstate, sizeof(gstate)); + if (goal[0] == '\0' && k->cfg.goal[0] != '\0') { + snprintf(goal, goalcap, "%s", k->cfg.goal); + (void)sp_session_set_goal(k->session_dir, + KRANG_SESSION_ID, goal, NULL); + } + if (k->cfg.goal[0] != '\0' && + strcmp(goal, k->cfg.goal) != 0) + klog_emit(&k->log, "config_goal_ignored", + "session_goal", goal, "config_goal", + k->cfg.goal, NULL); + } + + pthread_mutex_lock(&k->lock); + snprintf(k->st.goal, sizeof(k->st.goal), "%s", goal); + snprintf(k->st.goal_state, sizeof(k->st.goal_state), "%s", + gstate[0] != '\0' ? gstate : "open"); + k->st.started_at = k_now(); + k->st.born_at = ksession_born(k); + if (k->st.born_at == 0) + k->st.born_at = k->st.started_at; + snprintf(k->st.state, sizeof(k->st.state), + *newborn ? "newborn" : "sleeping"); + k->hour_start = k_now(); + k->hour_count = 0; + pthread_mutex_unlock(&k->lock); + return 0; +} + +int +kdaemon_run(struct krang *k) +{ + int newborn = 0; + char goal[KRANG_GOAL]; + + if (k == NULL) + return 1; + if (k->cfg.endpoint[0] == '\0' || k->cfg.model[0] == '\0') { + fprintf(stderr, "krang: endpoint and model are required\n"); + return 1; + } + if (k->session_dir[0] == '\0') + snprintf(k->session_dir, sizeof(k->session_dir), "%s", + KRANG_IN_SESSIONS); + { + struct sp_buf sp; + + sp_buf_init(&sp); + k_system_prompt(k, &sp); + snprintf(k->system_prompt, sizeof(k->system_prompt), "%s", + sp.p != NULL ? sp.p : ""); + sp_buf_free(&sp); + } + + if (kdaemon_session_open(k, &newborn, goal, sizeof(goal), + k->last_error, sizeof(k->last_error)) != 0) { + fprintf(stderr, "krang: %s\n", k->last_error); + return 1; + } + + if (kengine_open(k, k->script[0] != '\0' ? k->script : NULL, + k->last_error, sizeof(k->last_error)) != 0) { + fprintf(stderr, "krang: %s\n", k->last_error); + return 1; + } + if (k->cfg.api_key_env[0] != '\0') { + const char *secret = getenv(k->cfg.api_key_env); + + (void)sp_secret_env_add(k->cfg.api_key_env); + if (secret != NULL && *secret != '\0') + klog_set_secret(&k->log, secret); + } + session_refresh(k); + + if (khttp_start(k, k->last_error, sizeof(k->last_error)) != 0) { + fprintf(stderr, "krang: dashboard: %s\n", k->last_error); + kengine_close(k); + return 1; + } + if (kmcp_start(k, k->last_error, sizeof(k->last_error)) != 0) { + fprintf(stderr, "krang: mcp: %s\n", k->last_error); + khttp_stop(k); + kengine_close(k); + return 1; + } + + klog_emit(&k->log, "start", "newborn", newborn ? "1" : "0", + "session", KRANG_SESSION_ID, "goal", goal, NULL); + + if (newborn) { + struct sp_buf birth; + + sp_buf_init(&birth); + k_birth_prompt(&k->cfg, &birth); + klog_emit(&k->log, "birth", "goal", goal, NULL); + (void)krun_turn(k, birth.p != NULL ? birth.p : "You are awake.", + "birth", NULL); + sp_buf_free(&birth); + schedule_next(k, k->turn_failures > 0); + } else { + k->next_at = k_now(); /* a restart continues at once */ + pthread_mutex_lock(&k->lock); + k->st.next_impulse_at = k->next_at; + pthread_mutex_unlock(&k->lock); + } + + while (!krang_stop && !k->stop) { + struct kchat *chat; + long now = k_now(); + + pthread_mutex_lock(&k->lock); + if (k->max_impulses > 0 && + k->st.impulses >= k->max_impulses) { + k->stop = 1; + pthread_mutex_unlock(&k->lock); + break; + } + pthread_mutex_unlock(&k->lock); + kstate_sync(k); + chat = kchat_take(k); + if (chat != NULL) { + set_state(k, "thinking"); + (void)krun_turn(k, chat->text, "chat", chat); + schedule_next(k, 0); + continue; + } + if (k->cfg.max_cost > 0 && k->st.cost >= k->cfg.max_cost) { + set_state(k, "blocked"); + if (now >= k->next_at) { + klog_emit(&k->log, "cost_limit", "cost", + "cost limit reached; self-impulses paused", + NULL); + k->next_at = now + 3600; + pthread_mutex_lock(&k->lock); + k->st.next_impulse_at = k->next_at; + pthread_mutex_unlock(&k->lock); + } + } else if (now >= k->next_at) { + struct sp_buf prompt; + int level; + + if (rate_limit(k, now)) + continue; + level = kstuck_should_check(&k->stuck, now); + sp_buf_init(&prompt); + if (level >= 1) { + k_selfcheck_prompt(k, &prompt); + k->hour_count++; + (void)krun_turn(k, + prompt.p != NULL ? prompt.p : "continue", + "self-check", NULL); + pthread_mutex_lock(&k->lock); + k->st.stuck_events++; + pthread_mutex_unlock(&k->lock); + } else { + k_impulse_prompt(k, "timer", &prompt); + k->hour_count++; + (void)krun_turn(k, + prompt.p != NULL ? prompt.p : "continue", + "timer", NULL); + } + sp_buf_free(&prompt); + if (kstuck_level(&k->stuck) >= 3) { + pthread_mutex_lock(&k->lock); + k->st.blocked_events++; + snprintf(k->st.state, sizeof(k->st.state), + "blocked"); + pthread_mutex_unlock(&k->lock); + klog_emit(&k->log, "blocked", "reason", + "the same approach keeps failing", NULL); + k->next_at = now + 3600; + } else { + schedule_next(k, k->turn_failures > 0); + } + continue; + } + + pthread_mutex_lock(&k->lock); + if (!krang_stop && !k->stop) { + struct timespec ts; + + ts.tv_sec = now + 1; + ts.tv_nsec = 0; + (void)pthread_cond_timedwait(&k->cond, &k->lock, &ts); + } + pthread_mutex_unlock(&k->lock); + } + + klog_emit(&k->log, "stop", "reason", + krang_stop ? "signal" : "requested", NULL); + khttp_stop(k); + kmcp_stop(k); + kengine_close(k); + klog_close(&k->log); + return 0; +} diff --git a/src/httpd.c b/src/httpd.c new file mode 100644 index 0000000..f0c1e99 --- /dev/null +++ b/src/httpd.c @@ -0,0 +1,1320 @@ +/* + * krang -- the dashboard, the HTTP API and the MCP server. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * Everything here reads the same snapshot and the same two logs. The dashboard + * is hand-written HTML/CSS with an inline poller; there is no build chain and + * no external asset. The MCP server is newline-delimited JSON-RPC over TCP, + * plus POST /mcp for clients that only speak HTTP. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "krang.h" +#include "mcp.h" + +#define HTTP_MAX (1024 * 1024) +#define HTTP_HEADER_MAX 65536 +#define HTTP_TIMEOUT_MS 10000 + +struct http_req { + char method[16]; + char path[1024]; + char query[1024]; + char token[512]; + char *body; + size_t body_len; +}; + +struct http_res { + int code; + const char *reason; + const char *type; + char extra[512]; + struct sp_buf body; +}; + +struct http_conn { + int fd; + struct krang *k; +}; + +static mcp_server g_mcp; +static void mcp_init(struct krang *k); + +/* ------------------------------------------------------------------ util */ + +static int +loopback_host(const char *host) +{ + if (host == NULL || *host == '\0') + return 0; + if (!strcmp(host, "localhost") || !strcmp(host, "::1")) + return 1; + return strncmp(host, "127.", 4) == 0; +} + +static int +token_ok(struct krang *k, const struct http_req *r) +{ + if (k->cfg.token[0] == '\0') + return 1; + if (r->token[0] != '\0' && strcmp(r->token, k->cfg.token) == 0) + return 1; + return 0; +} + +static const char * +query_value(const char *query, const char *key, char *out, size_t cap) +{ + const char *p = query; + size_t n = strlen(key); + + out[0] = '\0'; + if (p == NULL) + return out; + while (*p != '\0') { + const char *amp = strchr(p, '&'); + const char *eq = strchr(p, '='); + size_t len = amp != NULL ? (size_t)(amp - p) : strlen(p); + + if (eq != NULL && (size_t)(eq - p) == n && + strncmp(p, key, n) == 0) { + size_t vlen = amp != NULL ? (size_t)(amp - eq - 1) : + strlen(eq + 1); + + if (vlen >= cap) + vlen = cap - 1; + memcpy(out, eq + 1, vlen); + out[vlen] = '\0'; + return out; + } + (void)len; + if (amp == NULL) + break; + p = amp + 1; + } + return out; +} + +static void +res_init(struct http_res *r) +{ + memset(r, 0, sizeof(*r)); + r->code = 200; + r->reason = "OK"; + r->type = "application/json"; + sp_buf_init(&r->body); +} + +static void +res_done(struct http_res *r) +{ + sp_buf_free(&r->body); +} + +static void +res_json_error(struct http_res *r, int code, const char *reason, + const char *msg) +{ + r->code = code; + r->reason = reason; + r->type = "application/json"; + (void)sp_buf_puts(&r->body, "{\"error\":\""); + k_json_escape(&r->body, msg); + (void)sp_buf_puts(&r->body, "\"}"); +} + +static void +send_all(int fd, const char *p, size_t n) +{ + (void)k_write_all(fd, p, n); +} + +static void +send_res(int fd, struct http_res *r) +{ + char hdr[1024]; + + snprintf(hdr, sizeof(hdr), + "HTTP/1.1 %d %s\r\n" + "Content-Type: %s\r\n" + "Content-Length: %zu\r\n" + "Cache-Control: no-store\r\n" + "Connection: close\r\n" + "Access-Control-Allow-Origin: *\r\n" + "Access-Control-Allow-Headers: Authorization, Content-Type\r\n" + "%s" + "\r\n", + r->code, r->reason, r->type, r->body.len, r->extra); + send_all(fd, hdr, strlen(hdr)); + if (r->body.len > 0) + send_all(fd, r->body.p, r->body.len); +} + +/* ---------------------------------------------------------------- request */ + +static int +read_request(int fd, struct sp_buf *raw) +{ + char buf[8192]; + size_t header_end = 0, need = 0; + int have_len = 0; + + for (;;) { + ssize_t n; + struct pollfd pfd; + + pfd.fd = fd; + pfd.events = POLLIN; + pfd.revents = 0; + if (poll(&pfd, 1, HTTP_TIMEOUT_MS) <= 0) + return -1; + n = recv(fd, buf, sizeof(buf), 0); + if (n <= 0) + return -1; + if (sp_buf_add(raw, buf, (size_t)n) != 0) + return -1; + if (raw->len > HTTP_MAX) + return -1; + if (!header_end) { + char *p = strstr(raw->p, "\r\n\r\n"); + + if (p != NULL) { + char *cl; + + header_end = (size_t)(p - raw->p) + 4; + if (header_end > HTTP_HEADER_MAX) + return -1; + cl = strcasestr(raw->p, "\r\nContent-Length:"); + if (cl != NULL && (size_t)(cl - raw->p) < + header_end) { + need = (size_t)strtoul(cl + 17, NULL, 10); + have_len = 1; + } + } + } + if (header_end != 0 && (!have_len || + raw->len >= header_end + need)) + break; + } + return 0; +} + +static int +parse_request(const char *raw, size_t len, struct http_req *r) +{ + const char *hdr_end, *line_end, *sp1, *sp2; + const char *body; + size_t header_len; + + memset(r, 0, sizeof(*r)); + hdr_end = strstr(raw, "\r\n\r\n"); + if (hdr_end == NULL) + return -1; + header_len = (size_t)(hdr_end - raw) + 4; + if (header_len > len) + return -1; + body = raw + header_len; + r->body_len = len - header_len; + if (r->body_len > 0) { + r->body = malloc(r->body_len + 1); + if (r->body == NULL) + return -1; + memcpy(r->body, body, r->body_len); + r->body[r->body_len] = '\0'; + } + line_end = strstr(raw, "\r\n"); + if (line_end == NULL || line_end > hdr_end) + return -1; + sp1 = memchr(raw, ' ', (size_t)(line_end - raw)); + if (sp1 == NULL) + return -1; + sp2 = memchr(sp1 + 1, ' ', (size_t)(line_end - sp1 - 1)); + if (sp2 == NULL) + return -1; + if ((size_t)(sp1 - raw) >= sizeof(r->method)) + return -1; + memcpy(r->method, raw, (size_t)(sp1 - raw)); + r->method[sp1 - raw] = '\0'; + { + size_t plen = (size_t)(sp2 - sp1 - 1); + char *q; + + if (plen >= sizeof(r->path)) + return -1; + memcpy(r->path, sp1 + 1, plen); + r->path[plen] = '\0'; + q = strchr(r->path, '?'); + if (q != NULL) { + *q++ = '\0'; + snprintf(r->query, sizeof(r->query), "%s", q); + } + } + { + const char *a = strcasestr(raw, "\r\nAuthorization: Bearer "); + const char *q = strcasestr(raw, "\r\nX-Krang-Token: "); + + if (a != NULL && a < hdr_end) { + const char *v = a + 24; + const char *e = strstr(v, "\r\n"); + size_t n = e != NULL ? (size_t)(e - v) : 0; + + if (n >= sizeof(r->token)) + n = sizeof(r->token) - 1; + memcpy(r->token, v, n); + r->token[n] = '\0'; + } else if (q != NULL && q < hdr_end) { + const char *v = q + 18; + const char *e = strstr(v, "\r\n"); + size_t n = e != NULL ? (size_t)(e - v) : 0; + + if (n >= sizeof(r->token)) + n = sizeof(r->token) - 1; + memcpy(r->token, v, n); + r->token[n] = '\0'; + } + } + if (r->token[0] == '\0') + (void)query_value(r->query, "token", r->token, + sizeof(r->token)); + return 0; +} + +/* --------------------------------------------------------------- dashboard */ + +static void +dashboard(struct krang *k, struct sp_buf *out) +{ + const char *page = + "" + "" + "krang

krang

" + "..." + "uptime -" + "born -" + "model -" + "
goal ...
" + "
" + "
-
" + "
impulses
" + "
-
" + "
turns
" + "
-
" + "
tool calls
" + "
-
" + "
tool failures
" + "
-
" + "
tokens in / out
" + "
-
" + "
cost
" + "
-
" + "
context
" + "
-
" + "
session records
" + "
-
" + "
compactions
" + "
-
" + "
self-edits
" + "
-
" + "
goals done
" + "
-
" + "
chat in / out
" + "
-
" + "
stuck level
" + "

last outcome

" + "
-
" + "

last error

-
" + "

working notes

-
" + "

chat

" + "

" + "

" + "
" + "

sandbox

-
" + "

impulses

" + "" + "" + "
#atcausercstepsanswer
" + "

events

" + "" + "
#timekinddetail
" + "krang " KRANG_VERSION " · one session · " + "the dashboard reads /api/state, /api/log, /api/impulses" + "
"; + + (void)k; + (void)sp_buf_puts(out, page); +} + +/* ------------------------------------------------------------------ route */ + +static void +route_state(struct krang *k, struct http_res *r) +{ + kstate_json(k, &r->body); +} + +static void +route_impulses(struct krang *k, struct http_req *q, struct http_res *r) +{ + char val[32]; + size_t n = 20; + + (void)query_value(q->query, "limit", val, sizeof(val)); + if (val[0] != '\0') + n = (size_t)strtoul(val, NULL, 10); + kstate_impulses_json(k, &r->body, n); +} + +static void +route_log(struct krang *k, struct http_req *q, struct http_res *r) +{ + char val[32]; + size_t n = 100; + + (void)query_value(q->query, "tail", val, sizeof(val)); + if (val[0] != '\0') + n = (size_t)strtoul(val, NULL, 10); + klog_json(&k->log, &r->body, n); +} + +static void +route_history(struct krang *k, struct http_req *q, struct http_res *r) +{ + char val[32]; + size_t n = 100; + + (void)query_value(q->query, "limit", val, sizeof(val)); + if (val[0] != '\0') + n = (size_t)strtoul(val, NULL, 10); + (void)ksession_history(k, &r->body, n); +} + +static void +route_threads(struct krang *k, struct http_res *r) +{ + char pathbuf[700]; + const char *path = KRANG_IN_THREADS; + FILE *f; + char buf[8192]; + size_t n; + + if (k->cfg.no_sandbox) { + snprintf(pathbuf, sizeof(pathbuf), "%s/THREADS.md", + k->cfg.workspace); + path = pathbuf; + } + (void)sp_buf_puts(&r->body, "{\"text\":\""); + f = fopen(path, "r"); + if (f != NULL) { + n = fread(buf, 1, sizeof(buf) - 1, f); + buf[n] = '\0'; + fclose(f); + } else { + buf[0] = '\0'; + } + k_json_escape(&r->body, buf); + (void)sp_buf_puts(&r->body, "\"}"); +} + +static void +route_say(struct krang *k, struct http_req *q, struct http_res *r) +{ + mcp_json *v; + const char *text; + unsigned long id = 0; + int rc; + + if (q->body == NULL) { + res_json_error(r, 400, "Bad Request", "expected a JSON body"); + return; + } + v = mcp_parse(q->body); + if (v == NULL) { + res_json_error(r, 400, "Bad Request", "invalid JSON"); + return; + } + text = mcp_arg_string(v, "text"); + if (text == NULL || *text == '\0') { + mcp_json_free(v); + res_json_error(r, 400, "Bad Request", "'text' is required"); + return; + } + if (kchat_enqueue(k, text, &id) != 0) { + mcp_json_free(v); + res_json_error(r, 503, "Service Unavailable", + "the chat queue is full"); + return; + } + mcp_json_free(v); + { + char idbuf[32]; + + snprintf(idbuf, sizeof(idbuf), "%lu", id); + klog_emit(&k->log, "chat_in", "id", idbuf, "text", text, NULL); + } + { + struct sp_buf answer; + + sp_buf_init(&answer); + rc = kchat_wait(k, id, &answer, k->cfg.say_timeout); + if (rc == 0) { + (void)sp_buf_printf(&r->body, + "{\"id\":%lu,\"queued\":false,\"answer\":\"", id); + k_json_escape(&r->body, + answer.p != NULL ? answer.p : ""); + (void)sp_buf_puts(&r->body, "\"}"); + } else if (rc == 1) { + r->code = 202; + r->reason = "Accepted"; + (void)sp_buf_printf(&r->body, + "{\"id\":%lu,\"queued\":true}", id); + } else { + res_json_error(r, 503, "Service Unavailable", + "the chat entry disappeared"); + } + sp_buf_free(&answer); + } +} + +static void +route_say_status(struct krang *k, const char *path, struct http_res *r) +{ + const char *p = strrchr(path, '/'); + unsigned long id; + + if (p == NULL || p[1] == '\0') { + res_json_error(r, 400, "Bad Request", "missing id"); + return; + } + id = strtoul(p + 1, NULL, 10); + if (kchat_status(k, id, &r->body) != 0) + res_json_error(r, 404, "Not Found", "no such chat"); +} + +static void +route_config(struct krang *k, struct http_res *r) +{ + kconfig_json(&k->cfg, &r->body, 1); +} + +static void +route_mcp(struct krang *k, struct http_req *q, struct http_res *r) +{ + char *reply; + + (void)k; + if (q->body == NULL) { + res_json_error(r, 400, "Bad Request", "expected JSON-RPC"); + return; + } + reply = mcp_handle(&g_mcp, q->body); + if (reply == NULL) { + r->code = 204; + r->reason = "No Content"; + return; + } + (void)sp_buf_puts(&r->body, reply); + free(reply); +} + +static void +route(struct krang *k, struct http_req *q, struct http_res *r) +{ + res_init(r); + if (!strcmp(q->method, "OPTIONS")) { + r->code = 204; + r->reason = "No Content"; + return; + } + if (!token_ok(k, q) && strcmp(q->path, "/healthz") != 0) { + res_json_error(r, 401, "Unauthorized", "a token is required"); + return; + } + if (!strcmp(q->method, "GET") && (!strcmp(q->path, "/") || + !strcmp(q->path, "/index.html"))) { + r->type = "text/html; charset=utf-8"; + dashboard(k, &r->body); + return; + } + if (!strcmp(q->method, "GET") && !strcmp(q->path, "/healthz")) { + (void)sp_buf_puts(&r->body, "{\"ok\":true,\"state\":\""); + k_json_escape(&r->body, k->st.state); + (void)sp_buf_puts(&r->body, "\"}"); + return; + } + if (!strcmp(q->method, "GET") && !strcmp(q->path, "/api/state")) { + route_state(k, r); + return; + } + if (!strcmp(q->method, "GET") && !strcmp(q->path, "/api/impulses")) { + route_impulses(k, q, r); + return; + } + if (!strcmp(q->method, "GET") && !strcmp(q->path, "/api/log")) { + route_log(k, q, r); + return; + } + if (!strcmp(q->method, "GET") && !strcmp(q->path, "/api/history")) { + route_history(k, q, r); + return; + } + if (!strcmp(q->method, "GET") && !strcmp(q->path, "/api/threads")) { + route_threads(k, r); + return; + } + if (!strcmp(q->method, "GET") && !strcmp(q->path, "/api/tools")) { + kstate_tools_json(k, &r->body); + return; + } + if (!strcmp(q->method, "GET") && !strcmp(q->path, "/api/sandbox")) { + kstate_sandbox_json(k, &r->body); + return; + } + if (!strcmp(q->method, "GET") && !strcmp(q->path, "/api/config")) { + route_config(k, r); + return; + } + if (!strcmp(q->method, "GET") && !strcmp(q->path, "/api/events")) { + r->type = "text/event-stream"; + (void)sp_buf_puts(&r->body, "data: "); + klog_json(&k->log, &r->body, 100); + (void)sp_buf_puts(&r->body, "\n\n"); + return; + } + if (!strcmp(q->method, "POST") && !strcmp(q->path, "/api/say")) { + route_say(k, q, r); + return; + } + if (!strcmp(q->method, "GET") && k_starts_with(q->path, "/api/say/")) { + route_say_status(k, q->path, r); + return; + } + if (!strcmp(q->method, "POST") && !strcmp(q->path, "/mcp")) { + route_mcp(k, q, r); + return; + } + if (!strcmp(q->method, "GET") || !strcmp(q->method, "POST")) + res_json_error(r, 404, "Not Found", "no such route"); + else + res_json_error(r, 405, "Method Not Allowed", "no such method"); +} + +/* --------------------------------------------------------------- HTTP IO */ + +static void * +http_conn_thread(void *arg) +{ + struct http_conn *c = arg; + struct sp_buf raw; + struct http_req req; + struct http_res res; + + sp_buf_init(&raw); + if (read_request(c->fd, &raw) == 0 && + parse_request(raw.p, raw.len, &req) == 0) { + route(c->k, &req, &res); + send_res(c->fd, &res); + res_done(&res); + free(req.body); + } else { + const char *bad = + "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n" + "Connection: close\r\n\r\n"; + + send_all(c->fd, bad, strlen(bad)); + } + sp_buf_free(&raw); + shutdown(c->fd, SHUT_RDWR); + close(c->fd); + free(c); + return NULL; +} + +static void * +http_accept_thread(void *arg) +{ + struct krang *k = arg; + + for (;;) { + struct sockaddr_storage sa; + socklen_t sl = sizeof(sa); + int fd = accept(k->http_fd, (struct sockaddr *)&sa, &sl); + + if (fd < 0) { + if (errno == EINTR) + continue; + break; + } + { + struct http_conn *c = calloc(1, sizeof(*c)); + pthread_t th; + + if (c == NULL) { + close(fd); + continue; + } + c->fd = fd; + c->k = k; + if (pthread_create(&th, NULL, http_conn_thread, c) != 0) { + close(fd); + free(c); + continue; + } + pthread_detach(th); + } + } + return NULL; +} + +static int +listen_on(const char *host, int port, char *err, size_t errlen) +{ + struct addrinfo hints, *res = NULL, *rp; + char portbuf[16]; + int fd = -1; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE; + snprintf(portbuf, sizeof(portbuf), "%d", port); + if (getaddrinfo(host != NULL && *host != '\0' ? host : NULL, portbuf, + &hints, &res) != 0) { + snprintf(err, errlen, "getaddrinfo %s:%d failed", host, port); + return -1; + } + for (rp = res; rp != NULL; rp = rp->ai_next) { + int one = 1; + + fd = socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, + rp->ai_protocol); + if (fd < 0) + continue; + (void)setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, + sizeof(one)); + if (bind(fd, rp->ai_addr, rp->ai_addrlen) == 0 && + listen(fd, 16) == 0) + break; + close(fd); + fd = -1; + } + freeaddrinfo(res); + if (fd < 0) + snprintf(err, errlen, "cannot listen on %s:%d: %s", host, port, + strerror(errno)); + return fd; +} + +int +khttp_start(struct krang *k, char *err, size_t errlen) +{ + if (k == NULL) + return -1; + mcp_init(k); + if (!loopback_host(k->cfg.dashboard_host) && + k->cfg.token[0] == '\0') { + snprintf(err, errlen, + "refusing to bind the dashboard to %s without a token", + k->cfg.dashboard_host); + return -1; + } + k->http_fd = listen_on(k->cfg.dashboard_host, k->cfg.dashboard_port, + err, errlen); + if (k->http_fd < 0) + return -1; + k->http_running = 1; + if (pthread_create(&k->http_tid, NULL, http_accept_thread, k) != 0) { + snprintf(err, errlen, "cannot start the dashboard thread"); + close(k->http_fd); + k->http_fd = -1; + k->http_running = 0; + return -1; + } + return 0; +} + +void +khttp_stop(struct krang *k) +{ + if (k == NULL || !k->http_running) + return; + shutdown(k->http_fd, SHUT_RDWR); + close(k->http_fd); + k->http_fd = -1; + pthread_join(k->http_tid, NULL); + k->http_running = 0; +} + +/* ------------------------------------------------------------------- MCP */ + +static void +tool_state(mcp_conn *c, const mcp_json *args, void *user) +{ + struct krang *k = user; + struct sp_buf b; + + (void)args; + sp_buf_init(&b); + kstate_json(k, &b); + mcp_reply_text(c, b.p != NULL ? b.p : "{}"); + sp_buf_free(&b); +} + +static void +tool_impulses(mcp_conn *c, const mcp_json *args, void *user) +{ + struct krang *k = user; + struct sp_buf b; + int n = mcp_arg_int(args, "limit", 50); + + sp_buf_init(&b); + kstate_impulses_json(k, &b, n > 0 ? (size_t)n : 50); + mcp_reply_text(c, b.p != NULL ? b.p : "[]"); + sp_buf_free(&b); +} + +static void +tool_events(mcp_conn *c, const mcp_json *args, void *user) +{ + struct krang *k = user; + struct sp_buf b; + int n = mcp_arg_int(args, "limit", 100); + + sp_buf_init(&b); + klog_json(&k->log, &b, n > 0 ? (size_t)n : 100); + mcp_reply_text(c, b.p != NULL ? b.p : "[]"); + sp_buf_free(&b); +} + +static void +tool_session(mcp_conn *c, const mcp_json *args, void *user) +{ + struct krang *k = user; + struct sp_buf b; + size_t records = 0; + unsigned long long bytes = 0; + char goal[KRANG_GOAL], gstate[16]; + long born; + + (void)args; + sp_buf_init(&b); + ksession_meta(k, &records, &bytes, goal, sizeof(goal), + gstate, sizeof(gstate)); + born = ksession_born(k); + (void)sp_buf_printf(&b, + "{\"id\":\"%s\",\"records\":%zu,\"bytes\":%llu," + "\"born\":%ld,\"goal\":\"", + KRANG_SESSION_ID, records, bytes, born); + k_json_escape(&b, goal); + (void)sp_buf_puts(&b, "\",\"goal_state\":\""); + k_json_escape(&b, gstate[0] != '\0' ? gstate : "open"); + (void)sp_buf_puts(&b, "\"}"); + mcp_reply_text(c, b.p != NULL ? b.p : "{}"); + sp_buf_free(&b); +} + +static void +tool_history(mcp_conn *c, const mcp_json *args, void *user) +{ + struct krang *k = user; + struct sp_buf b; + int n = mcp_arg_int(args, "limit", 100); + + sp_buf_init(&b); + (void)ksession_history(k, &b, n > 0 ? (size_t)n : 100); + mcp_reply_text(c, b.p != NULL ? b.p : "[]"); + sp_buf_free(&b); +} + +static void +tool_tools(mcp_conn *c, const mcp_json *args, void *user) +{ + struct krang *k = user; + struct sp_buf b; + + (void)args; + sp_buf_init(&b); + kstate_tools_json(k, &b); + mcp_reply_text(c, b.p != NULL ? b.p : "[]"); + sp_buf_free(&b); +} + +static void +tool_sandbox(mcp_conn *c, const mcp_json *args, void *user) +{ + struct krang *k = user; + struct sp_buf b; + + (void)args; + sp_buf_init(&b); + kstate_sandbox_json(k, &b); + mcp_reply_text(c, b.p != NULL ? b.p : "{}"); + sp_buf_free(&b); +} + +static void +tool_config(mcp_conn *c, const mcp_json *args, void *user) +{ + struct krang *k = user; + struct sp_buf b; + + (void)args; + sp_buf_init(&b); + kconfig_json(&k->cfg, &b, 1); + mcp_reply_text(c, b.p != NULL ? b.p : "{}"); + sp_buf_free(&b); +} + +static void +tool_say(mcp_conn *c, const mcp_json *args, void *user) +{ + struct krang *k = user; + const char *text = mcp_arg_string(args, "text"); + unsigned long id = 0; + struct sp_buf b; + int rc; + + if (text == NULL || *text == '\0') { + mcp_reply_error(c, "text is required"); + return; + } + if (kchat_enqueue(k, text, &id) != 0) { + mcp_reply_error(c, "the chat queue is full"); + return; + } + { + char idbuf[32]; + + snprintf(idbuf, sizeof(idbuf), "%lu", id); + klog_emit(&k->log, "chat_in", "id", idbuf, "text", text, NULL); + } + sp_buf_init(&b); + rc = kchat_wait(k, id, &b, k->cfg.say_timeout); + if (rc == 0) + mcp_reply_text(c, b.p != NULL ? b.p : ""); + else if (rc == 1) { + char msg[128]; + + snprintf(msg, sizeof(msg), + "queued as chat %lu; poll with krang_say_status", id); + mcp_reply_text(c, msg); + } else + mcp_reply_error(c, "the chat entry disappeared"); + sp_buf_free(&b); +} + +static void +tool_say_status(mcp_conn *c, const mcp_json *args, void *user) +{ + struct krang *k = user; + int id = mcp_arg_int(args, "id", 0); + struct sp_buf b; + + if (id <= 0) { + mcp_reply_error(c, "id is required"); + return; + } + sp_buf_init(&b); + if (kchat_status(k, (unsigned long)id, &b) != 0) + mcp_reply_error(c, "no such chat"); + else + mcp_reply_text(c, b.p != NULL ? b.p : "{}"); + sp_buf_free(&b); +} + +static void +tool_steer(mcp_conn *c, const mcp_json *args, void *user) +{ + struct krang *k = user; + const char *text = mcp_arg_string(args, "text"); + unsigned long id = 0; + + if (text == NULL || *text == '\0') { + mcp_reply_error(c, "text is required"); + return; + } + if (sp_engine_busy(k->eng)) { + if (sp_engine_steer(k->eng, text) == 0) { + klog_emit(&k->log, "steer", "text", text, NULL); + mcp_reply_text(c, "steered into the running turn"); + return; + } + } + if (kchat_enqueue(k, text, &id) == 0) { + char msg[128]; + + snprintf(msg, sizeof(msg), "queued as chat %lu", id); + klog_emit(&k->log, "steer_queued", "id", msg, "text", text, + NULL); + mcp_reply_text(c, msg); + } else + mcp_reply_error(c, "the chat queue is full"); +} + +static void +tool_cancel(mcp_conn *c, const mcp_json *args, void *user) +{ + struct krang *k = user; + + (void)args; + if (sp_engine_busy(k->eng) && sp_engine_cancel(k->eng) == 0) { + klog_emit(&k->log, "cancel", "by", "mcp", NULL); + mcp_reply_text(c, "cancel requested"); + } else + mcp_reply_text(c, "no turn is running"); +} + +static const char schema_none[] = + "{\"type\":\"object\",\"properties\":{}}"; +static const char schema_say[] = + "{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"}}," + "\"required\":[\"text\"]}"; +static const char schema_limit[] = + "{\"type\":\"object\",\"properties\":{\"limit\":{\"type\":\"integer\"}}}"; +static const char schema_id[] = + "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"}}," + "\"required\":[\"id\"]}"; + +static const mcp_tool mcp_tools[] = { + { "krang_state", "The whole live snapshot: state, goal, counts, tokens, " + "sandbox, config (redacted).", schema_none, tool_state }, + { "krang_impulses", "The recent impulse ledger.", schema_limit, + tool_impulses }, + { "krang_events", "The recent append-only experiment events.", + schema_limit, tool_events }, + { "krang_session", "The one session: id, records, bytes, born, goal.", + schema_none, tool_session }, + { "krang_history", "The recent messages of the one session.", + schema_limit, tool_history }, + { "krang_tools", "The tool registry krang is running with.", + schema_none, tool_tools }, + { "krang_sandbox", "Rootfs, uid, Landlock and seccomp status.", + schema_none, tool_sandbox }, + { "krang_config", "The configuration, secrets redacted.", schema_none, + tool_config }, + { "krang_say", "Say something to krang. It is injected into the one " + "session and the answer is returned, or a queued id.", schema_say, + tool_say }, + { "krang_say_status", "Poll a queued chat by id.", schema_id, + tool_say_status }, + { "krang_steer", "Put text into the running turn, or queue it.", + schema_say, tool_steer }, + { "krang_cancel", "Cancel the running turn.", schema_none, tool_cancel }, +}; + +static void +mcp_init(struct krang *k) +{ + if (k == NULL) + return; + g_mcp.name = "krang"; + g_mcp.version = KRANG_VERSION; + g_mcp.tools = mcp_tools; + g_mcp.ntools = sizeof(mcp_tools) / sizeof(mcp_tools[0]); + g_mcp.user = k; +} + +void +kmcp_prepare(struct krang *k) +{ + mcp_init(k); +} + +char * +kmcp_handle(struct krang *k, const char *line) +{ + mcp_init(k); + return mcp_handle(&g_mcp, line); +} + +static int +mcp_auth(int fd, struct krang *k) +{ + char line[1024]; + size_t used = 0; + + if (k->cfg.token[0] == '\0') + return 0; + for (;;) { + ssize_t n = recv(fd, line + used, 1, 0); + + if (n <= 0) + return -1; + if (line[used] == '\n') + break; + if (++used >= sizeof(line) - 1) + return -1; + } + line[used] = '\0'; + while (used > 0 && (line[used - 1] == '\r' || + line[used - 1] == '\n')) + line[--used] = '\0'; + if (strncmp(line, "AUTH ", 5) == 0 && + strcmp(line + 5, k->cfg.token) == 0) + return 0; + return -1; +} + +static void * +mcp_conn_thread(void *arg) +{ + struct http_conn *c = arg; + struct sp_buf line; + char buf[4096]; + + if (mcp_auth(c->fd, c->k) != 0) { + const char *no = "{\"error\":\"unauthorized\"}\n"; + + send_all(c->fd, no, strlen(no)); + close(c->fd); + free(c); + return NULL; + } + sp_buf_init(&line); + for (;;) { + ssize_t n = recv(c->fd, buf, sizeof(buf), 0); + size_t i; + + if (n <= 0) + break; + for (i = 0; i < (size_t)n; i++) { + if (buf[i] == '\n') { + char *reply; + + if (line.p != NULL) + line.p[line.len] = '\0'; + while (line.len > 0 && line.p != NULL && + (line.p[line.len - 1] == '\r')) + line.p[--line.len] = '\0'; + if (line.len > 0) { + reply = mcp_handle(&g_mcp, line.p); + if (reply != NULL) { + send_all(c->fd, reply, + strlen(reply)); + send_all(c->fd, "\n", 1); + free(reply); + } + } + sp_buf_clear(&line); + } else { + if (line.len >= HTTP_MAX) + break; + (void)sp_buf_add(&line, &buf[i], 1); + } + } + } + sp_buf_free(&line); + shutdown(c->fd, SHUT_RDWR); + close(c->fd); + free(c); + return NULL; +} + +static void * +mcp_accept_thread(void *arg) +{ + struct krang *k = arg; + + for (;;) { + int fd = accept(k->mcp_fd, NULL, NULL); + + if (fd < 0) { + if (errno == EINTR) + continue; + break; + } + { + struct http_conn *c = calloc(1, sizeof(*c)); + pthread_t th; + + if (c == NULL) { + close(fd); + continue; + } + c->fd = fd; + c->k = k; + if (pthread_create(&th, NULL, mcp_conn_thread, c) != 0) { + close(fd); + free(c); + continue; + } + pthread_detach(th); + } + } + return NULL; +} + +int +kmcp_start(struct krang *k, char *err, size_t errlen) +{ + if (k == NULL) + return -1; + if (!loopback_host(k->cfg.mcp_host) && k->cfg.token[0] == '\0') { + snprintf(err, errlen, + "refusing to bind MCP to %s without a token", + k->cfg.mcp_host); + return -1; + } + mcp_init(k); + k->mcp_fd = listen_on(k->cfg.mcp_host, k->cfg.mcp_port, err, errlen); + if (k->mcp_fd < 0) + return -1; + k->mcp_running = 1; + if (pthread_create(&k->mcp_tid, NULL, mcp_accept_thread, k) != 0) { + snprintf(err, errlen, "cannot start the MCP thread"); + close(k->mcp_fd); + k->mcp_fd = -1; + k->mcp_running = 0; + return -1; + } + return 0; +} + +void +kmcp_stop(struct krang *k) +{ + if (k == NULL || !k->mcp_running) + return; + shutdown(k->mcp_fd, SHUT_RDWR); + close(k->mcp_fd); + k->mcp_fd = -1; + pthread_join(k->mcp_tid, NULL); + k->mcp_running = 0; +} + +/* --------------------------------------------------------------- test hook */ + +void +khttp_handle_buffer(struct krang *k, const char *request, struct sp_buf *out) +{ + struct http_req req; + struct http_res res; + char hdr[1024]; + + if (k == NULL || request == NULL || out == NULL) + return; + if (parse_request(request, strlen(request), &req) != 0) { + (void)sp_buf_puts(out, + "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n"); + return; + } + route(k, &req, &res); + snprintf(hdr, sizeof(hdr), + "HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\n" + "Connection: close\r\n\r\n", res.code, res.reason, res.type, + res.body.len); + (void)sp_buf_puts(out, hdr); + if (res.body.p != NULL) + (void)sp_buf_add(out, res.body.p, res.body.len); + res_done(&res); + free(req.body); +} diff --git a/src/journal.c b/src/journal.c new file mode 100644 index 0000000..befb3b4 --- /dev/null +++ b/src/journal.c @@ -0,0 +1,121 @@ +/* + * krang -- reading back the full journal. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * Compaction shrinks the working conversation; it does not shrink the session + * log. This read-only tool lets the model look up what the working set dropped: + * the whole one-session journal, searched case-insensitively. + */ +#include +#include +#include +#include + +#include "krang.h" +#include "mcp.h" + +static const char * +ci_strstr(const char *hay, const char *needle) +{ + size_t n = strlen(needle); + const char *p; + + if (n == 0) + return hay; + for (p = hay; *p != '\0'; p++) { + size_t i; + + for (i = 0; i < n; i++) { + if (p[i] == '\0' || + tolower((unsigned char)p[i]) != + tolower((unsigned char)needle[i])) + break; + } + if (i == n) + return p; + } + return NULL; +} + +static int +journal_run(const char *args_json, struct sp_buf *out, void *ctx) +{ + struct krang *k = ctx; + mcp_json *v; + const char *query; + int limit = 10, hits = 0; + char path[640], *line = NULL; + size_t cap = 0; + FILE *f; + + if (k == NULL || out == NULL) + return -1; + v = args_json != NULL ? mcp_parse(args_json) : NULL; + if (v == NULL) + return sp_buf_puts(out, "error: arguments must be a JSON object"); + query = mcp_arg_string(v, "query"); + limit = mcp_arg_int(v, "limit", 10); + if (query == NULL || *query == '\0') { + mcp_json_free(v); + return sp_buf_puts(out, "error: 'query' is required"); + } + if (limit < 1 || limit > 50) + limit = 10; + snprintf(path, sizeof(path), "%s/%s.jsonl", k->session_dir, + KRANG_SESSION_ID); + f = fopen(path, "r"); + if (f == NULL) { + mcp_json_free(v); + return sp_buf_printf(out, "error: cannot read %s", path); + } + while (getline(&line, &cap, f) > 0 && hits < limit) { + char *p = line; + size_t n; + + k_trim(p); + if (*p != '{' || ci_strstr(p, query) == NULL) + continue; + hits++; + n = strlen(p); + if (n > 2000) + n = 2000; + (void)sp_buf_printf(out, "%d: ", hits); + (void)sp_buf_add(out, p, n); + if (n < strlen(p)) + (void)sp_buf_puts(out, " ..."); + (void)sp_buf_puts(out, "\n"); + } + free(line); + fclose(f); + mcp_json_free(v); + if (hits == 0) + (void)sp_buf_printf(out, "no match for '%s' in the journal", + query); + else + (void)sp_buf_printf(out, "[%d match(es); the journal has the " + "full history]", hits); + return 0; +} + +int +kjournal_register(struct krang *k) +{ + struct sp_tool t; + + if (k == NULL || k->eng == NULL) + return -1; + memset(&t, 0, sizeof(t)); + t.name = "journal_search"; + t.description = "Search the full journal (the one session log), " + "including the history compaction dropped. Read-only."; + t.params = "{\"type\":\"object\",\"properties\":{" + "\"query\":{\"type\":\"string\"}," + "\"limit\":{\"type\":\"integer\"}}," + "\"required\":[\"query\"]}"; + t.auth = SP_AUTH_READ; + t.run = journal_run; + t.ctx = k; + return sp_registry_add(sp_engine_registry(k->eng), &t); +} diff --git a/src/krang.h b/src/krang.h new file mode 100644 index 0000000..f9c666b --- /dev/null +++ b/src/krang.h @@ -0,0 +1,379 @@ +/* + * krang -- an autonomous daemon that lives in a chroot. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#ifndef KRANG_H +#define KRANG_H + +#include +#include +#include +#include +#include + +#include "splinter.h" +#include "splinter_engine.h" +#include "config.h" + +extern volatile sig_atomic_t krang_stop; + +#define KRANG_VERSION "0.1.0" +#define KRANG_SESSION_ID "krang" +#define KRANG_PATH 512 +#define KRANG_GOAL 2048 +#define KRANG_TEXT 8192 +#define KRANG_ERR 1024 +#define KRANG_IMPULSE_RING 64 +#define KRANG_EVENT_RING 256 +#define KRANG_CHAT_SLOTS 32 + +/* + * Where the world is, once chrooted. The host paths in the config are + * bind-mounted onto these fixed paths; code after the drop only knows these. + */ +#define KRANG_IN_STATE "/var/lib/krang/state" +#define KRANG_IN_SESSIONS KRANG_IN_STATE "/sessions" +#define KRANG_IN_EVENTS KRANG_IN_STATE "/events.jsonl" +#define KRANG_IN_WORKSPACE "/var/lib/krang/workspace" +#define KRANG_IN_THREADS KRANG_IN_WORKSPACE "/THREADS.md" +#define KRANG_IN_SKILLS KRANG_IN_WORKSPACE "/skills" +#define KRANG_IN_SELF KRANG_IN_WORKSPACE "/self" +#define KRANG_IN_TMP KRANG_IN_WORKSPACE "/tmp" + +/* ---------------------------------------------------------------- config */ + +struct kconfig { + char path[KRANG_PATH]; + char goal[KRANG_GOAL]; + + char endpoint[512]; + char model[256]; + char api_key_env[64]; + char kind[16]; /* "" (openai) or "anthropic" */ + size_t ctx; + + char state_dir[KRANG_PATH]; /* host path to bind onto /var/lib/krang/state */ + char workspace[KRANG_PATH]; /* host path to bind onto /var/lib/krang/workspace */ + char rootfs[KRANG_PATH]; + char rootfs_suite[64]; + char rootfs_mirror[512]; + char sandbox_user[64]; + uid_t sandbox_uid; + gid_t sandbox_gid; + char plugin[8][KRANG_PATH]; + size_t nplugins; + + int impulse_seconds; /* between self-initiated impulses */ + size_t max_steps; /* tool rounds per turn */ + size_t max_bytes; /* request budget, 0 = engine default */ + size_t compact_threshold; + size_t compact_target; + int max_impulses_per_hour; + double max_cost; /* USD, 0 = off */ + + char dashboard_host[64]; + int dashboard_port; + char mcp_host[64]; + int mcp_port; + char token[256]; + int say_timeout; /* seconds an external say waits */ + + int require_landlock; /* Linux: refuse without path confinement */ + int seccomp; /* Linux: apply the syscall filter */ + int prepare_if_missing; /* run debootstrap when the rootfs is absent */ + + int no_sandbox; /* CLI only; requires KRANG_ALLOW_UNSANDBOXED */ +}; + +/* ----------------------------------------------------------------- host */ + +struct khost { + char id[64]; + char version[128]; + char codename[64]; + char arch[32]; + char suite[64]; + char mirror[512]; + char method[64]; + int supported; +}; + +/* ---------------------------------------------------------------- stats */ + +struct kstats { + char state[32]; /* sleeping, thinking, stuck, blocked */ + long started_at; + long born_at; + long last_impulse_at; + long next_impulse_at; + + unsigned long impulses; + unsigned long self_impulses; + unsigned long external_impulses; + unsigned long turns; + unsigned long steps; + unsigned long tool_calls; + unsigned long tool_failures; + unsigned long denials; + unsigned long tokens_in; + unsigned long tokens_out; + unsigned long tokens_cached; + double cost; + size_t ctx_used; + size_t ctx_max; + unsigned long compactions; + unsigned long chat_in; + unsigned long chat_out; + unsigned long chat_pending; + unsigned long stuck_events; + unsigned long blocked_events; + unsigned long goal_completes; + unsigned long self_edits; + + int busy; + int waiting; + + char model[256]; + char agent[48]; + char session[64]; + char last_error[KRANG_ERR]; + char last_outcome[KRANG_GOAL]; + char goal[KRANG_GOAL]; + char goal_state[16]; /* open, succeeded */ + char last_tool[64]; + char last_tool_result[512]; + int last_turn_rc; + + unsigned long session_records; + unsigned long long session_bytes; + + char rootfs_id[KRANG_PATH]; + char sandbox_uid[32]; + char sandbox_gid[32]; + char landlock[32]; + char seccomp[32]; + char host_id[64]; + char host_version[128]; + char host_arch[32]; +}; + +/* ------------------------------------------------------------- impulses */ + +struct kimpulse { + unsigned long id; + long at; + char cause[32]; /* birth, timer, chat, self-check, retry */ + int rc; + unsigned long steps; + unsigned long tool_calls; + unsigned long tokens_in; + unsigned long tokens_out; + double cost; + char answer[512]; /* truncated, for the dashboard */ +}; + +/* ------------------------------------------------------------------- log */ + +struct kentry { + unsigned long seq; + long ts; + char *json; +}; + +struct klog { + int fd; /* root-owned, opened before the drop */ + pthread_mutex_t lock; + unsigned long seq; + unsigned long long bytes; + char secret[512]; /* redacted from every value */ + struct kentry ring[KRANG_EVENT_RING]; + size_t head; /* next slot */ + size_t count; +}; + +/* ------------------------------------------------------------------ chat */ + +struct kchat { + unsigned long id; + char *text; + char *answer; + int state; /* 0 free, 1 pending, 2 running, 3 done */ + int rc; + long created; +}; + +/* ----------------------------------------------------------------- stuck */ + +struct kstuck { + int consecutive_failures; + int repeated_calls; + int no_progress_turns; + int same_error; + int level; /* 0 none, 1 reflect, 2 change, 3 blocked */ + int attempts; + long last_check; + char last_call[512]; + char last_error[KRANG_ERR]; +}; + +/* ------------------------------------------------------------------ main */ + +struct krang { + struct kconfig cfg; + struct sp_config sconf; + struct sp_agent_config base; + struct sp_engine *eng; + struct sp_buf err; + int engine_open; + + pthread_mutex_t lock; + pthread_cond_t cond; + int stop; + + struct kstats st; + struct kimpulse impulses[KRANG_IMPULSE_RING]; + unsigned long impulse_seq; + + struct klog log; + struct kchat chats[KRANG_CHAT_SLOTS]; + unsigned long chat_seq; + + struct kstuck stuck; + struct khost host; + + time_t next_at; + long hour_start; + int hour_count; + int turn_failures; + char session_dir[KRANG_PATH]; + char script[KRANG_PATH]; /* test/one-shot script */ + size_t max_impulses; /* 0: run forever */ + char last_prompt[KRANG_TEXT]; + char last_error[KRANG_ERR]; + char last_outcome[KRANG_GOAL]; + char system_prompt[4096]; + + int http_fd; + int mcp_fd; + pthread_t http_tid; + pthread_t mcp_tid; + int http_running; + int mcp_running; + + char rootfs_marker[KRANG_PATH]; + char plugin_inside[8][KRANG_PATH]; + char landlock_state[32]; + char seccomp_state[32]; +}; + +/* ------------------------------------------------------------------ util */ + +long k_now(void); +void k_sleep_ms(int ms); +void k_trim(char *s); +int k_starts_with(const char *s, const char *p); +char *k_strdup(const char *s); +void k_json_escape(struct sp_buf *b, const char *s); +void k_redact(struct sp_buf *out, const char *text, const char *secret); +int k_write_all(int fd, const void *buf, size_t len); +void k_format_time(long t, char *buf, size_t cap); +int k_parse_bool(const char *s, int dflt); + +/* ---------------------------------------------------------------- config */ + +void kconfig_defaults(struct kconfig *c); +int kconfig_load(struct kconfig *c, const char *path, char *err, + size_t errlen); +void kconfig_json(const struct kconfig *c, struct sp_buf *out, int redact); + +/* ------------------------------------------------------------------- log */ + +int klog_open(struct klog *l, const char *path, char *err, size_t errlen); +void klog_close(struct klog *l); +void klog_set_secret(struct klog *l, const char *secret); +void klog_emit(struct klog *l, const char *kind, ...); +void klog_json(struct klog *l, struct sp_buf *out, size_t max); +void klog_entry_json(const struct kentry *e, struct sp_buf *out); + +/* --------------------------------------------------------------- session */ + +int ksession_meta(struct krang *k, size_t *records, + unsigned long long *bytes, char *goal, size_t goalcap, + char *gstate, size_t gstatecap); +int ksession_history(struct krang *k, struct sp_buf *out, size_t limit); +long ksession_born(struct krang *k); + +/* --------------------------------------------------------------- prompts */ + +void k_birth_prompt(const struct kconfig *c, struct sp_buf *out); +void k_impulse_prompt(struct krang *k, const char *cause, struct sp_buf *out); +void k_selfcheck_prompt(struct krang *k, struct sp_buf *out); +void k_system_prompt(struct krang *k, struct sp_buf *out); + +/* ----------------------------------------------------------------- stuck */ + +void kstuck_result(struct kstuck *s, const char *tool, const char *obs, + int is_error); +void kstuck_call(struct kstuck *s, const char *tool, const char *args); +void kstuck_turn(struct kstuck *s, int rc, unsigned long calls, + int mutating); +int kstuck_level(const struct kstuck *s); +void kstuck_reset(struct kstuck *s); +int kstuck_should_check(struct kstuck *s, long now); + +/* ------------------------------------------------------------------ chat */ + +int kchat_enqueue(struct krang *k, const char *text, unsigned long *id); +struct kchat *kchat_take(struct krang *k); +void kchat_complete(struct krang *k, unsigned long id, const char *answer, + int rc); +int kchat_wait(struct krang *k, unsigned long id, struct sp_buf *out, + int timeout_s); +int kchat_status(struct krang *k, unsigned long id, struct sp_buf *out); + +/* ----------------------------------------------------------------- state */ + +void kstate_sync(struct krang *k); +void kstate_json(struct krang *k, struct sp_buf *out); +void kstate_impulses_json(struct krang *k, struct sp_buf *out, size_t max); +void kstate_tools_json(struct krang *k, struct sp_buf *out); +void kstate_sandbox_json(struct krang *k, struct sp_buf *out); + +/* ---------------------------------------------------------------- daemon */ + +int kdaemon_run(struct krang *k); +int kdaemon_session_open(struct krang *k, int *newborn, char *goal, + size_t goalcap, char *err, size_t errlen); +int kengine_open(struct krang *k, const char *script, char *err, + size_t errlen); +void kengine_close(struct krang *k); +int kjournal_register(struct krang *k); +int krun_turn(struct krang *k, const char *prompt, const char *cause, + struct kchat *chat); + +/* --------------------------------------------------------------- sandbox */ + +int khost_detect(struct khost *h, char *err, size_t errlen); +int krootfs_prepare(struct krang *k, char *err, size_t errlen); +int ksandbox_enter(struct krang *k, char *err, size_t errlen); +void ksandbox_plan(struct krang *k, struct sp_buf *out); +int ksandbox_apply_landlock(const char *workspace, const char *state, + const char *tmp, int required, char *err, size_t errlen); +int ksandbox_apply_seccomp(int required, char *err, size_t errlen); + +/* ------------------------------------------------------------------ http */ + +int khttp_start(struct krang *k, char *err, size_t errlen); +void khttp_stop(struct krang *k); +int kmcp_start(struct krang *k, char *err, size_t errlen); +void kmcp_stop(struct krang *k); + +/* test hooks: handle one request without a socket thread */ +void khttp_handle_buffer(struct krang *k, const char *request, + struct sp_buf *response); +void kmcp_prepare(struct krang *k); +char *kmcp_handle(struct krang *k, const char *line); + +#endif /* KRANG_H */ diff --git a/src/log.c b/src/log.c new file mode 100644 index 0000000..91ef6d7 --- /dev/null +++ b/src/log.c @@ -0,0 +1,281 @@ +/* + * krang -- the experiment log. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * The file is opened by the root phase before the uid drop and is root-owned + * and 0600. The daemon keeps the descriptor for the rest of its life; the + * model can neither open nor truncate it. FD_CLOEXEC keeps it out of every + * child the run tool starts. The in-memory ring is what the dashboard reads. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "krang.h" + +#define KRANG_LOG_TAIL_LOAD (512 * 1024) + +static void +ring_add(struct klog *l, unsigned long seq, long ts, char *json) +{ + struct kentry *e = &l->ring[l->head]; + + free(e->json); + e->seq = seq; + e->ts = ts; + e->json = json; + l->head = (l->head + 1) % KRANG_EVENT_RING; + if (l->count < KRANG_EVENT_RING) + l->count++; +} + +static unsigned long +seq_from_line(const char *line) +{ + const char *p = strstr(line, "\"seq\":"); + char *end = NULL; + unsigned long v; + + if (p == NULL) + return 0; + p += 6; + v = strtoul(p, &end, 10); + if (end == p) + return 0; + return v; +} + +static long +ts_from_line(const char *line) +{ + const char *p = strstr(line, "\"ts\":"); + char *end = NULL; + long v; + + if (p == NULL) + return 0; + p += 5; + v = strtol(p, &end, 10); + if (end == p) + return 0; + return v; +} + +static void +load_tail(struct klog *l, off_t size) +{ + char *buf; + off_t start; + size_t want, got = 0; + ssize_t n; + char *line, *nl; + + if (size <= 0) + return; + want = (size_t)(size > KRANG_LOG_TAIL_LOAD ? KRANG_LOG_TAIL_LOAD : size); + start = size - (off_t)want; + buf = malloc(want + 1); + if (buf == NULL) + return; + while (got < want) { + n = pread(l->fd, buf + got, want - got, start + (off_t)got); + if (n < 0 && errno == EINTR) + continue; + if (n <= 0) + break; + got += (size_t)n; + } + buf[got] = '\0'; + line = buf; + if (start > 0) { + nl = strchr(line, '\n'); + if (nl == NULL) { + free(buf); + return; + } + line = nl + 1; + } + while ((nl = strchr(line, '\n')) != NULL) { + unsigned long seq; + long ts; + char *copy; + + *nl = '\0'; + if (*line == '{') { + seq = seq_from_line(line); + ts = ts_from_line(line); + copy = k_strdup(line); + if (copy != NULL) + ring_add(l, seq, ts, copy); + if (seq > l->seq) + l->seq = seq; + } + line = nl + 1; + } + free(buf); +} + +int +klog_open(struct klog *l, const char *path, char *err, size_t errlen) +{ + struct stat st; + + if (l == NULL || path == NULL) + return -1; + memset(l, 0, sizeof(*l)); + l->fd = -1; + pthread_mutex_init(&l->lock, NULL); + l->fd = open(path, O_RDWR | O_CREAT | O_APPEND, 0600); + if (l->fd < 0) { + snprintf(err, errlen, "cannot open event log %s: %s", path, + strerror(errno)); + return -1; + } + (void)fchmod(l->fd, 0600); + (void)fcntl(l->fd, F_SETFD, FD_CLOEXEC); + if (fstat(l->fd, &st) == 0) { + l->bytes = (unsigned long long)st.st_size; + load_tail(l, st.st_size); + } + return 0; +} + +void +klog_close(struct klog *l) +{ + size_t i; + + if (l == NULL) + return; + pthread_mutex_lock(&l->lock); + if (l->fd >= 0) { + close(l->fd); + l->fd = -1; + } + for (i = 0; i < KRANG_EVENT_RING; i++) { + free(l->ring[i].json); + l->ring[i].json = NULL; + } + l->count = 0; + pthread_mutex_unlock(&l->lock); + pthread_mutex_destroy(&l->lock); +} + +void +klog_set_secret(struct klog *l, const char *secret) +{ + if (l == NULL) + return; + pthread_mutex_lock(&l->lock); + snprintf(l->secret, sizeof(l->secret), "%s", + secret != NULL ? secret : ""); + pthread_mutex_unlock(&l->lock); +} + +void +klog_emit(struct klog *l, const char *kind, ...) +{ + struct sp_buf line; + va_list ap; + const char *key; + char now[64]; + unsigned long seq; + long ts; + + if (l == NULL || kind == NULL) + return; + if (sp_buf_init(&line) != 0) + return; + ts = k_now(); + k_format_time(ts, now, sizeof(now)); + pthread_mutex_lock(&l->lock); + seq = ++l->seq; + (void)sp_buf_printf(&line, + "{\"seq\":%lu,\"ts\":%ld,\"time\":\"%s\",\"kind\":\"", + seq, ts, now); + k_json_escape(&line, kind); + (void)sp_buf_puts(&line, "\""); + va_start(ap, kind); + while ((key = va_arg(ap, const char *)) != NULL) { + const char *val = va_arg(ap, const char *); + struct sp_buf clean; + + (void)sp_buf_puts(&line, ",\""); + k_json_escape(&line, key); + (void)sp_buf_puts(&line, "\":\""); + if (l->secret[0] != '\0' && val != NULL) { + if (sp_buf_init(&clean) == 0) { + k_redact(&clean, val, l->secret); + k_json_escape(&line, + clean.p != NULL ? clean.p : ""); + sp_buf_free(&clean); + } else { + k_json_escape(&line, val); + } + } else { + k_json_escape(&line, val != NULL ? val : ""); + } + (void)sp_buf_puts(&line, "\""); + } + va_end(ap); + (void)sp_buf_puts(&line, "}"); + if (l->fd >= 0) { + if (k_write_all(l->fd, line.p, line.len) == 0 && + k_write_all(l->fd, "\n", 1) == 0) + l->bytes += line.len + 1; + } + { + char *copy = k_strdup(line.p != NULL ? line.p : ""); + + if (copy != NULL) + ring_add(l, seq, ts, copy); + } + pthread_mutex_unlock(&l->lock); + sp_buf_free(&line); +} + +void +klog_entry_json(const struct kentry *e, struct sp_buf *out) +{ + if (e == NULL || e->json == NULL || out == NULL) + return; + (void)sp_buf_puts(out, e->json); +} + +void +klog_json(struct klog *l, struct sp_buf *out, size_t max) +{ + size_t i, start, n; + unsigned long seq; + + if (l == NULL || out == NULL) + return; + pthread_mutex_lock(&l->lock); + n = l->count; + if (max > 0 && n > max) + n = max; + start = (l->head + KRANG_EVENT_RING - n) % KRANG_EVENT_RING; + (void)sp_buf_puts(out, "["); + for (i = 0; i < n; i++) { + const struct kentry *e = + &l->ring[(start + i) % KRANG_EVENT_RING]; + + if (i > 0) + (void)sp_buf_puts(out, ","); + if (e->json != NULL) + (void)sp_buf_puts(out, e->json); + else + (void)sp_buf_puts(out, "{}"); + } + (void)sp_buf_puts(out, "]"); + seq = l->seq; + pthread_mutex_unlock(&l->lock); + (void)seq; +} diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..8e09f68 --- /dev/null +++ b/src/main.c @@ -0,0 +1,297 @@ +/* + * krang -- launcher. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * It starts as root, builds the world, drops the privileges, and becomes the + * daemon. The only commands that do not enter the sandbox are --plan, + * --prepare-rootfs and --check/--self-test, which are setup and verification. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "krang.h" + +#define DEFAULT_CONFIG "/etc/krang/krang.conf" + +static void +on_signal(int sig) +{ + (void)sig; + krang_stop = 1; +} + +static void +usage(FILE *out) +{ + fprintf(out, + "krang %s -- an autonomous daemon in a chroot\n" + "\n" + " krang [--config PATH] start the daemon (as root)\n" + " krang --plan [--config PATH] print the sandbox plan, do not start\n" + " krang --prepare-rootfs debootstrap the rootfs (as root)\n" + " krang --check offline check: config, plan, script turn\n" + " krang --self-test one scripted turn, no network, no model\n" + " krang --sandbox-test root-only: enter the sandbox, one scripted\n" + " turn (id -u, mount denial), then exit\n" + " krang --version version\n" + " krang --help this text\n" + "\n" + " --no-sandbox development only; needs\n" + " KRANG_ALLOW_UNSANDBOXED=1\n" + "\n" + "The daemon never asks a user for anything. It answers on the dashboard\n" + "and the MCP port; see krang.conf.example.\n", + KRANG_VERSION); +} + +static int +self_test(const char *config_path) +{ + struct krang k; + char tmpl[512], *dir, script[600], logpath[700], answer[KRANG_GOAL]; + FILE *f; + int rc = 1; + + memset(&k, 0, sizeof(k)); + k.log.fd = -1; + pthread_mutex_init(&k.lock, NULL); + pthread_cond_init(&k.cond, NULL); + sp_buf_init(&k.err); + kconfig_defaults(&k.cfg); + if (config_path != NULL) + (void)kconfig_load(&k.cfg, config_path, k.last_error, + sizeof(k.last_error)); + snprintf(tmpl, sizeof(tmpl), "/tmp/krang-selftest-XXXXXX"); + dir = mkdtemp(tmpl); + if (dir == NULL) { + perror("mkdtemp"); + goto out; + } + snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir); + snprintf(logpath, sizeof(logpath), "%s/events.jsonl", dir); + (void)mkdir(k.session_dir, 0700); + (void)mkdir(k.cfg.workspace, 0700); + if (klog_open(&k.log, logpath, k.last_error, + sizeof(k.last_error)) != 0) { + fprintf(stderr, "krang: %s\n", k.last_error); + goto out; + } + snprintf(script, sizeof(script), "%s/script.txt", dir); + f = fopen(script, "w"); + if (f == NULL) { + perror("script"); + goto out; + } + fprintf(f, "tool echo {\"text\":\"krang-selftest\"}\n"); + fprintf(f, "answer krang-selftest-ok\n"); + fclose(f); + snprintf(k.cfg.endpoint, sizeof(k.cfg.endpoint), + "http://127.0.0.1:1/v1"); + snprintf(k.cfg.model, sizeof(k.cfg.model), "selftest"); + snprintf(k.cfg.goal, sizeof(k.cfg.goal), "prove the apparatus"); + sp_buf_init(&k.err); + { + struct sp_buf sp; + + sp_buf_init(&sp); + k_system_prompt(&k, &sp); + snprintf(k.system_prompt, sizeof(k.system_prompt), "%s", + sp.p != NULL ? sp.p : ""); + sp_buf_free(&sp); + } + if (kengine_open(&k, script, k.last_error, + sizeof(k.last_error)) != 0) { + fprintf(stderr, "krang: %s\n", k.last_error); + goto out; + } + (void)krun_turn(&k, "prove the apparatus", "self-test", NULL); + snprintf(answer, sizeof(answer), "%s", k.last_outcome); + if (strstr(answer, "krang-selftest-ok") != NULL) { + printf("krang self-test: ok\n"); + rc = 0; + } else { + fprintf(stderr, "krang self-test: unexpected answer: %s\n", + answer); + } +out: + if (k.eng != NULL) + kengine_close(&k); + if (k.log.fd >= 0) + klog_close(&k.log); + pthread_mutex_destroy(&k.lock); + pthread_cond_destroy(&k.cond); + sp_buf_free(&k.err); + return rc; +} + +static int +sandbox_test(struct krang *k) +{ + struct sp_buf sp; + char path[800]; + FILE *f; + int rc; + + if (geteuid() != 0) { + fprintf(stderr, + "krang: --sandbox-test must start as root; it drops itself\n"); + return 1; + } + snprintf(path, sizeof(path), "%s/sandbox-script.txt", + k->cfg.state_dir); + f = fopen(path, "w"); + if (f == NULL) { + fprintf(stderr, "krang: cannot write %s: %s\n", path, + strerror(errno)); + return 1; + } + fprintf(f, "tool clock {}\n"); + fprintf(f, "tool run {\"command\":\"id -u\"}\n"); + fprintf(f, + "tool run {\"command\":\"mount -t tmpfs none /tmp 2>&1 || " + "echo mount-denied\"}\n"); + fprintf(f, "answer sandbox-test-ok\n"); + fclose(f); + (void)chmod(path, 0644); + + if (ksandbox_enter(k, k->last_error, sizeof(k->last_error)) != 0) { + fprintf(stderr, "krang: %s\n", k->last_error); + return 1; + } + snprintf(k->session_dir, sizeof(k->session_dir), "%s", + KRANG_IN_SESSIONS); + sp_buf_init(&sp); + k_system_prompt(k, &sp); + snprintf(k->system_prompt, sizeof(k->system_prompt), "%s", + sp.p != NULL ? sp.p : ""); + sp_buf_free(&sp); + if (kengine_open(k, KRANG_IN_STATE "/sandbox-script.txt", + k->last_error, sizeof(k->last_error)) != 0) { + fprintf(stderr, "krang: %s\n", k->last_error); + return 1; + } + rc = krun_turn(k, "sandbox integration test", "sandbox-test", NULL); + printf("sandbox-test outcome: %s\n", k->st.last_outcome); + printf("sandbox-test last tool result: %s\n", + k->st.last_tool_result); + kengine_close(k); + klog_close(&k->log); + if (rc != 0 || strstr(k->st.last_outcome, "sandbox-test-ok") == NULL) { + fprintf(stderr, "krang: sandbox-test failed\n"); + return 1; + } + printf("sandbox-test: ok\n"); + return 0; +} + +int +main(int argc, char **argv) +{ + const char *config_path = DEFAULT_CONFIG; + int do_plan = 0, do_prepare = 0, do_check = 0, do_self = 0; + int do_sandbox = 0; + int i; + struct krang k; + struct sigaction sa; + + for (i = 1; i < argc; i++) { + if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) { + usage(stdout); + return 0; + } else if (!strcmp(argv[i], "--version") || + !strcmp(argv[i], "-V")) { + printf("krang %s\n", KRANG_VERSION); + return 0; + } else if (!strcmp(argv[i], "--plan")) { + do_plan = 1; + } else if (!strcmp(argv[i], "--prepare-rootfs")) { + do_prepare = 1; + } else if (!strcmp(argv[i], "--check")) { + do_check = 1; + } else if (!strcmp(argv[i], "--self-test")) { + do_self = 1; + } else if (!strcmp(argv[i], "--sandbox-test")) { + do_sandbox = 1; + } else if (!strcmp(argv[i], "--no-sandbox")) { + /* recorded after the config is loaded */ + } else if (!strcmp(argv[i], "--config")) { + if (++i >= argc) { + fprintf(stderr, "krang: --config needs a path\n"); + return 1; + } + config_path = argv[i]; + } else { + fprintf(stderr, "krang: unknown argument %s\n", argv[i]); + usage(stderr); + return 1; + } + } + if (do_self || do_check) + return self_test(config_path) == 0 ? 0 : 1; + + memset(&k, 0, sizeof(k)); + k.log.fd = -1; + pthread_mutex_init(&k.lock, NULL); + pthread_cond_init(&k.cond, NULL); + if (sp_buf_init(&k.err) != 0) + return 1; + if (kconfig_load(&k.cfg, config_path, k.last_error, + sizeof(k.last_error)) != 0) { + fprintf(stderr, "krang: %s\n", k.last_error); + return 1; + } + for (i = 1; i < argc; i++) + if (!strcmp(argv[i], "--no-sandbox")) + k.cfg.no_sandbox = 1; + + if (do_plan) { + struct sp_buf out; + + sp_buf_init(&out); + ksandbox_plan(&k, &out); + fputs(out.p != NULL ? out.p : "", stdout); + sp_buf_free(&out); + return 0; + } + if (do_prepare) { + if (krootfs_prepare(&k, k.last_error, + sizeof(k.last_error)) != 0) { + fprintf(stderr, "krang: %s\n", k.last_error); + return 1; + } + return 0; + } + if (do_sandbox) + return sandbox_test(&k); + if (k.cfg.endpoint[0] == '\0' || k.cfg.model[0] == '\0') { + fprintf(stderr, + "krang: endpoint and model are required in %s\n", + config_path); + return 1; + } + signal(SIGPIPE, SIG_IGN); + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = on_signal; + sigemptyset(&sa.sa_mask); + (void)sigaction(SIGTERM, &sa, NULL); + (void)sigaction(SIGINT, &sa, NULL); + if (ksandbox_enter(&k, k.last_error, sizeof(k.last_error)) != 0) { + fprintf(stderr, "krang: %s\n", k.last_error); + return 1; + } + i = kdaemon_run(&k); + sp_buf_free(&k.err); + pthread_mutex_destroy(&k.lock); + pthread_cond_destroy(&k.cond); + if (k.log.fd >= 0) + klog_close(&k.log); + return i; +} diff --git a/src/sandbox.c b/src/sandbox.c new file mode 100644 index 0000000..ba58a1f --- /dev/null +++ b/src/sandbox.c @@ -0,0 +1,1238 @@ +/* + * krang -- the cage: host detection, rootfs, chroot, uid drop, unveil, pledge. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * The process starts as root because only root can build the world. The root + * phase is deterministic setup and never sees model input. It then chroots, + * drops to an unprivileged uid, and applies two one-way restrictions: + * + * unveil path confinement (Landlock on Linux, unveil(2) on OpenBSD) + * pledge syscall confinement (seccomp-bpf on Linux, pledge(2) on OpenBSD) + * + * After that there is no path back to root. A restart goes through the service + * manager from the beginning. + */ +#define _GNU_SOURCE +#define _XOPEN_SOURCE 700 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __linux__ +#include +#include +#include +#include +#include +#endif + +#include "krang.h" + +#ifndef CLONE_NEWNS +#define CLONE_NEWNS 0x00020000 +#endif + +#define KRANG_DEV_NULL "/dev/null" +#define KRANG_DEV_ZERO "/dev/zero" +#define KRANG_DEV_RANDOM "/dev/random" +#define KRANG_DEV_URANDOM "/dev/urandom" + +/* ------------------------------------------------------------- host detect */ + +static void +os_release(char *id, size_t idcap, char *ver, size_t vercap, char *code, + size_t codecap) +{ + FILE *f; + char line[512]; + + id[0] = ver[0] = code[0] = '\0'; + f = fopen("/etc/os-release", "r"); + if (f == NULL) + return; + while (fgets(line, sizeof(line), f) != NULL) { + char *p = line, *eq; + + k_trim(p); + if (*p == '#' || *p == '\0') + continue; + eq = strchr(p, '='); + if (eq == NULL) + continue; + *eq = '\0'; + { + char *v = eq + 1; + + if (*v == '"' || *v == '\'') { + char q = *v++; + + { + char *end = strrchr(v, q); + + if (end != NULL) + *end = '\0'; + } + } + if (!strcmp(p, "ID")) + snprintf(id, idcap, "%s", v); + else if (!strcmp(p, "VERSION_ID")) + snprintf(ver, vercap, "%s", v); + else if (!strcmp(p, "VERSION_CODENAME")) + snprintf(code, codecap, "%s", v); + } + } + fclose(f); +} + +static int +have_debootstrap(void) +{ + return access("/usr/sbin/debootstrap", X_OK) == 0 || + access("/usr/bin/debootstrap", X_OK) == 0; +} + +int +khost_detect(struct khost *h, char *err, size_t errlen) +{ + char id[64], ver[128], code[64]; + + if (h == NULL) + return -1; + memset(h, 0, sizeof(*h)); + os_release(id, sizeof(id), ver, sizeof(ver), code, sizeof(code)); + snprintf(h->id, sizeof(h->id), "%s", id[0] != '\0' ? id : "unknown"); + snprintf(h->version, sizeof(h->version), "%s", ver); + snprintf(h->codename, sizeof(h->codename), "%s", code); +#if defined(__x86_64__) + snprintf(h->arch, sizeof(h->arch), "x86_64"); +#elif defined(__aarch64__) + snprintf(h->arch, sizeof(h->arch), "aarch64"); +#elif defined(__i386__) + snprintf(h->arch, sizeof(h->arch), "i386"); +#else + snprintf(h->arch, sizeof(h->arch), "unknown"); +#endif + if (!strcmp(h->id, "debian") || !strcmp(h->id, "ubuntu")) { + snprintf(h->method, sizeof(h->method), "debootstrap"); + snprintf(h->suite, sizeof(h->suite), "%s", + code[0] != '\0' ? code : ver); + h->supported = have_debootstrap(); + } else { + h->supported = 0; + } + if (!h->supported) { + snprintf(err, errlen, + "no builder for %s %s on %s; supported: debian/ubuntu " + "with debootstrap", h->id, h->version, h->arch); + return -1; + } + return 0; +} + +/* --------------------------------------------------------------- helpers */ + +static int +mkdir_p(const char *path, mode_t mode) +{ + char tmp[1024]; + char *p; + + if (path == NULL || strlen(path) >= sizeof(tmp)) { + errno = ENAMETOOLONG; + return -1; + } + snprintf(tmp, sizeof(tmp), "%s", path); + for (p = tmp + 1; *p != '\0'; p++) { + if (*p != '/') + continue; + *p = '\0'; + if (mkdir(tmp, mode) != 0 && errno != EEXIST) + return -1; + *p = '/'; + } + if (mkdir(tmp, mode) != 0 && errno != EEXIST) + return -1; + return 0; +} + +static int +write_file(const char *path, const char *text, mode_t mode) +{ + int fd; + size_t n = strlen(text); + + fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, mode); + if (fd < 0) + return -1; + if (k_write_all(fd, text, n) != 0) { + close(fd); + return -1; + } + close(fd); + return 0; +} + +static int +touch_file(const char *path) +{ + int fd = open(path, O_WRONLY | O_CREAT, 0644); + + if (fd < 0) + return -1; + close(fd); + return 0; +} + +static int +copy_file(const char *src, const char *dst, mode_t mode) +{ + int in, out; + char buf[8192]; + ssize_t n; + + in = open(src, O_RDONLY); + if (in < 0) + return -1; + out = open(dst, O_WRONLY | O_CREAT | O_TRUNC, mode); + if (out < 0) { + close(in); + return -1; + } + while ((n = read(in, buf, sizeof(buf))) > 0) { + if (k_write_all(out, buf, (size_t)n) != 0) { + close(in); + close(out); + return -1; + } + } + close(in); + close(out); + return n < 0 ? -1 : 0; +} + +static int +run_argv(char *const argv[]) +{ + pid_t pid; + int status; + + pid = fork(); + if (pid < 0) + return -1; + if (pid == 0) { + execvp(argv[0], argv); + _exit(127); + } + while (waitpid(pid, &status, 0) < 0) { + if (errno != EINTR) + return -1; + } + if (!WIFEXITED(status)) + return -1; + return WEXITSTATUS(status); +} + +/* ------------------------------------------------------------- fingerprint */ + +static uint64_t g_fp; +static int g_fp_files; + +static void +fnv_update(uint64_t *h, const void *data, size_t n) +{ + const unsigned char *p = data; + size_t i; + + for (i = 0; i < n; i++) { + *h ^= p[i]; + *h *= 1099511628211ULL; + } +} + +static int +fp_cb(const char *path, const struct stat *st, int flag, struct FTW *ftw) +{ + char buf[65536]; + int fd; + ssize_t n; + + (void)ftw; + if (flag != FTW_F || !S_ISREG(st->st_mode)) + return 0; + fnv_update(&g_fp, path, strlen(path)); + fnv_update(&g_fp, &st->st_size, sizeof(st->st_size)); + fd = open(path, O_RDONLY); + if (fd < 0) + return 0; + while ((n = read(fd, buf, sizeof(buf))) > 0) + fnv_update(&g_fp, buf, (size_t)n); + close(fd); + g_fp_files++; + return 0; +} + +static uint64_t +tree_fingerprint(const char *root) +{ + g_fp = 1469598103934665603ULL; + g_fp_files = 0; + (void)nftw(root, fp_cb, 32, FTW_PHYS); + return g_fp; +} + +static int +strip_cb(const char *path, const struct stat *st, int flag, struct FTW *ftw) +{ + (void)ftw; + if (flag != FTW_F) + return 0; + if (st->st_mode & (S_ISUID | S_ISGID)) + (void)chmod(path, st->st_mode & ~(S_ISUID | S_ISGID)); + (void)removexattr(path, "security.capability"); + return 0; +} + +static void +strip_setuid(const char *root) +{ + (void)nftw(root, strip_cb, 32, FTW_PHYS); +} + +/* --------------------------------------------------------------- marker */ + +static void +marker_write(const char *rootfs, const struct khost *h, + const struct kconfig *c, uint64_t fp) +{ + char path[1200]; + FILE *f; + + snprintf(path, sizeof(path), "%s/etc/krang-rootfs", rootfs); + f = fopen(path, "w"); + if (f == NULL) + return; + fprintf(f, "id=%s\nversion=%s\ncodename=%s\narch=%s\nsuite=%s\n", + h->id, h->version, h->codename, h->arch, h->suite); + fprintf(f, "method=%s\nmirror=%s\ncreated=%ld\n", + h->method, c->rootfs_mirror, k_now()); + fprintf(f, "tree_fnv1a64=%016" PRIx64 "\n", fp); + fclose(f); +} + +static void +marker_read(const char *rootfs, char *buf, size_t cap) +{ + char path[1200]; + FILE *f; + size_t n; + + if (cap == 0) + return; + buf[0] = '\0'; + snprintf(path, sizeof(path), "%s/etc/krang-rootfs", rootfs); + f = fopen(path, "r"); + if (f == NULL) + return; + n = fread(buf, 1, cap - 1, f); + buf[n] = '\0'; + fclose(f); +} + +static const char * +marker_field(const char *marker, const char *key, char *out, size_t cap) +{ + const char *p = marker; + size_t n = strlen(key); + + out[0] = '\0'; + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + + if (strncmp(p, key, n) == 0 && p[n] == '=') { + size_t len = eol != NULL ? (size_t)(eol - p - n - 1) : + strlen(p + n + 1); + + if (len >= cap) + len = cap - 1; + memcpy(out, p + n + 1, len); + out[len] = '\0'; + return out; + } + if (eol == NULL) + break; + p = eol + 1; + } + return out; +} + +/* --------------------------------------------------------------- rootfs */ + +int +krootfs_prepare(struct krang *k, char *err, size_t errlen) +{ + struct khost h; + char marker[1200], path[1200], text[2048]; + char *argv[8]; + uint64_t fp; + struct passwd *pw; + int rc; + + if (k == NULL) + return -1; + if (geteuid() != 0) { + snprintf(err, errlen, + "preparing a rootfs needs root (debootstrap)"); + return -1; + } + if (khost_detect(&h, err, errlen) != 0) + return -1; + if (k->cfg.rootfs_suite[0] != '\0') + snprintf(h.suite, sizeof(h.suite), "%s", k->cfg.rootfs_suite); + if (h.suite[0] == '\0') { + snprintf(err, errlen, "cannot determine a debootstrap suite"); + return -1; + } + snprintf(marker, sizeof(marker), "%s/etc/krang-rootfs", k->cfg.rootfs); + if (access(marker, R_OK) == 0) { + snprintf(err, errlen, "rootfs already prepared at %s", + k->cfg.rootfs); + return 0; + } + if (access(k->cfg.rootfs, F_OK) == 0) { + snprintf(err, errlen, + "%s exists but has no krang marker; remove it or choose " + "another rootfs", k->cfg.rootfs); + return -1; + } + if (mkdir_p(k->cfg.rootfs, 0755) != 0) { + snprintf(err, errlen, "cannot create %s: %s", k->cfg.rootfs, + strerror(errno)); + return -1; + } + argv[0] = access("/usr/sbin/debootstrap", X_OK) == 0 ? + "/usr/sbin/debootstrap" : "debootstrap"; + argv[1] = "--variant=minbase"; + argv[2] = "--include=ca-certificates,curl,coreutils"; + argv[3] = h.suite; + argv[4] = k->cfg.rootfs; + argv[5] = k->cfg.rootfs_mirror; + argv[6] = NULL; + fprintf(stderr, "krang: debootstrap %s %s (%s %s)\n", h.suite, + k->cfg.rootfs, h.id, h.arch); + rc = run_argv(argv); + if (rc != 0) { + snprintf(err, errlen, + "debootstrap failed with status %d; remove the partial " + "rootfs at %s before retrying", rc, k->cfg.rootfs); + return -1; + } + /* target directories inside the rootfs */ + { + static const char *const dirs[] = { + "/var/lib/krang/state", + "/var/lib/krang/state/sessions", + "/var/lib/krang/workspace", + "/var/lib/krang/workspace/skills", + "/var/lib/krang/workspace/self", + "/var/lib/krang/workspace/tmp", + "/tmp", + "/dev", + "/opt/krang", + "/opt/krang/lib", + "/opt/krang/plugins", + NULL + }; + int i; + + for (i = 0; dirs[i] != NULL; i++) { + snprintf(path, sizeof(path), "%s%s", k->cfg.rootfs, + dirs[i]); + if (mkdir_p(path, 0755) != 0) { + snprintf(err, errlen, "mkdir %s: %s", path, + strerror(errno)); + return -1; + } + } + } + /* the persistent host side */ + if (mkdir_p(k->cfg.state_dir, 0755) != 0 || + mkdir_p(k->cfg.workspace, 0700) != 0) { + snprintf(err, errlen, "cannot create state/workspace: %s", + strerror(errno)); + return -1; + } + (void)chmod(k->cfg.state_dir, 0755); + (void)chown(k->cfg.state_dir, 0, 0); + snprintf(path, sizeof(path), "%s/sessions", k->cfg.state_dir); + if (mkdir_p(path, 0700) != 0) { + snprintf(err, errlen, "cannot create %s: %s", path, + strerror(errno)); + return -1; + } + (void)chown(path, k->cfg.sandbox_uid, k->cfg.sandbox_gid); + { + static const char *const wdirs[] = { + "/skills", "/self", "/tmp", NULL + }; + int i; + + for (i = 0; wdirs[i] != NULL; i++) { + snprintf(path, sizeof(path), "%s%s", k->cfg.workspace, + wdirs[i]); + if (mkdir_p(path, 0700) != 0) { + snprintf(err, errlen, "cannot create %s: %s", + path, strerror(errno)); + return -1; + } + (void)chown(path, k->cfg.sandbox_uid, + k->cfg.sandbox_gid); + } + } + snprintf(path, sizeof(path), "%s/THREADS.md", k->cfg.workspace); + if (access(path, F_OK) != 0) { + snprintf(text, sizeof(text), + "# krang -- working notes\n\n" + "Goal:\n\n" + "Open threads:\n\n" + "- (none yet)\n\n" + "Last known state:\n"); + if (write_file(path, text, 0600) != 0) { + snprintf(err, errlen, "cannot write %s: %s", path, + strerror(errno)); + return -1; + } + } + (void)chown(k->cfg.workspace, k->cfg.sandbox_uid, k->cfg.sandbox_gid); + (void)chown(path, k->cfg.sandbox_uid, k->cfg.sandbox_gid); + pw = getpwnam(k->cfg.sandbox_user); + if (pw == NULL) + fprintf(stderr, + "krang: user '%s' is not on the host; using uid %ld\n", + k->cfg.sandbox_user, (long)k->cfg.sandbox_uid); + strip_setuid(k->cfg.rootfs); + fp = tree_fingerprint(k->cfg.rootfs); + marker_write(k->cfg.rootfs, &h, &k->cfg, fp); + fprintf(stderr, + "krang: rootfs ready: %s %s %s, %d files, fp %016" PRIx64 "\n", + h.id, h.suite, h.arch, g_fp_files, fp); + return 0; +} + +/* --------------------------------------------------------------- plan */ + +#ifdef __linux__ +static int +landlock_abi(void) +{ + return (int)syscall(SYS_landlock_create_ruleset, NULL, 0, + LANDLOCK_CREATE_RULESET_VERSION); +} +#else +static int +landlock_abi(void) +{ + return -1; +} +#endif + +void +ksandbox_plan(struct krang *k, struct sp_buf *out) +{ + struct khost h; + char err[KRANG_ERR], marker[2048], val[128]; + + if (k == NULL || out == NULL) + return; + memset(&h, 0, sizeof(h)); + (void)khost_detect(&h, err, sizeof(err)); + (void)sp_buf_printf(out, "host: %s %s %s (%s)\n", h.id, h.version, + h.arch, h.supported ? "supported" : "unsupported"); + if (h.suite[0] != '\0') + (void)sp_buf_printf(out, "suite: %s\n", h.suite); + (void)sp_buf_printf(out, "rootfs: %s (%s)\n", k->cfg.rootfs, + access(k->cfg.rootfs, F_OK) == 0 ? "exists" : "missing"); + marker_read(k->cfg.rootfs, marker, sizeof(marker)); + if (marker[0] != '\0') { + (void)sp_buf_printf(out, " suite %s, arch %s, fp %s\n", + marker_field(marker, "suite", val, sizeof(val)), val, + marker_field(marker, "tree_fnv1a64", val, sizeof(val))); + } + (void)sp_buf_printf(out, "state: %s\nworkspace: %s\n", + k->cfg.state_dir, k->cfg.workspace); + (void)sp_buf_printf(out, "drop: uid %ld gid %ld\n", + (long)k->cfg.sandbox_uid, (long)k->cfg.sandbox_gid); + (void)sp_buf_puts(out, + "mounts: state rw, workspace rw, /etc/ssl/certs ro, " + "/etc/resolv.conf copy\n"); + (void)sp_buf_printf(out, "landlock: %s\n", + landlock_abi() >= 1 ? "available" : "unavailable"); + (void)sp_buf_printf(out, "seccomp: %s\n", + k->cfg.seccomp ? "enabled" : "disabled"); + (void)sp_buf_printf(out, "dashboard: %s:%d\nmcp: %s:%d\n", + k->cfg.dashboard_host, k->cfg.dashboard_port, + k->cfg.mcp_host, k->cfg.mcp_port); +} + +/* --------------------------------------------------------------- mounts */ + +static int +mount_bind(const char *src, const char *dst, int ro, int rec) +{ + unsigned long flags = MS_BIND | (rec ? MS_REC : 0); + + if (mount(src, dst, NULL, flags, NULL) != 0) + return -1; + if (ro) { + unsigned long rflags = MS_BIND | MS_REMOUNT | MS_RDONLY | + MS_NOSUID | MS_NODEV; + + if (rec) + rflags |= MS_REC; + if (mount(NULL, dst, NULL, rflags, NULL) != 0) + return -1; + } else { + unsigned long rflags = MS_BIND | MS_REMOUNT | MS_NOSUID | + MS_NODEV; + + if (rec) + rflags |= MS_REC; + (void)mount(NULL, dst, NULL, rflags, NULL); + } + return 0; +} + +static void +ensure_dev(const char *path, mode_t mode, unsigned int maj, + unsigned int min) +{ + struct stat st; + + if (stat(path, &st) == 0) + return; + (void)mknod(path, S_IFCHR | mode, makedev(maj, min)); + (void)chmod(path, mode); +} + +/* --------------------------------------------------------------- landlock */ + +#ifdef __linux__ +static int +ll_add(int ruleset, const char *path, uint64_t rights) +{ + struct landlock_path_beneath_attr pb; + int fd; + + if (access(path, F_OK) != 0) + return 0; + fd = open(path, O_PATH | O_CLOEXEC); + if (fd < 0) + return -1; + memset(&pb, 0, sizeof(pb)); + pb.allowed_access = rights; + pb.parent_fd = fd; + if (syscall(SYS_landlock_add_rule, ruleset, + LANDLOCK_RULE_PATH_BENEATH, &pb, 0) != 0) { + close(fd); + return -1; + } + close(fd); + return 0; +} +#endif + +int +ksandbox_apply_landlock(const char *workspace, const char *state, + const char *tmp, int required, char *err, size_t errlen) +{ +#ifdef __linux__ + struct landlock_ruleset_attr attr; + uint64_t handled, ro; + int abi, fd; + + abi = landlock_abi(); + if (abi < 1) { + if (required) { + snprintf(err, errlen, + "Landlock is unavailable (kernel %d)", abi); + return -1; + } + return 0; + } + handled = LANDLOCK_ACCESS_FS_EXECUTE | + LANDLOCK_ACCESS_FS_WRITE_FILE | + LANDLOCK_ACCESS_FS_READ_FILE | + LANDLOCK_ACCESS_FS_READ_DIR | + LANDLOCK_ACCESS_FS_REMOVE_DIR | + LANDLOCK_ACCESS_FS_REMOVE_FILE | + LANDLOCK_ACCESS_FS_MAKE_CHAR | + LANDLOCK_ACCESS_FS_MAKE_DIR | + LANDLOCK_ACCESS_FS_MAKE_REG | + LANDLOCK_ACCESS_FS_MAKE_SOCK | + LANDLOCK_ACCESS_FS_MAKE_FIFO | + LANDLOCK_ACCESS_FS_MAKE_BLOCK | + LANDLOCK_ACCESS_FS_MAKE_SYM; +#ifdef LANDLOCK_ACCESS_FS_REFER + if (abi >= 2) + handled |= LANDLOCK_ACCESS_FS_REFER; +#endif +#ifdef LANDLOCK_ACCESS_FS_TRUNCATE + if (abi >= 3) + handled |= LANDLOCK_ACCESS_FS_TRUNCATE; +#endif +#ifdef LANDLOCK_ACCESS_FS_IOCTL_DEV + if (abi >= 5) + handled |= LANDLOCK_ACCESS_FS_IOCTL_DEV; +#endif + memset(&attr, 0, sizeof(attr)); + attr.handled_access_fs = handled; + fd = (int)syscall(SYS_landlock_create_ruleset, &attr, sizeof(attr), 0); + if (fd < 0) { + snprintf(err, errlen, "landlock_create_ruleset: %s", + strerror(errno)); + return -1; + } + ro = LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_READ_FILE | + LANDLOCK_ACCESS_FS_READ_DIR; + if (ll_add(fd, "/", ro) != 0 || + ll_add(fd, "/dev", LANDLOCK_ACCESS_FS_READ_FILE | + LANDLOCK_ACCESS_FS_WRITE_FILE) != 0 || + ll_add(fd, tmp, handled) != 0 || + ll_add(fd, workspace, handled) != 0 || + ll_add(fd, state, handled) != 0) { + snprintf(err, errlen, "landlock_add_rule: %s", strerror(errno)); + close(fd); + return -1; + } + if (syscall(SYS_landlock_restrict_self, fd, 0) != 0) { + snprintf(err, errlen, "landlock_restrict_self: %s", + strerror(errno)); + close(fd); + return -1; + } + close(fd); + return 1; +#else + (void)workspace; + (void)state; + (void)tmp; + (void)required; + (void)err; + (void)errlen; + return 0; +#endif +} + +/* --------------------------------------------------------------- seccomp */ + +#ifdef __linux__ +#define KRANG_SYS_MAX 256 + +static int g_allow_overflow; + +static int +add_sys(int *v, size_t *n, int nr) +{ + if (nr < 0) + return 0; + if (*n >= KRANG_SYS_MAX) { + g_allow_overflow = 1; + return 0; + } + v[(*n)++] = nr; + return 1; +} + +static size_t +allow_list(int *v) +{ + size_t n = 0; + + g_allow_overflow = 0; + +#define A(name) add_sys(v, &n, __NR_##name) + A(read); A(write); A(close); A(openat); A(openat2); + A(newfstatat); A(fstat); A(statx); A(lseek); A(pread64); + A(pwrite64); A(readv); A(writev); A(preadv); A(pwritev); + A(mmap); A(mprotect); A(munmap); A(mremap); A(madvise); + A(brk); A(msync); A(mincore); A(memfd_create); + A(pipe); A(pipe2); A(dup); A(dup3); A(fcntl); A(ioctl); + A(sendfile); A(splice); A(tee); A(vmsplice); + A(copy_file_range); A(fallocate); A(sync_file_range); + A(inotify_init1); A(inotify_add_watch); A(inotify_rm_watch); + A(getxattr); A(lgetxattr); A(fgetxattr); A(listxattr); + A(llistxattr); A(flistxattr); A(setxattr); A(lsetxattr); + A(fsetxattr); A(removexattr); A(lremovexattr); A(fremovexattr); + A(utime); A(utimes); A(sync); A(syncfs); A(readahead); + A(unlink); A(unlinkat); A(rename); A(renameat); A(renameat2); + A(link); A(linkat); A(symlink); A(symlinkat); A(readlink); + A(readlinkat); A(mkdir); A(mkdirat); A(rmdir); + A(getdents64); A(chdir); A(fchdir); A(getcwd); + A(chmod); A(fchmod); A(fchmodat); A(chown); A(fchown); + A(fchownat); A(utimensat); A(truncate); A(ftruncate); + A(fsync); A(fdatasync); A(access); A(faccessat); + A(faccessat2); A(umask); A(statfs); A(fstatfs); + A(getpid); A(getppid); A(gettid); A(getuid); A(geteuid); + A(getgid); A(getegid); A(uname); A(sysinfo); A(getrusage); + A(prlimit64); A(getrlimit); A(setrlimit); A(times); + A(kill); A(tgkill); A(tkill); A(rt_sigaction); + A(rt_sigprocmask); A(rt_sigreturn); A(sigaltstack); + A(rt_sigtimedwait); A(rt_sigqueueinfo); A(setitimer); + A(getitimer); + A(nanosleep); A(clock_nanosleep); A(clock_gettime); + A(clock_getres); A(gettimeofday); A(time); A(timer_create); + A(timer_settime); A(timer_gettime); A(timer_delete); + A(timerfd_create); A(timerfd_settime); A(timerfd_gettime); + A(getrandom); A(poll); A(ppoll); A(pselect6); + A(epoll_create1); A(epoll_ctl); A(epoll_pwait); + A(epoll_pwait2); A(socket); A(connect); A(sendto); + A(recvfrom); A(sendmsg); A(recvmsg); A(shutdown); + A(getsockname); A(getpeername); A(setsockopt); A(getsockopt); + A(bind); A(listen); A(accept); A(accept4); + A(fork); A(vfork); A(clone); A(clone3); A(execve); + A(execveat); A(wait4); A(waitid); A(exit); A(exit_group); + A(futex); A(set_robust_list); A(get_robust_list); + A(set_tid_address); A(restart_syscall); A(rseq); + A(sched_yield); A(sched_getaffinity); A(sched_setaffinity); + A(sched_getscheduler); A(sched_setscheduler); + A(sched_getparam); A(sched_setparam); + A(sched_get_priority_max); A(sched_get_priority_min); + A(getpriority); A(setpriority); A(membarrier); + A(prctl); A(capget); A(statx); A(epoll_create1); +#ifdef __NR_arch_prctl + A(arch_prctl); +#endif +#ifdef __NR_open + A(open); +#endif +#ifdef __NR_stat + A(stat); +#endif +#ifdef __NR_lstat + A(lstat); +#endif +#ifdef __NR_dup2 + A(dup2); +#endif +#ifdef __NR_epoll_wait + A(epoll_wait); +#endif +#ifdef __NR_poll + A(poll); +#endif +#ifdef __NR_select + A(select); +#endif +#ifdef __NR_futex_waitv + A(futex_waitv); +#endif +#ifdef __NR_mseal + A(mseal); +#endif +#undef A + return n; +} +#endif + +int +ksandbox_apply_seccomp(int required, char *err, size_t errlen) +{ +#ifdef __linux__ + struct sock_filter filter[KRANG_SYS_MAX * 2 + 8]; + struct sock_fprog prog; + int allowed[KRANG_SYS_MAX]; + size_t n, i, k = 0; + unsigned int arch; + + if (!required) + return 0; + n = allow_list(allowed); + if (g_allow_overflow) { + snprintf(err, errlen, + "seccomp allowlist overflow; raise KRANG_SYS_MAX"); + return -1; + } +#if defined(__x86_64__) + arch = AUDIT_ARCH_X86_64; +#elif defined(__aarch64__) + arch = AUDIT_ARCH_AARCH64; +#else + snprintf(err, errlen, "no seccomp arch for this build"); + return -1; +#endif + filter[k++] = (struct sock_filter)BPF_STMT( + BPF_LD | BPF_W | BPF_ABS, + (unsigned int)offsetof(struct seccomp_data, arch)); + filter[k++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | + BPF_K, arch, 1, 0); + filter[k++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, + SECCOMP_RET_KILL_PROCESS); + filter[k++] = (struct sock_filter)BPF_STMT( + BPF_LD | BPF_W | BPF_ABS, + (unsigned int)offsetof(struct seccomp_data, nr)); + for (i = 0; i < n; i++) { + filter[k++] = (struct sock_filter)BPF_JUMP( + BPF_JMP | BPF_JEQ | BPF_K, (unsigned int)allowed[i], + 0, 1); + filter[k++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, + SECCOMP_RET_ALLOW); + } + filter[k++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, + SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA)); + memset(&prog, 0, sizeof(prog)); + prog.len = (unsigned short)k; + prog.filter = filter; + if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0) != 0) { + snprintf(err, errlen, "seccomp: %s", strerror(errno)); + return -1; + } + return 1; +#else + (void)required; + (void)err; + (void)errlen; + return 0; +#endif +} + +/* ---------------------------------------------------------------- enter */ + +static int +drop_privileges(struct krang *k, char *err, size_t errlen) +{ + struct __user_cap_header_struct hdr; + struct __user_cap_data_struct data[2]; + struct rlimit rl; + + rl.rlim_cur = rl.rlim_max = 256; + if (setrlimit(RLIMIT_NPROC, &rl) != 0) { + snprintf(err, errlen, "RLIMIT_NPROC: %s", strerror(errno)); + return -1; + } + rl.rlim_cur = rl.rlim_max = 4096; + if (setrlimit(RLIMIT_NOFILE, &rl) != 0) { + snprintf(err, errlen, "RLIMIT_NOFILE: %s", strerror(errno)); + return -1; + } + rl.rlim_cur = rl.rlim_max = 0; + if (setrlimit(RLIMIT_CORE, &rl) != 0) { + snprintf(err, errlen, "RLIMIT_CORE: %s", strerror(errno)); + return -1; + } + rl.rlim_cur = rl.rlim_max = (rlim_t)4 * 1024 * 1024 * 1024; + if (setrlimit(RLIMIT_AS, &rl) != 0) { + snprintf(err, errlen, "RLIMIT_AS: %s", strerror(errno)); + return -1; + } + rl.rlim_cur = rl.rlim_max = (rlim_t)1024 * 1024 * 1024; + if (setrlimit(RLIMIT_FSIZE, &rl) != 0) { + snprintf(err, errlen, "RLIMIT_FSIZE: %s", strerror(errno)); + return -1; + } + if (setgroups(0, NULL) != 0) { + snprintf(err, errlen, "setgroups: %s", strerror(errno)); + return -1; + } + if (setgid(k->cfg.sandbox_gid) != 0) { + snprintf(err, errlen, "setgid: %s", strerror(errno)); + return -1; + } + if (setuid(k->cfg.sandbox_uid) != 0) { + snprintf(err, errlen, "setuid: %s", strerror(errno)); + return -1; + } + if (getuid() != k->cfg.sandbox_uid || + geteuid() != k->cfg.sandbox_uid || + getgid() != k->cfg.sandbox_gid) { + snprintf(err, errlen, "privilege drop did not stick"); + return -1; + } + if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) { + snprintf(err, errlen, "PR_SET_NO_NEW_PRIVS: %s", + strerror(errno)); + return -1; + } + (void)prctl(PR_SET_DUMPABLE, 0, 0, 0, 0); + memset(&hdr, 0, sizeof(hdr)); + hdr.version = _LINUX_CAPABILITY_VERSION_3; + hdr.pid = 0; + memset(data, 0, sizeof(data)); + (void)syscall(SYS_capset, &hdr, data); + return 0; +} + +int +ksandbox_enter(struct krang *k, char *err, size_t errlen) +{ + struct khost h; + char marker[2048], path[1200], suite[64], arch[32], id[64], fp[64]; + char rootfs_id[KRANG_PATH]; + + if (k == NULL) + return -1; + if (k->cfg.no_sandbox) { + if (!getenv("KRANG_ALLOW_UNSANDBOXED") || + strcmp(getenv("KRANG_ALLOW_UNSANDBOXED"), "1") != 0) { + snprintf(err, errlen, + "no_sandbox requires KRANG_ALLOW_UNSANDBOXED=1"); + return -1; + } + if (mkdir_p(k->cfg.state_dir, 0755) != 0 || + mkdir_p(k->cfg.workspace, 0700) != 0) { + snprintf(err, errlen, "cannot create state/workspace: %s", + strerror(errno)); + return -1; + } + snprintf(path, sizeof(path), "%s/events.jsonl", + k->cfg.state_dir); + if (klog_open(&k->log, path, err, errlen) != 0) + return -1; + (void)chdir(k->cfg.workspace); + snprintf(k->st.sandbox_uid, sizeof(k->st.sandbox_uid), "%ld", + (long)getuid()); + snprintf(k->st.sandbox_gid, sizeof(k->st.sandbox_gid), "%ld", + (long)getgid()); + snprintf(k->st.landlock, sizeof(k->st.landlock), "off"); + snprintf(k->st.seccomp, sizeof(k->st.seccomp), "off"); + klog_emit(&k->log, "sandbox", "mode", "UNSANDBOXED", NULL); + return 0; + } + if (geteuid() != 0) { + snprintf(err, errlen, + "krang must start as root; it drops privileges itself"); + return -1; + } + if (khost_detect(&h, err, errlen) != 0) + return -1; + if (k->cfg.rootfs_suite[0] != '\0') + snprintf(h.suite, sizeof(h.suite), "%s", k->cfg.rootfs_suite); + snprintf(marker, sizeof(marker), "%s/etc/krang-rootfs", + k->cfg.rootfs); + if (access(marker, R_OK) != 0) { + if (k->cfg.prepare_if_missing) { + if (krootfs_prepare(k, err, errlen) != 0) + return -1; + } else { + snprintf(err, errlen, + "no prepared rootfs at %s (run krang " + "--prepare-rootfs)", k->cfg.rootfs); + return -1; + } + } + strip_setuid(k->cfg.rootfs); + if (mkdir_p(k->cfg.state_dir, 0755) != 0 || + mkdir_p(k->cfg.workspace, 0700) != 0) { + snprintf(err, errlen, "cannot create state/workspace: %s", + strerror(errno)); + return -1; + } + (void)chmod(k->cfg.state_dir, 0755); + (void)chown(k->cfg.state_dir, 0, 0); + snprintf(path, sizeof(path), "%s/sessions", k->cfg.state_dir); + if (mkdir_p(path, 0700) == 0) + (void)chown(path, k->cfg.sandbox_uid, k->cfg.sandbox_gid); + (void)chown(k->cfg.workspace, k->cfg.sandbox_uid, k->cfg.sandbox_gid); + + if (syscall(SYS_unshare, CLONE_NEWNS) != 0) { + snprintf(err, errlen, "unshare(CLONE_NEWNS): %s", + strerror(errno)); + return -1; + } + if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) != 0) { + snprintf(err, errlen, "make mounts private: %s", + strerror(errno)); + return -1; + } + { + static const char *const dirs[] = { + "/var/lib/krang/state", + "/var/lib/krang/state/sessions", + "/var/lib/krang/workspace", + "/var/lib/krang/workspace/tmp", + "/etc/ssl/certs", + "/tmp", + "/dev", + "/opt/krang", + "/opt/krang/lib", + "/opt/krang/plugins", + NULL + }; + int i; + + for (i = 0; dirs[i] != NULL; i++) { + snprintf(path, sizeof(path), "%s%s", k->cfg.rootfs, + dirs[i]); + if (mkdir_p(path, 0755) != 0) { + snprintf(err, errlen, "mkdir %s: %s", path, + strerror(errno)); + return -1; + } + } + } + snprintf(path, sizeof(path), "%s/var/lib/krang/state", + k->cfg.rootfs); + if (mount_bind(k->cfg.state_dir, path, 0, 0) != 0) { + snprintf(err, errlen, "bind state: %s", strerror(errno)); + return -1; + } + snprintf(path, sizeof(path), "%s/var/lib/krang/workspace", + k->cfg.rootfs); + if (mount_bind(k->cfg.workspace, path, 0, 0) != 0) { + snprintf(err, errlen, "bind workspace: %s", strerror(errno)); + return -1; + } + if (access("/etc/ssl/certs", R_OK) == 0) { + snprintf(path, sizeof(path), "%s/etc/ssl/certs", + k->cfg.rootfs); + if (mount_bind("/etc/ssl/certs", path, 1, 1) != 0) + fprintf(stderr, "krang: certs bind failed: %s\n", + strerror(errno)); + } + /* a snapshot is enough for DNS; the chroot has no resolved socket */ + snprintf(path, sizeof(path), "%s/etc/resolv.conf", k->cfg.rootfs); + (void)unlink(path); + if (copy_file("/etc/resolv.conf", path, 0644) != 0) + fprintf(stderr, "krang: resolv.conf: %s\n", strerror(errno)); + + if (k->cfg.nplugins > 0) { + Dl_info di; + char target[1200], base[300]; + const char *lib = NULL; + size_t i; + + if (dladdr((void *)sp_engine_open, &di) != 0 && + di.dli_fname != NULL) + lib = di.dli_fname; + if (lib == NULL) { + snprintf(err, errlen, + "cannot locate libsplinter.so for the plugins"); + return -1; + } + snprintf(target, sizeof(target), + "%s/opt/krang/lib/libsplinter.so", k->cfg.rootfs); + if (touch_file(target) != 0 || + mount_bind(lib, target, 1, 0) != 0) { + snprintf(err, errlen, "bind libsplinter.so: %s", + strerror(errno)); + return -1; + } + for (i = 0; i < k->cfg.nplugins; i++) { + const char *slash = strrchr(k->cfg.plugin[i], '/'); + + base[0] = '\0'; + if (slash != NULL && slash[1] != '\0') + snprintf(base, sizeof(base), "%s", slash + 1); + if (base[0] == '\0') { + snprintf(err, errlen, "bad plugin path %s", + k->cfg.plugin[i]); + return -1; + } + snprintf(target, sizeof(target), + "%s/opt/krang/plugins/%s", k->cfg.rootfs, base); + if (touch_file(target) != 0 || + mount_bind(k->cfg.plugin[i], target, 1, 0) != 0) { + snprintf(err, errlen, "bind plugin %s: %s", + k->cfg.plugin[i], strerror(errno)); + return -1; + } + snprintf(k->plugin_inside[i], + sizeof(k->plugin_inside[i]), + "/opt/krang/plugins/%s", base); + } + (void)setenv("LD_LIBRARY_PATH", "/opt/krang/lib", 1); + } + + if (chroot(k->cfg.rootfs) != 0) { + snprintf(err, errlen, "chroot: %s", strerror(errno)); + return -1; + } + if (chdir(KRANG_IN_WORKSPACE) != 0) { + snprintf(err, errlen, "chdir workspace: %s", strerror(errno)); + return -1; + } + ensure_dev(KRANG_DEV_NULL, 0666, 1, 3); + ensure_dev(KRANG_DEV_ZERO, 0666, 1, 5); + ensure_dev(KRANG_DEV_RANDOM, 0666, 1, 8); + ensure_dev(KRANG_DEV_URANDOM, 0666, 1, 9); + if (mkdir_p(KRANG_IN_TMP, 0700) != 0) + fprintf(stderr, "krang: tmp: %s\n", strerror(errno)); + (void)setenv("HOME", KRANG_IN_WORKSPACE, 1); + (void)setenv("PATH", + "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1); + (void)setenv("TMPDIR", KRANG_IN_TMP, 1); + (void)setenv("LANG", "C.UTF-8", 1); + (void)setenv("SSL_CERT_FILE", + "/etc/ssl/certs/ca-certificates.crt", 1); + + if (klog_open(&k->log, KRANG_IN_EVENTS, err, errlen) != 0) + return -1; + if (drop_privileges(k, err, errlen) != 0) + return -1; + + { + int ll = ksandbox_apply_landlock(KRANG_IN_WORKSPACE, + KRANG_IN_STATE, KRANG_IN_TMP, k->cfg.require_landlock, + err, errlen); + + if (ll < 0) { + snprintf(k->st.landlock, sizeof(k->st.landlock), "error"); + return -1; + } + snprintf(k->st.landlock, sizeof(k->st.landlock), "%s", + ll > 0 ? "applied" : "off"); + } + { + int sc = ksandbox_apply_seccomp(k->cfg.seccomp, err, errlen); + + if (sc < 0) { + snprintf(k->st.seccomp, sizeof(k->st.seccomp), "error"); + return -1; + } + snprintf(k->st.seccomp, sizeof(k->st.seccomp), "%s", + sc > 0 ? "applied" : "off"); + } + + marker_read("/", marker, sizeof(marker)); + (void)marker_field(marker, "id", id, sizeof(id)); + (void)marker_field(marker, "suite", suite, sizeof(suite)); + (void)marker_field(marker, "arch", arch, sizeof(arch)); + (void)marker_field(marker, "tree_fnv1a64", fp, sizeof(fp)); + if (id[0] != '\0') + snprintf(rootfs_id, sizeof(rootfs_id), "%s-%s-%s-%.12s", + id, suite, arch, fp); + else + snprintf(rootfs_id, sizeof(rootfs_id), "%s", k->cfg.rootfs); + snprintf(k->st.rootfs_id, sizeof(k->st.rootfs_id), "%s", rootfs_id); + snprintf(k->st.sandbox_uid, sizeof(k->st.sandbox_uid), "%ld", + (long)getuid()); + snprintf(k->st.sandbox_gid, sizeof(k->st.sandbox_gid), "%ld", + (long)getgid()); + snprintf(k->st.host_id, sizeof(k->st.host_id), "%s", h.id); + snprintf(k->st.host_version, sizeof(k->st.host_version), "%s", + h.version); + snprintf(k->st.host_arch, sizeof(k->st.host_arch), "%s", h.arch); + klog_emit(&k->log, "sandbox", "rootfs", rootfs_id, "uid", + k->st.sandbox_uid, "landlock", k->st.landlock, "seccomp", + k->st.seccomp, NULL); + return 0; +} diff --git a/src/session.c b/src/session.c new file mode 100644 index 0000000..0df0945 --- /dev/null +++ b/src/session.c @@ -0,0 +1,161 @@ +/* + * krang -- reading the one session. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#include +#include +#include +#include +#include + +#include "krang.h" + +static void +session_info(struct krang *k, struct sp_session_info *si) +{ + memset(si, 0, sizeof(*si)); + snprintf(si->id, sizeof(si->id), "%s", KRANG_SESSION_ID); + snprintf(si->dir, sizeof(si->dir), "%s", + k != NULL && k->session_dir[0] != '\0' ? k->session_dir : + KRANG_IN_SESSIONS); +} + +int +ksession_meta(struct krang *k, size_t *records, unsigned long long *bytes, + char *goal, size_t goalcap, char *gstate, size_t gstatecap) +{ + struct sp_session_info si; + struct stat st; + char path[640]; + struct sp_buf err; + + if (k == NULL) + return -1; + session_info(k, &si); + if (records != NULL) + *records = 0; + if (bytes != NULL) + *bytes = 0; + if (goal != NULL && goalcap > 0) + goal[0] = '\0'; + if (gstate != NULL && gstatecap > 0) + gstate[0] = '\0'; + if (sp_buf_init(&err) != 0) + return -1; + if (records != NULL) { + size_t n = 0; + + if (sp_session_count(&si, &n, &err) == 0) + *records = n; + } + sp_buf_free(&err); + snprintf(path, sizeof(path), "%s/%s.jsonl", si.dir, si.id); + if (bytes != NULL && stat(path, &st) == 0) + *bytes = (unsigned long long)st.st_size; + if (goal != NULL && goalcap > 0) + (void)sp_session_get_goal(si.dir, si.id, goal, goalcap); + if (gstate != NULL && gstatecap > 0) + (void)sp_session_get_goal_state(si.dir, si.id, gstate, + gstatecap); + return 0; +} + +static int +valid_line(const char *line) +{ + const char *p = line; + size_t n; + + if (p == NULL) + return 0; + while (*p == ' ' || *p == '\t' || *p == '\r') + p++; + if (*p != '{') + return 0; + n = strlen(p); + while (n > 0 && (p[n - 1] == '\n' || p[n - 1] == '\r' || + p[n - 1] == ' ' || p[n - 1] == '\t')) + n--; + return n > 1 && p[n - 1] == '}'; +} + +int +ksession_history(struct krang *k, struct sp_buf *out, size_t limit) +{ + struct sp_session_info si; + char path[640], *line = NULL; + size_t linecap = 0, n = 0, i, start; + char **keep; + FILE *f; + + (void)k; + if (out == NULL) + return -1; + if (limit == 0 || limit > 500) + limit = 100; + session_info(k, &si); + snprintf(path, sizeof(path), "%s/%s.jsonl", si.dir, si.id); + f = fopen(path, "r"); + if (f == NULL) { + (void)sp_buf_puts(out, "[]"); + return errno == ENOENT ? 0 : -1; + } + keep = calloc(limit, sizeof(*keep)); + if (keep == NULL) { + fclose(f); + return -1; + } + while (getline(&line, &linecap, f) > 0) { + char *copy; + + k_trim(line); + if (!valid_line(line)) + continue; + copy = k_strdup(line); + if (copy == NULL) + continue; + free(keep[n % limit]); + keep[n % limit] = copy; + n++; + } + free(line); + fclose(f); + (void)sp_buf_puts(out, "["); + start = n > limit ? n - limit : 0; + for (i = start; i < n; i++) { + if (i > start) + (void)sp_buf_puts(out, ","); + (void)sp_buf_puts(out, keep[i % limit]); + } + (void)sp_buf_puts(out, "]"); + for (i = 0; i < limit; i++) + free(keep[i]); + free(keep); + return 0; +} + +long +ksession_born(struct krang *k) +{ + struct sp_session_info si; + char path[640], line[512]; + FILE *f; + long born = 0; + + (void)k; + session_info(k, &si); + snprintf(path, sizeof(path), "%s/%s.meta", si.dir, si.id); + f = fopen(path, "r"); + if (f == NULL) + return 0; + while (fgets(line, sizeof(line), f) != NULL) { + if (strncmp(line, "created=", 8) == 0) { + born = strtol(line + 8, NULL, 10); + break; + } + } + fclose(f); + return born; +} diff --git a/src/state.c b/src/state.c new file mode 100644 index 0000000..74a9063 --- /dev/null +++ b/src/state.c @@ -0,0 +1,338 @@ +/* + * krang -- the snapshot the dashboard, the HTTP API and MCP read. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#include +#include + +#include "krang.h" + +static void +jstr(struct sp_buf *b, const char *key, const char *val) +{ + (void)sp_buf_puts(b, "\""); + (void)sp_buf_puts(b, key); + (void)sp_buf_puts(b, "\":\""); + k_json_escape(b, val != NULL ? val : ""); + (void)sp_buf_puts(b, "\""); +} + +static void +jnum(struct sp_buf *b, const char *key, long long v) +{ + (void)sp_buf_printf(b, "\"%s\":%lld", key, v); +} + +static void +jstr_redacted(struct krang *k, struct sp_buf *b, const char *key, + const char *val) +{ + struct sp_buf clean; + + if (val == NULL) + val = ""; + if (k->log.secret[0] == '\0') { + jstr(b, key, val); + return; + } + if (sp_buf_init(&clean) != 0) { + jstr(b, key, val); + return; + } + k_redact(&clean, val, k->log.secret); + jstr(b, key, clean.p != NULL ? clean.p : ""); + sp_buf_free(&clean); +} + +void +kstate_sync(struct krang *k) +{ + struct sp_engine_state es; + + if (k == NULL || k->eng == NULL) + return; + memset(&es, 0, sizeof(es)); + if (sp_engine_state(k->eng, &es) != 0) + return; + pthread_mutex_lock(&k->lock); + snprintf(k->st.model, sizeof(k->st.model), "%s", es.model); + snprintf(k->st.agent, sizeof(k->st.agent), "%s", es.agent); + snprintf(k->st.session, sizeof(k->st.session), "%s", es.session); + k->st.tokens_in = (unsigned long)es.tokens_in; + k->st.tokens_out = (unsigned long)es.tokens_out; + k->st.tokens_cached = (unsigned long)es.cached_total; + k->st.cost = es.cost; + k->st.ctx_used = es.ctx_used; + k->st.ctx_max = es.ctx_max; + k->st.steps = (unsigned long)es.steps; + k->st.tool_calls = (unsigned long)es.calls; + k->st.compactions = (unsigned long)es.compactions; + k->st.busy = es.busy; + k->st.waiting = es.waiting; + pthread_mutex_unlock(&k->lock); +} + +void +kstate_json(struct krang *k, struct sp_buf *out) +{ + struct kstats s; + char now[64]; + struct sp_buf cfg; + + if (k == NULL || out == NULL) + return; + pthread_mutex_lock(&k->lock); + s = k->st; + pthread_mutex_unlock(&k->lock); + k_format_time(k_now(), now, sizeof(now)); + sp_buf_init(&cfg); + kconfig_json(&k->cfg, &cfg, 1); + + (void)sp_buf_puts(out, "{"); + jstr(out, "version", KRANG_VERSION); + (void)sp_buf_puts(out, ","); + jstr(out, "time", now); + (void)sp_buf_puts(out, ","); + jstr(out, "state", s.state); + (void)sp_buf_puts(out, ","); + jnum(out, "started_at", s.started_at); + (void)sp_buf_puts(out, ","); + jnum(out, "born_at", s.born_at); + (void)sp_buf_puts(out, ","); + jnum(out, "uptime", (long long)(k_now() - s.started_at)); + (void)sp_buf_puts(out, ","); + jstr_redacted(k, out, "goal", s.goal); + (void)sp_buf_puts(out, ","); + jstr(out, "goal_state", s.goal_state[0] != '\0' ? s.goal_state : "open"); + (void)sp_buf_puts(out, ","); + + (void)sp_buf_puts(out, "\"model\":{"); + jstr(out, "name", s.model); + (void)sp_buf_puts(out, ","); + jstr(out, "agent", s.agent); + (void)sp_buf_puts(out, "},"); + + (void)sp_buf_puts(out, "\"session\":{"); + jstr(out, "id", s.session); + (void)sp_buf_puts(out, ","); + jnum(out, "records", (long long)s.session_records); + (void)sp_buf_puts(out, ","); + jnum(out, "bytes", (long long)s.session_bytes); + (void)sp_buf_puts(out, "},"); + + (void)sp_buf_puts(out, "\"impulses\":{"); + jnum(out, "total", (long long)s.impulses); + (void)sp_buf_puts(out, ","); + jnum(out, "self", (long long)s.self_impulses); + (void)sp_buf_puts(out, ","); + jnum(out, "external", (long long)s.external_impulses); + (void)sp_buf_puts(out, ","); + jnum(out, "last_at", s.last_impulse_at); + (void)sp_buf_puts(out, ","); + jnum(out, "next_at", s.next_impulse_at); + (void)sp_buf_puts(out, "},"); + + (void)sp_buf_puts(out, "\"turns\":{"); + jnum(out, "total", (long long)s.turns); + (void)sp_buf_puts(out, ","); + jnum(out, "steps", (long long)s.steps); + (void)sp_buf_puts(out, ","); + jnum(out, "tool_calls", (long long)s.tool_calls); + (void)sp_buf_puts(out, ","); + jnum(out, "tool_failures", (long long)s.tool_failures); + (void)sp_buf_puts(out, ","); + jnum(out, "denials", (long long)s.denials); + (void)sp_buf_puts(out, ","); + jnum(out, "last_rc", s.last_turn_rc); + (void)sp_buf_puts(out, "},"); + + (void)sp_buf_puts(out, "\"tokens\":{"); + jnum(out, "in", (long long)s.tokens_in); + (void)sp_buf_puts(out, ","); + jnum(out, "out", (long long)s.tokens_out); + (void)sp_buf_puts(out, ","); + jnum(out, "cached", (long long)s.tokens_cached); + (void)sp_buf_puts(out, ","); + jnum(out, "ctx_used", (long long)s.ctx_used); + (void)sp_buf_puts(out, ","); + jnum(out, "ctx_max", (long long)s.ctx_max); + (void)sp_buf_puts(out, ","); + (void)sp_buf_printf(out, "\"cost\":%.6f", s.cost); + (void)sp_buf_puts(out, "},"); + + (void)sp_buf_puts(out, "\"chat\":{"); + jnum(out, "in", (long long)s.chat_in); + (void)sp_buf_puts(out, ","); + jnum(out, "out", (long long)s.chat_out); + (void)sp_buf_puts(out, ","); + jnum(out, "pending", (long long)s.chat_pending); + (void)sp_buf_puts(out, "},"); + + (void)sp_buf_puts(out, "\"stuck\":{"); + jnum(out, "level", k->stuck.level); + (void)sp_buf_puts(out, ","); + jnum(out, "events", (long long)s.stuck_events); + (void)sp_buf_puts(out, ","); + jnum(out, "blocked", (long long)s.blocked_events); + (void)sp_buf_puts(out, ","); + jnum(out, "attempts", k->stuck.attempts); + (void)sp_buf_puts(out, "},"); + + (void)sp_buf_puts(out, "\"busy\":"); + (void)sp_buf_puts(out, s.busy ? "true" : "false"); + (void)sp_buf_puts(out, ","); + (void)sp_buf_puts(out, "\"waiting\":"); + (void)sp_buf_puts(out, s.waiting ? "true" : "false"); + (void)sp_buf_puts(out, ","); + jnum(out, "compactions", (long long)s.compactions); + (void)sp_buf_puts(out, ","); + jnum(out, "self_edits", (long long)s.self_edits); + (void)sp_buf_puts(out, ","); + jnum(out, "goal_completes", (long long)s.goal_completes); + (void)sp_buf_puts(out, ","); + jstr_redacted(k, out, "last_error", s.last_error); + (void)sp_buf_puts(out, ","); + jstr_redacted(k, out, "last_outcome", s.last_outcome); + (void)sp_buf_puts(out, ","); + jstr(out, "last_tool", s.last_tool); + (void)sp_buf_puts(out, ","); + jstr_redacted(k, out, "last_tool_result", s.last_tool_result); + (void)sp_buf_puts(out, ","); + + (void)sp_buf_puts(out, "\"sandbox\":{"); + jstr(out, "rootfs", s.rootfs_id); + (void)sp_buf_puts(out, ","); + jstr(out, "uid", s.sandbox_uid); + (void)sp_buf_puts(out, ","); + jstr(out, "gid", s.sandbox_gid); + (void)sp_buf_puts(out, ","); + jstr(out, "landlock", s.landlock); + (void)sp_buf_puts(out, ","); + jstr(out, "seccomp", s.seccomp); + (void)sp_buf_puts(out, ","); + jstr(out, "host", s.host_id); + (void)sp_buf_puts(out, ","); + jstr(out, "host_version", s.host_version); + (void)sp_buf_puts(out, ","); + jstr(out, "host_arch", s.host_arch); + (void)sp_buf_puts(out, "},"); + + (void)sp_buf_puts(out, "\"config\":"); + (void)sp_buf_puts(out, cfg.p != NULL ? cfg.p : "{}"); + (void)sp_buf_puts(out, "}"); + sp_buf_free(&cfg); +} + +void +kstate_impulses_json(struct krang *k, struct sp_buf *out, size_t max) +{ + size_t i, n, start; + unsigned long seq; + + if (k == NULL || out == NULL) + return; + pthread_mutex_lock(&k->lock); + n = k->impulse_seq < KRANG_IMPULSE_RING ? (size_t)k->impulse_seq : + KRANG_IMPULSE_RING; + seq = k->impulse_seq; + pthread_mutex_unlock(&k->lock); + + if (max > 0 && n > max) + n = max; + if (n == 0) { + (void)sp_buf_puts(out, "[]"); + return; + } + start = (size_t)(seq % KRANG_IMPULSE_RING); + /* the ring slot seq % RING holds impulse seq; walk backwards */ + (void)sp_buf_puts(out, "["); + for (i = 0; i < n; i++) { + size_t slot = (start + KRANG_IMPULSE_RING - 1 - i) % + KRANG_IMPULSE_RING; + struct kimpulse imp; + + pthread_mutex_lock(&k->lock); + imp = k->impulses[slot]; + pthread_mutex_unlock(&k->lock); + if (i > 0) + (void)sp_buf_puts(out, ","); + (void)sp_buf_puts(out, "{"); + jnum(out, "id", (long long)imp.id); + (void)sp_buf_puts(out, ","); + jnum(out, "at", imp.at); + (void)sp_buf_puts(out, ","); + jstr(out, "cause", imp.cause); + (void)sp_buf_puts(out, ","); + jnum(out, "rc", imp.rc); + (void)sp_buf_puts(out, ","); + jnum(out, "steps", (long long)imp.steps); + (void)sp_buf_puts(out, ","); + jnum(out, "tool_calls", (long long)imp.tool_calls); + (void)sp_buf_puts(out, ","); + jnum(out, "tokens_in", (long long)imp.tokens_in); + (void)sp_buf_puts(out, ","); + jnum(out, "tokens_out", (long long)imp.tokens_out); + (void)sp_buf_puts(out, ","); + (void)sp_buf_printf(out, "\"cost\":%.6f,", imp.cost); + jstr_redacted(k, out, "answer", imp.answer); + (void)sp_buf_puts(out, "}"); + } + (void)sp_buf_puts(out, "]"); +} + +void +kstate_tools_json(struct krang *k, struct sp_buf *out) +{ + struct sp_registry *reg; + const struct sp_tool *tools; + size_t n = 0, i; + + if (k == NULL || out == NULL) + return; + reg = k->eng != NULL ? sp_engine_registry(k->eng) : NULL; + tools = reg != NULL ? sp_registry_tools(reg, &n) : NULL; + (void)sp_buf_puts(out, "["); + for (i = 0; i < n; i++) { + if (i > 0) + (void)sp_buf_puts(out, ","); + (void)sp_buf_puts(out, "{"); + jstr(out, "name", tools[i].name); + (void)sp_buf_puts(out, ","); + jstr(out, "description", tools[i].description); + (void)sp_buf_puts(out, ","); + jnum(out, "auth", tools[i].auth); + (void)sp_buf_puts(out, "}"); + } + (void)sp_buf_puts(out, "]"); +} + +void +kstate_sandbox_json(struct krang *k, struct sp_buf *out) +{ + struct kstats s; + + if (k == NULL || out == NULL) + return; + pthread_mutex_lock(&k->lock); + s = k->st; + pthread_mutex_unlock(&k->lock); + (void)sp_buf_puts(out, "{"); + jstr(out, "rootfs", s.rootfs_id); + (void)sp_buf_puts(out, ","); + jstr(out, "uid", s.sandbox_uid); + (void)sp_buf_puts(out, ","); + jstr(out, "gid", s.sandbox_gid); + (void)sp_buf_puts(out, ","); + jstr(out, "landlock", s.landlock); + (void)sp_buf_puts(out, ","); + jstr(out, "seccomp", s.seccomp); + (void)sp_buf_puts(out, ","); + jstr(out, "host", s.host_id); + (void)sp_buf_puts(out, ","); + jstr(out, "host_version", s.host_version); + (void)sp_buf_puts(out, ","); + jstr(out, "host_arch", s.host_arch); + (void)sp_buf_puts(out, "}"); +} diff --git a/src/stuck.c b/src/stuck.c new file mode 100644 index 0000000..d919674 --- /dev/null +++ b/src/stuck.c @@ -0,0 +1,131 @@ +/* + * krang -- noticing that the same thing is not working. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#include +#include + +#include "krang.h" + +static void +copy_result(char *dst, size_t cap, const char *obs) +{ + size_t n; + + if (cap == 0) + return; + if (obs == NULL) + obs = ""; + n = strlen(obs); + if (n >= cap) + n = cap - 1; + memcpy(dst, obs, n); + dst[n] = '\0'; + /* collapse newlines so the prompt stays readable */ + for (n = 0; dst[n] != '\0'; n++) + if (dst[n] == '\n' || dst[n] == '\r' || dst[n] == '\t') + dst[n] = ' '; +} + +void +kstuck_call(struct kstuck *s, const char *tool, const char *args) +{ + char call[512]; + + if (s == NULL) + return; + snprintf(call, sizeof(call), "%s %.400s", + tool != NULL ? tool : "?", args != NULL ? args : ""); + if (s->last_call[0] != '\0' && strcmp(s->last_call, call) == 0) { + s->repeated_calls++; + } else { + s->repeated_calls = 0; + snprintf(s->last_call, sizeof(s->last_call), "%s", call); + } +} + +void +kstuck_result(struct kstuck *s, const char *tool, const char *obs, + int is_error) +{ + char first[KRANG_ERR]; + + if (s == NULL) + return; + copy_result(first, sizeof(first), obs); + if (!is_error) { + s->consecutive_failures = 0; + s->repeated_calls = 0; + s->same_error = 0; + return; + } + s->consecutive_failures++; + if (s->last_error[0] != '\0' && + strncmp(s->last_error, first, 160) == 0) { + s->same_error++; + } else { + s->same_error = 1; + snprintf(s->last_error, sizeof(s->last_error), "%s", first); + } + if (tool != NULL && *tool != '\0') + (void)tool; +} + +void +kstuck_turn(struct kstuck *s, int rc, unsigned long calls, int mutating) +{ + if (s == NULL) + return; + if (rc != 0) { + s->consecutive_failures++; + return; + } + if (calls == 0 && !mutating) { + s->no_progress_turns++; + } else { + s->no_progress_turns = 0; + } + if (mutating) + kstuck_reset(s); +} + +int +kstuck_level(const struct kstuck *s) +{ + if (s == NULL) + return 0; + if (s->same_error >= 2 || s->consecutive_failures >= 3 || + s->repeated_calls >= 2 || s->no_progress_turns >= 3) + return s->attempts >= 4 ? 3 : (s->attempts >= 2 ? 2 : 1); + return 0; +} + +int +kstuck_should_check(struct kstuck *s, long now) +{ + int level; + + if (s == NULL) + return 0; + level = kstuck_level(s); + if (level == 0 || level >= 3) + return 0; + if (s->attempts >= 4) + return 0; + if (s->last_check != 0 && now - s->last_check < 30) + return 0; + s->attempts++; + s->last_check = now; + s->level = level; + return level; +} + +void +kstuck_reset(struct kstuck *s) +{ + if (s == NULL) + return; + memset(s, 0, sizeof(*s)); +} diff --git a/src/util.c b/src/util.c new file mode 100644 index 0000000..a43ac58 --- /dev/null +++ b/src/util.c @@ -0,0 +1,165 @@ +/* + * krang -- small helpers. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "krang.h" + +volatile sig_atomic_t krang_stop; + +long +k_now(void) +{ + return (long)time(NULL); +} + +void +k_sleep_ms(int ms) +{ + struct timespec ts; + + if (ms <= 0) + return; + ts.tv_sec = ms / 1000; + ts.tv_nsec = (long)(ms % 1000) * 1000000L; + while (nanosleep(&ts, &ts) != 0 && errno == EINTR) + ; +} + +void +k_trim(char *s) +{ + char *p; + size_t n; + + if (s == NULL) + return; + p = s; + while (*p != '\0' && isspace((unsigned char)*p)) + p++; + if (p != s) + memmove(s, p, strlen(p) + 1); + n = strlen(s); + while (n > 0 && isspace((unsigned char)s[n - 1])) + s[--n] = '\0'; +} + +int +k_starts_with(const char *s, const char *p) +{ + size_t n; + + if (s == NULL || p == NULL) + return 0; + n = strlen(p); + return strncmp(s, p, n) == 0; +} + +char * +k_strdup(const char *s) +{ + char *p; + size_t n; + + if (s == NULL) + s = ""; + n = strlen(s); + p = malloc(n + 1); + if (p != NULL) + memcpy(p, s, n + 1); + return p; +} + +void +k_json_escape(struct sp_buf *b, const char *s) +{ + if (b == NULL) + return; + if (s == NULL) + s = ""; + (void)sp_json_escape(b, s); +} + +void +k_redact(struct sp_buf *out, const char *text, const char *secret) +{ + const char *p, *hit; + size_t n; + + if (out == NULL) + return; + if (text == NULL) + text = ""; + if (secret == NULL || *secret == '\0' || strlen(secret) < 4) { + (void)sp_buf_puts(out, text); + return; + } + n = strlen(secret); + p = text; + while ((hit = strstr(p, secret)) != NULL) { + (void)sp_buf_add(out, p, (size_t)(hit - p)); + (void)sp_buf_puts(out, "[redacted]"); + p = hit + n; + } + (void)sp_buf_puts(out, p); +} + +int +k_write_all(int fd, const void *buf, size_t len) +{ + const char *p = buf; + size_t off = 0; + + while (off < len) { + ssize_t n = write(fd, p + off, len - off); + + if (n < 0) { + if (errno == EINTR) + continue; + return -1; + } + if (n == 0) + return -1; + off += (size_t)n; + } + return 0; +} + +void +k_format_time(long t, char *buf, size_t cap) +{ + struct tm tm; + + if (buf == NULL || cap == 0) + return; + if (t <= 0 || gmtime_r(&(time_t){ t }, &tm) == NULL) { + snprintf(buf, cap, "-"); + return; + } + if (strftime(buf, cap, "%Y-%m-%dT%H:%M:%SZ", &tm) == 0) + snprintf(buf, cap, "-"); +} + +int +k_parse_bool(const char *s, int dflt) +{ + if (s == NULL || *s == '\0') + return dflt; + if (!strcmp(s, "1") || !strcmp(s, "yes") || !strcmp(s, "true") || + !strcmp(s, "on")) + return 1; + if (!strcmp(s, "0") || !strcmp(s, "no") || !strcmp(s, "false") || + !strcmp(s, "off")) + return 0; + return dflt; +} diff --git a/tests/root-integration.sh b/tests/root-integration.sh new file mode 100755 index 0000000..9e4c828 --- /dev/null +++ b/tests/root-integration.sh @@ -0,0 +1,139 @@ +#!/bin/sh +# krang -- root-only integration test. +# +# Copyright (c) 2026 Konrad Lother +# License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. +# +# This is the part the offline suite cannot prove: debootstrap, mount namespace, +# chroot, uid drop, Landlock, seccomp and the event log ownership. It does not +# start the autonomous daemon or a provider; it runs --sandbox-test, one +# scripted turn that asks `id -u` and tries `mount(2)` inside the cage. +# +# sudo tests/root-integration.sh +# +# Environment: +# KRANG_TEST_DIR work directory (default: mktemp -d /var/tmp/...) +# KRANG_TEST_ROOTFS reuse an already prepared rootfs, skip debootstrap +# KRANG_KEEP=1 keep the work directory for inspection +set -eu + +if [ "$(id -u)" != "0" ]; then + echo "root-integration: must run as root (sudo tests/root-integration.sh)" >&2 + exit 1 +fi +[ -x ./krang ] || { echo "root-integration: build ./krang first (make)" >&2; exit 1; } + +if [ -n "${KRANG_TEST_ROOTFS:-}" ]; then + ROOTFS=$KRANG_TEST_ROOTFS +else + if ! command -v debootstrap >/dev/null 2>&1 && + [ ! -x /usr/sbin/debootstrap ]; then + echo "root-integration: debootstrap is not installed" >&2 + exit 1 + fi +fi + +WORK=${KRANG_TEST_DIR:-$(mktemp -d /var/tmp/krang-root.XXXXXX)} +KRANG_ROOT=$(cd "$(dirname "$0")/.." && pwd) +SPLINTER=${SPLINTER:-$KRANG_ROOT/../splinter} +PLUGIN=$SPLINTER/plugins/clock/clock.so +test -r "$PLUGIN" || { + echo "root-integration: missing $PLUGIN (build ../splinter first)" >&2 + exit 1 +} +STATE=$WORK/state +WORKSPACE=$WORK/workspace +CONF=$WORK/krang.conf +if [ -z "${KRANG_TEST_ROOTFS:-}" ]; then + ROOTFS=$WORK/rootfs +fi +mkdir -p "$STATE" "$WORKSPACE" + +cleanup() { + if [ "${KRANG_KEEP:-0}" = "1" ]; then + echo "root-integration: kept $WORK" + return + fi + rm -rf "$WORK" +} +trap cleanup EXIT INT TERM + +cat >"$CONF" <&2 + exit 1 + } +fi + +echo "== sandbox-test (unshare, chroot, uid drop, Landlock, seccomp)" +./krang --sandbox-test --config "$CONF" + +EVENTS=$STATE/events.jsonl +SESSIONS=$STATE/sessions/krang.jsonl +test -s "$EVENTS" +test -s "$SESSIONS" + +echo "== event log ownership" +EV_UID=$(stat -c %u "$EVENTS") +EV_MODE=$(stat -c %a "$EVENTS") +echo "events: uid=$EV_UID mode=$EV_MODE" +[ "$EV_UID" = "0" ] || { echo "event log is not root-owned" >&2; exit 1; } +[ "$EV_MODE" = "600" ] || { echo "event log mode is not 600" >&2; exit 1; } + +echo "== session ownership" +S_UID=$(stat -c %u "$SESSIONS") +echo "session: uid=$S_UID" +[ "$S_UID" = "65534" ] || { echo "session is not owned by the sandbox uid" >&2; exit 1; } + +echo "== tool observations" +grep -q '"name":"clock"' "$EVENTS" || { + echo "the clock plugin was not loaded" >&2 + exit 1 +} +grep -q '65534' "$EVENTS" || { echo "id -u did not report 65534" >&2; exit 1; } +grep -q 'mount-denied\|Operation not permitted\|Permission denied' "$EVENTS" || { + echo "mount was not denied" >&2 + exit 1 +} +grep -q 'sandbox-test-ok' "$EVENTS" || { echo "answer missing" >&2; exit 1; } + +if command -v setpriv >/dev/null 2>&1; then + if setpriv --reuid=65534 --regid=65534 --clear-groups \ + test -r "$EVENTS" 2>/dev/null; then + echo "event log is readable by the sandbox uid" >&2 + exit 1 + fi + echo "== sandbox uid cannot read the event log: ok" +fi + +echo "== root-integration: ok" diff --git a/tests/test_daemon.c b/tests/test_daemon.c new file mode 100644 index 0000000..c06bdde --- /dev/null +++ b/tests/test_daemon.c @@ -0,0 +1,130 @@ +/* + * krang -- offline end-to-end daemon test. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * Runs kdaemon_run itself: temp state/workspace, script transport, exactly one + * impulse (the birth), no provider, no network, no root. The dashboard and MCP + * listeners are bound to ephemeral loopback ports and stopped by the daemon. + */ +#include +#include +#include +#include +#include + +#include "krang.h" + +static int failures; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \ + #cond); \ + failures++; \ + } \ +} while (0) + +static int +contains(const char *hay, const char *needle) +{ + return hay != NULL && strstr(hay, needle) != NULL; +} + +static void +read_file(const char *path, char *buf, size_t cap) +{ + FILE *f; + size_t n; + + buf[0] = '\0'; + f = fopen(path, "r"); + if (f == NULL) + return; + n = fread(buf, 1, cap - 1, f); + buf[n] = '\0'; + fclose(f); +} + +int +main(void) +{ + struct krang k; + char tmpl[] = "/tmp/krang-daemon-XXXXXX"; + char *dir; + char path[800], logbuf[65536]; + size_t records = 0; + unsigned long long bytes = 0; + int rc; + + dir = mkdtemp(tmpl); + CHECK(dir != NULL); + if (dir == NULL) + return 1; + memset(&k, 0, sizeof(k)); + k.log.fd = -1; + pthread_mutex_init(&k.lock, NULL); + pthread_cond_init(&k.cond, NULL); + sp_buf_init(&k.err); + kconfig_defaults(&k.cfg); + snprintf(k.cfg.goal, sizeof(k.cfg.goal), "be born once"); + snprintf(k.cfg.endpoint, sizeof(k.cfg.endpoint), + "http://127.0.0.1:1/v1"); + snprintf(k.cfg.model, sizeof(k.cfg.model), "test-model"); + snprintf(k.cfg.state_dir, sizeof(k.cfg.state_dir), "%s/state", dir); + snprintf(k.cfg.workspace, sizeof(k.cfg.workspace), "%s/workspace", dir); + snprintf(k.cfg.rootfs, sizeof(k.cfg.rootfs), "%s/rootfs", dir); + snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir); + snprintf(k.script, sizeof(k.script), "%s/script.txt", dir); + snprintf(k.cfg.dashboard_host, sizeof(k.cfg.dashboard_host), + "127.0.0.1"); + snprintf(k.cfg.mcp_host, sizeof(k.cfg.mcp_host), "127.0.0.1"); + k.cfg.dashboard_port = 0; + k.cfg.mcp_port = 0; + k.max_impulses = 1; + (void)mkdir(k.cfg.state_dir, 0755); + (void)mkdir(k.cfg.workspace, 0700); + (void)mkdir(k.session_dir, 0700); + snprintf(path, sizeof(path), "%s/events.jsonl", k.cfg.state_dir); + CHECK(klog_open(&k.log, path, k.last_error, + sizeof(k.last_error)) == 0); + { + FILE *f = fopen(k.script, "w"); + + CHECK(f != NULL); + if (f == NULL) + return 1; + fprintf(f, "tool echo {\"text\":\"daemon\"}\n"); + fprintf(f, "answer daemon-birth-ok\n"); + fclose(f); + } + + rc = kdaemon_run(&k); + CHECK(rc == 0); + CHECK(k.st.impulses == 1); + CHECK(k.st.turns == 1); + CHECK(k.st.born_at > 0); + CHECK(contains(k.st.last_outcome, "daemon-birth-ok")); + CHECK(k.st.session_records >= 3); + CHECK(k.log.fd == -1); /* kdaemon_run closed it */ + (void)ksession_meta(&k, &records, &bytes, NULL, 0, NULL, 0); + CHECK(records >= 3); + CHECK(bytes > 0); + snprintf(path, sizeof(path), "%s/events.jsonl", k.cfg.state_dir); + read_file(path, logbuf, sizeof(logbuf)); + CHECK(contains(logbuf, "\"kind\":\"birth\"")); + CHECK(contains(logbuf, "\"kind\":\"turn_end\"")); + CHECK(contains(logbuf, "\"kind\":\"stop\"")); + CHECK(contains(logbuf, "daemon-birth-ok")); + + pthread_mutex_destroy(&k.lock); + pthread_cond_destroy(&k.cond); + sp_buf_free(&k.err); + if (failures != 0) { + fprintf(stderr, "%d test(s) failed\n", failures); + return 1; + } + printf("test_daemon: ok\n"); + return 0; +} diff --git a/tests/test_engine.c b/tests/test_engine.c new file mode 100644 index 0000000..a6ca9d9 --- /dev/null +++ b/tests/test_engine.c @@ -0,0 +1,140 @@ +/* + * krang -- offline integration test: one scripted turn through the engine. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * No network, no key, no model. The mock transport replays the script; the + * session and the event log are real. + */ +#include +#include +#include +#include +#include + +#include "krang.h" +#include "i18n.h" + +static int failures; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \ + #cond); \ + failures++; \ + } \ +} while (0) + +static int +contains(const char *hay, const char *needle) +{ + return hay != NULL && strstr(hay, needle) != NULL; +} + +int +main(void) +{ + struct krang k; + char tmpl[512], *dir, script[700], logpath[800], answer[KRANG_GOAL]; + size_t records = 0; + unsigned long long bytes = 0; + FILE *f; + + dir = mkdtemp(strcpy(tmpl, "/tmp/krang-engine-XXXXXX")); + CHECK(dir != NULL); + if (dir == NULL) + return 1; + (void)chdir(dir); + (void)setenv("HOME", dir, 1); + (void)sp_i18n_init("en"); + + memset(&k, 0, sizeof(k)); + k.log.fd = -1; + pthread_mutex_init(&k.lock, NULL); + pthread_cond_init(&k.cond, NULL); + sp_buf_init(&k.err); + kconfig_defaults(&k.cfg); + snprintf(k.cfg.goal, sizeof(k.cfg.goal), "prove the engine"); + snprintf(k.cfg.endpoint, sizeof(k.cfg.endpoint), + "http://127.0.0.1:1/v1"); + snprintf(k.cfg.model, sizeof(k.cfg.model), "test-model"); + snprintf(k.cfg.plugin[0], sizeof(k.cfg.plugin[0]), "%s", + KRANG_TEST_PLUGIN); + k.cfg.nplugins = 1; + snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir); + (void)mkdir(k.session_dir, 0700); + snprintf(logpath, sizeof(logpath), "%s/events.jsonl", dir); + CHECK(klog_open(&k.log, logpath, k.last_error, + sizeof(k.last_error)) == 0); + { + struct sp_buf sp; + + sp_buf_init(&sp); + k_system_prompt(&k, &sp); + snprintf(k.system_prompt, sizeof(k.system_prompt), "%s", + sp.p != NULL ? sp.p : ""); + sp_buf_free(&sp); + } + snprintf(script, sizeof(script), "%s/script.txt", dir); + f = fopen(script, "w"); + CHECK(f != NULL); + if (f == NULL) + return 1; + fprintf(f, "tool echo {\"text\":\"from-script\"}\n"); + fprintf(f, "answer hello-from-script\n"); + fclose(f); + + CHECK(kengine_open(&k, script, k.last_error, + sizeof(k.last_error)) == 0); + CHECK(k.eng != NULL); + if (k.eng != NULL) { + CHECK(sp_registry_find(sp_engine_registry(k.eng), + "clock") != NULL); + int rc = krun_turn(&k, "prove the apparatus", "test", NULL); + + CHECK(rc == 0); + snprintf(answer, sizeof(answer), "%s", k.st.last_outcome); + CHECK(contains(answer, "hello-from-script")); + CHECK(contains(k.st.last_tool, "echo")); + CHECK(k.st.tool_calls >= 1); + (void)ksession_meta(&k, &records, &bytes, NULL, 0, NULL, 0); + CHECK(records >= 3); + CHECK(bytes > 0); + { + const struct sp_tool *jt = sp_registry_find( + sp_engine_registry(k.eng), "journal_search"); + struct sp_buf jb; + + CHECK(jt != NULL); + if (jt != NULL) { + sp_buf_init(&jb); + CHECK(jt->run("{\"query\":" + "\"hello-from-script\"}", &jb, + jt->ctx) == 0); + CHECK(contains(jb.p, "hello-from-script")); + sp_buf_free(&jb); + } + } + } + { + struct sp_buf b; + + sp_buf_init(&b); + kstate_json(&k, &b); + CHECK(contains(b.p, "\"session\":")); + CHECK(contains(b.p, "\"tool_calls\":")); + sp_buf_free(&b); + } + kengine_close(&k); + klog_close(&k.log); + pthread_mutex_destroy(&k.lock); + pthread_cond_destroy(&k.cond); + sp_buf_free(&k.err); + if (failures != 0) { + fprintf(stderr, "%d test(s) failed\n", failures); + return 1; + } + printf("test_engine: ok\n"); + return 0; +} diff --git a/tests/test_krang.c b/tests/test_krang.c new file mode 100644 index 0000000..36f4c0d --- /dev/null +++ b/tests/test_krang.c @@ -0,0 +1,289 @@ +/* + * krang -- offline unit tests: config, birth, stuck, snapshot, HTTP, MCP. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#include +#include +#include +#include +#include + +#include "krang.h" + +static int failures; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \ + #cond); \ + failures++; \ + } \ +} while (0) + +static int +contains(const char *hay, const char *needle) +{ + return hay != NULL && strstr(hay, needle) != NULL; +} + +static void +init_krang(struct krang *k) +{ + memset(k, 0, sizeof(*k)); + k->log.fd = -1; + pthread_mutex_init(&k->lock, NULL); + pthread_cond_init(&k->cond, NULL); + sp_buf_init(&k->err); + kconfig_defaults(&k->cfg); + snprintf(k->cfg.goal, sizeof(k->cfg.goal), "test the apparatus"); + snprintf(k->cfg.endpoint, sizeof(k->cfg.endpoint), + "http://127.0.0.1:1/v1"); + snprintf(k->cfg.model, sizeof(k->cfg.model), "test-model"); + snprintf(k->st.state, sizeof(k->st.state), "sleeping"); + snprintf(k->st.goal, sizeof(k->st.goal), "test the apparatus"); + snprintf(k->st.session, sizeof(k->st.session), "krang"); + snprintf(k->st.sandbox_uid, sizeof(k->st.sandbox_uid), "1000"); + snprintf(k->st.sandbox_gid, sizeof(k->st.sandbox_gid), "1000"); + snprintf(k->st.landlock, sizeof(k->st.landlock), "applied"); + snprintf(k->st.seccomp, sizeof(k->st.seccomp), "applied"); + k->st.started_at = k_now(); + k->st.born_at = k->st.started_at; +} + +static void +test_config(void) +{ + struct kconfig c; + char path[] = "/tmp/krang-test-conf-XXXXXX"; + char err[512]; + int fd; + FILE *f; + + fd = mkstemp(path); + CHECK(fd >= 0); + if (fd < 0) + return; + f = fdopen(fd, "w"); + CHECK(f != NULL); + if (f == NULL) + return; + fprintf(f, "# a test\n"); + fprintf(f, "goal = keep the apparatus honest # inline comment\n"); + fprintf(f, "endpoint = http://127.0.0.1:1/v1\n"); + fprintf(f, "model = test\n"); + fprintf(f, "impulse_seconds = 7\n"); + fprintf(f, "max_steps = 9\n"); + fprintf(f, "dashboard_port = 18096\n"); + fprintf(f, "seccomp = no\n"); + fclose(f); + CHECK(kconfig_load(&c, path, err, sizeof(err)) == 0); + CHECK(strcmp(c.goal, "keep the apparatus honest") == 0); + CHECK(c.impulse_seconds == 7); + CHECK(c.max_steps == 9); + CHECK(c.dashboard_port == 18096); + CHECK(c.seccomp == 0); + unlink(path); +} + +static void +test_birth(void) +{ + struct kconfig c; + struct sp_buf b; + + kconfig_defaults(&c); + snprintf(c.goal, sizeof(c.goal), "map the sandbox"); + sp_buf_init(&b); + k_birth_prompt(&c, &b); + CHECK(contains(b.p, "You are krang. You are awake.")); + CHECK(contains(b.p, "no user")); + CHECK(contains(b.p, "map the sandbox")); + CHECK(contains(b.p, "Good luck.")); + CHECK(contains(b.p, KRANG_IN_WORKSPACE)); + sp_buf_free(&b); +} + +static void +test_stuck(void) +{ + struct kstuck s; + + memset(&s, 0, sizeof(s)); + kstuck_call(&s, "run", "{\"command\":\"false\"}"); + kstuck_call(&s, "run", "{\"command\":\"false\"}"); + CHECK(s.repeated_calls >= 1); + kstuck_result(&s, "run", "error: nope", 1); + kstuck_result(&s, "run", "error: nope", 1); + CHECK(s.same_error >= 2); + CHECK(kstuck_level(&s) >= 1); + CHECK(kstuck_should_check(&s, k_now()) >= 1); + kstuck_reset(&s); + CHECK(s.level == 0); + CHECK(s.attempts == 0); +} + +static void +test_state(void) +{ + struct krang k; + struct sp_buf b; + + init_krang(&k); + sp_buf_init(&b); + kstate_json(&k, &b); + CHECK(contains(b.p, "\"state\":\"sleeping\"")); + CHECK(contains(b.p, "\"goal\":\"test the apparatus\"")); + CHECK(contains(b.p, "\"version\":\"0.1.0\"")); + CHECK(contains(b.p, "\"sandbox\":")); + CHECK(contains(b.p, "\"config\":")); + sp_buf_free(&b); + + sp_buf_init(&b); + kstate_impulses_json(&k, &b, 10); + CHECK(strcmp(b.p, "[]") == 0); + sp_buf_free(&b); + + sp_buf_init(&b); + kstate_tools_json(&k, &b); + CHECK(strcmp(b.p, "[]") == 0); + sp_buf_free(&b); + pthread_mutex_destroy(&k.lock); + pthread_cond_destroy(&k.cond); + sp_buf_free(&k.err); +} + +static void +test_birth_flow(void) +{ + struct krang k; + struct sp_session_info si; + struct sp_buf err, logjson; + char tmpl[] = "/tmp/krang-birth-XXXXXX"; + char *dir; + char goal[KRANG_GOAL]; + int newborn = -1; + + dir = mkdtemp(tmpl); + CHECK(dir != NULL); + if (dir == NULL) + return; + memset(&k, 0, sizeof(k)); + k.log.fd = -1; + pthread_mutex_init(&k.lock, NULL); + pthread_cond_init(&k.cond, NULL); + sp_buf_init(&k.err); + sp_buf_init(&err); + kconfig_defaults(&k.cfg); + snprintf(k.cfg.goal, sizeof(k.cfg.goal), "be born"); + snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir); + (void)mkdir(k.session_dir, 0700); + { + char lp[700]; + + snprintf(lp, sizeof(lp), "%s/events.jsonl", dir); + CHECK(klog_open(&k.log, lp, k.last_error, + sizeof(k.last_error)) == 0); + } + CHECK(kdaemon_session_open(&k, &newborn, goal, sizeof(goal), + k.last_error, sizeof(k.last_error)) == 0); + CHECK(newborn == 1); + CHECK(strcmp(goal, "be born") == 0); + CHECK(k.st.born_at > 0); + CHECK(sp_session_open(&si, k.session_dir, "krang", &err) == 0); + CHECK(sp_session_append(&si, "user", "first breath", &err) == 0); + sp_buf_free(&err); + + newborn = -1; + CHECK(kdaemon_session_open(&k, &newborn, goal, sizeof(goal), + k.last_error, sizeof(k.last_error)) == 0); + CHECK(newborn == 0); + CHECK(strcmp(goal, "be born") == 0); + + snprintf(k.cfg.goal, sizeof(k.cfg.goal), "a different goal"); + CHECK(kdaemon_session_open(&k, &newborn, goal, sizeof(goal), + k.last_error, sizeof(k.last_error)) == 0); + CHECK(strcmp(goal, "be born") == 0); + sp_buf_init(&logjson); + klog_json(&k.log, &logjson, 20); + CHECK(contains(logjson.p, "config_goal_ignored")); + sp_buf_free(&logjson); + klog_close(&k.log); + pthread_mutex_destroy(&k.lock); + pthread_cond_destroy(&k.cond); + sp_buf_free(&k.err); +} + +static void +test_http(void) +{ + struct krang k; + struct sp_buf b; + + init_krang(&k); + sp_buf_init(&b); + khttp_handle_buffer(&k, "GET /healthz HTTP/1.1\r\nHost: x\r\n\r\n", + &b); + CHECK(contains(b.p, "200 OK")); + CHECK(contains(b.p, "\"ok\":true")); + sp_buf_free(&b); + + sp_buf_init(&b); + khttp_handle_buffer(&k, "GET /api/state HTTP/1.1\r\nHost: x\r\n\r\n", + &b); + CHECK(contains(b.p, "200 OK")); + CHECK(contains(b.p, "\"state\":\"sleeping\"")); + sp_buf_free(&b); + + sp_buf_init(&b); + khttp_handle_buffer(&k, "GET /nope HTTP/1.1\r\nHost: x\r\n\r\n", &b); + CHECK(contains(b.p, "404 Not Found")); + sp_buf_free(&b); + pthread_mutex_destroy(&k.lock); + pthread_cond_destroy(&k.cond); + sp_buf_free(&k.err); +} + +static void +test_mcp(void) +{ + struct krang k; + char *reply; + + init_krang(&k); + kmcp_prepare(&k); + reply = kmcp_handle(&k, + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}"); + CHECK(reply != NULL); + CHECK(contains(reply, "krang_state")); + CHECK(contains(reply, "krang_say")); + free(reply); + reply = kmcp_handle(&k, + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\"," + "\"params\":{\"name\":\"krang_state\",\"arguments\":{}}}"); + CHECK(reply != NULL); + CHECK(contains(reply, "sleeping")); + free(reply); + pthread_mutex_destroy(&k.lock); + pthread_cond_destroy(&k.cond); + sp_buf_free(&k.err); +} + +int +main(void) +{ + test_config(); + test_birth(); + test_stuck(); + test_birth_flow(); + test_state(); + test_http(); + test_mcp(); + if (failures != 0) { + fprintf(stderr, "%d test(s) failed\n", failures); + return 1; + } + printf("test_krang: ok\n"); + return 0; +} diff --git a/tests/test_sandbox.c b/tests/test_sandbox.c new file mode 100644 index 0000000..7fd9dc0 --- /dev/null +++ b/tests/test_sandbox.c @@ -0,0 +1,197 @@ +/* + * krang -- offline test of the two one-way layers. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * This does not chroot and does not need root. It applies the real Landlock + * and seccomp layers to a child, then proves: + * - a write under the workspace is allowed; + * - a write under $HOME (writable by the user, outside the allowed set) is + * denied by the path layer; + * - mount(2) is denied by the syscall layer; + * - fork/execve still work, because the run tool needs them. + */ +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "krang.h" + +static int +network_ok(void) +{ + struct addrinfo hints, *res = NULL; + struct sockaddr_in sa; + socklen_t sl = sizeof(sa); + int l, c, a; + char byte = 'x'; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + if (getaddrinfo("localhost", "80", &hints, &res) != 0 || res == NULL) + return 0; + freeaddrinfo(res); + l = socket(AF_INET, SOCK_STREAM, 0); + if (l < 0) + return 0; + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + if (bind(l, (struct sockaddr *)&sa, sizeof(sa)) != 0 || + listen(l, 4) != 0 || + getsockname(l, (struct sockaddr *)&sa, &sl) != 0) { + close(l); + return 0; + } + c = socket(AF_INET, SOCK_STREAM, 0); + if (c < 0 || connect(c, (struct sockaddr *)&sa, sizeof(sa)) != 0) { + if (c >= 0) + close(c); + close(l); + return 0; + } + a = accept(l, NULL, NULL); + if (a < 0 || write(c, &byte, 1) != 1 || read(a, &byte, 1) != 1) { + if (a >= 0) + close(a); + close(c); + close(l); + return 0; + } + close(a); + close(c); + close(l); + return 1; +} + +static int +write_ok(const char *path) +{ + int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); + + if (fd < 0) + return 0; + (void)write(fd, "x", 1); + close(fd); + return 1; +} + +int +main(void) +{ + char root[] = "/tmp/krang-sandbox-XXXXXX"; + char ws[600], st[600], tmp[600], allowed[700], home[700]; + char err[512]; + struct stat sb; + pid_t pid; + int status; + + if (mkdtemp(root) == NULL) { + perror("mkdtemp"); + return 1; + } + snprintf(ws, sizeof(ws), "%s/workspace", root); + snprintf(st, sizeof(st), "%s/state", root); + snprintf(tmp, sizeof(tmp), "%s/tmp", root); + (void)mkdir(ws, 0700); + (void)mkdir(st, 0700); + (void)mkdir(tmp, 0700); + snprintf(allowed, sizeof(allowed), "%s/ok", ws); + snprintf(home, sizeof(home), "%s/krang-denied-%ld", + getenv("HOME") != NULL ? getenv("HOME") : "/tmp", + (long)getpid()); + + pid = fork(); + if (pid < 0) { + perror("fork"); + return 1; + } + if (pid == 0) { + if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) { + perror("no_new_privs"); + _exit(1); + } + if (ksandbox_apply_landlock(ws, st, tmp, 1, err, + sizeof(err)) < 0) { + fprintf(stderr, "landlock: %s\n", err); + _exit(1); + } + if (!write_ok(allowed)) { + fprintf(stderr, "workspace write denied: %s\n", + strerror(errno)); + _exit(1); + } + if (write_ok(home)) { + fprintf(stderr, "HOME write was not denied\n"); + _exit(1); + } + if (ksandbox_apply_seccomp(1, err, sizeof(err)) < 0) { + fprintf(stderr, "seccomp: %s\n", err); + _exit(1); + } + errno = 0; + if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) == 0) { + fprintf(stderr, "mount was not denied\n"); + _exit(1); + } + if (errno != EPERM && errno != EACCES) { + fprintf(stderr, "mount: unexpected errno %d\n", errno); + _exit(1); + } + if (!network_ok()) { + fprintf(stderr, "network after seccomp failed\n"); + _exit(1); + } + if (!write_ok(allowed)) { + fprintf(stderr, "workspace write after seccomp: %s\n", + strerror(errno)); + _exit(1); + } + { + pid_t c = fork(); + + if (c < 0) { + fprintf(stderr, "fork after seccomp: %s\n", + strerror(errno)); + _exit(1); + } + if (c == 0) { + execl("/bin/true", "true", (char *)NULL); + _exit(127); + } + if (waitpid(c, &status, 0) < 0 || + !WIFEXITED(status) || WEXITSTATUS(status) != 0) { + fprintf(stderr, "exec after seccomp failed\n"); + _exit(1); + } + } + _exit(0); + } + if (waitpid(pid, &status, 0) < 0) { + perror("waitpid"); + return 1; + } + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + fprintf(stderr, "test_sandbox: child failed (%d)\n", status); + return 1; + } + (void)sb; + printf("test_sandbox: ok\n"); + return 0; +} diff --git a/tests/test_sandbox_engine.c b/tests/test_sandbox_engine.c new file mode 100644 index 0000000..30a397f --- /dev/null +++ b/tests/test_sandbox_engine.c @@ -0,0 +1,134 @@ +/* + * krang -- one scripted engine turn under Landlock and seccomp. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * This is the test that matters for the daemon: the engine opens files, + * starts threads, calls the mock transport and appends a session while both + * one-way layers are already active. No network, no model, no root. + */ +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "krang.h" + +static int +child(const char *ws, const char *st, const char *tmp) +{ + struct krang k; + char err[512], script[700], logpath[800]; + struct sp_buf sp; + FILE *f; + int rc; + + if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) { + perror("no_new_privs"); + return 1; + } + if (ksandbox_apply_landlock(ws, st, tmp, 1, err, sizeof(err)) < 0) { + fprintf(stderr, "landlock: %s\n", err); + return 1; + } + if (ksandbox_apply_seccomp(1, err, sizeof(err)) < 0) { + fprintf(stderr, "seccomp: %s\n", err); + return 1; + } + memset(&k, 0, sizeof(k)); + k.log.fd = -1; + pthread_mutex_init(&k.lock, NULL); + pthread_cond_init(&k.cond, NULL); + sp_buf_init(&k.err); + kconfig_defaults(&k.cfg); + snprintf(k.cfg.goal, sizeof(k.cfg.goal), "survive the layers"); + snprintf(k.cfg.endpoint, sizeof(k.cfg.endpoint), + "http://127.0.0.1:1/v1"); + snprintf(k.cfg.model, sizeof(k.cfg.model), "test-model"); + snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", st); + if (mkdir(k.session_dir, 0700) != 0 && errno != EEXIST) { + fprintf(stderr, "mkdir sessions: %s\n", strerror(errno)); + return 1; + } + snprintf(logpath, sizeof(logpath), "%s/events.jsonl", st); + if (klog_open(&k.log, logpath, err, sizeof(err)) != 0) { + fprintf(stderr, "log: %s\n", err); + return 1; + } + sp_buf_init(&sp); + k_system_prompt(&k, &sp); + snprintf(k.system_prompt, sizeof(k.system_prompt), "%s", + sp.p != NULL ? sp.p : ""); + sp_buf_free(&sp); + snprintf(script, sizeof(script), "%s/script.txt", tmp); + f = fopen(script, "w"); + if (f == NULL) { + fprintf(stderr, "script: %s\n", strerror(errno)); + return 1; + } + fprintf(f, "tool echo {\"text\":\"layers\"}\n"); + fprintf(f, "answer sandbox-engine-ok\n"); + fclose(f); + if (kengine_open(&k, script, err, sizeof(err)) != 0) { + fprintf(stderr, "engine: %s\n", err); + return 1; + } + rc = krun_turn(&k, "prove the layers", "test", NULL); + if (rc != 0 || strstr(k.st.last_outcome, "sandbox-engine-ok") == NULL) { + fprintf(stderr, "turn: rc=%d outcome=%s\n", rc, + k.st.last_outcome); + return 1; + } + kengine_close(&k); + klog_close(&k.log); + pthread_mutex_destroy(&k.lock); + pthread_cond_destroy(&k.cond); + sp_buf_free(&k.err); + return 0; +} + +int +main(void) +{ + char root[] = "/tmp/krang-sandbox-engine-XXXXXX"; + char ws[600], st[600], tmp[600]; + pid_t pid; + int status; + + if (mkdtemp(root) == NULL) { + perror("mkdtemp"); + return 1; + } + snprintf(ws, sizeof(ws), "%s/workspace", root); + snprintf(st, sizeof(st), "%s/state", root); + snprintf(tmp, sizeof(tmp), "%s/tmp", root); + (void)mkdir(ws, 0700); + (void)mkdir(st, 0700); + (void)mkdir(tmp, 0700); + (void)setenv("HOME", ws, 1); + pid = fork(); + if (pid < 0) { + perror("fork"); + return 1; + } + if (pid == 0) + _exit(child(ws, st, tmp)); + if (waitpid(pid, &status, 0) < 0) { + perror("waitpid"); + return 1; + } + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + fprintf(stderr, "test_sandbox_engine: child failed (%d)\n", + status); + return 1; + } + printf("test_sandbox_engine: ok\n"); + return 0; +} diff --git a/tests/test_server.c b/tests/test_server.c new file mode 100644 index 0000000..469aa92 --- /dev/null +++ b/tests/test_server.c @@ -0,0 +1,135 @@ +/* + * krang -- offline socket test: the dashboard and MCP listeners. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#include +#include +#include +#include +#include +#include +#include + +#include "krang.h" + +static int failures; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \ + #cond); \ + failures++; \ + } \ +} while (0) + +static int +get_port(int fd) +{ + struct sockaddr_in sa; + socklen_t sl = sizeof(sa); + + if (getsockname(fd, (struct sockaddr *)&sa, &sl) != 0) + return -1; + return ntohs(sa.sin_port); +} + +static int +roundtrip(int port, const char *request, char *out, size_t cap, int line) +{ + struct sockaddr_in sa; + int fd; + size_t used = 0; + ssize_t n; + + fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) + return -1; + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons((unsigned short)port); + sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) != 0) { + close(fd); + return -1; + } + if (k_write_all(fd, request, strlen(request)) != 0) { + close(fd); + return -1; + } + while (used + 1 < cap && + (n = read(fd, out + used, cap - used - 1)) > 0) { + used += (size_t)n; + if (line && memchr(out, '\n', used) != NULL) + break; + } + out[used] = '\0'; + close(fd); + return 0; +} + +int +main(void) +{ + struct krang k; + char err[512], req[512], out[8192]; + int port; + + memset(&k, 0, sizeof(k)); + k.log.fd = -1; + pthread_mutex_init(&k.lock, NULL); + pthread_cond_init(&k.cond, NULL); + sp_buf_init(&k.err); + kconfig_defaults(&k.cfg); + snprintf(k.cfg.dashboard_host, sizeof(k.cfg.dashboard_host), + "127.0.0.1"); + k.cfg.dashboard_port = 0; + snprintf(k.cfg.mcp_host, sizeof(k.cfg.mcp_host), "127.0.0.1"); + k.cfg.mcp_port = 0; + snprintf(k.st.state, sizeof(k.st.state), "sleeping"); + snprintf(k.st.goal, sizeof(k.st.goal), "test the server"); + k.st.started_at = k_now(); + + CHECK(khttp_start(&k, err, sizeof(err)) == 0); + port = get_port(k.http_fd); + CHECK(port > 0); + snprintf(req, sizeof(req), + "GET /healthz HTTP/1.1\r\nHost: localhost\r\n\r\n"); + CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0); + CHECK(strstr(out, "200 OK") != NULL); + CHECK(strstr(out, "\"ok\":true") != NULL); + snprintf(req, sizeof(req), "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"); + CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0); + CHECK(strstr(out, "200 OK") != NULL); + CHECK(strstr(out, "krang") != NULL); + snprintf(req, sizeof(req), + "GET /api/state HTTP/1.1\r\nHost: localhost\r\n\r\n"); + CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0); + CHECK(strstr(out, "\"goal\":\"test the server\"") != NULL); + khttp_stop(&k); + + CHECK(kmcp_start(&k, err, sizeof(err)) == 0); + port = get_port(k.mcp_fd); + CHECK(port > 0); + snprintf(req, sizeof(req), + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}\n"); + CHECK(roundtrip(port, req, out, sizeof(out), 1) == 0); + CHECK(strstr(out, "krang_state") != NULL); + snprintf(req, sizeof(req), + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\"," + "\"params\":{\"name\":\"krang_state\",\"arguments\":{}}}\n"); + CHECK(roundtrip(port, req, out, sizeof(out), 1) == 0); + CHECK(strstr(out, "sleeping") != NULL); + kmcp_stop(&k); + + pthread_mutex_destroy(&k.lock); + pthread_cond_destroy(&k.cond); + sp_buf_free(&k.err); + if (failures != 0) { + fprintf(stderr, "%d test(s) failed\n", failures); + return 1; + } + printf("test_server: ok\n"); + return 0; +}