diff --git a/.env.example b/.env.example index 5702035..0736c5a 100644 --- a/.env.example +++ b/.env.example @@ -1,11 +1,12 @@ # ShellClaw Environment Variables -# Copy to .env and fill in your values -# NEVER commit the .env file +# Copy this file to ~/.shellclaw/.env with mode 0600. +# Remove the first # from each variable you use. Set its value. +# Keep your .env file outside the repository. # # See config.example.toml for TOML equivalents. Env vars override TOML where supported. # --- LLM Providers (at least one required for cloud path) --- -ANTHROPIC_API_KEY=sk-ant-your-key-here +# ANTHROPIC_API_KEY=sk-ant-your-key-here # OPENAI_API_KEY=sk-your-key-here # OPENROUTER_API_KEY=sk-or-your-key-here @@ -22,7 +23,7 @@ ANTHROPIC_API_KEY=sk-ant-your-key-here # SHELLCLAW_LOCAL_MODEL=tinyllama-1.1b-q4 # --- Channels --- -TELEGRAM_BOT_TOKEN=123456:ABC-your-token-here +# TELEGRAM_BOT_TOKEN=123456:ABC-your-token-here # DISCORD_BOT_TOKEN=your-discord-token-here # --- Gateway (optional overrides) --- @@ -37,7 +38,7 @@ TELEGRAM_BOT_TOKEN=123456:ABC-your-token-here # --- ASAP Protocol (optional) --- # SHELLCLAW_ASAP_PUBLIC_BASE_URL=https://your-host.example.com -# SHELLCLAW_ASAP_DESCRIPTION=Override manifest description +# SHELLCLAW_ASAP_DESCRIPTION="Override manifest description" # SHELLCLAW_ASAP_REGISTRY_URL=https://raw.githubusercontent.com/asap-protocol/asap-protocol/main/registry.json # SHELLCLAW_ASAP_REVOCATION_LIST_URL=https://registry.asap.agent/revoked_agents.json diff --git a/README.md b/README.md index bbc1cf5..fd1de4c 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,50 @@ ShellClaw is **not another OpenClaw clone** in a different language. It is a **h **Build:** `make shellclaw` → binary at `build/shellclaw`. `make test` → builds and runs all tests in `build/`. -**Run:** `./build/shellclaw` +### First run + +On Linux, run the installer as your user. + +```bash +make shellclaw +./scripts/install.sh +``` + +The installer places the binary in `~/.local/bin` and creates the configuration in `~/.shellclaw`. +If you install without the Linux script, create the configuration files yourself. +```bash +install -d -m 0700 "$HOME/.shellclaw" +install -m 0600 config.example.toml "$HOME/.shellclaw/config.toml" +install -m 0600 .env.example "$HOME/.shellclaw/.env" +``` + +Edit `~/.shellclaw/config.toml` to select your model. For the default Anthropic model, set `ANTHROPIC_API_KEY` in `~/.shellclaw/.env`. +Use plain variable assignments so that Bash and systemd can both read the file. + +The terminal reads variables from the process environment. Source only the private file that you created and trust. + +```bash +( + set -a + . "$HOME/.shellclaw/.env" + set +a + "$HOME/.local/bin/shellclaw" -m "Reply with hello." +) +``` + +If you used the manual steps, use `./build/shellclaw` in the last command. + +### Linux user service + +After you configure a provider, start the service. systemd reads the same `~/.shellclaw/.env` file. + +```bash +systemctl --user daemon-reload +systemctl --user enable --now shellclaw.service +``` + +To change the install paths, set `SHELLCLAW_INSTALL_BIN` or `SHELLCLAW_HOME` before you run the installer. +Use the paths printed by the installer when you run it from the terminal. For a custom configuration directory, pass `--config` with the full `config.toml` path. **Quality checks:** - `make static` — cppcheck on `src/` (requires cppcheck) @@ -59,7 +102,9 @@ ShellClaw is **not another OpenClaw clone** in a different language. It is a **h See [CONTRIBUTING.md](CONTRIBUTING.md) for PR workflow, coding standards, and the pre-tag `gpio-mockup` release ritual. -**Configuration:** copy [`config.example.toml`](config.example.toml) to `~/.shellclaw/config.toml` and [`.env.example`](.env.example) to `.env`. Phase 3+ keys (ASAP, sandbox, gateway) and the Jetson `[hardware]` block are documented there. Install **libwebsockets** (`pkg-config` must find it) to build the gateway and run `GATEWAY=1 make test_gateway_http`. +[`config.example.toml`](config.example.toml) documents the configuration keys. +Install libwebsockets to build the gateway and run `GATEWAY=1 make test_gateway_http`. +Make sure that `pkg-config` can find libwebsockets. **Jetson install (v1.0):** `./scripts/install.sh`, `./scripts/build_llama_jetson.sh`, `./scripts/download_model.sh phi3` — details in [`docs/HARDWARE_JETSON.md`](docs/HARDWARE_JETSON.md) and [`docs/LOCAL_INFERENCE.md`](docs/LOCAL_INFERENCE.md). diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a198f3b..e3affce 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -115,7 +115,7 @@ SFIO pins (I2C/UART/SPI) are rejected by GPIO tools with a pinmux error — use ShellClaw does **not** embed llama.cpp. A separate **`llama-server`** process serves OpenAI-compatible chat completions; `providers/local.c` probes `GET /health` and `GET /v1/models` at startup. -- **Jetson:** CUDA build via `scripts/build_llama_jetson.sh`; systemd unit `llama-server.service` + `/etc/shellclaw/llama-server.env`. +- **Jetson:** CUDA build via `scripts/build_llama_jetson.sh`; systemd unit `llama-server.service` + `~/.shellclaw/llama-server.env`. - **RPi:** CPU build via `scripts/build_llama_rpi.sh` (validated in Phase 6). Details: [LOCAL_INFERENCE.md](LOCAL_INFERENCE.md). diff --git a/docs/LOCAL_INFERENCE.md b/docs/LOCAL_INFERENCE.md index bf3cde9..cf88331 100644 --- a/docs/LOCAL_INFERENCE.md +++ b/docs/LOCAL_INFERENCE.md @@ -1,6 +1,6 @@ # Local inference (llama.cpp) -ShellClaw uses an external **`llama-server`** process (from [llama.cpp](https://github.com/ggml-org/llama.cpp)) as an OpenAI-compatible chat backend. The agent binary talks HTTP only — it does not link CUDA or GGML. Configuration: `[providers.local]` in `~/.shellclaw/config.toml` and `/etc/shellclaw/llama-server.env` for the systemd unit. +ShellClaw uses an external **`llama-server`** process (from [llama.cpp](https://github.com/ggml-org/llama.cpp)) as an OpenAI-compatible chat backend. The agent binary talks HTTP only — it does not link CUDA or GGML. Configuration: `[providers.local]` in `~/.shellclaw/config.toml` and `~/.shellclaw/llama-server.env` for the systemd user unit. For software architecture, see [ARCHITECTURE.md](ARCHITECTURE.md). For Jetson setup order, see [HARDWARE_JETSON.md](HARDWARE_JETSON.md). @@ -66,9 +66,13 @@ Verify: `llama-server --version` must **not** report CUDA/GPU. ## systemd integration -`./scripts/install.sh` copies board-specific env to `/etc/shellclaw/llama-server.env` and installs user units: +Run `./scripts/install.sh` to install the user units and `~/.shellclaw/llama-server.env`. +To use a different directory for `llama-server.env`, set `SHELLCLAW_ETC_DIR` before you run the installer. +Set `MODEL` in that file to the full path to your downloaded model. +Start both services after you install the model and `llama-server`. ```bash +systemctl --user daemon-reload systemctl --user enable --now llama-server.service shellclaw.service ``` diff --git a/scripts/install.sh b/scripts/install.sh index 5816dd8..ca016f9 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1,31 +1,72 @@ #!/usr/bin/env bash -# Install helper: copy systemd user units next to ~/.config/systemd/user and print enable steps. -# -# Purpose: `./scripts/install.sh` — aligns with Phase 4 PRD §4.4.30; Phase 5 Task 3.5 adds -# board-specific llama-server env under /etc/shellclaw (override via SHELLCLAW_ETC_DIR). +# Install ShellClaw and its systemd user units. set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user" INSTALL_BIN="${SHELLCLAW_INSTALL_BIN:-${HOME%/}/.local/bin/shellclaw}" -SHELLCLAW_HOME="${SHELLCLAW_HOME:-${HOME%/}/.shellclaw}" -LLAMA_ENV_DIR="${SHELLCLAW_ETC_DIR:-/etc/shellclaw}" +BUILT_BIN="${ROOT}/build/shellclaw" +STATE_DIR="${SHELLCLAW_HOME:-${HOME%/}/.shellclaw}" +LLAMA_ENV_DIR="${SHELLCLAW_ETC_DIR:-${STATE_DIR}}" LLAMA_ENV_DEST="${LLAMA_ENV_DIR}/llama-server.env" +LEGACY_LLAMA_ENV="/etc/shellclaw/llama-server.env" JETSON_ENV="${ROOT}/systemd/llama-server.jetson.env" RPI_ENV="${ROOT}/systemd/llama-server.rpi.env" -install_llama_env_file() { - local src_template="$1" - mkdir -p "${LLAMA_ENV_DIR}" - if [[ -w "${LLAMA_ENV_DIR}" ]]; then - install -m 0644 "${src_template}" "${LLAMA_ENV_DEST}" - elif [[ "${LLAMA_ENV_DIR}" == /etc/shellclaw ]] && command -v sudo >/dev/null 2>&1; then - sudo install -m 0644 "${src_template}" "${LLAMA_ENV_DEST}" - else - echo "Cannot write ${LLAMA_ENV_DEST}; set SHELLCLAW_ETC_DIR or run with sufficient permissions." >&2 +validate_path() { + if [[ "$1" != /* || "$1" == *[[:cntrl:]]* ]]; then + printf 'Use an absolute path without control characters for %s.\n' "$2" >&2 + exit 1 + fi +} + +validate_env_dir() { + validate_path "$1" "$2" + if [[ "$1" == *[\*\?\[\\]* ]]; then + printf 'Use a path without wildcard characters for %s.\n' "$2" >&2 exit 1 fi } +quote_unit_value() { + local value="${1//%/%%}" + value="${value//\\/\\\\}" + value="${value//\"/\\\"}" + printf '"%s"' "${value}" +} + +render_unit() { + local line + while IFS= read -r line; do + case "${line}" in + Environment=SHELLCLAW_HOME=*) + printf 'Environment=%s\n' "$(quote_unit_value "SHELLCLAW_HOME=${STATE_DIR}")" + ;; + EnvironmentFile=-%h/.shellclaw/.env) + printf 'EnvironmentFile=-%s/.env\n' "${STATE_DIR//%/%%}" + ;; + EnvironmentFile=%h/.shellclaw/llama-server.env) + printf 'EnvironmentFile=%s\n' "${LLAMA_ENV_DEST//%/%%}" + ;; + ExecStart=%h/.local/bin/shellclaw*) + # systemd limits executable names. env passes the full path as an argument. + printf 'ExecStart=:/usr/bin/env -- %s --config %s%s\n' "$(quote_unit_value "${INSTALL_BIN}")" \ + "$(quote_unit_value "${STATE_DIR}/config.toml")" "${line#*%h/.shellclaw/config.toml}" + ;; + *) printf '%s\n' "${line}" ;; + esac + done <"$1" +} + +install_config() { + local line + local default_prefix='~/.shellclaw/' + local state_prefix="${STATE_DIR//\\/\\\\}" + state_prefix="${state_prefix//\"/\\\"}/" + while IFS= read -r line; do + printf '%s\n' "${line//"${default_prefix}"/"${state_prefix}"}" + done <"${ROOT}/config.example.toml" >"${STATE_DIR}/config.toml" +} + detect_board_id() { if [[ ! -x "${INSTALL_BIN}" ]]; then echo "unknown" @@ -60,6 +101,14 @@ board_llama_env_source() { esac } +install_llama_env() ( + local stage + stage="$(mktemp "${LLAMA_ENV_DIR}/.llama-server.env.XXXXXX")" + trap 'rm -f -- "${stage}"' EXIT + install -m 0600 "$1" "${stage}" + mv -n -- "${stage}" "${LLAMA_ENV_DEST}" +) + board_download_model_key() { local board="$1" case "${board}" in @@ -83,56 +132,94 @@ maybe_prompt_download_model() { return 0 fi local reply="" - read -r -p "Download default GGUF now via scripts/download_model.sh (${model_key})? [y/N] " reply + read -r -p "Download the default model (${model_key})? [y/N] " reply || return 0 if [[ "${reply}" =~ ^[Yy]$ ]]; then bash "${ROOT}/scripts/download_model.sh" "${model_key}" fi } -mkdir -p "${UNIT_DIR}" -install -m 0644 "${ROOT}/systemd/shellclaw.service" "${UNIT_DIR}/shellclaw.service" -install -m 0644 "${ROOT}/systemd/llama-server.service" "${UNIT_DIR}/llama-server.service" +validate_path "${UNIT_DIR}" XDG_CONFIG_HOME +validate_path "${INSTALL_BIN}" SHELLCLAW_INSTALL_BIN +validate_env_dir "${STATE_DIR}" SHELLCLAW_HOME +validate_env_dir "${LLAMA_ENV_DIR}" SHELLCLAW_ETC_DIR -board_id="$(detect_board_id)" -env_src="$(board_llama_env_source "${board_id}")" -install_llama_env_file "${env_src}" - -case "${board_id}" in -jetson_orin_nano) - echo "Installed llama-server env (Jetson) at ${LLAMA_ENV_DEST}" - ;; -rpi_zero2w) - echo "Installed llama-server env (RPi) at ${LLAMA_ENV_DEST}" - ;; -stub) - echo "Board stub: installed Jetson llama-server env template at ${LLAMA_ENV_DEST} (dev/CI)" - ;; -unknown|*) - echo "Board unknown: installed Jetson llama-server env template at ${LLAMA_ENV_DEST}" - ;; -esac +directories=("${STATE_DIR}" "${UNIT_DIR}") +if [[ ! -e "${LLAMA_ENV_DEST}" ]]; then + directories+=("${LLAMA_ENV_DIR}") +fi +selected_bin="${INSTALL_BIN}" +copy_binary=0 +if [[ ! -x "${INSTALL_BIN}" || ( -z "${SHELLCLAW_INSTALL_BIN:-}" && -x "${BUILT_BIN}" ) ]]; then + if [[ ! -x "${BUILT_BIN}" ]]; then + echo "Run make shellclaw before installation." >&2 + exit 1 + fi + selected_bin="${BUILT_BIN}" + copy_binary=1 + directories+=("$(dirname "${INSTALL_BIN}")") +fi -maybe_prompt_download_model "${board_id}" +# Pass --headless before --help so the binary must parse both options. +if ! "${selected_bin}" --headless --help >/dev/null 2>&1; then + printf 'ShellClaw at %s does not accept --headless.\n' "${selected_bin}" >&2 + echo 'Run make shellclaw. If you set SHELLCLAW_INSTALL_BIN, use a compatible binary.' >&2 + exit 1 +fi -echo "Installed units into ${UNIT_DIR}" -echo "" -if [[ ! -x "${INSTALL_BIN}" ]]; then - echo "Warning: ShellClaw binary not found or not executable at ${INSTALL_BIN}" >&2 - echo "Build or copy the binary before starting the service (see README)." >&2 - echo "" +llama_env_source="" +if [[ ! -e "${LLAMA_ENV_DEST}" && -z "${SHELLCLAW_ETC_DIR:-}" && + ( -e "${LEGACY_LLAMA_ENV}" || -L "${LEGACY_LLAMA_ENV}" ) ]]; then + if [[ ! -f "${LEGACY_LLAMA_ENV}" || ! -r "${LEGACY_LLAMA_ENV}" ]]; then + printf 'Cannot read the previous llama-server environment at %s.\n' "${LEGACY_LLAMA_ENV}" >&2 + exit 1 + fi + llama_env_source="${LEGACY_LLAMA_ENV}" fi -echo "Environment (override before enable if needed):" -echo " SHELLCLAW_INSTALL_BIN=${INSTALL_BIN}" -echo " SHELLCLAW_HOME=${SHELLCLAW_HOME}" -echo " SHELLCLAW_ETC_DIR=${LLAMA_ENV_DIR} (llama-server.env)" -echo "" -echo "Next:" -echo ' Prefix `systemctl` with `sudo` only if you use system-wide systemd instead of `--user`.' + +umask 077 +mkdir -p "${directories[@]}" +for dir in "${directories[@]}"; do + if [[ ! -w "${dir}" || ! -x "${dir}" ]]; then + printf 'Cannot write to %s.\n' "${dir}" >&2 + exit 1 + fi +done +for path in "${INSTALL_BIN}" "${STATE_DIR}/config.toml" "${STATE_DIR}/.env" "${LLAMA_ENV_DEST}" \ + "${UNIT_DIR}/shellclaw.service" "${UNIT_DIR}/llama-server.service"; do + if [[ ( -e "${path}" || -L "${path}" ) && ! -f "${path}" ]]; then + printf 'Expected a regular file at %s.\n' "${path}" >&2 + exit 1 + fi +done + +if ((copy_binary)); then + install -m 0755 "${selected_bin}" "${INSTALL_BIN}" +fi +if [[ ! -e "${STATE_DIR}/config.toml" ]]; then + install_config +fi +if [[ ! -e "${STATE_DIR}/.env" ]]; then + install -m 0600 "${ROOT}/.env.example" "${STATE_DIR}/.env" +fi +board_id="$(detect_board_id)" +if [[ ! -e "${LLAMA_ENV_DEST}" ]]; then + install_llama_env "${llama_env_source:-$(board_llama_env_source "${board_id}")}" +fi +unit_stage="$(mktemp -d)" +trap 'rm -rf -- "${unit_stage}"' EXIT +for unit in shellclaw.service llama-server.service; do + render_unit "${ROOT}/systemd/${unit}" >"${unit_stage}/${unit}" + install -m 0644 "${unit_stage}/${unit}" "${UNIT_DIR}/${unit}" +done + +echo "Installed user units in ${UNIT_DIR}." +echo "ShellClaw binary is at ${INSTALL_BIN}." +echo "Edit ${STATE_DIR}/config.toml before you start ShellClaw." +echo "For a cloud provider, set its API key in ${STATE_DIR}/.env." echo " systemctl --user daemon-reload" echo " systemctl --user enable --now shellclaw.service" -echo "Optional (local inference):" -echo " Build llama-server: ./scripts/build_llama_jetson.sh or ./scripts/build_llama_rpi.sh" -echo " Download model: ./scripts/download_model.sh phi3 # Jetson default" -echo " ./scripts/download_model.sh tinyllama # RPi default" +echo "If you use local inference, build llama-server and download a model." +echo "Set MODEL in ${LLAMA_ENV_DEST} to the model path." echo " systemctl --user enable --now llama-server.service" -echo " (uses ${LLAMA_ENV_DEST}; restart after editing MODEL=)" + +maybe_prompt_download_model "${board_id}" diff --git a/src/channels/channel.h b/src/channels/channel.h index cb64cb8..be71987 100644 --- a/src/channels/channel.h +++ b/src/channels/channel.h @@ -96,6 +96,9 @@ int channel_send_chunked(const char *text, size_t max_bytes, channel_chunk_post_fn post, void *ctx, channel_chunk_fail_t *fail); +/** Poll result when the channel can no longer receive input. */ +#define CHANNEL_POLL_CLOSED 2 + /** * Channel vtable: init, poll, send, cleanup. CLI and Telegram implement this. */ @@ -107,7 +110,7 @@ typedef struct channel { * Poll for incoming message. Block up to timeout_ms. * @param out Filled on success; caller must channel_incoming_msg_clear(). * @param timeout_ms Max wait in milliseconds. - * @return 1 if message received, 0 if timeout/no message, -1 on error. + * @return 1 for a message, 0 for no message, CHANNEL_POLL_CLOSED for closed input, or -1 on error. */ int (*poll)(channel_incoming_msg_t *out, int timeout_ms); /** diff --git a/src/channels/cli.c b/src/channels/cli.c index 037f532..3a83b45 100644 --- a/src/channels/cli.c +++ b/src/channels/cli.c @@ -19,6 +19,11 @@ static char *g_one_shot; static int g_verbose; +static int g_one_shot_mode; +static char g_input[LINE_BUF_SIZE - 1]; +static size_t g_input_length; +static int g_prompt_written; +static int g_input_closed; void channel_cli_set_one_shot(const char *msg) { @@ -34,48 +39,106 @@ void channel_cli_set_verbose(int v) static int cli_init(const config_t *cfg) { (void)cfg; + g_one_shot_mode = g_one_shot != NULL; + g_input_length = 0; + g_prompt_written = 0; + g_input_closed = 0; return 0; } -static int cli_poll(channel_incoming_msg_t *out, int timeout_ms) +static int cli_message(channel_incoming_msg_t *out, const char *text) { - if (!out) return -1; - memset(out, 0, sizeof(*out)); - if (g_one_shot) { - out->session_id = strdup(CLI_SESSION_ID); - out->user_id = strdup(CLI_USER_ID); - out->text = strdup(g_one_shot); - out->attachments = NULL; - out->attachments_count = 0; - free(g_one_shot); - g_one_shot = NULL; - return 1; + out->session_id = strdup(CLI_SESSION_ID); + out->user_id = strdup(CLI_USER_ID); + out->text = strdup(text); + if (!out->session_id || !out->user_id || !out->text) { + channel_incoming_msg_clear(out); + return -1; } + return 1; +} + +static int cli_read_input(int timeout_ms) +{ fd_set rfds; struct timeval tv; FD_ZERO(&rfds); FD_SET(STDIN_FILENO, &rfds); tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000; - int r = select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv); - if (r <= 0) return r; - if (!FD_ISSET(STDIN_FILENO, &rfds)) return 0; - if (isatty(STDIN_FILENO)) - fprintf(stdout, "You: "); - fflush(stdout); - char line[LINE_BUF_SIZE]; - if (!fgets(line, sizeof(line), stdin)) return 0; - size_t len = strlen(line); - while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) - line[--len] = '\0'; - out->session_id = strdup(CLI_SESSION_ID); - out->user_id = strdup(CLI_USER_ID); - out->text = strdup(line); - out->attachments = NULL; - out->attachments_count = 0; + int result = select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv); + if (result == 0 || (result < 0 && errno == EINTR)) + return 0; + if (result < 0) { + g_input_closed = 1; + return 1; + } + + ssize_t count = read(STDIN_FILENO, g_input + g_input_length, sizeof(g_input) - g_input_length); + if (count < 0 && (errno == EINTR || errno == EAGAIN)) + return 0; + if (count <= 0) + g_input_closed = 1; + else + g_input_length += (size_t)count; return 1; } +static size_t cli_line_length(void) +{ + const char *newline = memchr(g_input, '\n', g_input_length); + if (newline) + return (size_t)(newline - g_input) + 1U; + return g_input_closed || g_input_length == sizeof(g_input) ? g_input_length : 0; +} + +static int cli_poll(channel_incoming_msg_t *out, int timeout_ms) +{ + if (!out) return -1; + memset(out, 0, sizeof(*out)); + if (g_one_shot_mode) { + if (!g_one_shot) + return 0; + int result = cli_message(out, g_one_shot); + free(g_one_shot); + g_one_shot = NULL; + return result; + } + if (!g_input_closed && !g_prompt_written && isatty(STDIN_FILENO)) { + fputs("You: ", stdout); + fflush(stdout); + g_prompt_written = 1; + } + + size_t length = cli_line_length(); + if (!length && !g_input_closed && cli_read_input(timeout_ms)) + length = cli_line_length(); + if (!length) + return g_input_closed ? CHANNEL_POLL_CLOSED : 0; + + char line[LINE_BUF_SIZE]; + memcpy(line, g_input, length); + g_input_length -= length; + memmove(g_input, g_input + length, g_input_length); + while (length > 0 && (line[length - 1] == '\n' || line[length - 1] == '\r')) + length--; + line[length] = '\0'; + g_prompt_written = 0; + if (strcmp(line, "/quit") == 0) { + g_input_length = 0; + g_input_closed = 1; + return CHANNEL_POLL_CLOSED; + } + if (strcmp(line, "/help") == 0) { + puts("/status Show the provider status.\n" + "/reset Clear this conversation.\n" + "/quit Close terminal input."); + fflush(stdout); + return 0; + } + return cli_message(out, line); +} + static int cli_send(const char *recipient, const char *text, const channel_attachment_t *attachments, size_t att_count) { diff --git a/src/core/dispatch.c b/src/core/dispatch.c index 9f51edc..aafce1f 100644 --- a/src/core/dispatch.c +++ b/src/core/dispatch.c @@ -63,7 +63,7 @@ static int send_then_maybe_ack_cron(const channel_t *ch, const channel_incoming_ send_err = ch->send(msg->session_id, text, NULL, 0); if (send_err != 0) return send_err; - return agent_err == 0 ? maybe_ack_cron(cron_job_id, NULL) : 0; + return agent_err == 0 ? maybe_ack_cron(cron_job_id, NULL) : agent_err; } int dispatch_delete_session(const char *session_id) @@ -91,9 +91,22 @@ int handle_message(const channel_t *ch, const channel_incoming_msg_t *msg) return send_then_maybe_ack_cron(ch, msg, "Session cleared.", 0); } if (strcmp(text, "/status") == 0) { - char buf[128]; - snprintf(buf, sizeof(buf), "ShellClaw %s — agent ready.", - SHELLCLAW_RELEASE_VERSION); + char backend[96]; + char last_error[768]; + char buf[1024]; + agent_lock(); + provider_router_active_backend_snapshot(backend, sizeof(backend)); + provider_router_last_error_snapshot(last_error, sizeof(last_error)); + agent_unlock(); + if (!backend[0]) + snprintf(buf, sizeof(buf), "ShellClaw %s. No provider is selected.", + SHELLCLAW_RELEASE_VERSION); + else if (last_error[0]) + snprintf(buf, sizeof(buf), "ShellClaw %s. Selected provider is %s. Last provider error: %s", + SHELLCLAW_RELEASE_VERSION, backend, last_error); + else + snprintf(buf, sizeof(buf), "ShellClaw %s. Selected provider is %s. No provider error recorded.", + SHELLCLAW_RELEASE_VERSION, backend); return send_then_maybe_ack_cron(ch, msg, buf, 0); } char resp_buf[RESPONSE_BUF_SIZE]; diff --git a/src/core/dispatch.h b/src/core/dispatch.h index e94bb48..3f976d7 100644 --- a/src/core/dispatch.h +++ b/src/core/dispatch.h @@ -14,7 +14,7 @@ extern "C" { /** * Handle an incoming channel message (/reset, /status, or agent run). - * @return Result of channel send(), or -1 on internal error. + * @return 0 on success, or a nonzero turn, delivery, or cron acknowledgment error. */ int handle_message(const channel_t *ch, const channel_incoming_msg_t *msg); diff --git a/src/core/main.c b/src/core/main.c index 30ae75e..e27cb6a 100644 --- a/src/core/main.c +++ b/src/core/main.c @@ -27,12 +27,15 @@ #include "channels/channel.h" #include "hardware/board_detect.h" #include "providers/provider.h" +#include "tools/cron.h" #include #include #include #include #include +#include #include +#include #define DEFAULT_CONFIG_PATH "~/.shellclaw/config.toml" #define POLL_TIMEOUT_MS 1000 @@ -41,6 +44,7 @@ static volatile sig_atomic_t g_shutdown; static const char *g_cli_one_shot; static int g_verbose; static int g_want_daemon; +static int g_headless; static void on_signal(int sig) { @@ -63,8 +67,30 @@ static void setup_signals(void) fprintf(stderr, "warning: sigaction(SIGHUP) failed\n"); } -static void main_loop(int one_shot, config_t **pcfg) +static int has_background_channels(void) { + for (int i = 0; i < bootstrap_channel_count(); i++) { + const channel_t *channel = bootstrap_channel_at(i); + if (channel != channel_cli_get() && channel != channel_cron_get()) + return 1; + } + return 0; +} + +/* Older systemd units use /dev/null for stdin and start ShellClaw without --headless. */ +static int uses_systemd_null_input(void) +{ + const char *invocation_id = getenv("INVOCATION_ID"); + struct stat input, null_device; + return invocation_id && invocation_id[0] && fstat(STDIN_FILENO, &input) == 0 && + S_ISCHR(input.st_mode) && stat("/dev/null", &null_device) == 0 && + input.st_rdev == null_device.st_rdev; +} + +static int main_loop(int one_shot, config_t **pcfg) +{ + int cli_closed = g_headless || g_want_daemon; + int keep_running = cli_closed || has_background_channels() || (!one_shot && uses_systemd_null_input()); while (!g_shutdown) { if (g_reload_requested) { g_reload_requested = 0; @@ -80,9 +106,15 @@ static void main_loop(int one_shot, config_t **pcfg) int nch = bootstrap_channel_count(); for (int i = 0; i < nch && !got; i++) { const channel_t *ch = bootstrap_channel_at(i); - if (!ch) + if (!ch || (cli_closed && ch == channel_cli_get())) continue; int r = ch->poll(&msg, POLL_TIMEOUT_MS); + if (r == CHANNEL_POLL_CLOSED) { + cli_closed = 1; + if (!keep_running) + return one_shot ? EXIT_FAILURE : EXIT_SUCCESS; + continue; + } if (r == 1) { got = 1; which = ch; @@ -92,18 +124,23 @@ static void main_loop(int one_shot, config_t **pcfg) channel_incoming_msg_clear(&msg); } if (got && which) { - handle_message(which, &msg); + int result = handle_message(which, &msg); channel_incoming_msg_clear(&msg); if (one_shot) - g_shutdown = 1; + return result == 0 ? EXIT_SUCCESS : EXIT_FAILURE; + } else if (cli_closed && !g_shutdown) { + /* Cron and heartbeat can return at once when no job is due. */ + const struct timespec delay = { .tv_sec = 0, .tv_nsec = 50000000L }; + (void)nanosleep(&delay, NULL); } } + return one_shot ? EXIT_FAILURE : EXIT_SUCCESS; } -static void print_usage(const char *prog) +static void print_usage(FILE *stream, const char *prog) { - fprintf(stderr, - "Usage: %s [--config ] [--verbose] [--daemon] [--detect-board] [--rotate-keys] [--version] [-m \"message\"]\n", + fprintf(stream, + "Usage: %s [--config ] [--verbose] [--daemon | --headless] [--detect-board] [--rotate-keys] [--version] [--help] [-m \"message\"]\n", prog); } @@ -114,6 +151,11 @@ static int parse_args(int argc, char **argv, const char **config_path_out) g_want_daemon = 0; daemon_set_want(0); for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) { + print_usage(stdout, argv[0]); + puts("Run with --headless to keep the process open without terminal input."); + exit(0); + } if (strcmp(argv[i], "--version") == 0) { printf("%s\n", SHELLCLAW_RELEASE_VERSION); exit(0); @@ -141,6 +183,10 @@ static int parse_args(int argc, char **argv, const char **config_path_out) daemon_set_want(1); continue; } + if (strcmp(argv[i], "--headless") == 0) { + g_headless = 1; + continue; + } if (strcmp(argv[i], "--config") == 0) { if (i + 1 >= argc) { fprintf(stderr, "Error: --config requires a path argument\n"); @@ -158,7 +204,7 @@ static int parse_args(int argc, char **argv, const char **config_path_out) continue; } fprintf(stderr, "Error: unknown option '%s'\n", argv[i]); - print_usage(argv[0]); + print_usage(stderr, argv[0]); return -1; } return 0; @@ -174,6 +220,11 @@ int main(int argc, char **argv) fprintf(stderr, "Error: %s\n", errbuf[0] ? errbuf : "failed to load config"); return 1; } + if (g_headless && g_cli_one_shot) { + fprintf(stderr, "Error: Use -m without --headless.\n"); + config_free(cfg); + return 1; + } if (g_want_daemon && g_cli_one_shot) { fprintf(stderr, "Error: --daemon cannot be used together with -m\n"); config_free(cfg); @@ -199,7 +250,7 @@ int main(int argc, char **argv) config_free(cfg); return 1; } - main_loop(g_cli_one_shot != NULL, &cfg); + int result = main_loop(g_cli_one_shot != NULL, &cfg); { config_t *live = bootstrap_get_cfg(); cleanup_subsystems(); @@ -208,5 +259,5 @@ int main(int argc, char **argv) stale_free_all(); config_free(live); } - return 0; + return result; } diff --git a/src/gateway/http.c b/src/gateway/http.c index 6b571ff..90901be 100644 --- a/src/gateway/http.c +++ b/src/gateway/http.c @@ -119,6 +119,7 @@ int http_start(const config_t *cfg, struct auth_ctx *auth_ctx, const char *confi return -1; ctx = calloc(1, sizeof(*ctx)); if (!ctx) return -1; + atomic_init(&ctx->running, 0); ctx->cfg = cfg; ctx->auth = auth_ctx; ctx->config_path = config_path ? strdup(config_path) : NULL; @@ -158,8 +159,10 @@ void http_stop(void) { provider_router_set_status_changed_callback(NULL); if (!g_ctx) return; - g_ctx->running = 0; + atomic_store(&g_ctx->running, 0); ws_shutdown_signal(); + /* Wake lws_service when the gateway has no network activity. */ + lws_cancel_service(g_ctx->lws_ctx); if (g_ctx->thread) { pthread_join(g_ctx->thread, NULL); g_ctx->thread = 0; diff --git a/src/gateway/http_lws.h b/src/gateway/http_lws.h index 5f6f3e8..4e5b95f 100644 --- a/src/gateway/http_lws.h +++ b/src/gateway/http_lws.h @@ -13,6 +13,7 @@ #include "gateway/ws.h" #include #include +#include #include #ifdef __cplusplus @@ -40,7 +41,7 @@ typedef struct http_server_ctx { time_t start_time; struct lws_context *lws_ctx; pthread_t thread; - volatile int running; + atomic_int running; } http_server_ctx_t; /** Global server context (set by http_start, cleared by http_stop). */ diff --git a/src/gateway/ws.c b/src/gateway/ws.c index 0bce15e..ff0d51a 100644 --- a/src/gateway/ws.c +++ b/src/gateway/ws.c @@ -79,7 +79,7 @@ static int g_outgoing_count; static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER; static atomic_int g_next_conn_id; -static volatile int g_ws_shutdown; +static int g_ws_shutdown; static struct lws_context *g_lws_ctx; void ws_set_context(void *ctx) @@ -436,8 +436,10 @@ ws_enqueue_outgoing_locked(m); void ws_shutdown_signal(void) { + pthread_mutex_lock(&g_mutex); g_ws_shutdown = 1; pthread_cond_broadcast(&g_cond); + pthread_mutex_unlock(&g_mutex); } void ws_cleanup(void) diff --git a/src/providers/local.c b/src/providers/local.c index 1bcd4aa..0e19ae0 100644 --- a/src/providers/local.c +++ b/src/providers/local.c @@ -221,12 +221,12 @@ static void local_cleanup(void) s_local_reprobe_last_wall = (time_t)0; } -#ifdef SHELLCLAW_TEST -int local_provider_is_unavailable_for_test(void) +int provider_local_is_unavailable(void) { return s_local_unavailable; } +#ifdef SHELLCLAW_TEST void local_provider_test_reset(void) { s_local_test_http_body = NULL; diff --git a/src/providers/provider.h b/src/providers/provider.h index 8e3ea99..ce47284 100644 --- a/src/providers/provider.h +++ b/src/providers/provider.h @@ -158,11 +158,13 @@ const provider_t *provider_local_get(void); void provider_local_set_live_config(const config_t *cfg); /** Lightweight GET probe via `/v1/models` or `/health`; used by init, chat retry, and router recovery. */ int provider_local_endpoint_reachable(const char *endpoint); + +/** Return 1 if the last probe found the local server unavailable. */ +int provider_local_is_unavailable(void); /** After a successful recovery GET probe on local; clears init-time unreachable flag. */ void provider_local_recovery_probe_succeeded(void); #ifdef SHELLCLAW_TEST -int local_provider_is_unavailable_for_test(void); void local_provider_test_reset(void); void local_provider_test_set_http_response(const char *json_body); void local_provider_test_set_skip_probe(int skip); diff --git a/src/providers/router.c b/src/providers/router.c index 20098a2..2762912 100644 --- a/src/providers/router.c +++ b/src/providers/router.c @@ -316,7 +316,8 @@ static int fallback_composite_init(const config_t *cfg) return -1; } router_snap_set_active(g_backends[0]->name ? g_backends[0]->name : "", 0U); - snapshot_set_last_err(""); + if (g_backends[0] == provider_local_get() && provider_local_is_unavailable()) + snapshot_set_last_err("Local inference server unreachable"); g_recovery_last_wall = time(NULL); return 0; } @@ -358,7 +359,8 @@ static int fallback_composite_chat(const provider_message_t *messages, size_t me return 0; } snapshot_set_last_err(response && response->content ? response->content : ""); - if (!provider_error_allows_fallback_retry(response && response->content ? response->content : NULL)) + if (ix + 1U == g_backend_count || + !provider_error_allows_fallback_retry(response ? response->content : NULL)) return ret; provider_response_clear(response); } diff --git a/systemd/llama-server.jetson.env b/systemd/llama-server.jetson.env index 391e4f6..ff17b87 100644 --- a/systemd/llama-server.jetson.env +++ b/systemd/llama-server.jetson.env @@ -1,5 +1,5 @@ # Jetson Orin Nano Super defaults for llama-server.service (Phase 5 Q-MODEL). -# Install (Task 3.5) copies this file to /etc/shellclaw/llama-server.env. +# The installer copies this file to ~/.shellclaw/llama-server.env. # # To swap model: point MODEL= at a different GGUF under /var/lib/shellclaw/models/ # (filenames from scripts/download_model.sh), then restart llama-server.service: diff --git a/systemd/llama-server.rpi.env b/systemd/llama-server.rpi.env index 15dfca8..6cf572c 100644 --- a/systemd/llama-server.rpi.env +++ b/systemd/llama-server.rpi.env @@ -1,5 +1,5 @@ # Raspberry Pi defaults for llama-server.service (Phase 5). -# Install (Task 3.5) copies this file to /etc/shellclaw/llama-server.env. +# The installer copies this file to ~/.shellclaw/llama-server.env. # # To swap model: point MODEL= at a different GGUF under /var/lib/shellclaw/models/ # (filenames from scripts/download_model.sh), then restart llama-server.service: diff --git a/systemd/llama-server.service b/systemd/llama-server.service index 3c1ab73..61e3c27 100644 --- a/systemd/llama-server.service +++ b/systemd/llama-server.service @@ -1,7 +1,7 @@ # Optional llama.cpp HTTP server consumed by ShellClaw local provider (PRD §4.4.29) # # Board-specific defaults: systemd/llama-server.jetson.env or llama-server.rpi.env. -# Install copies one to /etc/shellclaw/llama-server.env (Task 3.5). Port must match +# The installer copies one to %h/.shellclaw/llama-server.env. Port must match # [providers.local] in config.toml (default http://127.0.0.1:8080). [Unit] Description=llama.cpp HTTP server for ShellClaw fallback @@ -9,7 +9,7 @@ After=network.target [Service] Type=simple -EnvironmentFile=/etc/shellclaw/llama-server.env +EnvironmentFile=%h/.shellclaw/llama-server.env ExecStart=/usr/local/bin/llama-server --model "${MODEL}" --host 127.0.0.1 --port "${PORT}" -t "${THREADS}" -ngl "${NGL}" -c "${CTX_SIZE}" Restart=on-failure RestartSec=5 diff --git a/systemd/shellclaw.service b/systemd/shellclaw.service index 0f79a67..2eda8cd 100644 --- a/systemd/shellclaw.service +++ b/systemd/shellclaw.service @@ -5,14 +5,13 @@ [Unit] Description=ShellClaw autonomous agent After=network-online.target llama-server.service -Wants=network-online.target llama-server.service +Wants=network-online.target [Service] Type=simple Environment=SHELLCLAW_HOME=%h/.shellclaw -Environment=SHELLCLAW_INSTALL_BIN=%h/.local/bin/shellclaw EnvironmentFile=-%h/.shellclaw/.env -ExecStart=%h/.local/bin/shellclaw --config %h/.shellclaw/config.toml +ExecStart=%h/.local/bin/shellclaw --config %h/.shellclaw/config.toml --headless Restart=on-failure RestartSec=5 diff --git a/tests/test_bootstrap_keys.c b/tests/test_bootstrap_keys.c index 16369c8..4494c5b 100644 --- a/tests/test_bootstrap_keys.c +++ b/tests/test_bootstrap_keys.c @@ -45,6 +45,7 @@ static int test_cli_starts_without_keys_dir(void) ASSERT(f); fprintf(f, "[agent]\nmodel = \"bootstrap-keys-test\"\nmax_tool_iterations = 3\n\n" + "[providers]\nfallback_chain = [\"stub\"]\n\n" "[memory]\ndb_path = \"%s\"\n", db_path); fclose(f); diff --git a/tests/test_cli.c b/tests/test_cli.c index 74b940f..b2a72c7 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -7,6 +7,7 @@ #include "core/config.h" #include #include +#include static int tests_run = 0; static int tests_failed = 0; @@ -62,6 +63,42 @@ static void test_cli_one_shot_consumed_after_poll(void) ch->cleanup(); } +static void test_cli_piped_input_keeps_the_last_line(void) +{ + const channel_t *ch = channel_cli_get(); + channel_incoming_msg_t msg = {0}; + const char input[] = "first\nlast"; + int input_pipe[2]; + int saved_stdin = dup(STDIN_FILENO); + + MU_ASSERT(pipe(input_pipe) == 0, "open input pipe"); + MU_ASSERT(write(input_pipe[1], input, sizeof(input) - 1) == sizeof(input) - 1, "write both lines"); + close(input_pipe[1]); + MU_ASSERT(dup2(input_pipe[0], STDIN_FILENO) == STDIN_FILENO, "replace stdin"); + if (input_pipe[0] != STDIN_FILENO) + close(input_pipe[0]); + + ch->init(NULL); + int first_result = ch->poll(&msg, 0); + int first_matches = msg.text && strcmp(msg.text, "first") == 0; + channel_incoming_msg_clear(&msg); + int last_result = ch->poll(&msg, 0); + int last_matches = msg.text && strcmp(msg.text, "last") == 0; + channel_incoming_msg_clear(&msg); + int closed = ch->poll(&msg, 0); + ch->cleanup(); + + if (saved_stdin >= 0) { + dup2(saved_stdin, STDIN_FILENO); + close(saved_stdin); + } else { + close(STDIN_FILENO); + } + MU_ASSERT(first_result == 1 && first_matches, "read the first piped line"); + MU_ASSERT(last_result == 1 && last_matches, "read the final line without a newline"); + MU_ASSERT(closed == CHANNEL_POLL_CLOSED, "report closed input"); +} + static void test_cli_send_succeeds(void) { const channel_t *ch = channel_cli_get(); @@ -77,6 +114,7 @@ int main(void) MU_RUN(test_cli_one_shot_returns_message); MU_RUN(test_cli_one_shot_consumed_after_poll); MU_RUN(test_cli_send_succeeds); + MU_RUN(test_cli_piped_input_keeps_the_last_line); printf("%d tests run, %d failed\n", tests_run, tests_failed); return tests_failed ? 1 : 0; } diff --git a/tests/test_daemon_smoke.sh b/tests/test_daemon_smoke.sh index ffa0809..7895851 100755 --- a/tests/test_daemon_smoke.sh +++ b/tests/test_daemon_smoke.sh @@ -36,6 +36,35 @@ if [[ "${stub_out}" != "stub" ]]; then exit 1 fi +# systemd sets INVOCATION_ID and uses /dev/null for the old unit's stdin. +service_id=7d2d19cbe1f748b7be0651d680b95b51 +SHELLCLAW_INSTALL_BIN="${BIN}" INVOCATION_ID="${service_id}" \ + "${BIN}" --config "${CFG}" /dev/null; then + echo "test_daemon_smoke: ShellClaw exited after EOF in the old systemd unit" >&2 + exit 1 +fi +kill "${service_pid}" +wait "${service_pid}" + +# A systemd service can also pass a finite stream from its caller. +printf '/help\n' | INVOCATION_ID="${service_id}" "${BIN}" --config "${CFG}" >"${TMP_HOME}/pipe.log" & +pipe_pid=$! +for ((i = 0; i < 50; i++)); do + kill -0 "${pipe_pid}" 2>/dev/null || break + sleep 0.1 +done +if kill -0 "${pipe_pid}" 2>/dev/null; then + kill "${pipe_pid}" + wait "${pipe_pid}" || true + echo "test_daemon_smoke: ShellClaw stayed active after the service pipe closed" >&2 + exit 1 +fi +wait "${pipe_pid}" +grep -Fq '/reset' "${TMP_HOME}/pipe.log" + "${BIN}" --daemon --config "${CFG}" sleep 1 diff --git a/tests/test_dispatch.c b/tests/test_dispatch.c index a2f6d2c..1cae681 100644 --- a/tests/test_dispatch.c +++ b/tests/test_dispatch.c @@ -257,7 +257,7 @@ static int test_status_returns_version(void) ASSERT(handle_message(&mock_channel, &msg) == 0); ASSERT(g_send_calls == 1); ASSERT(strstr(g_last_text, "ShellClaw " SHELLCLAW_RELEASE_VERSION) != NULL); - ASSERT(strstr(g_last_text, "agent ready") != NULL); + ASSERT(strstr(g_last_text, "No provider is selected.") != NULL); return 0; } @@ -281,7 +281,7 @@ static int test_agent_failure_fallback_message(void) msg.session_id = "cli:fail"; msg.text = "hello"; - ASSERT(handle_message(&mock_channel, &msg) == 0); + ASSERT(handle_message(&mock_channel, &msg) == -1); ASSERT(g_send_calls == 1); ASSERT(strstr(g_last_text, "Error: agent failed (code -1)") != NULL); @@ -443,7 +443,8 @@ static int test_cron_agent_failure_does_not_ack(void) msg.session_id = "cli:default"; msg.user_id = "cron_fail"; msg.text = "hello"; - ASSERT(handle_message(&cron_mock_channel, &msg) == 0); + ASSERT(handle_message(&cron_mock_channel, &msg) == -1); + ASSERT(g_send_calls == 1); memset(&row, 0, sizeof(row)); ASSERT(cron_job_get_by_id("cron_fail", &row) == 1); ASSERT(row.next_run == due_at); @@ -518,7 +519,7 @@ static int test_cron_blank_reply_acks_without_sending(void) g_spy_openai_body = bodies[i]; msg.user_id = id; msg.session_id = (char *)routes[i]; - ASSERT(handle_message(cron, &msg) == (i == 0 ? -1 : 0)); + ASSERT(handle_message(cron, &msg) == (i < 3 ? -1 : 0)); ASSERT(g_send_calls == (i == 1 || i == 2 ? 1 : 0)); ASSERT(cron_job_get_by_id(id, &row) == (i < 3 ? 1 : 0)); if (i < 3) diff --git a/tests/test_gateway_http.c b/tests/test_gateway_http.c index a1e61bc..5f61573 100644 --- a/tests/test_gateway_http.c +++ b/tests/test_gateway_http.c @@ -1699,6 +1699,49 @@ static int test_api_hardware_camera_deferred(const char *token) return 0; } +static pid_t start_gateway(const char *config_path) +{ + pid_t pid = fork(); + if (pid < 0) { + fprintf(stderr, "test_gateway_http: fork failed\n"); + return -1; + } + if (pid == 0) { + int devnull = open("/dev/null", O_WRONLY); + if (devnull >= 0) { + dup2(devnull, STDOUT_FILENO); + dup2(devnull, STDERR_FILENO); + close(devnull); + } + execl("./build/shellclaw", "shellclaw", "--config", config_path, (char *)NULL); + _exit(1); + } + return pid; +} + +static int test_idle_shutdown(pid_t pid) +{ + const struct timespec delay = { .tv_sec = 0, .tv_nsec = 50000000L }; + int status; + + if (wait_for_health(40) == 0 && kill(pid, SIGTERM) == 0) { + for (int i = 0; i < 80; i++) { + pid_t result = waitpid(pid, &status, WNOHANG); + if (result == pid) { + ASSERT(WIFEXITED(status) && WEXITSTATUS(status) == 0); + return 0; + } + if (result < 0 && errno != EINTR) + break; + (void)nanosleep(&delay, NULL); + } + } + fprintf(stderr, "FAIL: idle gateway did not exit after SIGTERM\n"); + kill(pid, SIGKILL); + waitpid(pid, NULL, 0); + return 1; +} + int main(int argc, char **argv) { (void)argc; @@ -1754,21 +1797,14 @@ int main(int argc, char **argv) fclose(f); setenv("HOME", g_test_home, 1); setenv("SHELLCLAW_TEST_MODE", "1", 1); - pid_t pid = fork(); - if (pid < 0) { - fprintf(stderr, "test_gateway_http: fork failed\n"); + pid_t pid = start_gateway(config_path); + if (pid < 0) + return 1; + if (test_idle_shutdown(pid) != 0) + return 1; + pid = start_gateway(config_path); + if (pid < 0) return 1; - } - if (pid == 0) { - int devnull = open("/dev/null", O_WRONLY); - if (devnull >= 0) { - dup2(devnull, STDOUT_FILENO); - dup2(devnull, STDERR_FILENO); - close(devnull); - } - execl("./build/shellclaw", "shellclaw", "--config", config_path, (char *)NULL); - _exit(1); - } char pairing_code[16] = {0}; if (wait_for_health(40) != 0) { fprintf(stderr, "test_gateway_http: /health poll timeout on %s\n", g_base_url); diff --git a/tests/test_install_script.sh b/tests/test_install_script.sh index deeecc7..b47622e 100755 --- a/tests/test_install_script.sh +++ b/tests/test_install_script.sh @@ -9,10 +9,20 @@ export HOME="${sandbox}/home" export XDG_CONFIG_HOME="${HOME}/.config" mkdir -p "${HOME}" +# Use a source fixture so these tests control whether a build is available. +repo="${ROOT}" +ROOT="${sandbox}/source" +mkdir -p "${ROOT}/scripts" "${ROOT}/build" +cp "${repo}/scripts/install.sh" "${ROOT}/scripts/" +cp "${repo}/config.example.toml" "${repo}/.env.example" "${ROOT}/" +cp -R "${repo}/systemd" "${ROOT}/" + fake_bin="${sandbox}/bin" mkdir -p "${fake_bin}" fake_shellclaw="${fake_bin}/shellclaw" -etc_dir="${sandbox}/etc/shellclaw" +etc_dir="${sandbox}/etc /shellclaw%h" +state_dir="${sandbox}/claw & state" +unset SHELLCLAW_INSTALL_BIN SHELLCLAW_HOME SHELLCLAW_ETC_DIR unit_dir="${XDG_CONFIG_HOME}/systemd/user" jetson_marker="Phi-3-mini-4k-instruct-Q4_K_M.gguf" rpi_marker="tinyllama-1.1b-chat-Q4_K_M.gguf" @@ -21,6 +31,9 @@ write_fake_shellclaw() { local board="$1" cat >"${fake_shellclaw}" <"${HOME}/.shellclaw/${file}" +done +SHELLCLAW_INSTALL_NONINTERACTIVE=1 bash "${ROOT}/scripts/install.sh" +for file in config.toml .env llama-server.env; do + grep -Fx '# local file' "${HOME}/.shellclaw/${file}" +done + +# A custom path with an older executable must keep its binary and units. +cp -R "${unit_dir}" "${sandbox}/previous-units" +compatible_bin="${sandbox}/compatible-shellclaw" +cp "${fake_shellclaw}" "${compatible_bin}" +cat >"${fake_shellclaw}" <<'EOF' +#!/usr/bin/env bash +case "$*" in + --help) echo "Usage: shellclaw [--help] [--detect-board]" ;; + --detect-board) echo stub ;; + *) exit 1 ;; +esac +EOF +cp "${fake_shellclaw}" "${sandbox}/previous-binary" + +for build in absent present; do + if [[ "${build}" == present ]]; then + cp "${compatible_bin}" "${ROOT}/build/shellclaw" + fi + if SHELLCLAW_INSTALL_BIN="${fake_shellclaw}" SHELLCLAW_INSTALL_NONINTERACTIVE=1 \ + bash "${ROOT}/scripts/install.sh" >"${sandbox}/rejected.log" 2>&1; then + printf 'test_install_script: incompatible custom binary accepted with build %s\n' "${build}" >&2 + exit 1 + fi + grep -F -- '--headless' "${sandbox}/rejected.log" + cmp "${fake_shellclaw}" "${sandbox}/previous-binary" + diff -r "${unit_dir}" "${sandbox}/previous-units" +done + +cp "${compatible_bin}" "${fake_shellclaw}" +SHELLCLAW_INSTALL_BIN="${fake_shellclaw}" SHELLCLAW_INSTALL_NONINTERACTIVE=1 \ + bash "${ROOT}/scripts/install.sh" +grep -Fx "ExecStart=:/usr/bin/env -- \"${fake_shellclaw}\" --config \"${HOME}/.shellclaw/config.toml\" --headless" \ + "${unit_dir}/shellclaw.service" +cmp "${fake_shellclaw}" "${compatible_bin}" + +invalid_xdg="${sandbox}/invalid-xdg" +touch "${sandbox}/not-a-directory" +if XDG_CONFIG_HOME="${invalid_xdg}" SHELLCLAW_ETC_DIR="${sandbox}/not-a-directory" \ + SHELLCLAW_INSTALL_NONINTERACTIVE=1 bash "${ROOT}/scripts/install.sh"; then + echo "test_install_script: invalid destination accepted" >&2 + exit 1 +fi +test ! -e "${invalid_xdg}/systemd/user/shellclaw.service" +test ! -e "${invalid_xdg}/systemd/user/llama-server.service" + +if SHELLCLAW_HOME="${sandbox}/state*" SHELLCLAW_INSTALL_NONINTERACTIVE=1 \ + bash "${ROOT}/scripts/install.sh"; then + echo "test_install_script: wildcard in environment file path accepted" >&2 + exit 1 +fi +test ! -e "${sandbox}/state*" + echo "test_install_script: OK" diff --git a/tests/test_local_provider.c b/tests/test_local_provider.c index 1b4dc13..dd81d27 100644 --- a/tests/test_local_provider.c +++ b/tests/test_local_provider.c @@ -60,7 +60,7 @@ static int test_init_unreachable_sets_unavailable_then_chat_errors(void) const provider_t *p = provider_local_get(); ASSERT(p->init(cfg) == 0); #ifdef SHELLCLAW_TEST - ASSERT(local_provider_is_unavailable_for_test() != 0); + ASSERT(provider_local_is_unavailable() != 0); #endif provider_message_t msg = { .role = "user", .content = "hello", .tool_calls = NULL, .tool_calls_count = 0, .tool_use_id = NULL }; provider_response_t response = {0}; @@ -101,7 +101,7 @@ static int test_chat_reprobes_when_server_comes_up(void) p = provider_local_get(); ASSERT(p->init(cfg) == 0); #ifdef SHELLCLAW_TEST - ASSERT(local_provider_is_unavailable_for_test() != 0); + ASSERT(provider_local_is_unavailable() != 0); #endif local_provider_test_set_skip_probe(1); local_provider_test_set_http_response( @@ -111,7 +111,7 @@ static int test_chat_reprobes_when_server_comes_up(void) ASSERT(response.content != NULL); ASSERT(strstr(response.content, "back online") != NULL); #ifdef SHELLCLAW_TEST - ASSERT(local_provider_is_unavailable_for_test() == 0); + ASSERT(provider_local_is_unavailable() == 0); #endif p->cleanup(); provider_response_clear(&response); @@ -150,7 +150,7 @@ static int test_chat_reprobe_throttled_within_min_interval(void) p = provider_local_get(); ASSERT(p->init(cfg) == 0); #ifdef SHELLCLAW_TEST - ASSERT(local_provider_is_unavailable_for_test() != 0); + ASSERT(provider_local_is_unavailable() != 0); #endif /* First chat after the startup miss: the probe runs against port 1 * and fails, arming the throttle window. */ @@ -172,7 +172,7 @@ static int test_chat_reprobe_throttled_within_min_interval(void) local_provider_test_reset(); ASSERT(p->init(cfg) == 0); #ifdef SHELLCLAW_TEST - ASSERT(local_provider_is_unavailable_for_test() != 0); + ASSERT(provider_local_is_unavailable() != 0); #endif local_provider_test_set_skip_probe(1); local_provider_test_set_http_response( diff --git a/tests/test_router.c b/tests/test_router.c index ee76497..011fc6f 100644 --- a/tests/test_router.c +++ b/tests/test_router.c @@ -473,6 +473,7 @@ static int test_fallback_chain_all_backends_fail_records_last_error(void) msg.content = "hi"; memset(&resp, 0, sizeof(resp)); ASSERT(router->chat(&msg, 1, NULL, 0, &resp) != 0); + ASSERT(resp.content != NULL && strstr(resp.content, "Connection refused") != NULL); provider_router_last_error_snapshot(snap_err, sizeof(snap_err)); ASSERT(strstr(snap_err, "Connection refused") != NULL); json = provider_router_api_status_json();