Distribute and run LLMs with a single file.
C++ cross-platformggufllama-cpplocal-ailocal-inferencelocal-llmopen-source-aisingle-file-executablespeech-to-text
Agentfile v0.0000001 (#1060)
Davide Eynardce6a2a03b844
diff --git a/.gitmodules b/.gitmodulesindex bb112767..e0fff699 100644--- a/.gitmodules+++ b/.gitmodules@@ -10,6 +10,9 @@[submodule "third_party/zipalign"]path = third_party/zipalignurl = https://github.com/jart/zipalign.git+[submodule "agent.cpp"]+ path = agent.cpp+ url = https://github.com/mozilla-ai/agent.cpp.git[submodule "transcribe.cpp"]path = transcribe.cppurl = https://github.com/handy-computer/transcribe.cpp.gitdiff --git a/Makefile b/Makefileindex ea73cd35..74f9326f 100644--- a/Makefile+++ b/Makefile@@ -18,10 +18,12 @@ include llama.cpp/BUILD.mkinclude whisper.cpp/BUILD.mkinclude transcribe.cpp/BUILD.mkinclude stable-diffusion.cpp/BUILD.mk+include agent.cpp/BUILD.mkinclude llamafile/BUILD.mkinclude whisperfile/BUILD.mkinclude transcribefile/BUILD.mkinclude diffusionfile/BUILD.mk+include agentfile/BUILD.mkinclude tests/BUILD.mkendif@@ -36,6 +38,7 @@ o/$(MODE)/: o/$(MODE)/llamafile \o/$(MODE)/transcribe.cpp \o/$(MODE)/transcribefile \o/$(MODE)/diffusionfile \+ o/$(MODE)/agentfile \o/$(MODE)/third_party/zipalign.PHONY: install@@ -47,6 +50,7 @@ install: o/$(MODE)/llamafile/llamafile \$(INSTALL) o/$(MODE)/llamafile/llamafile $(PREFIX)/bin/llamafile$(INSTALL) o/$(MODE)/whisperfile/whisperfile $(PREFIX)/bin/whisperfile$(INSTALL) o/$(MODE)/diffusionfile/diffusionfile $(PREFIX)/bin/diffusionfile+ $(INSTALL) o/$(MODE)/agentfile/agentfile $(PREFIX)/bin/agentfile$(INSTALL) o/$(MODE)/transcribefile/transcribefile $(PREFIX)/bin/transcribefile$(INSTALL) o/$(MODE)/third_party/zipalign/zipalign $(PREFIX)/bin/zipalignmkdir -p $(PREFIX)/share/man/man1@@ -124,13 +128,21 @@ setup: # Initialize and configure all dependencies (submodules, patches, etc.)echo "Initializing zipalign submodule..."; \git submodule update --init third_party/zipalign; \fi++ @if [ ! -f agent.cpp/.git ]; then \+ echo "Initializing agent.cpp submodule..."; \+ git submodule update --init agent.cpp; \+ fi+ @echo "Applying agent.cpp patches..."+ @export TMPDIR=$$(pwd)/o/tmp && ./agent.cpp.patches/apply-patches.sh+@echo "Setup complete!"@$(MAKE) cosmocc.PHONY: reset-reporeset-repo: # Reset all submodules to their original state (removes patches or any other change)@echo "Resetting submodules to original state..."- @for dir in llama.cpp whisper.cpp stable-diffusion.cpp transcribe.cpp third_party/zipalign; do \+ @for dir in llama.cpp whisper.cpp stable-diffusion.cpp transcribe.cpp third_party/zipalign agent.cpp; do \if [ -e "$$dir" ]; then \echo "Removing $$dir..."; \rm -rf "$$dir"; \diff --git a/RELEASE.md b/RELEASE.mdindex 965df50a..eae2e313 100644--- a/RELEASE.md+++ b/RELEASE.md@@ -48,6 +48,7 @@ The zip is structured as follows.llamafile-<version>|-- README.md|-- bin+| |-- agentfile| |-- diffusionfile| |-- llamafile| |-- transcribefile@@ -79,6 +80,7 @@ The following binaries are part of the release:- `whisperfile`- `diffusionfile`- `transcribefile`+- `agentfile`You can use the script to create the appropriately named binaries:diff --git a/agent.cpp b/agent.cppnew file mode 160000index 00000000..cc02877f--- /dev/null+++ b/agent.cpp@@ -0,0 +1 @@+Subproject commit cc02877fd092493bd8154a130b897bba1eb8f028diff --git a/agent.cpp.patches/apply-patches.sh b/agent.cpp.patches/apply-patches.shnew file mode 100755index 00000000..d37b3ca5--- /dev/null+++ b/agent.cpp.patches/apply-patches.sh@@ -0,0 +1,41 @@+#!/bin/bash+# Apply llamafile patches to agent.cpp submodule++set -e++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+AGENT_DIR="$SCRIPT_DIR/../agent.cpp"+PATCHES_DIR="$SCRIPT_DIR/patches"+LLAMAFILE_FILES_DIR="$SCRIPT_DIR/llamafile-files"++cd "$AGENT_DIR"++# Check if status is dirty, if so, exit+if [ -n "$(git status --porcelain)" ]; then+ echo "Git status is dirty. Please commit or stash your changes before applying patches."+ exit 1+fi++echo "Applying patches to agent.cpp submodule..."++# Copy the llamafile-specific files (BUILD.mk) into the submodule root+if [ -n "$(ls -A "$LLAMAFILE_FILES_DIR" 2>/dev/null)" ]; then+ echo "Copying llamafile-files into agent.cpp..."+ cp -r "$LLAMAFILE_FILES_DIR"/* .+fi++cd ..+echo "Applying modifications to upstream files..."+shopt -s nullglob+for patch_file in "$PATCHES_DIR"/*.patch; do+ if [ -f "$patch_file" ]; then+ echo "Applying $(basename "$patch_file")..."+ patch -p1 < "$patch_file"+ fi+done++echo ""+echo "Patches applied successfully!"+echo "Note: These changes are not committed to the submodule."+echo "To reset the submodule to its clean state, run:"+echo " cd agent.cpp && git reset --hard && git clean -fdx"diff --git a/agent.cpp.patches/llamafile-files/BUILD.mk b/agent.cpp.patches/llamafile-files/BUILD.mknew file mode 100644index 00000000..0301726a--- /dev/null+++ b/agent.cpp.patches/llamafile-files/BUILD.mk@@ -0,0 +1,93 @@+#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐+#── vi: set noet ft=make ts=8 sw=8 fenc=utf-8 :vi ────────────────────┘+#+# Copyright 2026 Mozilla.ai+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# BUILD.mk for agent.cpp library+#+# agent.cpp provides an agentic loop on top of llama.cpp:+# - Agent: orchestrates LLM <-> tool conversation+# - Model: thin wrapper around llama_context with sampler+# - Tool/Callback/Error: extension points+#+# This BUILD.mk produces a single static library (agent.cpp.a) that+# combines model.cpp + agent.cpp. Links against llama.cpp.a's common+# library for chat templating and parsing.+#+# MCP, OAuth, and OpenTelemetry support are explicitly disabled in v0.+#++PKGS += AGENT_CPP++# ==============================================================================+# Source files+# ==============================================================================++AGENT_CPP_SRCS_CPP := \+ agent.cpp/src/model.cpp \+ agent.cpp/src/agent.cpp++AGENT_CPP_OBJS := $(AGENT_CPP_SRCS_CPP:%.cpp=o/$(MODE)/%.cpp.o)++# ==============================================================================+# Include paths+# ==============================================================================++AGENT_CPP_INCLUDES := \+ -iquote agent.cpp/src \+ -iquote llama.cpp/common \+ -iquote llama.cpp/include \+ -iquote llama.cpp/ggml/include \+ -isystem llama.cpp/vendor++# ==============================================================================+# Compiler flags+# ==============================================================================++$(AGENT_CPP_OBJS): private CPPFLAGS += $(AGENT_CPP_INCLUDES)+$(AGENT_CPP_OBJS): private CCFLAGS += -DNDEBUG++o/$(MODE)/agent.cpp/%.cpp.o: agent.cpp/%.cpp agent.cpp/BUILD.mk+ @mkdir -p $(@D)+ $(COMPILE.cc) -o $@ $<++# ==============================================================================+# Combined static library+# ==============================================================================++o/$(MODE)/agent.cpp/agent.cpp.a: $(AGENT_CPP_OBJS)++# ==============================================================================+# Dependencies+# ==============================================================================++# Headers whose layout is compiled into these objects: agent.cpp's own+# classes, the llama.cpp common types they embed (common_chat_msg,+# common_sampler, ...), and the ggml, jinja and nlohmann headers those pull+# in (llamafile patches ggml-backend.h and ggml-cpu.h). AGENT_CPP declares+# no SRCS/HDRS, so mkdeps never scans these sources; without this list a+# patch to model.h or a llama.cpp bump leaves stale objects in agent.cpp.a+# (the failure AGENTFILE_EXT_HDRS in agentfile/BUILD.mk guards against for+# agentfile.o).+AGENT_CPP_DEP_HDRS := \+ $(wildcard agent.cpp/src/*.h) \+ $(wildcard llama.cpp/common/*.h) \+ $(wildcard llama.cpp/common/jinja/*.h) \+ $(wildcard llama.cpp/include/*.h) \+ $(wildcard llama.cpp/ggml/include/*.h) \+ $(wildcard llama.cpp/vendor/nlohmann/*.hpp)++$(AGENT_CPP_OBJS): agent.cpp/BUILD.mk $(AGENT_CPP_DEP_HDRS)++# ==============================================================================+# Main target+# ==============================================================================++.PHONY: o/$(MODE)/agent.cpp+o/$(MODE)/agent.cpp: o/$(MODE)/agent.cpp/agent.cpp.adiff --git a/agent.cpp.patches/patches/src_model.cpp.patch b/agent.cpp.patches/patches/src_model.cpp.patchnew file mode 100644index 00000000..b2a18110--- /dev/null+++ b/agent.cpp.patches/patches/src_model.cpp.patch@@ -0,0 +1,512 @@+diff --git a/src/model.cpp b/src/model.cpp+--- a/agent.cpp/src/model.cpp++++ b/agent.cpp/src/model.cpp+@@ -1,9 +1,14 @@+ #include "model.h"+ #include "chat.h"++#include "sampling.h" // common_sampler (llamafile)++#include "log.h" // LOG_WRN (llamafile)++#include <nlohmann/json.hpp> // heuristic tool-call recovery (llamafile)+ #include "error.h"+ #include <algorithm>+ #include <cstdio>+ #include <fstream>++#include <optional>++#include <random> // new_tool_call_id (llamafile)+ #include <sstream>++ namespace agent_cpp {+@@ -78,7 +83,7 @@ Model::create_with_weights(std::shared_ptr<ModelWeights> weights,+ Model::~Model()+ {+ if (sampler_ != nullptr) {+- llama_sampler_free(sampler_);++ common_sampler_free(sampler_);+ }+ if (ctx_ != nullptr) {+ llama_free(ctx_);+@@ -93,7 +98,6 @@ Model::Model(Model&& other) noexcept+ : weights_(std::move(other.weights_))+ , ctx_(other.ctx_)+ , sampler_(other.sampler_)+- , grammar_sampler_(other.grammar_sampler_)+ , loras_(std::move(other.loras_))+ , processed_tokens_(std::move(other.processed_tokens_))+ , n_past_(other.n_past_)+@@ -101,7 +105,6 @@ Model::Model(Model&& other) noexcept+ {+ other.ctx_ = nullptr;+ other.sampler_ = nullptr;+- other.grammar_sampler_ = nullptr;+ other.n_past_ = 0;+ }++@@ -110,7 +113,7 @@ Model::operator=(Model&& other) noexcept+ {+ if (this != &other) {+ if (sampler_ != nullptr) {+- llama_sampler_free(sampler_);++ common_sampler_free(sampler_);+ }+ if (ctx_ != nullptr) {+ llama_free(ctx_);+@@ -122,7 +125,6 @@ Model::operator=(Model&& other) noexcept+ weights_ = std::move(other.weights_);+ ctx_ = other.ctx_;+ sampler_ = other.sampler_;+- grammar_sampler_ = other.grammar_sampler_;+ loras_ = std::move(other.loras_);+ processed_tokens_ = std::move(other.processed_tokens_);+ n_past_ = other.n_past_;+@@ -130,12 +132,45 @@ Model::operator=(Model&& other) noexcept++ other.ctx_ = nullptr;+ other.sampler_ = nullptr;+- other.grammar_sampler_ = nullptr;+ other.n_past_ = 0;+ }+ return *this;+ }+++namespace {++++/// common_sampler_init() throws (it never returns nullptr) on a bad grammar++/// or a rejected grammar prefill; surface that as a library error.++common_sampler*++init_sampler(const llama_model* model,++ common_params_sampling& params,++ const char* what)++{++ try {++ return common_sampler_init(model, params);++ } catch (const std::exception& e) {++ throw ModelError(std::string(what) + ": " + e.what());++ }++}++++/// Sampling settings from ModelConfig, including the user's GBNF grammar.++common_params_sampling++sampling_params(const ModelConfig& config)++{++ common_params_sampling sp;++ sp.temp = config.temp;++ sp.top_k = config.top_k;++ sp.top_p = config.top_p;++ sp.min_p = config.min_p;++ sp.seed = config.seed;++ if (!config.grammar.empty()) {++ sp.grammar = { COMMON_GRAMMAR_TYPE_USER, config.grammar };++ }++ return sp;++}++++}+++ void+ Model::initialize_context(const ModelConfig& model_config)+ {+@@ -173,57 +208,37 @@ Model::initialize_context(const ModelConfig& model_config)+ }+ }++- sampler_ = llama_sampler_chain_init(llama_sampler_chain_default_params());+-+- if (!model_config.grammar.empty()) {+- llama_sampler* grammar_sampler =+- llama_sampler_init_grammar(weights_->get_vocab(),+- model_config.grammar.c_str(),+- model_config.grammar_root.c_str());+- if (grammar_sampler == nullptr) {+- llama_sampler_free(sampler_);+- sampler_ = nullptr;+- throw ModelError("failed to parse GBNF grammar (root rule '" ++- model_config.grammar_root + "')");+- }+- // Add grammar before the rest of the sampler chain+- llama_sampler_chain_add(sampler_, grammar_sampler);+- // Keep a non-owning reference so we can reset this sampler between+- // turns+- grammar_sampler_ = grammar_sampler;+- }+-+- llama_sampler_chain_add(sampler_,+- llama_sampler_init_top_k(model_config.top_k));+- llama_sampler_chain_add(sampler_,+- llama_sampler_init_top_p(model_config.top_p, 1));+- llama_sampler_chain_add(sampler_,+- llama_sampler_init_min_p(model_config.min_p, 1));+- llama_sampler_chain_add(sampler_,+- llama_sampler_init_temp(model_config.temp));+- llama_sampler_chain_add(sampler_,+- llama_sampler_init_dist(model_config.seed));++ // llamafile: grammar-aware common_sampler instead of a raw chain. The++ // user's GBNF grammar (if any) rides along; generate() re-inits the++ // sampler per call, with the user grammar or the chat template's++ // tool-call grammar. Note: common_grammar has no root-rule field, so the++ // grammar's start rule must be "root" (ModelConfig::grammar_root is++ // ignored).++ common_params_sampling sp = sampling_params(model_config);++ sampler_ = init_sampler(weights_->get_model(), sp,++ "failed to initialize sampler (bad GBNF grammar?)");+ }++ std::vector<llama_token>+ Model::tokenize(const std::string& prompt) const+ {+ const llama_vocab* vocab = weights_->get_vocab();+- // Use processed_tokens to determine if this is the first tokenization+- // This is important for cache loading: even if KV cache memory is+- // populated, we need IS_FIRST=true if we're tokenizing a full prompt from+- // scratch to ensure consistent BOS token handling for prefix matching+- const bool IS_FIRST = processed_tokens_.empty();++ // llamafile: every caller tokenizes a full rendered prompt from scratch++ // (the chat template strips its BOS text when the vocab adds one), so++ // always add special tokens. Keying this on processed_tokens_ dropped++ // BOS on every call after the first, which broke the KV prefix match at++ // token 0 and re-decoded the whole conversation without BOS.++ const bool ADD_SPECIAL = true;++ const int N_PROMPT_TOKENS = -llama_tokenize(+- vocab, prompt.c_str(), prompt.size(), nullptr, 0, IS_FIRST, true);++ vocab, prompt.c_str(), prompt.size(), nullptr, 0, ADD_SPECIAL, true);+ std::vector<llama_token> prompt_tokens(N_PROMPT_TOKENS);+ if (llama_tokenize(vocab,+ prompt.c_str(),+ prompt.size(),+ prompt_tokens.data(),+ prompt_tokens.size(),+- IS_FIRST,++ ADD_SPECIAL,+ true) < 0) {+ return {}; // Return empty vector on failure+ }+@@ -261,6 +276,9 @@ parse_with_parser(const common_peg_arena& parser,+ // (ggml-org/llama.cpp#18675). Without them tool calls stay as raw text.+ syntax.generation_prompt = params.generation_prompt;+ syntax.parse_tool_calls = true;++ // llamafile: extract <think>...</think> into reasoning_content instead++ // of leaving it inline in content (callers decide how to show it).++ syntax.reasoning_format = COMMON_REASONING_FORMAT_AUTO;++ try {+ auto parsed_msg =+@@ -276,6 +294,62 @@ parse_with_parser(const common_peg_arena& parser,+ }+ }+++/// llamafile: moves a leading reasoning block out of msg.content into++/// msg.reasoning_content, using the template's thinking tags. For raw text++/// the parser refused. An unclosed block is all reasoning.++void++split_reasoning(const common_chat_params& params, common_chat_msg& msg)++{++ const std::string& start = params.thinking_start_tag;++ if (start.empty() || params.thinking_end_tags.empty()) {++ return;++ }++ std::string text = msg.content;++ size_t begin = text.find_first_not_of(" \t\r\n");++ if (begin != std::string::npos &&++ text.compare(begin, start.size(), start) == 0) {++ text.erase(0, begin + start.size());++ } else {++ // The generation prompt may have opened the block already.++ std::string gp = params.generation_prompt;++ gp.erase(gp.find_last_not_of(" \t\r\n") + 1);++ if (gp.size() < start.size() ||++ gp.compare(gp.size() - start.size(), start.size(), start) != 0) {++ return;++ }++ }++ // The first end tag closes the block; others (e.g. "<tool_call>" for++ // Qwen3-Coder) also end reasoning but belong to the content.++ size_t cut = std::string::npos;++ size_t skip = 0;++ for (size_t k = 0; k < params.thinking_end_tags.size(); k++) {++ const std::string& tag = params.thinking_end_tags[k];++ size_t p = tag.empty() ? std::string::npos : text.find(tag);++ if (p < cut) {++ cut = p;++ skip = k == 0 ? tag.size() : 0;++ }++ }++ msg.reasoning_content = text.substr(0, cut);++ msg.content = cut == std::string::npos ? "" : text.substr(cut + skip);++ for (std::string* s : { &msg.reasoning_content, &msg.content }) {++ s->erase(0, s->find_first_not_of(" \t\r\n"));++ }++}++++/// llamafile: an id for a tool call the chat parser left without one.++std::string++new_tool_call_id()++{++ static std::mt19937 rng{ std::random_device{}() };++ static const char hex[] = "0123456789abcdef";++ std::string id = "call_";++ for (int i = 0; i < 8; ++i) {++ id += hex[rng() % 16];++ }++ return id;++}+++ }++ common_chat_msg+@@ -288,11 +362,97 @@ Model::generate(const std::vector<common_chat_msg>& messages,+ inputs.tools = tools;+ inputs.tool_choice = COMMON_CHAT_TOOL_CHOICE_AUTO;+ inputs.add_generation_prompt = true;+- inputs.enable_thinking = false;++ inputs.enable_thinking = config_.enable_thinking; // llamafile: was false++ // llamafile: build the template's parser with reasoning rules so any++ // <think>...</think> the model emits anyway is extracted into++ // reasoning_content (matching syntax.reasoning_format in the parse).++ inputs.reasoning_format = COMMON_REASONING_FORMAT_AUTO;++ auto params =+ common_chat_templates_apply(weights_->get_templates(), inputs);+++ // llamafile: when the chat template provides a tool-calling grammar++ // (or preserved tokens / triggers), re-init the sampler with it so++ // generation is constrained to syntactically valid tool calls. Mirrors++ // llama-server's wiring. An explicit user grammar in ModelConfig takes++ // precedence; it is rebuilt every call because common_sampler_reset()++ // resets the chain but not the grammar, and a grammar that completed on++ // the last turn would only allow EOG on this one.++ if (!config_.grammar.empty()) {++ common_params_sampling sp = sampling_params(config_);++ common_sampler* sampler = init_sampler(++ weights_->get_model(), sp,++ "failed to initialize sampler (bad GBNF grammar?)");++ common_sampler_free(sampler_);++ sampler_ = sampler;++ } else if (!params.grammar.empty() || !params.grammar_triggers.empty() ||++ !params.preserved_tokens.empty()) {++ common_params_sampling sp = sampling_params(config_);++ sp.generation_prompt = params.generation_prompt;++ sp.grammar = { COMMON_GRAMMAR_TYPE_TOOL_CALLS, params.grammar };++ sp.grammar_lazy = params.grammar_lazy;++++ const llama_vocab* vocab = weights_->get_vocab();++++ // Tell the sampler where reasoning starts and ends: a lazy grammar++ // must not fire on a tool-call tag the model writes inside <think>.++ // With these set, common_sampler keeps the grammar dormant until the++ // reasoning block closes. Mirrors server-common.cpp.++ if (!params.thinking_end_tags.empty()) {++ sp.reasoning_budget_start =++ common_tokenize(vocab, params.thinking_start_tag,++ /*add_special=*/false,++ /*parse_special=*/true);++ for (const auto& tag : params.thinking_end_tags) {++ if (!tag.empty()) {++ sp.reasoning_budget_end.push_back(++ common_tokenize(vocab, tag,++ /*add_special=*/false,++ /*parse_special=*/true));++ }++ }++ }++++ // Resolve preserved-token strings to single token ids.++ for (const auto& t : params.preserved_tokens) {++ auto ids = common_tokenize(vocab, t,++ /*add_special=*/false,++ /*parse_special=*/true);++ if (ids.size() == 1) {++ sp.preserved_tokens.insert(ids[0]);++ }++ }++++ // WORD-type triggers become TOKEN-type when the word is a single++ // preserved token. Mirrors server-task.cpp.++ for (const auto& t : params.grammar_triggers) {++ if (t.type == COMMON_GRAMMAR_TRIGGER_TYPE_WORD) {++ auto ids = common_tokenize(vocab, t.value,++ /*add_special=*/false,++ /*parse_special=*/true);++ if (ids.size() == 1 &&++ sp.preserved_tokens.count(ids[0])) {++ common_grammar_trigger trig;++ trig.type = COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN;++ trig.value = t.value;++ trig.token = ids[0];++ sp.grammar_triggers.push_back(std::move(trig));++ } else {++ sp.grammar_triggers.push_back(t);++ }++ } else {++ sp.grammar_triggers.push_back(t);++ }++ }++++ // Swap only once the new sampler exists: if init throws, sampler_++ // must still be the live one that ~Model frees.++ common_sampler* sampler = init_sampler(++ weights_->get_model(), sp, "failed to initialize tool-call sampler");++ common_sampler_free(sampler_);++ sampler_ = sampler;++ }+++ // Tokenize the prompt+ std::vector<llama_token> prompt_tokens = tokenize(params.prompt);+ if (prompt_tokens.empty()) {+@@ -308,8 +468,114 @@ Model::generate(const std::vector<common_chat_msg>& messages,+ parser_source_ = params.parser;+ }++- return parse_with_parser(+- parser_arena_, params, response, config_.chat_format);++ common_chat_msg parsed_msg;++ std::optional<ModelError> parse_error;++ try {++ parsed_msg = parse_with_parser(++ parser_arena_, params, response, config_.chat_format);++ } catch (const ModelError& e) {++ // llamafile: a parse refusal must not kill the agent loop. Fall++ // back to content-only, with the reasoning split off so it is++ // neither returned as the answer nor scanned for tool calls; the++ // recovery scan below may still lift tool calls out of the rest.++ LOG_WRN("[agent.cpp] %s; using heuristic recovery\n", e.what());++ // common_log prints from a worker thread; flush so the warning++ // lands before a confirmation prompt for a call recovered here.++ common_log_flush(common_log_main());++ parse_error = e;++ parsed_msg.content = response;++ split_reasoning(params, parsed_msg);++ }++ // A reply that ends inside a reasoning block it never closed, with++ // nothing else, holds the model's answer in that block: small models++ // do this after a tool result. Take it as the content, so a tool call++ // in it is recovered below like one the parser left in the content.++ bool unclosed_reasoning = false;++ if (parsed_msg.tool_calls.empty() && parsed_msg.content.empty() &&++ !parsed_msg.reasoning_content.empty() &&++ std::none_of(params.thinking_end_tags.begin(),++ params.thinking_end_tags.end(),++ [&](const std::string& tag) {++ return !tag.empty() &&++ response.find(tag) != std::string::npos;++ })) {++ parsed_msg.content = std::move(parsed_msg.reasoning_content);++ parsed_msg.reasoning_content.clear();++ unclosed_reasoning = true;++ }++ // llamafile heuristic recovery: lift <tool_call>{json}</tool_call>++ // blocks out of the content. Only when the parser failed, has no++ // tool-call format of its own (no grammar), or read the text as++ // reasoning (above): after a clean parse by a tool-aware parser, such++ // text in the content is prose, not a call.++ if (parsed_msg.tool_calls.empty() &&++ (parse_error || params.grammar.empty() || unclosed_reasoning)) {++ const std::string text = parsed_msg.content;++ const std::string open = "<tool_call>";++ const std::string close = "</tool_call>";++ std::string content_clean;++ size_t i = 0;++ while (i < text.size()) {++ auto a = text.find(open, i);++ if (a == std::string::npos) {++ content_clean.append(text, i, std::string::npos);++ break;++ }++ content_clean.append(text, i, a - i);++ auto b = text.find(close, a + open.size());++ if (b == std::string::npos) break;++ std::string payload =++ text.substr(a + open.size(), b - (a + open.size()));++ size_t s = payload.find_first_not_of(" \t\r\n");++ size_t e2 = payload.find_last_not_of(" \t\r\n");++ if (s != std::string::npos && e2 != std::string::npos) {++ payload = payload.substr(s, e2 - s + 1);++ }++ try {++ // ordered_json keeps the keys in the order the model wrote++ // them, so the next prompt renders this call exactly as it++ // was generated and reuses its tokens from the KV cache.++ auto j = nlohmann::ordered_json::parse(payload);++ common_chat_tool_call call;++ call.name = j.value("name", std::string{});++ // Calls to parameterless tools often omit "arguments", and++ // some models say "parameters"; the tool loop needs JSON.++ auto args = nlohmann::ordered_json::object();++ if (j.contains("arguments")) {++ args = j["arguments"];++ } else if (j.contains("parameters")) {++ args = j["parameters"];++ }++ call.arguments =++ args.is_string() ? args.get<std::string>() : args.dump();++ if (!call.name.empty()) {++ parsed_msg.tool_calls.push_back(std::move(call));++ }++ } catch (...) {++ content_clean.append(open).append(payload).append(close);++ }++ i = b + close.size();++ }++ if (!parsed_msg.tool_calls.empty()) {++ parsed_msg.content = content_clean;++ }++ }++ // A tool call the parser refused and recovery could not lift is not an++ // answer: report the parse error rather than return the raw markup.++ if (parse_error && parsed_msg.tool_calls.empty() &&++ parsed_msg.content.find("<tool_call>") != std::string::npos) {++ throw *parse_error;++ }++ // llamafile: every tool call gets an id, as llama-server gives them, so++ // the tool result can name the call it answers. Some templates' parsers++ // leave ids empty, and so does the recovery above.++ for (auto& call : parsed_msg.tool_calls) {++ if (call.id.empty()) {++ call.id = new_tool_call_id();++ }++ }++ parsed_msg.role = "assistant";++ return parsed_msg;+ }++ common_chat_msg+@@ -338,10 +604,16 @@ Model::generate_from_tokens(const std::vector<llama_token>& all_tokens,+ common_prefix++;+ }++- // If tokens diverged, clear KV cache from divergence point onwards++ // If tokens diverged, clear KV cache from divergence point onwards.++ // llamafile: recurrent/hybrid models cannot rewind their state to a++ // mid-sequence position — llama_memory_seq_rm refuses and returns++ // false. Fall back to dropping the whole memory and re-decoding.+ if (common_prefix < processed_tokens_.size()) {+ llama_memory_t mem = llama_get_memory(ctx_);+- llama_memory_seq_rm(mem, 0, common_prefix, -1);++ if (!llama_memory_seq_rm(mem, 0, common_prefix, -1)) {++ llama_memory_clear(mem, /*data=*/true);++ common_prefix = 0;++ }+ processed_tokens_.resize(common_prefix);+ n_past_ = common_prefix;+ }+@@ -370,15 +642,15 @@ Model::generate_from_tokens(const std::vector<llama_token>& all_tokens,+ i += batch_size;+ }++- // Reset the grammar sampler before each turn so a finished grammar does+- // not force EOS on the next call.+- if (grammar_sampler_ != nullptr) {+- llama_sampler_reset(grammar_sampler_);+- }++ // Reset the sampler chain before each turn. This leaves the grammar++ // alone; generate() rebuilds the sampler when a grammar must restart.++ common_sampler_reset(sampler_);++ llama_token new_token_id{};+ while (true) {+- new_token_id = llama_sampler_sample(sampler_, ctx_, -1);++ new_token_id = common_sampler_sample(sampler_, ctx_, -1);++ common_sampler_accept(sampler_, new_token_id,++ /*accept_grammar=*/true);++ if (llama_vocab_is_eog(vocab, new_token_id)) {+ break;diff --git a/agent.cpp.patches/patches/src_model.h.patch b/agent.cpp.patches/patches/src_model.h.patchnew file mode 100644index 00000000..efd9bfae--- /dev/null+++ b/agent.cpp.patches/patches/src_model.h.patch@@ -0,0 +1,29 @@+diff --git a/src/model.h b/src/model.h+--- a/agent.cpp/src/model.h++++ b/agent.cpp/src/model.h+@@ -49,6 +49,10 @@ struct ModelConfig+ // loaded from the shared ModelWeights' base model, so different Model+ // instances sharing the same weights can each carry their own set.+ std::vector<LoraAdapterConfig> loras;++ // llamafile: ask the chat template to enable model reasoning++ // (<think> blocks). Off by default: agent turns favor latency, and++ // reasoning is extracted to reasoning_content when it appears anyway.++ bool enable_thinking = false;+ };++ /// Reads a GBNF file into a string for ModelConfig::grammar+@@ -225,10 +229,10 @@ class Model++ std::shared_ptr<ModelWeights> weights_;+ llama_context* ctx_ = nullptr;+- llama_sampler* sampler_ = nullptr;+- // Non-owning pointer to the grammar sampler in sampler_'s chain+- // Reset this one between turns without resetting the rest of the chain+- llama_sampler* grammar_sampler_ = nullptr;++ // Grammar-aware sampler (llamafile: common_sampler instead of a raw++ // llama_sampler chain, so chat-template tool-call grammars and the++ // user's GBNF grammar both constrain sampling).++ struct common_sampler* sampler_ = nullptr;+ // Owning handles for this Model's LoRA adapters, in ModelConfig::loras+ // order. Set on this Model's context only, so different Model instances+ // sharing the same ModelWeights can carry independent adapters.diff --git a/agentfile/BUILD.mk b/agentfile/BUILD.mknew file mode 100644index 00000000..f56b0171--- /dev/null+++ b/agentfile/BUILD.mk@@ -0,0 +1,135 @@+#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐+#── vi: set noet ft=make ts=8 sw=8 fenc=utf-8 :vi ────────────────────┘+#+# Copyright 2026 Mozilla.ai+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# BUILD.mk for agentfile (agentic CLI binary)+#+# agentfile is a cosmocc-compiled APE binary that runs an agentic loop+# end-to-end from a single CLI invocation. It builds on pieces the tree+# already compiles: agent.cpp's Agent/Model (loop + llama.cpp wrapper),+# llama.cpp's server-tools objects (the tool implementations), llama.cpp.a,+# and the TOOL_LLAMAFILE_OBJS providing GPU dispatch + zip filesystem.+#++PKGS += AGENTFILE++# ==============================================================================+# Source files+# ==============================================================================++AGENTFILE_SRCS_CPP := \+ agentfile/agentfile.cpp++# _DEP_HDRS, not _HDRS: deps.mk collects $(PKG)_SRCS/_HDRS/_INCS for+# mkdeps, which would scan these headers and warn about includes it cannot+# resolve (agent.cpp and llama.cpp declare no header lists). Like+# AGENT_CPP_DEP_HDRS, this list only triggers recompiles.+AGENTFILE_DEP_HDRS := $(wildcard agentfile/*.h) \+ $(wildcard agentfile/callbacks/*.h) \+ $(wildcard agentfile/tools/*.h)++# Headers from other projects that agentfile.cpp includes (agent.cpp's+# list plus server, mtmd, vendored and llamafile ones). A submodule bump+# changes them without touching agentfile sources, and a stale agentfile.o+# then fails to link against the new objects.+AGENTFILE_EXT_HDRS := \+ $(AGENT_CPP_DEP_HDRS) \+ $(wildcard llama.cpp/tools/server/server-*.h) \+ $(wildcard llama.cpp/tools/mtmd/*.h) \+ llama.cpp/vendor/cpp-httplib/httplib.h \+ llama.cpp/vendor/sheredom/subprocess.h \+ llamafile/llamafile.h++# llama.cpp server-tools objects the adapter needs (tool implementations+# plus the TUs providing their symbols; no server.cpp — that has main()).+AGENTFILE_SERVER_OBJS := \+ o/$(MODE)/llama.cpp/tools/server/server-tools.cpp.o \+ o/$(MODE)/llama.cpp/tools/server/server-common.cpp.o \+ o/$(MODE)/llama.cpp/tools/server/server-queue.cpp.o \+ o/$(MODE)/llama.cpp/tools/server/server-mcp.cpp.o \+ o/$(MODE)/llama.cpp/tools/server/server-http.cpp.o++AGENTFILE_OBJS := $(AGENTFILE_SRCS_CPP:%.cpp=o/$(MODE)/%.o)++# ==============================================================================+# Include paths+# ==============================================================================++AGENTFILE_INCLUDES := \+ -iquote agentfile \+ -iquote llamafile \+ -iquote agent.cpp/src \+ -iquote llama.cpp/common \+ -iquote llama.cpp/include \+ -iquote llama.cpp/ggml/include \+ -iquote llama.cpp/tools/server \+ -iquote llama.cpp/tools/mtmd \+ -isystem llama.cpp/vendor++# ==============================================================================+# Compiler flags+# ==============================================================================++# COSMOCC enables the cosmo_args("/zip/.args") call in agentfile.cpp, as in+# llamafile/BUILD.mk; cosmocc itself only predefines __COSMOCC__.+AGENTFILE_CPPFLAGS := $(AGENTFILE_INCLUDES) \+ -DLLAMAFILE_VERSION_STRING=\"$(LLAMAFILE_VERSION_STRING)\" \+ -DCOSMOCC=1++# cpp-httplib is built with its Mbed TLS backend (see the HTTPS section in+# llama.cpp.patches/llamafile-files/BUILD.mk). The macro changes httplib+# class layouts, so agentfile objects that include httplib.h (http_fetch,+# web_search) must define it too, and the executable must link mbedtls.a.+AGENTFILE_CPPFLAGS += \+ -DCPPHTTPLIB_MBEDTLS_SUPPORT \+ -isystem third_party/mbedtls/include++# common/subproc.h (reached through server-common.h) switches subprocess_s+# between its real and dummy definition on LLAMA_SUBPROCESS. The server and+# common objects linked below are built with it (see the subprocess section+# in llama.cpp.patches/llamafile-files/BUILD.mk), so agentfile must agree.+AGENTFILE_CPPFLAGS += -DLLAMA_SUBPROCESS++o/$(MODE)/agentfile/%.o: agentfile/%.cpp agentfile/BUILD.mk $(AGENTFILE_DEP_HDRS) $(AGENTFILE_EXT_HDRS)+ @mkdir -p $(@D)+ $(COMPILE.cc) $(AGENTFILE_CPPFLAGS) -o $@ $<++# ==============================================================================+# Executable+# ==============================================================================+# Links:+# - agentfile sources (agentfile.cpp)+# - agent.cpp static lib (Agent, Model, ModelWeights)+# - llama.cpp static archive (ggml, llama, common)+# - llamafile objects for runtime GPU dispatch + zip filesystem+# - LLAMAFILE_METAL_SOURCES: embedded Metal kernel sources (macOS)+# - TINYBLAS_CPU_OBJS for matmul kernels+# - HTTPLIB_OBJS: cpp-httplib implementation (server tools, http_fetch,+# web_search)++o/$(MODE)/agentfile/agentfile: \+ $(AGENTFILE_OBJS) \+ o/$(MODE)/agent.cpp/agent.cpp.a \+ o/$(MODE)/llama.cpp/llama.cpp.a \+ o/$(MODE)/third_party/mbedtls/mbedtls.a \+ $(AGENTFILE_SERVER_OBJS) \+ $(TOOL_LLAMAFILE_OBJS) \+ $(LLAMAFILE_METAL_SOURCES) \+ $(TINYBLAS_CPU_OBJS) \+ $(HTTPLIB_OBJS)+ @mkdir -p $(@D)+ $(LINK.o) $(AGENTFILE_OBJS) o/$(MODE)/agent.cpp/agent.cpp.a $(AGENTFILE_SERVER_OBJS) $(TOOL_LLAMAFILE_OBJS) $(LLAMAFILE_METAL_SOURCES) $(TINYBLAS_CPU_OBJS) $(HTTPLIB_OBJS) o/$(MODE)/llama.cpp/llama.cpp.a o/$(MODE)/third_party/mbedtls/mbedtls.a $(LOADLIBES) $(LDLIBS) -fopenmp -lpthread -o $@++# ==============================================================================+# Main target+# ==============================================================================++.PHONY: o/$(MODE)/agentfile+o/$(MODE)/agentfile: o/$(MODE)/agentfile/agentfilediff --git a/agentfile/DESIGN.md b/agentfile/DESIGN.mdnew file mode 100644index 00000000..96a55d8d--- /dev/null+++ b/agentfile/DESIGN.md@@ -0,0 +1,323 @@+# agentfile — design++agentfile is a self-contained, multi-platform APE binary that runs a focused+agent loop from a single CLI invocation. The product promise: preconfigure an+agent (model + system prompt + tool allowlist) and share it as **one file**+that runs anywhere, llamafile-style.++Upstream llama.cpp ships the tools (server tools, isolation runtimes,+`permission_write` metadata) and a thin client-side agent loop in its web+UI. What it does not have, and what agentfile is for: a serverless one-shot+CLI, single-file packaged agents, session/trace recording, and KV-warm+packaging. agentfile is **the file format for shipping agents**, not+another harness.++## Decisions++1. **agent.cpp** provides the loop and the model wrapper: a submodule+ plus local patches (`agent.cpp.patches/`), no vendored fork, no+ upstream PRs for now.+2. **Tools come from llama.cpp's server tools** through one adapter.+ agentfile's own tools are written as `server_tool` subclasses, so the+ adapter is the only bridge.+3. **Interaction**: unix-tool one-shot by default, `-i/--interactive`+ opt-in. No TUI.+4. **Network**: `http_fetch` and `web_search` are built in, over HTTPS+ via mbedtls. No host `curl`: it would break the single-file promise.+5. **Packaging**: `.args` plus zipalign, as llamafile does.+6. **Records**: two existing formats, nothing invented: pi's session+ format and OTLP/JSON spans, written without the OTel SDK.+7. **API drift**: depending on server-tools internals is a conscious+ choice. We can pin, or start vendoring, if they churn too hard.++## Architecture++One translation unit, `agentfile.cpp`, plus headers:++- `server_tools_adapter.h`: `ServerToolbox` owns llama.cpp's+ `server_tools` registry plus the native tools; `ServerToolAdapter`+ exposes one tool as an `agent_cpp::Tool`. Every call goes through+ `server_tools::handle_post`, the handler behind llama-server's+ `POST /tools`: upstream drops the keys the model must not set (`cwd`,+ `runtime`, `resp_type`), routes the call to the `--tools-runtime`+ isolate and maps exceptions to error responses. The request body is+ also the json boundary: agent.cpp speaks `nlohmann::json`, server+ tools llama.cpp's `common_json`.+- `tools/`: native tools (`get_datetime`, `http_fetch`, `web_search`).+ They stay here because llama.cpp keeps its server tools to minimal I/O+ and shell tools, and sends date/time and web search to MCP or the web+ UI.+- `callbacks/`: agent.cpp callbacks, registered in this order:+ session recorder, confirmation, progress, iteration cap, trace, error+ recovery. The trace comes after the confirmation so tool spans+ measure execution, not the time the user spent deciding, and after the+ iteration cap so the call the cap refuses gets no chat span. Error+ recovery comes after the observers so they record a failed call as+ failed before it is handed back to the model.+- `util.h`: terminal escaping (`terminal_text`), asking on the terminal+ (`ask_terminal`), ids, timestamps.++The toolset and the record files are set up before GPU init and the+model load, so a bad `--tools`, `--tools-runtime`, `--session` or+`--trace` value fails at once.++### agent.cpp patches++Pinned at upstream `63d23da` (v0.4.0). The build compiles `src/model.cpp`+and `src/agent.cpp` against llamafile's `llama.cpp/` (never agent.cpp's own+`deps/llama.cpp`). When a llama.cpp bump breaks them, fix it in the local+patch. The patches (`src_model.{cpp,h}.patch`) do the following, and all+of it could go upstream:++- **Sampling**: `common_sampler` with the chat template's tool-call+ grammar. A user GBNF rides along as `COMMON_GRAMMAR_TYPE_USER` (caveat:+ `ModelConfig::grammar_root` is ignored, so grammars must use "root").+ The template's thinking tags become the sampler's reasoning-budget tags,+ so a lazy tool-call grammar stays dormant inside `<think>`, as in+ llama-server.+- **Reasoning round-trip**: replies are parsed with reasoning extraction,+ so `<think>` blocks land in `reasoning_content`. Re-renders then stay+ byte-stable and the KV prefix survives turns; on hybrid models+ (Qwen3.5) a rewind is a full re-prefill. Rejected alternative: an+ append-only token stream that never re-renders history. It bloats the+ context with old reasoning, fights the template's seams, and breaks as+ soon as context trimming edits history.+- **Parse failures** don't end the loop: on refusal the content is kept,+ the reasoning is split off, and `<tool_call>{json}</tool_call>` blocks+ are lifted out by a heuristic scan. The scan runs only when the parser+ failed, the template has no tool-call grammar, or the reply ended+ inside a reasoning block it never closed. A `<tool_call>` the scan+ can't lift rethrows the parse error (exit 2). Recovered arguments keep+ the model's key order, so the next prompt matches the KV cache.+- **Tool-call ids**: every call gets one (`call_` + 8 hex) when the+ template's parser leaves it empty, as llama-server does, so every tool+ result names its call whichever callbacks run.+- **KV reuse**: on recurrent state, where `llama_memory_seq_rm` returns+ false, fall back to `llama_memory_clear` and a full re-decode.+ `tokenize()` always adds special tokens; keying BOS on an empty cache+ dropped it after the first call and broke the prefix match.+- `ModelConfig::enable_thinking`, for `--think`.++## CLI++- One-shot by default. The final answer goes to **stdout**; progress,+ confirmations and errors go to **stderr**, so the answer pipes cleanly.+ On a terminal the answer is escaped with `terminal_text`, so model text+ can't erase or restyle the tool lines above it; piped output is+ unchanged.+- No `-p` and stdin not a tty: stdin is the prompt.+- `-i/--interactive`: after each answer, ask for the next message on the+ terminal (`ask_terminal`: the answer comes from stdin, or `/dev/tty`+ when stdin was a pipe; the question goes to stderr, or to that same+ terminal when stderr is redirected). Empty line or EOF ends the session, and so does+ an error in a follow-up turn, with the same exit code as a one-shot run. Turns reuse the same `messages`, so+ the KV prefix carries over. `--max-iterations` is a per-turn budget.+- Parsing is **last-wins**, and every mode flag has an inverse+ (`--confirm` for `--yes`, `--no-interactive`, `--no-think`), so+ packaged `.args` defaults (prepended by `cosmo_args`) can always be+ overridden.+- `--system-file PATH` reads the system prompt from a file, `/zip/` paths+ included.+- `-c/--ctx-size` defaults to `kDefaultCtx` (65536, room for a few full+ `http_fetch` results plus history). The context never exceeds the+ model's training context, the default included; `0` asks for exactly+ that. `-c` and `--max-iterations` take non-negative integers only.+- Exit codes: `0` ok, `1` usage error, `2` agent error, `3` other error,+ `4` `--max-iterations` reached.+ - Declining a confirmation is not an exit: the model gets+ `{"skipped": "declined by the user; do not retry this call"}` and+ decides how to continue. Models do retry anyway, so three declines+ in a row end the run (exit 2).+ - No answer at all (no terminal, or EOF at the prompt) ends the run+ (exit 2): every later guarded call would go unanswered too.+ - The confirmation discards anything typed before it appeared, so text+ typed ahead can't answer it.+ - A failed tool call (a tool the model doesn't have, arguments that+ are not JSON) goes back to the model as an error result. Four+ failures in a row end the run (exit 2).++### stderr verbosity++- `--quiet`: nothing except, under `--yes`, a one-line `[tool --yes]+ args` audit record per destructive call.+- Default: a progress line before and after each tool call; `--think`+ reasoning, dimmed.+- `-v`: also truncated tool results; llama.cpp's own warnings and errors+ (`llama_log`: why a model fails to load); and `common_log` messages+ below errors (such as a reply the chat parser refused). `common_log`+ can quote model output and prints it unescaped, hence only on request;+ the `llama_log` lines go through agentfile's callback and are escaped.+- `-vv`: also llama.cpp's info log (model metadata), and everything the+ GPU backends log. Those are DSOs that call log callbacks from native+ code, where only llamafile's no-op callback is safe, so they cannot be+ filtered: silent below `-vv`, their own unescaped logger at `-vv`.++Model and tool text on stderr goes through `terminal_text`: under `--yes`+these lines are the only record of a call.++## Session records & tracing++### Session records: pi session-format v3 (JSONL)++`--session FILE` writes the conversation in [pi](https://pi.dev)'s session+format (`pi/packages/coding-agent/docs/session-format.md`, `version: 3`),+so sessions open in pi (`/import`), export to HTML, and can be compared+with pi's own runs.++- Header `{"type":"session","version":3,"id":…,"timestamp":…,"cwd":…}`,+ then tree-linked `user`, `assistant` and `toolResult` entries. The+ history is linear: each `parentId` is the previous entry.+- `provider` is `"agentfile"`, `model` the GGUF basename. Costs are zero,+ and so is token usage: agent.cpp doesn't expose per-call counts.+- A failed tool call is `isError: true` with the message, pi's own shape.+ The model gets the same error as `{"error": true, "tool": …,+ "message": …}`.+- Risk: an application format owned by Earendil, with migrations. We pin+ v3 and revisit when pi bumps.++### Spans: OTLP/JSON with GenAI semconv++`--trace FILE` writes one `ExportTraceServiceRequest` per line, OTLP's+JSON encoding. The OTel Collector ingests it with the `otlpjsonfile`+receiver.++- Span structure and attributes follow agent.cpp's `examples/tracing`:+ `invoke_agent` → `chat` / `execute_tool`, GenAI semantic conventions.+- No OTel SDK, protobuf or curl: OTLP/JSON needs only a JSON library.+ Span and trace ids are random hex.++## Tools++The set comes from the toolbox (`-h` lists it). Tools with+`permission_write` (writes, shell, network) ask for confirmation before+each call unless `--yes`. `--tools` takes `all`, `read_only` (every tool+without `permission_write`) or a list of names; an unknown or unavailable+name is an error, not a smaller toolset.++### http_fetch++GET only. The body is capped at `kMaxBody` (64 KB; the download stops+there, the result says `truncated`). 30 s timeout. Redirects are reported+as `redirect_to`, not followed, so every fetched URL is one the model asked+for and the confirmation prompt showed. The prompt also names the host the+URL connects to. The model gets the raw body: no HTML-to-text. A binary+body (an image, audio, video, font or PDF by its `Content-Type`, or any+body with a NUL byte) stops the download and is not returned: the result+has status, headers and a note instead, since escaped binary would+overflow the context.++### web_search (SearXNG)++- Arguments: `query` (required), `page` → `pageno`, `time_range`+ (`day|month|year`), `categories`.+- The instance is **not** a tool argument, so the model can't choose+ where queries go: `--searxng-url URL` or `SEARXNG_URL`. With neither,+ the tool isn't registered (no dead tool in the schema).+- `GET {base}/search?format=json&…`. Returns one page of results as+ `title`, `url`, `snippet`, `engine`; snippets are capped at+ `kMaxSnippet` bytes.+- HTTP 403 gets a message saying the instance must enable `json` under+ `search: formats:` in `settings.yml` (public instances usually don't;+ self-hosted is the expected deployment).++## Security model++agentfile does **not** sandbox itself: there is no `pledge()`/`unveil()`+call in it, so every tool runs with the invoking user's permissions.++- The confirmation prompt for `permission_write` tools is the only gate.+ `--yes` removes it; under `--yes --quiet` each such call is still logged+ to stderr, one line each.+- Tool inputs go through llama-server's own handler, which drops+ model-supplied `runtime`, `cwd` and `resp_type`. The confirmation prompt+ shows the arguments as the tool will get them.+- Isolation, when wanted, comes from `--tools-runtime`, with llama-server's+ specs, checked at startup:+ - `docker-container:ID` attaches to a running container;+ - `docker:IMAGE` starts a container and stops it on exit (podman+ likewise);+ - `ssh:TARGET` runs on a remote host.++ That is the right boundary for an agent whose purpose is running shell+ commands against a filesystem. `http_fetch` and `web_search` ignore the+ runtime: they always connect from this host, localhost services and+ cloud metadata endpoints included. Leave them out of `--tools` when+ network access must be contained too.++Why not llamafile's pledge sandbox now:+- On macOS it is a no-op, and the GPU gate skips it anyway.+- A policy derived from the enabled toolset would make "is the sandbox+ on?" depend on `--tools`, `--session`, `--trace`, GPU, OS and+ `--unsecure` at once.++Follow-up, in its own PR: one fixed rule modelled on the server table in+`docs/built-in-tools.md`, a status line at every start, `--unsecure` to opt+out, and a startup check naming the enabled tools that can't work under it.++## Packaging++`cosmo_args("/zip/.args", &argv)` plus zipalign embed the agent in the+binary:++```+cp o//agentfile/agentfile my-agent+o//third_party/zipalign/zipalign -j0 my-agent model.gguf system.md .args+# .args, one argument per line:+# -m /zip/model.gguf+# --system-file /zip/system.md+# --tools read_file,grep_search,web_search+# --max-iterations 25+# --searxng-url http://localhost:8888+```++`--session` and `--trace` stay off in `.args`: recording is the user's+opt-in. **Never** put `--yes` in `.args`: a packaged agent must not+silently pre-authorize destructive tools.++## Roadmap++- **Packaging**:+ - smoke-test the recipe end to end on a second machine;+ - `--name`/`--description`, so an agent describes itself in `-h`;+ - a prewarmed KV cache: at pack time, run `load_or_create_cache` over+ the system prompt and tool definitions, zip the state+ (`/zip/prompt.cache`), and on load validate it against model and+ context parameters, falling back to live warming on a mismatch.+ Flags `--warm-cache PATH` / `--load-cache PATH`;+ - later, an `agentfile pack` subcommand wrapping the recipe.+- **Full llama.cpp parameter surface**, mirroring llamafile+ (`llamafile/args.cpp`):+ - parse agentfile's own flags first and hand the rest to+ `common_params_parse(..., LLAMA_EXAMPLE_CLI)`;+ - two-tier help: short agentfile help, then `--help` delegates to+ llama.cpp's full catalogue. Delegating, not copying, keeps it from+ drifting;+ - `-hf REPO[:TAG]` and URLs through `common_download_model` (HF cache,+ `--offline`), with download progress on stderr. A packaged agent can+ then carry `-hf repo:tag` instead of an embedded model;+ - open: agent.cpp's `ModelConfig` covers a subset of `common_params`.+ Either extend agent.cpp's Model to take `common_params`, or document+ the flags it ignores (`-ngl`, flash-attn, …).+- **Tests**: `tests/integration/tests/test_agentfile.py` covers the tools,+ sessions, confirmations and flag validation. Still missing: a+ `--max-iterations` run, a trace schema check, a packaged `.args` run,+ and a compile-only `o//agentfile` check on llama.cpp bumps.+- `--otlp-endpoint URL`: POST the same OTLP/JSON to a collector+ (`/v1/traces`) via cpp-httplib.++## Open items (defaults chosen, veto anytime)++- `http_fetch`: an optional `max_bytes` argument (clamped server-side)?+ `--insecure` for self-signed local instances? Is 64 KB the right cap?+ Server tools keep 16 KB for their own outputs.+- `web_search` snippet length.+- Context management: `-c` only sizes the window, so a long tool-heavy+ session still ends with "context size exceeded". Real fix: a trimming+ callback in `before_llm_call` that drops or summarizes old tool+ results (agent.cpp's ContextTrimmerCallback pattern).+- No per-call token cap (deferred 2026-10-06). With greedy decoding, a+ model stuck repeating itself fills the whole context before the call+ fails. `--max-iterations` caps calls, not tokens.+- Token usage in session files is zero until agent.cpp exposes per-call+ counts (upstream or local patch).+- Trace field names: freeze them after the first real consumer.diff --git a/agentfile/agentfile.cpp b/agentfile/agentfile.cppnew file mode 100644index 00000000..e01968e6--- /dev/null+++ b/agentfile/agentfile.cpp@@ -0,0 +1,531 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2026 Mozilla.ai+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++//+// agentfile: a self-contained agentic CLI. One APE binary runs an+// agent.cpp loop with llama.cpp's server tools (plus agentfile's own+// http_fetch/web_search), entirely in-process: prompt in, answer out.+//+// Layout: this file is the only translation unit — flags, wiring, and the+// interactive loop. Tools come through server_tools_adapter.h; the loop's+// observers (confirmation, progress, recorders, iteration cap) live in+// callbacks/. Answers go to stdout; everything else goes to stderr.+//++#include <cerrno>+#include <climits>+#include <csignal>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <memory>+#include <set>+#include <string>+#include <unistd.h>+#include <vector>++#include "llama.h"+#include "chat.h"+#include "common.h"+#include "log.h"++#include "agent.h"+#include "callbacks.h"+#include "error.h"+#include "model.h"+#include "tool.h"++#include "llamafile.h"++#include "callbacks/confirmation.h"+#include "callbacks/error_recovery.h"+#include "callbacks/max_iterations.h"+#include "callbacks/progress.h"+#include "callbacks/session_recorder.h"+#include "callbacks/trace.h"+#include "server_tools_adapter.h"++// Last, as in llama-server's server.cpp: cosmo.h defines a defer() macro+// that breaks server_queue::defer() in server-queue.h.+#ifdef COSMOCC+#include <cosmo.h>+#endif++namespace {++// Default context window: room for a few full http_fetch results (64 KB,+// roughly 16-24k tokens each) plus the rest of the conversation.+constexpr int kDefaultCtx = 64 * 1024;++// Lowest llama.cpp / ggml log level that reaches stderr: -v shows warnings+// and errors, -vv also info. Above GGML_LOG_LEVEL_ERROR (the default) is+// silent.+int g_llama_log_min = GGML_LOG_LEVEL_ERROR + 1;++// For llama_log_set. CONT carries on the previous message (a line printed+// in pieces, the loading dots), so it takes that message's level. GGUF+// metadata strings pass through here, so the text is escaped.+void llama_log_to_stderr(ggml_log_level level, const char *text, void *) {+ static thread_local ggml_log_level last = GGML_LOG_LEVEL_NONE;+ if (level == GGML_LOG_LEVEL_CONT)+ level = last;+ else+ last = level;+ if (level >= g_llama_log_min && level <= GGML_LOG_LEVEL_ERROR)+ fputs(agentfile::terminal_text(text, /*keep_newlines=*/true).c_str(),+ stderr);+}++// The tools part of the help comes from the toolbox, so it always matches+// the registered tools. searxng_url is the value parsed so far, so+// web_search shows as available when it is.+void print_tools_help(const std::string &searxng_url) {+ try {+ agentfile::ServerToolbox toolbox(searxng_url, "");+ auto names = toolbox.tool_names();+ auto guarded = toolbox.write_tool_names(names);+ std::string ro, wr;+ for (const auto &name : names) {+ std::string &dst = guarded.count(name) ? wr : ro;+ dst += (dst.empty() ? "" : ", ") + name;+ }+ fprintf(stderr,+ "Tools (choose with --tools LIST, \"all\", \"read_only\" or "+ "\"none\"; default: none —\n"+ "tools cost context and widen the attack surface, so they "+ "are opt-in):\n"+ " read-only: %s\n"+ " guarded: %s\n"+ " (ask confirmation before each call; --yes skips,\n"+ " --confirm restores)\n",+ ro.c_str(), wr.c_str());+ for (const auto &[name, why] : toolbox.missing()) {+ fprintf(stderr, " unavailable: %s — %s\n", name.c_str(),+ why.c_str());+ }+ fprintf(stderr,+ " --searxng-url URL SearXNG instance used by web_search;\n"+ " also read from SEARXNG_URL\n"+ " --tools-runtime SPEC Run tools in an isolate, as llama-server does\n"+ " (default: this host): \"docker-container:ID\"\n"+ " (a running container), \"docker:IMAGE\" (started\n"+ " here, stopped on exit; podman likewise) or\n"+ " \"ssh:TARGET\". http_fetch and web_search still\n"+ " connect from this host.\n"+ " Tools run with this process's permissions; agentfile does not\n"+ " sandbox itself. The confirmation prompt is the only gate (--yes\n"+ " removes it); use --tools-runtime for isolation.\n");+ } catch (const std::exception &e) {+ fprintf(stderr, "Tools: unavailable in this build (%s)\n", e.what());+ }+}++void print_usage(const char *prog, const std::string &searxng_url) {+ fprintf(stderr,+ "agentfile — agentic CLI on top of agent.cpp + llama.cpp\n"+ "\n"+ "Usage:\n"+ " %s -m MODEL.gguf -p \"prompt\" [options]\n"+ " echo \"prompt\" | %s -m MODEL.gguf [options]\n"+ "\n"+ "Options:\n"+ " -m PATH Path to a GGUF model file (required)\n"+ " -p TEXT User prompt (read from stdin if omitted\n"+ " and stdin is not a terminal)\n"+ " -c, --ctx-size N Context window in tokens (default: %d), never\n"+ " more than the model's maximum. 0 = the model's\n"+ " maximum — mind the KV-cache memory on\n"+ " long-context models\n"+ " -s TEXT System instructions (default: helpful assistant)\n"+ " --system-file PATH Read system instructions from a file\n"+ " (works with /zip/ paths in packaged agents)\n"+ " --tools LIST Tools the model may use (default: none;\n"+ " see Tools below)\n"+ " --session FILE Record the conversation as a pi session\n"+ " (https://pi.dev, session-format v3 JSONL;\n"+ " overwrites FILE)\n"+ " --trace FILE Record spans as OTLP/JSON lines (OpenTelemetry\n"+ " collector `otlpjsonfile` receiver format;\n"+ " overwrites FILE)\n"+ " --think Enable model reasoning (<think> blocks; shown\n"+ " dimmed on stderr, never in the answer).\n"+ " --no-think undoes it (default: off)\n"+ " -i, --interactive After the answer, prompt for a follow-up and\n"+ " continue the conversation (empty line or EOF\n"+ " ends the session). --no-interactive undoes it.\n"+ " --yes Skip confirmation prompts for destructive tools\n"+ " --confirm Re-enable confirmation prompts (inverse of\n"+ " --yes; later flag wins)\n"+ " --max-iterations N Cap agent loop at N LLM calls (default: unlimited)\n"+ " --quiet Don't print tool-execution progress to stderr\n"+ " (destructive tools run under --yes are still\n"+ " logged, one line each)\n"+ " -v, --verbose Also print truncated tool results, and\n"+ " llama.cpp warnings and errors (such as why a\n"+ " model fails to load) to stderr; chat parser\n"+ " warnings come unescaped\n"+ " -vv Like -v, plus llama.cpp's info log (model\n"+ " metadata, GPU setup)\n"+ " -h Show this help\n"+ "\n",+ prog, prog, kDefaultCtx);+ print_tools_help(searxng_url);+ fprintf(stderr,+ "\n"+ "Exit codes: 0 ok, 1 usage error, 2 agent error, 3 other error,\n"+ " 4 --max-iterations cap reached\n");+}++// Read a whole FILE* into a string.+bool slurp(FILE *f, std::string &out) {+ char buf[4096];+ size_t n;+ while ((n = fread(buf, 1, sizeof(buf), f)) > 0)+ out.append(buf, n);+ return !ferror(f);+}++// --tools: "none" (the default: tools cost context and widen the attack+// surface, so they are opt-in), "all", "read_only" (every tool without+// permission_write), or a comma-separated list of names, which main checks+// against the toolbox.+std::set<std::string> parse_tools_flag(const std::string &spec,+ const agentfile::ServerToolbox &toolbox) {+ std::set<std::string> names;+ if (spec == "none") return names;+ if (spec == "all" || spec == "read_only") {+ names = toolbox.tool_names();+ if (spec == "read_only") {+ for (const auto &name : toolbox.write_tool_names(names))+ names.erase(name);+ }+ return names;+ }+ for (const auto &item : string_split<std::string>(spec, ',')) {+ std::string name = string_strip(item);+ if (!name.empty()) names.insert(name);+ }+ return names;+}++} // namespace++int main(int argc, char **argv) {+ signal(SIGPIPE, SIG_IGN);++#ifdef COSMOCC+ argc = cosmo_args("/zip/.args", &argv);+#endif++ std::string model_path;+ std::string prompt;+ std::string instructions =+ "You are a helpful assistant. Answer concisely.";+ bool always_yes = false;+ bool interactive = false;+ bool think = false;+ int n_ctx = kDefaultCtx; // tokens; 0 = the model's maximum+ int verbosity = 1; // 0 = --quiet, 1 = default, 2 = -v, 3 = -vv+ int max_iterations = 0; // 0 = no cap+ std::string tools_spec = "none";+ std::string session_path;+ std::string trace_path;+ std::string searxng_url;+ std::string tools_runtime;+ if (const char *env = std::getenv("SEARXNG_URL")) searxng_url = env;++ // The last flag wins and every mode flag has an inverse, so a packaged+ // agent's defaults (/zip/.args, which cosmo_args puts first) can always+ // be overridden.+ auto need_value = [&](int &i) -> const char * {+ if (i + 1 >= argc) {+ fprintf(stderr, "agentfile: %s requires a value\n", argv[i]);+ exit(1);+ }+ return argv[++i];+ };+ // 0 means "no limit" for -c and --max-iterations, so a typo must fail+ // instead of becoming 0, as it would with atoi().+ auto need_count = [&](int &i) -> int {+ const char *flag = argv[i];+ const char *s = need_value(i);+ char *end;+ errno = 0;+ long v = std::strtol(s, &end, 10);+ if (end == s || *end || errno || v < 0 || v > INT_MAX) {+ fprintf(stderr,+ "agentfile: %s: expected a non-negative integer, got "+ "\"%s\"\n",+ flag, s);+ exit(1);+ }+ return static_cast<int>(v);+ };+ for (int i = 1; i < argc; ++i) {+ if (std::strcmp(argv[i], "-m") == 0) {+ model_path = need_value(i);+ } else if (std::strcmp(argv[i], "-p") == 0) {+ prompt = need_value(i);+ } else if (std::strcmp(argv[i], "-c") == 0 ||+ std::strcmp(argv[i], "--ctx-size") == 0) {+ n_ctx = need_count(i);+ } else if (std::strcmp(argv[i], "-s") == 0) {+ instructions = need_value(i);+ } else if (std::strcmp(argv[i], "--system-file") == 0) {+ const char *path = need_value(i);+ FILE *f = fopen(path, "r");+ if (!f) {+ fprintf(stderr, "agentfile: --system-file: cannot open %s\n",+ path);+ return 1;+ }+ instructions.clear();+ bool ok = slurp(f, instructions);+ fclose(f);+ if (!ok) {+ fprintf(stderr, "agentfile: --system-file: error reading %s\n",+ path);+ return 1;+ }+ } else if (std::strcmp(argv[i], "--tools") == 0) {+ tools_spec = need_value(i);+ } else if (std::strcmp(argv[i], "--searxng-url") == 0) {+ searxng_url = need_value(i);+ } else if (std::strcmp(argv[i], "--tools-runtime") == 0) {+ tools_runtime = need_value(i);+ } else if (std::strcmp(argv[i], "--session") == 0) {+ session_path = need_value(i);+ } else if (std::strcmp(argv[i], "--trace") == 0) {+ trace_path = need_value(i);+ } else if (std::strcmp(argv[i], "-i") == 0 ||+ std::strcmp(argv[i], "--interactive") == 0) {+ interactive = true;+ } else if (std::strcmp(argv[i], "--no-interactive") == 0) {+ interactive = false;+ } else if (std::strcmp(argv[i], "--think") == 0) {+ think = true;+ } else if (std::strcmp(argv[i], "--no-think") == 0) {+ think = false;+ } else if (std::strcmp(argv[i], "--yes") == 0) {+ always_yes = true;+ } else if (std::strcmp(argv[i], "--confirm") == 0) {+ always_yes = false;+ } else if (std::strcmp(argv[i], "--quiet") == 0) {+ verbosity = 0;+ } else if (std::strcmp(argv[i], "-v") == 0 ||+ std::strcmp(argv[i], "--verbose") == 0) {+ verbosity = 2;+ } else if (std::strcmp(argv[i], "-vv") == 0) {+ verbosity = 3;+ } else if (std::strcmp(argv[i], "--max-iterations") == 0) {+ max_iterations = need_count(i);+ } else if (std::strcmp(argv[i], "-h") == 0 ||+ std::strcmp(argv[i], "--help") == 0) {+ print_usage(argv[0], searxng_url);+ return 0;+ } else {+ fprintf(stderr, "agentfile: unknown argument: %s\n\n", argv[i]);+ print_usage(argv[0], searxng_url);+ return 1;+ }+ }++ // No -p and stdin is piped: the pipe is the prompt.+ if (prompt.empty() && !isatty(STDIN_FILENO)) {+ if (!slurp(stdin, prompt)) {+ fprintf(stderr, "agentfile: error reading prompt from stdin\n");+ return 1;+ }+ while (!prompt.empty() &&+ (prompt.back() == '\n' || prompt.back() == '\r'))+ prompt.pop_back();+ }++ if (model_path.empty() || prompt.empty()) {+ print_usage(argv[0], searxng_url);+ return 1;+ }++ // Logging, set before the backends start. llama.cpp's own log: silent+ // unless -v (warnings, errors) or -vv (also info).+ if (verbosity >= 2) {+ g_llama_log_min =+ verbosity >= 3 ? GGML_LOG_LEVEL_INFO : GGML_LOG_LEVEL_WARN;+ }+ llama_log_set(llama_log_to_stderr, nullptr);+ // The GPU backends are separate libraries with their own logger. Their+ // callback runs as native code, where only llamafile's no-op is safe,+ // so they are either silent or (at -vv) print everything themselves.+ if (verbosity < 3) {+ llamafile_metal_log_set(llamafile_log_callback_null, nullptr);+ llamafile_cuda_log_set(llamafile_log_callback_null, nullptr);+ llamafile_vulkan_log_set(llamafile_log_callback_null, nullptr);+ }+ // common_log (llama.cpp common, agent.cpp) prints model text unescaped,+ // so only its errors show unless -v.+ if (verbosity < 2)+ common_log_set_verbosity_thold(LOG_LEVEL_ERROR);++ try {+ // Whatever a bad flag can break is set up before the slow part (GPU+ // init, model load): the toolset first, then the record files. A+ // requested tool that isn't available is an error, not a smaller+ // toolset the model would improvise with.+ agentfile::ServerToolbox toolbox(searxng_url, tools_runtime);+ auto keep = parse_tools_flag(tools_spec, toolbox);+ if (keep.empty() && tools_spec != "none") {+ fprintf(stderr, "agentfile: --tools: no tool names in \"%s\"\n",+ tools_spec.c_str());+ return 1;+ }+ {+ auto known = toolbox.tool_names();+ for (const auto &name : keep) {+ if (known.count(name)) continue;+ auto it = toolbox.missing().find(name);+ if (it != toolbox.missing().end()) {+ fprintf(stderr, "agentfile: %s %s\n", name.c_str(),+ it->second.c_str());+ } else {+ fprintf(stderr, "agentfile: unknown tool: %s\n",+ name.c_str());+ }+ return 1;+ }+ }+ auto tools = toolbox.make_adapters(keep);+ if (verbosity > 1) {+ std::string roster;+ for (const auto &name : keep)+ roster += (roster.empty() ? "" : ", ") + name;+ fprintf(stderr, "%s[tools: %s]%s\n", agentfile::dim(),+ roster.empty() ? "none" : roster.c_str(),+ agentfile::dim_off());+ }++ // Model name for session/trace records: the GGUF basename.+ std::string model_name = model_path;+ if (auto slash = model_name.find_last_of('/');+ slash != std::string::npos)+ model_name.erase(0, slash + 1);++ // Order matters: the trace goes after the confirmation (tool spans+ // time the tool, not the user deciding) and after the iteration cap+ // (a refused call opens no span); error recovery goes last, so the+ // others record a failed call as failed.+ std::vector<std::unique_ptr<agent_cpp::Callback>> callbacks;+ if (!session_path.empty()) {+ callbacks.emplace_back(+ std::make_unique<agentfile::SessionRecorderCallback>(+ session_path, model_name));+ }+ callbacks.emplace_back(+ std::make_unique<agentfile::DestructiveOpsConfirmationCallback>(+ always_yes, toolbox.write_tool_names(keep),+ /*audit=*/verbosity == 0));+ if (verbosity > 0) {+ callbacks.emplace_back(+ std::make_unique<agentfile::ProgressCallback>(verbosity > 1));+ }+ if (max_iterations > 0) {+ callbacks.emplace_back(+ std::make_unique<agentfile::MaxIterationsCallback>(+ max_iterations));+ }+ if (!trace_path.empty()) {+ callbacks.emplace_back(+ std::make_unique<agentfile::OtlpTraceCallback>(trace_path,+ model_name));+ }+ callbacks.emplace_back(+ std::make_unique<agentfile::ErrorRecoveryCallback>());++ // Initialize llamafile GPU backends (Metal, CUDA, Vulkan, ROCm),+ // which also registers them.+ llamafile_has_gpu();+ llama_backend_init();++ auto weights = agent_cpp::ModelWeights::create(model_path);+ agent_cpp::ModelConfig cfg; // defaults: temp=0, top_p=1, top_k=0+ // agent.cpp's default (-1) wraps around in llama_context's unsigned+ // n_batch and breaks context creation. 2048 is llama.cpp's default.+ cfg.n_batch = 2048;+ // The context never exceeds what the model was trained on; -c 0+ // asks for exactly that.+ int n_ctx_train = llama_model_n_ctx_train(weights->get_model());+ if (n_ctx_train > 0 && (n_ctx == 0 || n_ctx > n_ctx_train))+ n_ctx = n_ctx_train;+ cfg.n_ctx = n_ctx;+ cfg.enable_thinking = think;+ auto model = agent_cpp::Model::create_with_weights(weights, cfg);++ agent_cpp::Agent agent(std::move(model), std::move(tools),+ std::move(callbacks), instructions);++ std::vector<common_chat_msg> messages;+ common_chat_msg user_msg;+ user_msg.role = "user";+ user_msg.content = prompt;+ messages.push_back(std::move(user_msg));++ // The answer goes to stdout as is when piped, and escaped on a+ // terminal, where it could otherwise rewrite the lines above it.+ const bool stdout_tty = isatty(STDOUT_FILENO);+ auto print_reply = [&](const std::string &reply) {+ std::string out = stdout_tty+ ? agentfile::terminal_text(reply, /*keep_newlines=*/true)+ : reply;+ out += '\n';+ fwrite(out.data(), 1, out.size(), stdout);+ };++ print_reply(agent.run_loop(messages));++ // Follow-up turns reuse `messages`, so the cached prefix carries+ // over. An empty line, EOF or no terminal ends the session.+ while (interactive) {+ fflush(stdout);+ std::string followup;+ if (!agentfile::ask_terminal(std::string(agentfile::dim()) ++ "\n> " + agentfile::dim_off(),+ followup) ||+ followup.empty())+ break;+ common_chat_msg msg;+ msg.role = "user";+ msg.content = followup;+ messages.push_back(std::move(msg));+ print_reply(agent.run_loop(messages));+ }+ } catch (const agentfile::MaxIterationsExceeded &e) {+ fprintf(stderr, "%s\n", e.what());+ return 4;+ } catch (const agent_cpp::Error &e) {+ // Error text can quote the model or a tool (an unknown tool name,+ // a tool's error), so it is escaped like the other stderr lines.+ fprintf(stderr, "agentfile error: %s\n",+ agentfile::terminal_text(e.what()).c_str());+ return 2;+ } catch (const std::exception &e) {+ fprintf(stderr, "error: %s\n",+ agentfile::terminal_text(e.what()).c_str());+ return 3;+ }++ llama_backend_free();+ return 0;+}diff --git a/agentfile/callbacks/confirmation.h b/agentfile/callbacks/confirmation.hnew file mode 100644index 00000000..74b7281e--- /dev/null+++ b/agentfile/callbacks/confirmation.h@@ -0,0 +1,106 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2026 Mozilla.ai+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//+// DestructiveOpsConfirmationCallback — asks "Allow? [y/N]" before each call+// to a guarded tool (writes, shell, network). --yes skips the question;+// with --quiet as well, a one-line record is printed instead, so a guarded+// call never runs without a trace.+//++#pragma once++#include "callbacks.h"+#include "error.h"++#include "server_tools_adapter.h" // printable_arguments+#include "util.h"++#include <cctype>+#include <cstdio>+#include <set>+#include <string>++namespace agentfile {++// No terminal to ask on (CI, cron) or EOF at the prompt: every later call+// would go unanswered too, so the run ends (main exits 2).+class ConfirmationUnavailable : public agent_cpp::Error {+ public:+ explicit ConfirmationUnavailable(const std::string &tool_name)+ : agent_cpp::Error("cannot confirm " + tool_name ++ ": no answer from a terminal (use --yes for "+ "unattended runs)") {}+};++class DestructiveOpsConfirmationCallback : public agent_cpp::Callback {+ // A model can retry a declined call again and again: this many replies+ // in a row with a declined call end the run.+ static constexpr int kMaxDeclines = 3;++ bool always_yes_;+ bool audit_; // print a record under --yes+ std::set<std::string> destructive_; // tools with permission_write+ int declines_ = 0; // replies in a row, this turn+ bool declined_in_reply_ = false;++ public:+ DestructiveOpsConfirmationCallback(bool always_yes,+ std::set<std::string> destructive,+ bool audit = false)+ : always_yes_(always_yes), audit_(audit),+ destructive_(std::move(destructive)) {}++ void before_agent_loop(std::vector<common_chat_msg> &) override {+ declines_ = 0;+ }++ void after_llm_call(common_chat_msg &) override {+ declined_in_reply_ = false;+ }++ void before_tool_execution(std::string &tool_name,+ std::string &arguments) override {+ if (!destructive_.count(tool_name)) return;+ std::string args = printable_arguments(arguments);+ if (always_yes_) {+ if (audit_) {+ std::fprintf(stderr, "[%s --yes] %s\n", tool_name.c_str(),+ args.c_str());+ }+ return;+ }+ std::string answer;+ if (!ask_terminal("\n[" + tool_name + "] " + args ++ "\nAllow? [y/N]: ",+ answer, /*discard_typeahead=*/true)) {+ throw ConfirmationUnavailable(tool_name);+ }+ if (answer.empty() || std::tolower((unsigned char)answer[0]) != 'y') {+ if (!declined_in_reply_ && ++declines_ >= kMaxDeclines) {+ throw agent_cpp::Error("tool calls declined in " ++ std::to_string(declines_) ++ " replies in a row");+ }+ declined_in_reply_ = true;+ throw agent_cpp::ToolExecutionSkipped(+ "declined by the user; do not retry this call");+ }+ declines_ = 0;+ }+};++} // namespace agentfilediff --git a/agentfile/callbacks/error_recovery.h b/agentfile/callbacks/error_recovery.hnew file mode 100644index 00000000..bc4bc20d--- /dev/null+++ b/agentfile/callbacks/error_recovery.h@@ -0,0 +1,82 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2026 Mozilla.ai+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//+// ErrorRecoveryCallback — hands a failed tool call (a tool the model doesn't+// have, arguments that aren't JSON) back to the model as {"error": true,+// "tool": ..., "message": ...}, so it can fix the call instead of the run+// ending. After kMaxConsecutiveFailures in a row, the next failure ends the+// run (main exits 2).+//++#pragma once++#include "callbacks.h"+#include "error.h"+#include "tool_result.h"++#include "server-common.h" // json, safe_json_to_str++#include <string>+#include <vector>++namespace agentfile {++class ErrorRecoveryCallback : public agent_cpp::Callback {+ // Without a cap, a model that keeps calling a tool it doesn't have+ // loops until the context fills.+ static constexpr int kMaxConsecutiveFailures = 3;+ int failures_ = 0;++ public:+ void before_agent_loop(std::vector<common_chat_msg> &) override {+ failures_ = 0;+ }++ // A call whose arguments aren't JSON stays in the history, and chat+ // templates can't render it: store such arguments as a JSON string.+ void before_llm_call(std::vector<common_chat_msg> &messages) override {+ for (auto &msg : messages) {+ for (auto &tc : msg.tool_calls) {+ if (json::parse_no_throw(tc.arguments).is_discarded()) {+ tc.arguments = safe_json_to_str(json(tc.arguments));+ }+ }+ }+ }++ void after_tool_execution(std::string &tool_name,+ agent_cpp::ToolResult &result) override {+ if (!result.has_error()) {+ failures_ = 0;+ return;+ }+ if (++failures_ > kMaxConsecutiveFailures) {+ throw agent_cpp::Error("giving up after " ++ std::to_string(failures_) ++ " failed tool calls in a row; last: " ++ result.error().message);+ }+ json err = {+ {"error", true},+ {"tool", tool_name},+ {"message", result.error().message},+ };+ result.recover(safe_json_to_str(err));+ }+};++} // namespace agentfilediff --git a/agentfile/callbacks/max_iterations.h b/agentfile/callbacks/max_iterations.hnew file mode 100644index 00000000..11f53dc1--- /dev/null+++ b/agentfile/callbacks/max_iterations.h@@ -0,0 +1,57 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2026 Mozilla.ai+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//+// MaxIterationsCallback — --max-iterations: ends the run when a turn makes+// more than N LLM calls.+//++#pragma once++#include "callbacks.h"++#include <stdexcept>++namespace agentfile {++// Distinct type so main can map the iteration cap to its own exit code.+class MaxIterationsExceeded : public std::runtime_error {+ public:+ MaxIterationsExceeded()+ : std::runtime_error(+ "agentfile: agent loop exceeded --max-iterations cap") {}+};++class MaxIterationsCallback : public agent_cpp::Callback {+ int max_;+ int count_ = 0;++ public:+ explicit MaxIterationsCallback(int max) : max_(max) {}++ // The cap is per turn: each -i follow-up starts again from zero.+ void before_agent_loop(std::vector<common_chat_msg> & /*messages*/) override {+ count_ = 0;+ }++ void before_llm_call(std::vector<common_chat_msg> & /*messages*/) override {+ if (max_ > 0 && ++count_ > max_) {+ throw MaxIterationsExceeded();+ }+ }+};++} // namespace agentfilediff --git a/agentfile/callbacks/progress.h b/agentfile/callbacks/progress.hnew file mode 100644index 00000000..a0cf26a2--- /dev/null+++ b/agentfile/callbacks/progress.h@@ -0,0 +1,89 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2026 Mozilla.ai+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//+// ProgressCallback — prints a line on stderr before and after each tool+// call, and with -v a preview of the result. Model and tool text is+// escaped: under --yes these lines are the only record of a call.+//++#pragma once++#include "callbacks.h"+#include "tool_result.h"++#include "server_tools_adapter.h" // printable_arguments+#include "util.h"++#include <cstdio>+#include <string>++namespace agentfile {++class ProgressCallback : public agent_cpp::Callback {+ bool verbose_;+ bool running_ = false; // false after a declined confirmation++ public:+ explicit ProgressCallback(bool verbose = false) : verbose_(verbose) {}++ // Reasoning is commentary, not answer: show it dimmed on stderr and+ // keep stdout for the final result only.+ void after_llm_call(common_chat_msg &parsed_msg) override {+ if (!parsed_msg.reasoning_content.empty()) {+ std::fprintf(stderr, "%s[think] %s%s\n", dim(),+ terminal_text(parsed_msg.reasoning_content,+ /*keep_newlines=*/true)+ .c_str(),+ dim_off());+ }+ }++ void before_tool_execution(std::string &tool_name,+ std::string &arguments) override {+ running_ = true;+ std::fprintf(stderr, "%s[tool: %s %s]%s\n", dim(),+ terminal_text(tool_name).c_str(),+ printable_arguments(arguments).c_str(), dim_off());+ }++ void after_tool_execution(std::string &tool_name,+ agent_cpp::ToolResult &result) override {+ if (!running_) return; // declined: nothing ran+ running_ = false;+ if (result.has_error()) {+ std::fprintf(stderr, "%s[tool: %s -> error: %s]%s\n", dim(),+ terminal_text(tool_name).c_str(),+ terminal_text(result.error().message).c_str(),+ dim_off());+ } else {+ const auto &out = result.output();+ std::fprintf(stderr, "%s[tool: %s -> %zu bytes]%s\n", dim(),+ terminal_text(tool_name).c_str(), out.size(),+ dim_off());+ if (verbose_ && !out.empty()) {+ constexpr size_t kPreview = 512;+ std::fprintf(stderr, "%s %s%s%s\n", dim(),+ terminal_text(out.substr(0, kPreview),+ /*keep_newlines=*/true)+ .c_str(),+ out.size() > kPreview ? "…" : "", dim_off());+ }+ }+ }+};++} // namespace agentfilediff --git a/agentfile/callbacks/session_recorder.h b/agentfile/callbacks/session_recorder.hnew file mode 100644index 00000000..ecf73b47--- /dev/null+++ b/agentfile/callbacks/session_recorder.h@@ -0,0 +1,182 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2026 Mozilla.ai+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//+// SessionRecorderCallback — records the conversation in pi's session format+// (https://pi.dev, pi/packages/coding-agent/docs/session-format.md, v3): a+// header line, then one line per message. The history is linear, so each+// entry's parent is the previous one. Token counts are zero: agent.cpp+// doesn't report them.+//++#pragma once++#include "callbacks.h"+#include "tool_result.h"++#include "server-common.h" // json, safe_json_to_str+#include "util.h"++#include <cstdio>+#include <deque>+#include <stdexcept>+#include <string>+#include <unistd.h>+#include <vector>++namespace agentfile {++class SessionRecorderCallback : public agent_cpp::Callback {++ FILE *file_;+ std::string model_name_;+ std::string parent_id_; // last entry id; empty = root+ // Tool calls run in order, so the front id belongs to the next result.+ std::deque<std::string> pending_tool_calls_;+ size_t seen_messages_ = 0; // messages already recorded++ public:+ SessionRecorderCallback(const std::string &path,+ const std::string &model_name)+ : model_name_(model_name) {+ file_ = std::fopen(path.c_str(), "w");+ if (!file_) {+ throw std::runtime_error("--session: cannot open " + path);+ }+ char cwd[4096];+ json header = {+ {"type", "session"},+ {"version", 3},+ {"id", random_uuid()},+ {"timestamp", iso8601_now()},+ {"cwd", getcwd(cwd, sizeof(cwd)) ? cwd : ""},+ };+ write_line(header);+ }++ ~SessionRecorderCallback() override {+ if (file_) std::fclose(file_);+ }++ SessionRecorderCallback(const SessionRecorderCallback &) = delete;+ SessionRecorderCallback &operator=(const SessionRecorderCallback &) = delete;++ void before_agent_loop(std::vector<common_chat_msg> &messages) override {+ // New user messages; the other roles are recorded by their own+ // hooks, and pi has no system message.+ for (size_t i = seen_messages_; i < messages.size(); ++i) {+ if (messages[i].role != "user") continue;+ append_message({+ {"role", "user"},+ {"content", messages[i].content},+ {"timestamp", unix_ms_now()},+ });+ }+ seen_messages_ = messages.size();+ }++ void after_llm_call(common_chat_msg &parsed_msg) override {+ json content = json::array();+ if (!parsed_msg.reasoning_content.empty()) {+ content.push_back(+ {{"type", "thinking"}, {"thinking", parsed_msg.reasoning_content}});+ }+ if (!parsed_msg.content.empty()) {+ content.push_back({{"type", "text"}, {"text", parsed_msg.content}});+ }+ for (const auto &tc : parsed_msg.tool_calls) {+ json args;+ try {+ args = json::parse(tc.arguments);+ } catch (...) {+ args = {{"_raw", tc.arguments}};+ }+ content.push_back({{"type", "toolCall"},+ {"id", tc.id},+ {"name", tc.name},+ {"arguments", args}});+ pending_tool_calls_.push_back(tc.id);+ }++ json zero_usage = {+ {"input", 0}, {"output", 0}, {"cacheRead", 0},+ {"cacheWrite", 0}, {"totalTokens", 0},+ {"cost",+ {{"input", 0.0},+ {"output", 0.0},+ {"cacheRead", 0.0},+ {"cacheWrite", 0.0},+ {"total", 0.0}}},+ };++ append_message({+ {"role", "assistant"},+ {"content", content},+ {"api", "agent.cpp"},+ {"provider", "agentfile"},+ {"model", model_name_},+ {"usage", zero_usage},+ {"stopReason", parsed_msg.tool_calls.empty() ? "stop" : "toolUse"},+ {"timestamp", unix_ms_now()},+ });+ }++ void after_tool_execution(std::string &tool_name,+ agent_cpp::ToolResult &result) override {+ std::string call_id;+ if (!pending_tool_calls_.empty()) {+ call_id = pending_tool_calls_.front();+ pending_tool_calls_.pop_front();+ }+ bool is_error = result.has_error();+ const std::string &text =+ is_error ? result.error().message : result.output();+ append_message({+ {"role", "toolResult"},+ {"toolCallId", call_id},+ {"toolName", tool_name},+ {"content", json::array({{{"type", "text"}, {"text", text}}})},+ {"isError", is_error},+ {"timestamp", unix_ms_now()},+ });+ }++ private:+ void append_message(json message) {+ std::string id = random_hex(8);+ json entry = {+ {"type", "message"},+ {"id", id},+ {"parentId",+ parent_id_.empty() ? json(nullptr) : json(parent_id_)},+ {"timestamp", iso8601_now()},+ {"message", std::move(message)},+ };+ write_line(entry);+ parent_id_ = id;+ }++ // Tool output can be any bytes: safe_json_to_str replaces invalid UTF-8+ // where dump() would throw.+ void write_line(const json &j) {+ std::string line = safe_json_to_str(j);+ std::fwrite(line.data(), 1, line.size(), file_);+ std::fputc('\n', file_);+ std::fflush(file_);+ }+};++} // namespace agentfilediff --git a/agentfile/callbacks/trace.h b/agentfile/callbacks/trace.hnew file mode 100644index 00000000..79ffee95--- /dev/null+++ b/agentfile/callbacks/trace.h@@ -0,0 +1,219 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2026 Mozilla.ai+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//+// OtlpTraceCallback — records spans as OTLP/JSON, one+// ExportTraceServiceRequest per line: the format the OpenTelemetry+// Collector's `otlpjsonfile` receiver reads. Spans and GenAI attributes+// follow agent.cpp's examples/tracing:+//+// invoke_agent <agent> one per turn+// ├── chat <model> per LLM call+// └── execute_tool <tool> per tool call+//+// A span is written when it ends. Spans still open when the run fails are+// closed by the destructor, with an error status.+//++#pragma once++#include "callbacks.h"+#include "tool_result.h"++#include "server-common.h" // json, safe_json_to_str+#include "util.h"++#include <cstdio>+#include <stdexcept>+#include <string>+#include <vector>++namespace agentfile {++class OtlpTraceCallback : public agent_cpp::Callback {++ struct OpenSpan {+ std::string span_id;+ int64_t start_ns = 0;+ bool open = false;+ };++ FILE *file_;+ std::string model_name_;+ std::string agent_name_;+ std::string provider_name_;+ std::string trace_id_;+ OpenSpan agent_, chat_, tool_;+ std::string tool_name_;++ public:+ OtlpTraceCallback(const std::string &path, const std::string &model_name,+ const std::string &agent_name = "agentfile",+ const std::string &provider_name = "llamafile")+ : model_name_(model_name), agent_name_(agent_name),+ provider_name_(provider_name) {+ file_ = std::fopen(path.c_str(), "w");+ if (!file_) {+ throw std::runtime_error("--trace: cannot open " + path);+ }+ }++ ~OtlpTraceCallback() override {+ if (chat_.open) end_chat("error", "aborted", "aborted");+ if (tool_.open) {+ end_span(tool_, "execute_tool " + tool_name_, tool_attributes(),+ "aborted", "aborted");+ }+ if (agent_.open) {+ end_span(agent_, "invoke_agent " + agent_name_,+ agent_attributes(), "aborted", "aborted");+ }+ if (file_) std::fclose(file_);+ }++ OtlpTraceCallback(const OtlpTraceCallback &) = delete;+ OtlpTraceCallback &operator=(const OtlpTraceCallback &) = delete;++ void before_agent_loop(std::vector<common_chat_msg> &) override {+ trace_id_ = random_hex(32);+ start(agent_);+ }++ void after_agent_loop(std::vector<common_chat_msg> &,+ std::string &) override {+ end_span(agent_, "invoke_agent " + agent_name_, agent_attributes());+ }++ void before_llm_call(std::vector<common_chat_msg> &) override {+ start(chat_);+ }++ void after_llm_call(common_chat_msg &parsed_msg) override {+ end_chat(parsed_msg.tool_calls.empty() ? "stop" : "tool_calls");+ }++ void before_tool_execution(std::string &tool_name, std::string &) override {+ tool_name_ = tool_name;+ start(tool_);+ }++ void after_tool_execution(std::string &tool_name,+ agent_cpp::ToolResult &result) override {+ // A declined call never reached before_tool_execution: give it a+ // zero-length span.+ if (!tool_.open) {+ tool_name_ = tool_name;+ start(tool_);+ }+ end_span(tool_, "execute_tool " + tool_name_, tool_attributes(),+ result.has_error() ? result.error().message : "");+ }++ private:+ void start(OpenSpan &s) {+ s.span_id = random_hex(16);+ s.start_ns = unix_ns_now();+ s.open = true;+ }++ static json attr(const std::string &key, const std::string &value) {+ return {{"key", key}, {"value", {{"stringValue", value}}}};+ }++ json agent_attributes() const {+ return json::array({+ attr("gen_ai.operation.name", "invoke_agent"),+ attr("gen_ai.provider.name", provider_name_),+ attr("gen_ai.agent.name", agent_name_),+ attr("gen_ai.request.model", model_name_),+ });+ }++ json tool_attributes() const {+ return json::array({+ attr("gen_ai.operation.name", "execute_tool"),+ attr("gen_ai.tool.name", tool_name_),+ attr("gen_ai.tool.type", "function"),+ });+ }++ void end_chat(const std::string &finish_reason,+ const std::string &error_message = "",+ const std::string &error_type = "") {+ json attrs = json::array({+ attr("gen_ai.operation.name", "chat"),+ attr("gen_ai.provider.name", provider_name_),+ attr("gen_ai.request.model", model_name_),+ attr("gen_ai.output.type", "text"),+ });+ attrs.push_back(+ {{"key", "gen_ai.response.finish_reasons"},+ {"value",+ {{"arrayValue",+ {{"values", json::array({{{"stringValue", finish_reason}}})}}}}}});+ end_span(chat_, "chat " + model_name_, attrs, error_message,+ error_type);+ }++ // Ends the span and writes its ExportTraceServiceRequest line.+ // A non-empty error_message sets STATUS_CODE_ERROR per semconv.+ void end_span(OpenSpan &s, const std::string &name, json attributes,+ const std::string &error_message = "",+ const std::string &error_type = "tool_execution_error") {+ if (!s.open) return;+ s.open = false;++ json span = {+ {"traceId", trace_id_},+ {"spanId", s.span_id},+ {"name", name},+ {"kind", 1}, // SPAN_KIND_INTERNAL+ {"startTimeUnixNano", std::to_string(s.start_ns)},+ {"endTimeUnixNano", std::to_string(unix_ns_now())},+ {"attributes", std::move(attributes)},+ };+ if (&s != &agent_ && agent_.open) {+ span["parentSpanId"] = agent_.span_id;+ }+ if (!error_message.empty()) {+ span["attributes"].push_back(attr("error.type", error_type));+ span["status"] = {{"code", 2}, // STATUS_CODE_ERROR+ {"message", error_message}};+ } else {+ span["status"] = json::object();+ }++ json request = {+ {"resourceSpans",+ json::array(+ {{{"resource",+ {{"attributes",+ json::array({attr("service.name", "agentfile")})}}},+ {"scopeSpans",+ json::array({{{"scope", {{"name", "agentfile"}}},+ {"spans", json::array({span})}}})}}})},+ };++ // safe_json_to_str doesn't throw on invalid UTF-8: this also runs+ // from the destructor, where a throw would abort.+ std::string line = safe_json_to_str(request);+ std::fwrite(line.data(), 1, line.size(), file_);+ std::fputc('\n', file_);+ std::fflush(file_);+ }+};++} // namespace agentfilediff --git a/agentfile/server_tools_adapter.h b/agentfile/server_tools_adapter.hnew file mode 100644index 00000000..cee25d0d--- /dev/null+++ b/agentfile/server_tools_adapter.h@@ -0,0 +1,206 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2026 Mozilla.ai+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//+// Bridges llama.cpp's server tools (tools/server/server-tools.h) into+// agent.cpp's Tool interface, so agentfile uses the upstream tools and+// their isolation runtimes instead of keeping its own copies.+//+// ServerToolAdapter wraps one server_tool as an agent_cpp::Tool+// ServerToolbox owns the tools, upstream and agentfile's own+// (get_datetime, http_fetch, web_search); must+// outlive the Agent that uses them+//+// Every call goes through server_tools::handle_post, the handler behind+// llama-server's POST /tools: it drops the keys the model must not set+// (cwd, runtime, resp_type), runs the tool in the --tools-runtime isolate+// if one is set, and turns exceptions into error responses.+//++#pragma once++#include "server-tools.h" // server_tool, server_tools+#include "server-mcp.h" // server_mcp (empty manager)++#include "chat.h"+#include "tool.h"+#include "util.h"++#include "tools/get_datetime.h"+#include "tools/http_fetch.h"+#include "tools/web_search.h"++#include <functional>+#include <map>+#include <memory>+#include <set>+#include <string>+#include <vector>++namespace agentfile {++// Tool-call arguments as the confirmation prompt and progress line show+// them: as the tool will get them (re-serialized, without the keys+// handle_post drops) and escaped for the terminal, so model text can't+// hide or fake part of the line. A "url" also shows the host and port the+// request really goes to (http://[email protected]/ goes to b.example).+// Arguments that aren't JSON are shown escaped, as they are.+inline std::string printable_arguments(const std::string &arguments) {+ std::string text = arguments;+ std::string note;+ try {+ // Parsed the way the call parses them: agent.cpp's json, then the+ // server tools' json.+ auto args = json::parse(nlohmann::json::parse(arguments).dump());+ if (args.is_object()) {+ for (const char *key : {"cwd", "runtime", "resp_type"}) {+ if (args.contains(key)) args.erase(key);+ }+ if (args.contains("url") && args.at("url").is_string()) {+ try {+ auto parts = common_http_parse_url(+ args.at("url").get<std::string>());+ note += " (connects to " + parts.scheme + "://" ++ common_http_format_host(parts.host) + ":" ++ std::to_string(parts.port) + ")";+ } catch (const std::exception &) {+ // http_fetch reports the bad URL itself.+ }+ }+ }+ text = safe_json_to_str(args);+ } catch (const std::exception &) {+ }+ return terminal_text(text + note);+}++class ServerToolAdapter : public agent_cpp::Tool {+ // Both borrowed from ServerToolbox.+ const server_tool *tool_;+ const server_http_context::handler_t &handle_post_;++ public:+ ServerToolAdapter(const server_tool *tool,+ const server_http_context::handler_t &handle_post)+ : tool_(tool), handle_post_(handle_post) {}++ std::string get_name() const override { return tool_->name; }++ common_chat_tool get_definition() const override {+ // server_tool definitions are OpenAI-shaped:+ // {"type":"function","function":{name,description,parameters}}+ json d = tool_->get_definition();+ const json &f = d.at("function");+ return {f.at("name").get<std::string>(),+ f.at("description").get<std::string>(),+ f.at("parameters").dump()};+ }++ // agent.cpp speaks nlohmann::json, server tools speak llama.cpp's json+ // (common_json): the request body is the boundary between them.+ std::string execute(const nlohmann::json &arguments) override {+ static const std::function<bool()> never_stop = [] { return false; };+ json body = {{"tool", tool_->name},+ {"params", json::parse(arguments.dump())}};+ server_http_req req{.body = body.dump(), .should_stop = never_stop};+ auto res = handle_post_(req);+ // The handler serializes with safe_json_to_str, which also replaces+ // invalid UTF-8 (a Latin-1 file, a byte-truncated snippet).+ json result = json::parse(res->data);+ if (res->status != 200) {+ // A tool threw (bad arguments, say): pass the message on in the+ // {"error": msg} shape the tools use themselves.+ return safe_json_to_str(+ json{{"error", json_value(result, "message", res->data)}});+ }+ // Hand a {"plain_text_response": text} result on as the text+ // itself, not as escaped JSON.+ if (result.is_object() && !result.contains("error") &&+ result.contains("plain_text_response") &&+ result.at("plain_text_response").is_string()) {+ return result.at("plain_text_response").get<std::string>();+ }+ return res->data;+ }+};++class ServerToolbox {+ server_mcp mcp_; // default-constructed: no MCP servers+ server_tools st_;+ // Tools that exist but could not be registered, with the reason —+ // shown by --tools validation and in the help text.+ std::map<std::string, std::string> missing_;++ public:+ // searxng_url empty = web_search not registered.+ // runtime_spec empty = tools run directly on the host; otherwise a+ // --tools-runtime spec, which setup() checks (throws if invalid) and,+ // for "docker:IMAGE", starts a container that lives as long as the+ // toolbox.+ ServerToolbox(const std::string &searxng_url,+ const std::string &runtime_spec) {+ st_.setup({"all"}, mcp_, runtime_spec);+ st_.tools.push_back(std::make_unique<tools::GetDatetimeTool>());+ st_.tools.push_back(std::make_unique<tools::HttpFetchTool>());+ if (!searxng_url.empty()) {+ st_.tools.push_back(+ std::make_unique<tools::WebSearchTool>(searxng_url));+ } else {+ missing_["web_search"] =+ "requires a SearXNG instance: pass --searxng-url URL or "+ "set SEARXNG_URL";+ }+ }++ // name -> why it is not available in this configuration.+ const std::map<std::string, std::string> &missing() const {+ return missing_;+ }++ ServerToolbox(const ServerToolbox &) = delete;+ ServerToolbox &operator=(const ServerToolbox &) = delete;++ std::set<std::string> tool_names() const {+ std::set<std::string> names;+ for (const auto &t : st_.tools) names.insert(t->name);+ return names;+ }++ // The tools among `names` that mutate state or reach the network+ // (permission_write) — these get a confirmation prompt unless --yes is+ // given.+ std::set<std::string>+ write_tool_names(const std::set<std::string> &names) const {+ std::set<std::string> out;+ for (const auto &t : st_.tools)+ if (t->permission_write && names.count(t->name))+ out.insert(t->name);+ return out;+ }++ // Adapters for the tools among `names`. The toolbox must outlive them.+ std::vector<std::unique_ptr<agent_cpp::Tool>>+ make_adapters(const std::set<std::string> &names) const {+ std::vector<std::unique_ptr<agent_cpp::Tool>> out;+ for (const auto &t : st_.tools)+ if (names.count(t->name))+ out.push_back(std::make_unique<ServerToolAdapter>(+ t.get(), st_.handle_post));+ return out;+ }+};++} // namespace agentfilediff --git a/agentfile/tools/get_datetime.h b/agentfile/tools/get_datetime.hnew file mode 100644index 00000000..0808f283--- /dev/null+++ b/agentfile/tools/get_datetime.h@@ -0,0 +1,85 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2026 Mozilla.ai+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//+// get_datetime: the current date and time in UTC. llama.cpp moved this+// tool out of the server into its web UI (#27255), where the client's+// clock lives; for agentfile the CLI is the client, so it keeps the tool.+// Same definition and output as the server tool it replaces.+//++#pragma once++#include "server-tools.h"++#include <chrono>+#include <ctime>+#include <string>++namespace agentfile {+namespace tools {++struct GetDatetimeTool : server_tool {+ GetDatetimeTool() {+ name = "get_datetime";+ display_name = "Get Date & Time";+ permission_write = false;+ }++ json get_definition() const override {+ return {+ {"type", "function"},+ {"function", {+ {"name", name},+ {"description", "Returns the current date and time in UTC"},+ {"parameters", {+ {"type", "object"},+ {"properties", {+ {"format", {+ {"type", "string"},+ {"description",+ "strftime()-style format string for the output "+ "(default: \"%Y-%m-%dT%H:%M:%SZ\", e.g. ISO "+ "8601). Choose your own format if you need "+ "something else, e.g. \"%A, %B %d %Y\" for a "+ "human-readable date."},+ }},+ }},+ }},+ }},+ };+ }++ json invoke(json params, server_tool::stream *) const override {+ std::string format =+ json_value(params, "format", std::string("%Y-%m-%dT%H:%M:%SZ"));++ auto now = std::chrono::system_clock::now();+ auto time = std::chrono::system_clock::to_time_t(now);+ std::tm tm_utc;+ gmtime_r(&time, &tm_utc);++ char buf[256];+ size_t len = std::strftime(buf, sizeof(buf), format.c_str(), &tm_utc);+ if (len == 0) {+ return {{"error", "invalid format string"}};+ }+ return {{"result", std::string(buf, len)}};+ }+};++} // namespace tools+} // namespace agentfilediff --git a/agentfile/tools/http_fetch.h b/agentfile/tools/http_fetch.hnew file mode 100644index 00000000..e9aeb678--- /dev/null+++ b/agentfile/tools/http_fetch.h@@ -0,0 +1,209 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2026 Mozilla.ai+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//+// http_fetch: HTTP(S) GET on llama.cpp's common_http_client. A server_tool,+// run through ServerToolAdapter like the upstream tools; it lives here+// because llama.cpp keeps its server tools to file and shell I/O.+//+// Limits: GET only; body capped at 64 KB (the download stops there and the+// result is marked truncated); text only (a binary body is not returned);+// 30s timeout; redirects are reported (redirect_to), not followed.+//++#pragma once++#include "server-tools.h"++#include <cpp-httplib/httplib.h>+#include "http.h" // common_http_client, common_http_parse_url++#include <cctype>+#include <cstring> // memchr+#include <string>++namespace agentfile {+namespace tools {++struct HttpFetchTool : server_tool {+ static constexpr size_t kMaxBody = 64 * 1024;+ static constexpr int kTimeoutSeconds = 30;++ HttpFetchTool() {+ name = "http_fetch";+ display_name = "Fetch URL";+ // Network access: confirm before running (unless --yes).+ permission_write = true;+ }++ json get_definition() const override {+ return {+ {"type", "function"},+ {"function", {+ {"name", name},+ {"description",+ "Fetch a URL with HTTP GET and return status + headers + "+ "body. Response body is capped at 64 KB; binary content "+ "(images, PDFs, archives) is not returned. Redirects are not "+ "followed automatically: a 3xx response carries redirect_to; "+ "call http_fetch again with that URL to retrieve the content. "+ "Use sparingly — this tool grants the model network access."},+ {"parameters", {+ {"type", "object"},+ {"properties", {+ {"url", {{"type", "string"},+ {"description", "HTTP or HTTPS URL to fetch"}}},+ }},+ {"required", json::array({"url"})},+ }},+ }},+ };+ }++ // True if loc starts with an RFC 3986 scheme (ALPHA *( ALPHA / DIGIT /+ // "+" / "-" / "." ) ":"), i.e. is absolute. A "://" further on, as in+ // /login?next=https://x, does not count.+ static bool has_scheme(const std::string &loc) {+ size_t end = loc.find_first_not_of(+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"+ "0123456789+-.");+ return end != std::string::npos && end > 0 && loc[end] == ':' &&+ std::isalpha(static_cast<unsigned char>(loc[0]));+ }++ // Binary content isn't returned: escaped into the result, 64 KB of it+ // would take more tokens than the default context holds. Images, audio,+ // video, fonts and PDFs are known from their Content-Type (SVG, being+ // XML, is text); any other body counts as binary once a NUL byte shows.+ static bool is_binary_type(const std::string &content_type) {+ std::string t = content_type;+ for (auto &c : t) c = std::tolower(static_cast<unsigned char>(c));+ if (t.find("xml") != std::string::npos) return false;+ for (const char *bin :+ {"image/", "audio/", "video/", "font/", "application/pdf"})+ if (t.rfind(bin, 0) == 0) return true;+ return false;+ }++ // Resolve a Location header against the request URL (RFC 3986-lite:+ // absolute, scheme-relative, host-relative, query-only, or+ // path-relative).+ static std::string resolve_location(const common_http_url &parts,+ const std::string &loc) {+ if (has_scheme(loc)) return loc;+ if (loc.rfind("//", 0) == 0) return parts.scheme + ":" + loc;+ std::string origin = parts.scheme + "://" ++ common_http_format_host(parts.host) + ":" ++ std::to_string(parts.port);+ if (!loc.empty() && loc[0] == '/') return origin + loc;+ // The request's query is not part of its directory: a '/' inside+ // it must not become the base of a relative Location.+ std::string path = parts.path.substr(0, parts.path.find('?'));+ if (!loc.empty() && loc[0] == '?') return origin + path + loc;+ std::string dir = path.substr(0, path.rfind('/') + 1);+ if (dir.empty()) dir = "/";+ return origin + dir + loc;+ }++ json invoke(json params, server_tool::stream *) const override {+ if (!params.contains("url")) {+ return {{"error", "missing required parameter: url"}};+ }+ std::string url = params.at("url").get<std::string>();++ try {+ auto [cli, parts] = common_http_client(url);+ // Report redirects instead of following them, so every URL that+ // gets fetched is one the model asked for by name — and one the+ // confirmation prompt showed the user.+ cli.set_follow_location(false);+ cli.set_read_timeout(kTimeoutSeconds, 0);+ cli.set_connection_timeout(kTimeoutSeconds, 0);++ // Stream the body and stop reading at the cap, instead of+ // buffering whatever the server sends (httplib would accept up+ // to CPPHTTPLIB_PAYLOAD_MAX_LENGTH) and truncating afterwards.+ // A binary body stops the download as soon as it is known.+ int status = 0;+ httplib::Headers headers;+ std::string body;+ bool truncated = false;+ bool binary = false;+ auto res = cli.Get(+ parts.path,+ [&](const httplib::Response &r) {+ status = r.status;+ headers = r.headers;+ binary = is_binary_type(r.get_header_value("Content-Type"));+ return !binary;+ },+ [&](const char *data, size_t n) {+ if (std::memchr(data, 0, n)) {+ binary = true;+ return false;+ }+ size_t room = kMaxBody - body.size();+ if (n > room) {+ body.append(data, room);+ truncated = true;+ return false; // abort the download at the cap+ }+ body.append(data, n);+ return true;+ });+ // Aborting the read ourselves surfaces as a failed Result, but+ // the status and headers already arrived before the body.+ if (!res && !truncated && !binary) {+ return {{"error", "request failed: " ++ httplib::to_string(res.error())}};+ }++ json resp_headers = json::object();+ for (const auto &h : headers) {+ resp_headers[h.first] = h.second;+ }++ json out = json::object();+ // Lead with the redirect so the model sees it before the+ // headers/body noise.+ auto loc = headers.find("Location");+ if (status >= 300 && status < 400 && loc != headers.end()) {+ out["redirect_to"] = resolve_location(parts, loc->second);+ out["note"] = "Redirect, not followed automatically. The "+ "content is at redirect_to; call http_fetch "+ "with that URL to retrieve it.";+ }+ out["status"] = status;+ out["headers"] = resp_headers;+ if (binary && !out.contains("redirect_to")) {+ auto type = headers.find("Content-Type");+ std::string what = type != headers.end() ? type->second+ : "no Content-Type";+ out["note"] = "Binary content (" + what ++ ") not returned: http_fetch returns text only.";+ return out;+ }+ out["body"] = body;+ out["truncated"] = truncated;+ return out;+ } catch (const std::exception &e) {+ return {{"error", std::string("http_fetch failed: ") + e.what()}};+ }+ }+};++} // namespace tools+} // namespace agentfilediff --git a/agentfile/tools/web_search.h b/agentfile/tools/web_search.hnew file mode 100644index 00000000..76ea2422--- /dev/null+++ b/agentfile/tools/web_search.h@@ -0,0 +1,164 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2026 Mozilla.ai+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//+// web_search: queries a SearXNG instance (https://docs.searxng.org) through+// its JSON API. A server_tool, run through ServerToolAdapter like the+// upstream tools; it lives here because llama.cpp leaves web search to MCP+// or its web UI.+//+// The instance is not a tool argument, so the model can't choose where+// queries go: it comes from --searxng-url or SEARXNG_URL, and without+// either the tool isn't registered. The instance must enable `json` under+// `search: formats:` in settings.yml (public ones usually don't).+//++#pragma once++#include "server-tools.h"++#include <cpp-httplib/httplib.h>+#include "http.h" // common_http_client, common_http_parse_url++#include <string>++namespace agentfile {+namespace tools {++struct WebSearchTool : server_tool {+ static constexpr int kTimeoutSeconds = 30;+ // Snippet clip is input sanitation only: SearXNG engines send ~160+ // chars today, so this triggers only on unusual engines/instances.+ static constexpr size_t kMaxSnippet = 512;++ std::string base_url; // e.g. "http://localhost:8888", no trailing slash++ explicit WebSearchTool(std::string url) : base_url(std::move(url)) {+ while (!base_url.empty() && base_url.back() == '/')+ base_url.pop_back();+ name = "web_search";+ display_name = "Web search";+ // Network access: confirm before running (unless --yes).+ permission_write = true;+ }++ json get_definition() const override {+ return {+ {"type", "function"},+ {"function", {+ {"name", name},+ {"description",+ "Search the web via a SearXNG instance and return one page "+ "of results as JSON (title, url, snippet). Use precise "+ "queries; ask for the next page if the answer isn't there; "+ "fetch promising URLs with other tools for more detail."},+ {"parameters", {+ {"type", "object"},+ {"properties", {+ {"query", {{"type", "string"},+ {"description", "The search query"}}},+ {"page", {{"type", "integer"},+ {"description", "Result page number (default 1)"}}},+ {"time_range", {{"type", "string"},+ {"enum", json::array({"day", "month", "year"})},+ {"description", "Restrict results to this time range"}}},+ {"categories", {{"type", "string"},+ {"description", "Comma-separated SearXNG categories, "+ "e.g. \"general\", \"news\", \"it\""}}},+ }},+ {"required", json::array({"query"})},+ }},+ }},+ };+ }++ json invoke(json params, server_tool::stream *) const override {+ if (!params.contains("query")) {+ return {{"error", "missing required parameter: query"}};+ }+ std::string query = params.at("query").get<std::string>();++ std::string url = base_url + "/search?format=json&q=" ++ httplib::encode_query_component(query);+ int page = json_value(params, "page", 1);+ if (page > 1) url += "&pageno=" + std::to_string(page);+ std::string time_range = json_value(params, "time_range", std::string{});+ if (time_range == "day" || time_range == "month" ||+ time_range == "year") {+ url += "&time_range=" + time_range;+ }+ std::string categories = json_value(params, "categories", std::string{});+ if (!categories.empty())+ url += "&categories=" + httplib::encode_query_component(categories);++ try {+ auto [cli, parts] = common_http_client(url);+ cli.set_read_timeout(kTimeoutSeconds, 0);+ cli.set_connection_timeout(kTimeoutSeconds, 0);++ auto res = cli.Get(parts.path,+ httplib::Headers{{"Accept", "application/json"}});+ if (!res) {+ return {{"error", "request failed: " ++ httplib::to_string(res.error())}};+ }+ if (res->status == 403) {+ return {{"error",+ "SearXNG returned 403: the instance at " + base_url ++ " does not allow the JSON API. Enable `json` "+ "under `search: formats:` in its settings.yml."}};+ }+ if (res->status != 200) {+ return {{"error", "SearXNG returned HTTP " ++ std::to_string(res->status)}};+ }++ json body = json::parse(res->body);+ json results = json::array();+ if (body.contains("results") && body["results"].is_array()) {+ for (const auto &r : body["results"]) {+ // json_value, not r.value(): a null or non-string+ // field must not throw away the whole result list.+ std::string snippet =+ json_value(r, "content", std::string());+ if (snippet.size() > kMaxSnippet) {+ snippet.resize(kMaxSnippet);+ snippet += "…";+ }+ results.push_back({+ {"title", json_value(r, "title", std::string())},+ {"url", json_value(r, "url", std::string())},+ {"snippet", snippet},+ {"engine", json_value(r, "engine", std::string())},+ });+ }+ }+ return {+ {"query", query},+ {"results", results},+ };+ } catch (const common_json_error &e) {+ return {{"error",+ std::string("SearXNG returned unparseable JSON: ") ++ e.what()}};+ } catch (const std::exception &e) {+ return {{"error", std::string("web_search failed: ") + e.what()}};+ }+ }+};++} // namespace tools+} // namespace agentfilediff --git a/agentfile/util.h b/agentfile/util.hnew file mode 100644index 00000000..4dcb78c9--- /dev/null+++ b/agentfile/util.h@@ -0,0 +1,177 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2026 Mozilla.ai+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//+// Small shared helpers: terminal output and input, random ids, and the+// timestamps the session (ISO 8601, Unix ms) and trace (Unix ns) use.+//++#pragma once++#include <chrono>+#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <ctime>+#include <random>+#include <string>+#include <termios.h>+#include <unistd.h>++namespace agentfile {++// Dim style for the stderr lines (progress, prompts), so they stand apart+// from the answer. Empty when stderr isn't a terminal or NO_COLOR is set.+inline const char *dim() {+ static const bool on = isatty(STDERR_FILENO) && !std::getenv("NO_COLOR");+ return on ? "\033[2m" : "";+}+inline const char *dim_off() {+ static const bool on = isatty(STDERR_FILENO) && !std::getenv("NO_COLOR");+ return on ? "\033[0m" : "";+}++// Model or tool text headed for the terminal. Escapes what a terminal+// acts on or reorders instead of printing (C0 controls, DEL, C1 controls,+// bidi controls) and bytes that are not UTF-8, so the text cannot+// overprint, restyle or reorder what is shown around it. '\t' always+// passes; '\n' passes only for multi-line text.+inline std::string terminal_text(const std::string &s,+ bool keep_newlines = false) {+ std::string out;+ out.reserve(s.size());+ char buf[12];+ for (size_t i = 0; i < s.size();) {+ unsigned char c = s[i];+ size_t n = c < 0x80 ? 1 : (c >> 5) == 0x6 ? 2 : (c >> 4) == 0xe ? 3+ : (c >> 3) == 0x1e ? 4 : 0;+ uint32_t cp = n == 1 ? c : n == 2 ? c & 0x1f : n == 3 ? c & 0x0f+ : c & 0x07;+ bool ok = n > 0 && i + n <= s.size();+ for (size_t k = 1; ok && k < n; ++k) {+ unsigned char cc = s[i + k];+ ok = (cc & 0xc0) == 0x80;+ cp = (cp << 6) | (cc & 0x3f);+ }+ // Overlong forms, surrogates and code points past U+10FFFF are+ // not UTF-8 either.+ ok = ok && !(n == 2 && cp < 0x80) && !(n == 3 && cp < 0x800) &&+ !(n == 4 && (cp < 0x10000 || cp > 0x10ffff)) &&+ !(cp >= 0xd800 && cp <= 0xdfff);+ if (!ok) {+ std::snprintf(buf, sizeof(buf), "\\x%02x", c);+ out += buf;+ ++i;+ continue;+ }+ bool control = (cp < 0x20 && cp != '\t' &&+ !(keep_newlines && cp == '\n')) ||+ (cp >= 0x7f && cp <= 0x9f) || cp == 0x061c ||+ cp == 0x200e || cp == 0x200f ||+ (cp >= 0x202a && cp <= 0x202e) ||+ (cp >= 0x2066 && cp <= 0x2069);+ if (control) {+ std::snprintf(buf, sizeof(buf),+ cp < 0x80 ? "\\x%02x" : "\\u%04x", (unsigned)cp);+ out += buf;+ } else {+ out.append(s, i, n);+ }+ i += n;+ }+ return out;+}++// Asks the user a question on their terminal and reads one line of answer.+// The answer comes from stdin, or from /dev/tty when the prompt was piped+// in. The question goes to stderr, or, when stderr is redirected, to the+// terminal the answer comes from (else the user would wait on a question+// they can't see). With discard_typeahead, anything typed before the+// question appeared is dropped, so it can't answer a question the user+// never saw. Returns false when there is no terminal to ask, or on EOF.+inline bool ask_terminal(const std::string &question, std::string &answer,+ bool discard_typeahead = false) {+ FILE *in = isatty(STDIN_FILENO) ? stdin : std::fopen("/dev/tty", "r");+ if (!in) return false;+ const char *in_tty = isatty(STDERR_FILENO) ? nullptr : ttyname(fileno(in));+ FILE *tty_out = in_tty ? std::fopen(in_tty, "w") : nullptr;+ FILE *out = tty_out ? tty_out : stderr;+ if (discard_typeahead) tcflush(fileno(in), TCIFLUSH);+ std::fputs(question.c_str(), out);+ std::fflush(out);++ answer.clear();+ bool got = false;+ char buf[4096];+ while (std::fgets(buf, sizeof(buf), in)) {+ got = true;+ answer += buf;+ if (answer.back() == '\n') break;+ }+ if (in != stdin) std::fclose(in);+ if (tty_out) std::fclose(tty_out);+ while (!answer.empty() && (answer.back() == '\n' || answer.back() == '\r'))+ answer.pop_back();+ return got;+}++// n random lowercase hex characters (n/2 random bytes).+inline std::string random_hex(size_t n) {+ static thread_local std::mt19937_64 rng{std::random_device{}()};+ static const char digits[] = "0123456789abcdef";+ std::string out(n, '0');+ for (size_t i = 0; i < n; ++i)+ out[i] = digits[rng() & 0xf];+ return out;+}++// RFC 4122-shaped random UUID (version 4).+inline std::string random_uuid() {+ std::string h = random_hex(32);+ h[12] = '4';+ static const char variant[] = "89ab";+ h[16] = variant[h[16] & 0x3];+ return h.substr(0, 8) + "-" + h.substr(8, 4) + "-" + h.substr(12, 4) ++ "-" + h.substr(16, 4) + "-" + h.substr(20);+}++inline int64_t unix_ms_now() {+ return std::chrono::duration_cast<std::chrono::milliseconds>(+ std::chrono::system_clock::now().time_since_epoch())+ .count();+}++inline int64_t unix_ns_now() {+ return std::chrono::duration_cast<std::chrono::nanoseconds>(+ std::chrono::system_clock::now().time_since_epoch())+ .count();+}++// ISO 8601 UTC with millisecond precision, e.g. "2026-07-02T14:00:01.234Z".+inline std::string iso8601_now() {+ int64_t ms = unix_ms_now();+ time_t secs = (time_t)(ms / 1000);+ struct tm tm_utc;+ gmtime_r(&secs, &tm_utc);+ char buf[40];+ std::snprintf(buf, sizeof(buf), "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",+ tm_utc.tm_year + 1900, tm_utc.tm_mon + 1, tm_utc.tm_mday,+ tm_utc.tm_hour, tm_utc.tm_min, tm_utc.tm_sec,+ (int)(ms % 1000));+ return buf;+}++} // namespace agentfilediff --git a/docs/SUMMARY.md b/docs/SUMMARY.mdindex 69830758..f2c09b85 100644--- a/docs/SUMMARY.md+++ b/docs/SUMMARY.md@@ -12,6 +12,7 @@* [Running a llamafile](running_llamafile.md)* [API server](api.md)* [Built-in local tools](built-in-tools.md)+* [Agentfile](agentfile.md)* [Creating llamafiles](creating_llamafiles.md)* [Source installation](source_installation.md)* [Building DLLs](building_dlls.md)diff --git a/docs/agentfile.md b/docs/agentfile.mdnew file mode 100644index 00000000..44a4b5e4--- /dev/null+++ b/docs/agentfile.md@@ -0,0 +1,114 @@+# Agentfile++Agentfile runs a small, focused AI agent from a single command: one+executable, one model, a prompt in, an answer out. The model can use tools+— read and write files, run shell commands, fetch pages, search the web —+and every run works the same way on Linux, macOS, Windows and BSD, with no+installation and no server.++```sh+# Plain question, no tools+./agentfile -m Qwen3-4B.gguf -p "Explain git rebase in two sentences."++# Let it use the web (asks before each network call; --yes skips asking)+./agentfile -m Qwen3-4B.gguf --tools all --searxng-url http://localhost:8888 \+ -p "Find the latest llamafile release and summarize what changed."++# Keep the conversation going+./agentfile -m Qwen3-4B.gguf --tools read_only -i -p "What is in this directory?"+```++The answer goes to stdout; everything else (tool activity, prompts,+warnings) goes to stderr. `./agentfile result.txt 2>/dev/null` style+piping works as you would expect.++## Tools++**Tools are off by default.** Tool descriptions take up context the model+could use for your task, and every tool is capability you may not want to+hand out — so you enable exactly what a run needs:++```sh+--tools read_only # look, don't touch+--tools all # everything available+--tools read_file,exec_shell_command # a specific set+```++The tools (run `agentfile -h` to see this list live):++| Tool | What it does | Asks first? |+|---|---|---|+| `read_file`, `file_glob_search`, `grep_search` | read and search files | no |+| `get_datetime`, `get_info` | date/time, system info | no |+| `write_file`, `edit_file` | create and change files | yes |+| `exec_shell_command` | run shell commands | yes |+| `http_fetch` | GET a URL (http/https) | yes |+| `web_search` | search via SearXNG | yes |++"Asks first" tools print the exact call and wait for your `y` before+running. `--yes` turns the prompts off for unattended runs (each call is+still logged, one line each); `--confirm` turns them back on, which+matters for packaged agents that bake in `--yes`.++Most tools are llama.cpp's own [built-in tools](built-in-tools.md), so+they behave exactly as they do in llama-server. `get_datetime`,+`http_fetch` and `web_search` are agentfile additions.++### Web search++`web_search` talks to a [SearXNG](https://docs.searxng.org) instance you+point it at with `--searxng-url URL` (or the `SEARXNG_URL` environment+variable). Without an instance, the tool is simply not available. The+instance must allow the JSON API: add `json` under `search: formats:` in+its `settings.yml` — most public instances don't, so self-hosting is the+expected setup. The model picks the query; it can never pick the instance.++### Sandboxing++By default tools run with your permissions on your machine, and the+confirmation prompt is the only gate. For real isolation, run the tools+somewhere expendable:++```sh+--tools-runtime docker-container:NAME # a container you already started+--tools-runtime docker:IMAGE # started for this run, stopped after+--tools-runtime ssh:TARGET # a remote machine+```++Shell and file tools then operate inside the sandbox (podman works like+docker). `http_fetch` and `web_search` still connect from this host.++## Recording runs++- `--session FILE` writes the whole conversation as a+ [pi](https://pi.dev) session (JSONL). You can open it with pi, branch+ it, export it to HTML, or parse it with a few lines of Python.+- `--trace FILE` writes timing spans (model calls, tool calls) as+ OTLP/JSON lines, which an OpenTelemetry collector ingests directly —+ useful to see where a slow run spent its time.++Both are off unless asked for, and both overwrite their file.++## Useful flags++- `-i` / `--interactive`: after the answer, agentfile asks for a+ follow-up on the terminal; an empty line ends the session. Follow-ups+ reuse the work already done, so they start fast. Tip: models with a+ hybrid/recurrent design (Mamba-style, e.g. Qwen3.5) re-process the+ whole conversation on each follow-up — plain transformers feel snappier+ here.+- `--think`: lets reasoning models think; the reasoning shows dimmed on+ stderr and never mixes into the answer on stdout.+- `-c N`: context window (default 65536, never more than the model's+ maximum; `0` means the model's maximum). Web-heavy tasks want room — a+ single fetched page can be ~16k tokens.+- `--max-iterations N`: a per-reply budget of model calls; exceeding it+ exits with code 4. Good seatbelt for unattended runs.+- `-s TEXT` / `--system-file PATH`: the system prompt, inline or from a+ file.+- `--quiet` / `-v` / `-vv`: from silent to llama.cpp's full logs. `-v`+ also prints the enabled-tools roster and truncated tool results.++Exit codes: `0` ok, `1` usage error, `2` agent error, `3` other error,+`4` iteration cap reached — so scripts can tell "the model failed" from+"the run was cut short".diff --git a/docs/creating_llamafiles.md b/docs/creating_llamafiles.mdindex 90e5ffd5..14a1898f 100644--- a/docs/creating_llamafiles.md+++ b/docs/creating_llamafiles.md@@ -70,8 +70,6 @@ on-n32768--no-context-shift---load-mode-none...```@@ -82,12 +80,6 @@ none> prefix is required whenever referencing a file packaged inside the llamafile.> The `...` token is replaced with any additional CLI arguments the user passes> at runtime.->-> `--load-mode none` disables memory mapping. It replaces `--no-mmap`, which-> llama.cpp removed in b11100. Existing `.args` files that still use-> `--no-mmap`, `--mmap` or `--mlock` keep working, because llamafile-> translates them (see [Model Loading Flags](cli_arguments.md#model-loading-flags)).-> New ones should use `--load-mode`.- Copy the llamafile executable and run zipalign to embed the weights and args:diff --git a/llama.cpp.patches/patches/common_http.h.patch b/llama.cpp.patches/patches/common_http.h.patchindex 1f7a8c69..a598abda 100644--- a/llama.cpp.patches/patches/common_http.h.patch+++ b/llama.cpp.patches/patches/common_http.h.patch@@ -1,7 +1,73 @@diff --git a/common/http.h b/common/http.h--- a/llama.cpp/common/http.h+++ b/llama.cpp/common/http.h-@@ -104,7 +104,7 @@ static std::pair<httplib::Client, common_http_url> common_http_client(const std:+@@ -40,10 +40,15 @@ static common_http_url common_http_parse_url(const std::string & url) {+ }++ auto rest = url.substr(scheme_end + 3);+- auto at_pos = rest.find('@');++++ // the authority ends at the first '/', '?' or '#' (RFC 3986), userinfo can only be inside it++ auto auth_end = rest.find_first_of("/?#");++ auto authority = rest.substr(0, auth_end);++ auto path = auth_end == std::string::npos ? std::string() : rest.substr(auth_end);++ auto at_pos = authority.find('@');++ if (at_pos != std::string::npos) {+- auto auth = rest.substr(0, at_pos);++ auto auth = authority.substr(0, at_pos);+ auto colon_pos = auth.find(':');+ if (colon_pos != std::string::npos) {+ parts.user = auth.substr(0, colon_pos);+@@ -51,18 +56,14 @@ static common_http_url common_http_parse_url(const std::string & url) {+ } else {+ parts.user = auth;+ }+- rest = rest.substr(at_pos + 1);++ authority = authority.substr(at_pos + 1);+ }++- auto slash_pos = rest.find('/');++ parts.host = authority;++- if (slash_pos != std::string::npos) {+- parts.host = rest.substr(0, slash_pos);+- parts.path = rest.substr(slash_pos);+- } else {+- parts.host = rest;+- parts.path = "/";+- }++ // the fragment is never sent, and a query right after the authority still needs the '/'++ path = path.substr(0, path.find('#'));++ parts.path = (path.empty() || path.front() != '/') ? "/" + path : path;++ // split the authority into host and optional port, a bracketed IPv6 literal keeps its inner colons (RFC 3986)+ std::string port_str;+@@ -74,6 +75,8 @@ static common_http_url common_http_parse_url(const std::string & url) {+ auto after = parts.host.substr(close + 1);+ if (!after.empty() && after.front() == ':') {+ port_str = after.substr(1);++ } else if (!after.empty()) {++ throw std::runtime_error("invalid IPv6 URL authority: " + parts.host);+ }+ parts.host = parts.host.substr(1, close - 1);+ } else {+@@ -85,7 +88,14 @@ static common_http_url common_http_parse_url(const std::string & url) {+ }++ if (!port_str.empty()) {++ // digits only, so std::stoi can not stop early and ignore the rest++ if (port_str.size() > 5 || port_str.find_first_not_of("0123456789") != std::string::npos) {++ throw std::runtime_error("invalid URL port: " + port_str);++ }+ parts.port = std::stoi(port_str);++ if (parts.port < 1 || parts.port > 65535) {++ throw std::runtime_error("invalid URL port: " + port_str);++ }+ } else if (parts.scheme == "http") {+ parts.port = 80;+ } else if (parts.scheme == "https") {+@@ -104,7 +114,7 @@ static std::pair<httplib::Client, common_http_url> common_http_client(const std:throw std::runtime_error("error: invalid URL format");}diff --git a/llamafile/args.cpp b/llamafile/args.cppindex b8446ed5..30b76307 100644--- a/llamafile/args.cpp+++ b/llamafile/args.cpp@@ -43,10 +43,9 @@ static bool is_llamafile_flag(const char* arg) {}// llama.cpp b11100 replaced --mmap/--no-mmap/--mlock/-dio/-ndio with-// --load-mode and now rejects them, which would break existing llamafiles-// whose .args still use them. They are dropped here and one equivalent-// "--load-mode <mode>" is inserted where the last of them was, so an-// explicit --load-mode keeps working and the last flag wins, as upstream.+// --load-mode and now rejects them. If they are still provided as input,+// the following code takes care of translating them into equivalent+// "--load-mode <mode>".//// The mode follows the original semantics, where the flags were independent// settings: mmap on by default, --mlock adds locking to it (mmap+mlock, notdiff --git a/llamafile/release.sh b/llamafile/release.shindex b292dd34..0940db3c 100644--- a/llamafile/release.sh+++ b/llamafile/release.sh@@ -36,7 +36,7 @@ DEST_DIR="${RELEASE_DIR}/release"mkdir "${DEST_DIR}"# list of binaries to copy and rename-BINARIES="llamafile zipalign whisperfile diffusionfile transcribefile"+BINARIES="llamafile zipalign whisperfile diffusionfile transcribefile agentfile"for binary in $BINARIES; doif [ -f "${ZIP_DIR}/bin/${binary}" ]; thendiff --git a/tests/integration/tests/test_agentfile.py b/tests/integration/tests/test_agentfile.pynew file mode 100644index 00000000..acc61243--- /dev/null+++ b/tests/integration/tests/test_agentfile.py@@ -0,0 +1,693 @@+"""Ad hoc integration tests for agentfile.++Run from tests/integration, unsandboxed (they bind a loopback HTTP server):++ AGENTFILE_EXECUTABLE=$PWD/../../o/agentfile/agentfile \+ AGENTFILE_MODEL=~/ggufs/Qwen3.5-9B-Q5_K_S.gguf \+ uv run pytest tests/test_agentfile.py -v++The model drives the tool calls at temperature 0, so assertions target the+recorded tool results (--session JSONL) and stderr, not the model's prose.+"""++import json+import os+import re+import select+import subprocess+import threading+import time+from dataclasses import dataclass, field+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path++import pytest++EXE = os.environ.get("AGENTFILE_EXECUTABLE")+MODEL = os.path.expanduser(os.environ.get("AGENTFILE_MODEL", ""))++pytestmark = pytest.mark.skipif(+ not EXE or not MODEL,+ reason="set AGENTFILE_EXECUTABLE and AGENTFILE_MODEL to run agentfile tests",+)++CAP = 64 * 1024 # http_fetch body cap (kMaxBody)+BIG_TOTAL = 256 * 1024 # /big body size: > CAP, small enough to be quick+BIG_CHUNK = 16 * 1024+BIG_DELAY = 0.1 # per chunk, so an early abort is measurable+SECRET = "secret-token-7f3a9"+RUN_TIMEOUT = 300+LATIN1_TEXT = "Café crème brûlée costs 4 euros"+SNIPPET_CAP = 512 # web_search snippet clip (kMaxSnippet)+++@dataclass+class ServerState:+ requests: list = field(default_factory=list)+ big_bytes_sent: int = 0+ big_disconnected: bool = False+++def _make_handler(state: ServerState, base_url_box: list):+ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *_):+ pass++ def _bytes(self, code: int, data: bytes, ctype: str = "text/plain",+ extra: dict | None = None):+ self.send_response(code)+ self.send_header("Content-Type", ctype)+ self.send_header("Content-Length", str(len(data)))+ for k, v in (extra or {}).items():+ self.send_header(k, v)+ self.end_headers()+ self.wfile.write(data)++ def _text(self, code: int, body: str, extra: dict | None = None):+ self._bytes(code, body.encode(), extra=extra)++ def do_GET(self):+ state.requests.append(self.path)+ if self.path.startswith("/search"):+ # SearXNG JSON API. The snippet is cut at SNIPPET_CAP bytes,+ # which lands inside a two-byte "é" (odd offset).+ body = {"results": [{"title": "Crème brûlée", "url": "http://example.com/",+ "content": "x" + "é" * SNIPPET_CAP, "engine": "mock"}]}+ self._bytes(200, json.dumps(body).encode(), "application/json")+ elif self.path.startswith("/nulls/search"):+ # SearXNG JSON API (--searxng-url .../nulls) with null fields.+ body = {"results": [{"title": None, "url": "http://example.com/a",+ "content": None, "engine": None},+ {"title": "Second", "url": "http://example.com/b",+ "content": "ok", "engine": "mock"}]}+ self._bytes(200, json.dumps(body).encode(), "application/json")+ elif self.path == "/sso":+ # Relative Location whose query carries an absolute URL.+ self._text(302, "", {"Location": "/login?next=https://example.com/x"})+ elif self.path.startswith("/?ref="):+ self._text(200, "at-ok")+ elif self.path.startswith("/?next="):+ # Relative Location: resolves against "/", not a '/' in the query.+ self._text(302, "", {"Location": "login"})+ elif self.path == "/latin1":+ self._bytes(200, LATIN1_TEXT.encode("latin-1"),+ "text/plain; charset=iso-8859-1")+ elif self.path == "/cut":+ # UTF-8, with a two-byte "é" straddling the CAP boundary.+ self._bytes(200, b"x" * (CAP - 1) + "é".encode() * 8,+ "text/plain; charset=utf-8")+ elif self.path == "/redir":+ self._text(302, "", {"Location": base_url_box[0] + "/target"})+ elif self.path == "/target":+ self._text(200, SECRET)+ elif self.path == "/small":+ self._text(200, "hello from small")+ elif self.path == "/big":+ self._stream("text/plain", b"x")+ elif self.path == "/photo.png":+ self._stream("image/png", b"\x89")+ elif self.path == "/config.toml":+ self._bytes(200, b'name = "agentfile"\n', "application/toml")+ elif self.path == "/blob":+ # No telling type: the NUL bytes mark it binary.+ self._bytes(200, b"%PDF-1.7\n" + bytes(range(256)) * 64,+ "application/octet-stream")+ else:+ self._text(404, "not found")++ def _stream(self, ctype: str, byte: bytes):+ self.send_response(200)+ self.send_header("Content-Type", ctype)+ self.send_header("Content-Length", str(BIG_TOTAL))+ self.end_headers()+ sent = 0+ try:+ while sent < BIG_TOTAL:+ chunk = byte * min(BIG_CHUNK, BIG_TOTAL - sent)+ self.wfile.write(chunk)+ self.wfile.flush()+ sent += len(chunk)+ state.big_bytes_sent = sent+ time.sleep(BIG_DELAY)+ except (BrokenPipeError, ConnectionResetError):+ state.big_disconnected = True++ return Handler+++def http_server():+ state = ServerState()+ base_url_box = [""]+ srv = ThreadingHTTPServer(("127.0.0.1", 0), _make_handler(state, base_url_box))+ base_url_box[0] = f"http://127.0.0.1:{srv.server_address[1]}"+ t = threading.Thread(target=srv.serve_forever, daemon=True)+ t.start()+ try:+ yield base_url_box[0], state+ finally:+ srv.shutdown()+ srv.server_close()+++@dataclass+class AgentRun:+ proc: subprocess.CompletedProcess+ tool_calls: list+ tool_results: list++ def results_for(self, tool: str) -> list:+ return [r for r in self.tool_results if r.get("toolName") == tool]++ @staticmethod+ def result_text(r: dict) -> str:+ return "".join(c.get("text", "") for c in r.get("content", []))+++def run_agentfile(prompt: str, tools: str, tmp_path: Path, extra=(), cwd=None,+ model=None) -> AgentRun:+ session = tmp_path / "session.jsonl"+ # APE binaries need a shell launcher on macOS (kernel rejects the format).+ # tools=None omits the flag entirely, to exercise the default.+ cmd = [*(["sh"] if os.name != "nt" else []), EXE, "-m", model or MODEL, "-p", prompt,+ *([] if tools is None else ["--tools", tools]),+ "--session", str(session), "--no-think", *extra]+ # No stdin and no terminal, so a confirmation prompt gets no answer+ # instead of waiting on the keyboard: a new session on POSIX; on Windows,+ # where /dev/tty opens the console (CONIN$) and start_new_session is+ # ignored, no console at all.+ detach = ({"creationflags": subprocess.DETACHED_PROCESS} if os.name == "nt"+ else {"start_new_session": True})+ proc = subprocess.run(cmd, capture_output=True, text=True, stdin=subprocess.DEVNULL,+ cwd=cwd or tmp_path, timeout=RUN_TIMEOUT, **detach)+ tool_calls, tool_results = [], []+ if session.exists():+ for line in session.read_text().splitlines():+ if not line.strip():+ continue+ entry = json.loads(line)+ if entry.get("type") != "message":+ continue+ msg = entry.get("message", entry)+ if msg.get("role") == "assistant":+ tool_calls += [c for c in msg.get("content", []) if c.get("type") == "toolCall"]+ elif msg.get("role") == "toolResult":+ tool_results.append(msg)+ return AgentRun(proc, tool_calls, tool_results)+++def _dump(run: AgentRun) -> str:+ return (f"\nexit={run.proc.returncode}\n--- stdout\n{run.proc.stdout}"+ f"\n--- stderr\n{run.proc.stderr}\n--- tool results\n"+ + "\n".join(AgentRun.result_text(r)[:500] for r in run.tool_results))+++# --- http_fetch -------------------------------------------------------------++def test_http_fetch_reports_redirect_without_following(http_server, tmp_path):+ base, state = http_server+ run = run_agentfile(+ f"Fetch {base}/redir with http_fetch and reply with the text content of the page.",+ "http_fetch", tmp_path, extra=["--yes"])+ fetches = run.results_for("http_fetch")+ assert fetches, "model did not call http_fetch" + _dump(run)+ first = json.loads(AgentRun.result_text(fetches[0]))+ assert first.get("status") == 302, _dump(run)+ assert first.get("redirect_to", "").endswith("/target"), _dump(run)+ assert "/redir" in state.requests+ # The redirect is reported, not followed: the model has to fetch the+ # target itself in a second call (which is what the confirmation prompt+ # would gate in an interactive run).+ assert "/target" in state.requests, "model did not follow up on the reported redirect" + _dump(run)+ if SECRET not in run.proc.stdout:+ pytest.xfail("model fetched the target but did not quote it (prose check, non-fatal)")+++def test_http_fetch_stops_reading_at_cap(http_server, tmp_path):+ base, state = http_server+ run = run_agentfile(+ f"Use the http_fetch tool to fetch {base}/big and tell me whether the body was truncated.",+ "http_fetch", tmp_path, extra=["--yes"])+ fetches = run.results_for("http_fetch")+ assert fetches, "model did not call http_fetch" + _dump(run)+ first = json.loads(AgentRun.result_text(fetches[0]))+ assert first.get("status") == 200, _dump(run)+ assert first.get("truncated") is True, _dump(run)+ assert len(first.get("body", "")) == CAP, _dump(run)+ # The download must stop at the cap instead of buffering the whole body.+ assert state.big_bytes_sent <= BIG_TOTAL // 2, (+ f"server sent {state.big_bytes_sent} of {BIG_TOTAL} bytes; client did not abort at the cap")+++# A binary body went to the model escaped into the JSON result, and 64 KB of+# an image or a PDF takes more tokens than the default context holds.+def test_http_fetch_skips_binary_type(http_server, tmp_path):+ base, state = http_server+ run = run_agentfile(+ f"Use the http_fetch tool to fetch {base}/photo.png and tell me its content type.",+ "http_fetch", tmp_path, extra=["--yes"])+ fetches = run.results_for("http_fetch")+ assert fetches, "model did not call http_fetch" + _dump(run)+ first = json.loads(AgentRun.result_text(fetches[0]))+ assert first.get("status") == 200, _dump(run)+ assert "body" not in first, _dump(run)+ assert "Binary content (image/png)" in first.get("note", ""), _dump(run)+ # The Content-Type is enough: the download stops before the body.+ assert state.big_bytes_sent <= BIG_TOTAL // 2, (+ f"server sent {state.big_bytes_sent} of {BIG_TOTAL} bytes; client did not abort")+++def test_http_fetch_sniffs_untyped_binary(http_server, tmp_path):+ base, _ = http_server+ run = run_agentfile(+ f"Use the http_fetch tool to fetch {base}/blob and tell me its content type.",+ "http_fetch", tmp_path, extra=["--yes"])+ fetches = run.results_for("http_fetch")+ assert fetches, "model did not call http_fetch" + _dump(run)+ first = json.loads(AgentRun.result_text(fetches[0]))+ assert first.get("status") == 200, _dump(run)+ assert "body" not in first, _dump(run)+ assert "Binary content (application/octet-stream)" in first.get("note", ""), _dump(run)+++# Text served under a type that isn't text/* is still text.+def test_http_fetch_returns_text_with_other_types(http_server, tmp_path):+ base, _ = http_server+ run = run_agentfile(+ f"Use the http_fetch tool to fetch {base}/config.toml and tell me the name it sets.",+ "http_fetch", tmp_path, extra=["--yes"])+ fetches = run.results_for("http_fetch")+ assert fetches, "model did not call http_fetch" + _dump(run)+ first = json.loads(AgentRun.result_text(fetches[0]))+ assert 'name = "agentfile"' in first.get("body", ""), _dump(run)+++# Tool results used to go through a strict json dump(), so a body with+# invalid UTF-8 reached the model as a type_error.316 message instead.+def test_http_fetch_latin1_page_is_returned(http_server, tmp_path):+ base, _ = http_server+ run = run_agentfile(+ f"Fetch {base}/latin1 with http_fetch and tell me what the page says.",+ "http_fetch", tmp_path, extra=["--yes"])+ fetches = run.results_for("http_fetch")+ assert fetches, "model did not call http_fetch" + _dump(run)+ first = json.loads(AgentRun.result_text(fetches[0]))+ assert "error" not in first, _dump(run)+ assert first.get("status") == 200, _dump(run)+ assert "Caf" in first.get("body", ""), _dump(run)+++def test_http_fetch_cap_inside_utf8_char(http_server, tmp_path):+ base, _ = http_server+ run = run_agentfile(+ f"Use the http_fetch tool to fetch {base}/cut and tell me whether the body was truncated.",+ "http_fetch", tmp_path, extra=["--yes"])+ fetches = run.results_for("http_fetch")+ assert fetches, "model did not call http_fetch" + _dump(run)+ first = json.loads(AgentRun.result_text(fetches[0]))+ assert "error" not in first, _dump(run)+ assert first.get("status") == 200, _dump(run)+ assert first.get("truncated") is True, _dump(run)+++# common_http_parse_url took the first '@' anywhere after the scheme as the+# end of the userinfo, so this URL connected to 127.0.0.2 while the+# confirmation prompt showed 127.0.0.1.+def test_http_fetch_at_sign_stays_on_displayed_host(http_server, tmp_path):+ base, state = http_server+ port = base.rsplit(":", 1)[1]+ url = f"{base}/[email protected]:{port}/"+ run = run_agentfile(+ f"Call http_fetch once with exactly this url, unchanged: {url} and report the status code.",+ "http_fetch", tmp_path, extra=["--yes"])+ fetches = run.results_for("http_fetch")+ assert fetches, "model did not call http_fetch" + _dump(run)+ assert any(p.startswith("/?ref=a") for p in state.requests), (+ f"request did not reach the displayed host: {state.requests}" + _dump(run))+ first = json.loads(AgentRun.result_text(fetches[0]))+ assert first.get("status") == 200, _dump(run)++++# std::stoi stopped at the first non-digit, so this URL connected to+# 127.0.0.1 on the test server's port instead of being refused.+def test_http_fetch_rejects_junk_after_port(http_server, tmp_path):+ base, state = http_server+ url = f"{base}.evil.invalid/"+ run = run_agentfile(+ f"Call http_fetch once with exactly this url, unchanged: {url} and report what happened.",+ "http_fetch", tmp_path, extra=["--yes"])+ fetches = run.results_for("http_fetch")+ assert fetches, "model did not call http_fetch" + _dump(run)+ first = json.loads(AgentRun.result_text(fetches[0]))+ assert "invalid URL port" in first.get("error", ""), _dump(run)+ assert not state.requests, f"a request reached the test server: {state.requests}" + _dump(run)+++# resolve_location took the base directory from a path that includes the+# query, so a relative redirect resolved against the '/' in "next=a/b".+def test_http_fetch_relative_redirect_after_query(http_server, tmp_path):+ base, _ = http_server+ run = run_agentfile(+ f"Call http_fetch once with exactly this url, unchanged: {base}?next=a/b and report the status code.",+ "http_fetch", tmp_path, extra=["--yes"])+ fetches = run.results_for("http_fetch")+ assert fetches, "model did not call http_fetch" + _dump(run)+ first = json.loads(AgentRun.result_text(fetches[0]))+ assert first.get("status") == 302, _dump(run)+ assert first.get("redirect_to") == f"{base}/login", _dump(run)+++# resolve_location took any Location containing "://" as absolute, so this+# relative redirect came back as a bare path the model could not fetch.+def test_http_fetch_relative_redirect_with_url_in_query(http_server, tmp_path):+ base, _ = http_server+ run = run_agentfile(+ f"Call http_fetch once with exactly this url, unchanged: {base}/sso and report the status code.",+ "http_fetch", tmp_path, extra=["--yes"])+ fetches = run.results_for("http_fetch")+ assert fetches, "model did not call http_fetch" + _dump(run)+ first = json.loads(AgentRun.result_text(fetches[0]))+ assert first.get("status") == 302, _dump(run)+ assert first.get("redirect_to") == f"{base}/login?next=https://example.com/x", _dump(run)++# --- web_search -------------------------------------------------------------++def test_web_search_snippet_cut_inside_utf8_char(http_server, tmp_path):+ base, state = http_server+ run = run_agentfile(+ "Use web_search to search for creme brulee and tell me the title of the first result.",+ "web_search", tmp_path, extra=["--yes", "--searxng-url", base])+ searches = run.results_for("web_search")+ assert searches, "model did not call web_search" + _dump(run)+ assert any(p.startswith("/search") for p in state.requests)+ first = json.loads(AgentRun.result_text(searches[0]))+ assert "error" not in first, _dump(run)+ assert first["results"][0]["snippet"].endswith("…"), _dump(run)+++# A null field threw inside the result loop, and the whole search came back+# as "SearXNG returned unparseable JSON".+def test_web_search_null_fields_keep_results(http_server, tmp_path):+ base, _ = http_server+ run = run_agentfile(+ "Use web_search to search for creme brulee and tell me the title of the second result.",+ "web_search", tmp_path, extra=["--yes", "--searxng-url", f"{base}/nulls"])+ searches = run.results_for("web_search")+ assert searches, "model did not call web_search" + _dump(run)+ first = json.loads(AgentRun.result_text(searches[0]))+ assert "error" not in first, _dump(run)+ results = first["results"]+ assert len(results) == 2, _dump(run)+ assert results[0]["title"] == "" and results[0]["snippet"] == "", _dump(run)+ assert results[1]["title"] == "Second", _dump(run)+++# print_tools_help read only SEARXNG_URL, so --searxng-url (on the command+# line or in a packaged agent's .args) still listed web_search as unavailable.+def test_help_honors_searxng_url_flag(tmp_path, monkeypatch):+ monkeypatch.delenv("SEARXNG_URL", raising=False)+ run = run_agentfile("hi", "all", tmp_path, extra=["--searxng-url", "http://127.0.0.1:9", "-h"])+ assert run.proc.returncode == 0, _dump(run)+ assert "web_search" in run.proc.stderr, _dump(run)+ assert "unavailable: web_search" not in run.proc.stderr, _dump(run)+++# --- --tools ----------------------------------------------------------------++# An empty keep-set means "all tools" to make_adapters, so a list naming+# nothing used to enable every tool, exec_shell_command included.[email protected]("spec", [",", " ", ""])+def test_tools_list_naming_nothing_is_rejected(tmp_path, spec):+ run = run_agentfile("hi", spec, tmp_path, extra=["--yes"])+ assert run.proc.returncode == 1, _dump(run)+ assert "--tools: no tool names" in run.proc.stderr, _dump(run)+ assert not run.tool_calls, _dump(run)++++# Tools are opt-in: without --tools the model gets none (they cost context+# and widen the attack surface). The -v roster line is the contract.+def test_tools_default_is_none(tmp_path):+ run = run_agentfile("What is 2 plus 2? Answer with just the number.",+ None, tmp_path, extra=["-v"])+ assert run.proc.returncode == 0, _dump(run)+ assert "[tools: none]" in run.proc.stderr, _dump(run)+ assert "[tool: " not in run.proc.stderr, _dump(run)+ assert not run.tool_results, _dump(run)+++def test_tools_roster_lists_enabled_tools(tmp_path):+ run = run_agentfile("What is 2 plus 2? Answer with just the number.",+ "read_only", tmp_path, extra=["-v"])+ assert run.proc.returncode == 0, _dump(run)+ roster = [l for l in run.proc.stderr.splitlines() if "[tools: " in l]+ assert roster, _dump(run)+ assert "read_file" in roster[0], _dump(run)+ assert "write_file" not in roster[0], _dump(run)+++# --tools-runtime specs went unchecked until the first tool call; llama.cpp's+# server_tools::setup now checks them at startup.+def test_bad_tools_runtime_fails_at_startup(tmp_path):+ run = run_agentfile("hi", "read_only", tmp_path, extra=["--tools-runtime", "bogus:x"])+ assert run.proc.returncode == 3, _dump(run)+ assert "unknown tool runtime: bogus:x" in run.proc.stderr, _dump(run)+ assert not run.tool_calls, _dump(run)+++# llama.cpp b11100 dropped get_datetime from its server tools, and the+# read_only preset, which names it, then failed with "unknown tool".+def test_read_only_preset_has_get_datetime(tmp_path):+ run = run_agentfile("Use the get_datetime tool and tell me today's date.", "read_only", tmp_path)+ assert run.proc.returncode == 0, _dump(run)+ results = run.results_for("get_datetime")+ assert results, "model did not call get_datetime" + _dump(run)+ assert "result" in json.loads(AgentRun.result_text(results[0])), _dump(run)++# --- -c / --max-iterations --------------------------------------------------++# atoi() turned bad values into 0 ("no limit": the model's full native+# context, or no iteration cap) or a truncated number (-c 32k -> 32).[email protected]("flag,value", [+ ("-c", "abc"), ("-c", "32k"), ("-c", "-1"),+ ("--max-iterations", "abc"), ("--max-iterations", "-5"),+])+def test_bad_count_flag_is_rejected(tmp_path, flag, value):+ run = run_agentfile("hi", "read_only", tmp_path, extra=[flag, value])+ assert run.proc.returncode == 1, _dump(run)+ assert f"{flag}: expected a non-negative integer" in run.proc.stderr, _dump(run)+ assert not run.tool_calls, _dump(run)++# The context is 64K tokens by default and never more than the model's+# maximum, an explicit -c included.[email protected]("ctx_flag,wanted", [((), 65536), (("-c", "10000000"), 10000000)])+def test_context_is_capped_at_model_max(tmp_path, ctx_flag, wanted):+ run = run_agentfile("Reply with OK.", "read_only", tmp_path, extra=["-vv", *ctx_flag])+ assert run.proc.returncode == 0, _dump(run)+ train = re.search(r"n_ctx_train\s*=\s*(\d+)", run.proc.stderr)+ ctx = re.search(r"llama_context: n_ctx\s*=\s*(\d+)", run.proc.stderr)+ assert train and ctx, _dump(run)+ assert int(ctx.group(1)) == min(wanted, int(train.group(1))), _dump(run)++# --- --session --------------------------------------------------------------++# The session recorder used a strict json dump(): a tool result with invalid+# UTF-8 (here a Latin-1 file) killed the run with exit 3.+def test_session_records_latin1_file(tmp_path):+ (tmp_path / "menu.txt").write_bytes(LATIN1_TEXT.encode("latin-1"))+ run = run_agentfile("Use read_file to read menu.txt and tell me what it says.",+ "read_file", tmp_path)+ assert run.proc.returncode == 0, _dump(run)+ reads = run.results_for("read_file")+ assert reads, "model did not call read_file (or the result was not recorded)" + _dump(run)+ text = AgentRun.result_text(reads[0])+ assert "Caf" in text and "�" in text, _dump(run)+++# Missing tool-call ids were assigned by the session recorder, so the prompt+# changed with --session. Model::generate assigns them now; the recorder+# only records them.+def test_session_tool_calls_have_paired_ids(tmp_path):+ (tmp_path / "menu.txt").write_text("soup")+ run = run_agentfile("Use read_file to read menu.txt and tell me what it says.",+ "read_file", tmp_path)+ assert run.proc.returncode == 0, _dump(run)+ assert run.tool_calls and run.tool_results, _dump(run)+ call_ids = [c.get("id") for c in run.tool_calls]+ assert all(call_ids), f"tool call without an id: {call_ids}" + _dump(run)+ assert [r.get("toolCallId") for r in run.tool_results] == call_ids, _dump(run)+++# The recorders opened their files after the model loaded, so a bad path+# used to fail only after the whole load. The model path here doesn't+# exist: the record path must fail first.[email protected]("flag", ["--session", "--trace"])+def test_unwritable_record_path_fails_before_load(tmp_path, flag):+ path = str(tmp_path / "missing-dir" / "out.jsonl")+ run = run_agentfile("hi", "read_only", tmp_path, extra=[flag, path],+ model=str(tmp_path / "missing.gguf"))+ assert run.proc.returncode == 3, _dump(run)+ assert f"{flag}: cannot open {path}" in run.proc.stderr, _dump(run)+ assert "load model" not in run.proc.stderr, _dump(run)+++# --- -v / -vv ---------------------------------------------------------------++# llama.cpp's own log was silenced at every verbosity, so -v could not show+# why a model failed to load.+def test_verbose_shows_model_load_error(tmp_path):+ bad = tmp_path / "bad.gguf"+ bad.write_bytes(b"not a gguf file\n" * 64)+ default = run_agentfile("hi", "read_only", tmp_path, model=str(bad))+ verbose = run_agentfile("hi", "read_only", tmp_path, model=str(bad), extra=["-v"])+ for run in (default, verbose):+ assert run.proc.returncode == 2, _dump(run)+ assert "unable to load model" in run.proc.stderr, _dump(run)+ assert "error loading model" not in default.proc.stderr, _dump(default)+ assert "llama_model_load: error loading model" in verbose.proc.stderr, _dump(verbose)+++def test_very_verbose_shows_llama_info_log(tmp_path):+ marker = "llama_model_loader: loaded meta data"+ verbose = run_agentfile("Reply with OK.", "read_only", tmp_path, extra=["-v"])+ very = run_agentfile("Reply with OK.", "read_only", tmp_path, extra=["-vv"])+ for run in (verbose, very):+ assert run.proc.returncode == 0, _dump(run)+ assert marker not in run.proc.stdout, "log output on stdout" + _dump(run)+ assert marker not in verbose.proc.stderr, _dump(verbose)+ assert marker in very.proc.stderr, _dump(very)+++# --- --quiet --yes audit ----------------------------------------------------++WRITE_PROMPT = ("Use the write_file tool to create a file named note.txt in the "+ "current directory containing exactly the text hello. Then reply done.")+++def test_quiet_yes_prints_audit_line(tmp_path):+ run = run_agentfile(WRITE_PROMPT, "write_file", tmp_path, extra=["--yes", "--quiet"])+ assert (tmp_path / "note.txt").exists(), _dump(run)+ assert "[write_file --yes]" in run.proc.stderr, _dump(run)+ assert "[tool: write_file" not in run.proc.stderr, "progress output leaked under --quiet" + _dump(run)+++def test_default_verbosity_has_progress_not_audit(tmp_path):+ run = run_agentfile(WRITE_PROMPT, "write_file", tmp_path, extra=["--yes"])+ assert (tmp_path / "note.txt").exists(), _dump(run)+ assert "[tool: write_file" in run.proc.stderr, _dump(run)+ assert "--yes]" not in run.proc.stderr, "duplicate audit line at default verbosity" + _dump(run)+++# --- confirmation without a terminal ----------------------------------------++# With no terminal to confirm on, a guarded call used to come back as+# "user cancelled" and the model retried it without end.+def test_guarded_call_without_terminal_ends_run(tmp_path):+ run = run_agentfile(WRITE_PROMPT, "write_file", tmp_path)+ assert run.proc.returncode == 2, _dump(run)+ assert run.proc.stderr.count("cannot confirm write_file") == 1, _dump(run)+ # Nothing to ask on, so no question nobody can answer.+ assert "Allow? [y/N]" not in run.proc.stderr, _dump(run)+ assert not (tmp_path / "note.txt").exists(), _dump(run)+++# --- the terminal: confirmation and -i (driven through a pty) ---------------++posix_only = pytest.mark.skipif(os.name == "nt", reason="drives a pty")+++def _pump(fd, on_output) -> str:+ """Read fd to EOF, calling on_output(everything so far) after each read."""+ out = b""+ while select.select([fd], [], [], RUN_TIMEOUT)[0]:+ try:+ chunk = os.read(fd, 4096)+ except OSError: # the pty closed+ break+ if not chunk:+ break+ out += chunk+ on_output(out)+ return out.decode(errors="replace")+++def run_on_terminal(tmp_path, args, on_terminal, typeahead=b"", stderr_on_terminal=False):+ """Run agentfile in its own session with stdin on a pty; stderr goes to+ a file unless stderr_on_terminal. on_terminal(master, text so far)+ answers what agentfile asks on the pty. Returns (exit code, terminal+ text, stdout, stderr)."""+ import pty+ master, slave = pty.openpty()+ log = tmp_path / "stderr.log"+ with open(log, "wb") as err:+ proc = subprocess.Popen(["sh", EXE, "-m", MODEL, "--no-think", *args],+ stdin=slave, stdout=subprocess.PIPE,+ stderr=slave if stderr_on_terminal else err,+ cwd=tmp_path, start_new_session=True)+ os.close(slave)+ os.write(master, typeahead)+ term = _pump(master, lambda text: on_terminal(master, text))+ proc.wait(timeout=RUN_TIMEOUT)+ os.close(master)+ return (proc.returncode, term, proc.stdout.read().decode(errors="replace"),+ log.read_text(errors="replace"))+++def answer_every_prompt(answer: bytes):+ answered = [0]++ def on_terminal(master, text):+ while text.count(b"Allow? [y/N]") > answered[0]:+ os.write(master, answer + b"\n")+ answered[0] += 1+ return on_terminal+++WRITE_ARGS = ["-p", WRITE_PROMPT, "--tools", "write_file"]+++# With stderr redirected, the question used to go there, and the run waited+# on a question nobody could see. It goes to the terminal now.+@posix_only+def test_confirmation_yes_runs_the_call(tmp_path):+ code, term, _, err = run_on_terminal(tmp_path, WRITE_ARGS, answer_every_prompt(b"y"))+ assert code == 0, term + err+ assert "Allow? [y/N]" in term and "Allow?" not in err, term + err+ assert (tmp_path / "note.txt").exists(), term + err+++# Models retry a declined call, and each retry asked again, without end.+@posix_only+def test_declined_calls_end_the_run(tmp_path):+ code, term, _, err = run_on_terminal(tmp_path, WRITE_ARGS, answer_every_prompt(b"n"))+ assert code in (0, 2), term + err+ assert term.count("Allow? [y/N]") <= 3, term + err+ assert not (tmp_path / "note.txt").exists(), term + err+ # Nothing ran, so no result line either.+ assert "[tool: write_file ->" not in err, err+++# The answer was read from whatever was typed before the question appeared.+@posix_only+def test_typed_ahead_text_does_not_answer_the_prompt(tmp_path):+ code, term, _, err = run_on_terminal(tmp_path, WRITE_ARGS, answer_every_prompt(b"n"),+ typeahead=b"yes please\n")+ assert not (tmp_path / "note.txt").exists(), term + err+++@posix_only+def test_interactive_follow_up_then_empty_line_ends(tmp_path):+ sent = [0]++ def on_terminal(master, text):+ if text.count(b"\n> ") > sent[0]:+ os.write(master, b"Now reply with the single word banana.\n" if sent[0] == 0 else b"\n")+ sent[0] += 1+ code, term, out, _ = run_on_terminal(+ tmp_path, ["-p", "Reply with the single word apple.", "-i", "--tools", "read_only"],+ on_terminal, stderr_on_terminal=True)+ assert code == 0, term+ assert "apple" in out.lower() and "banana" in out.lower(), out + term