Files
lemonade/test/cpp/test_pi_profile.cpp
Sawan SrivastavaandClaude Opus 5.5 3614598dc8 Improve lemonade launch pi integration (#3786)
* feat(cli): write model metadata and keep the API key off disk for pi

lemonade launch pi now writes per-model contextWindow/maxTokens (from the
model's saved ctx_size, 40960 otherwise, as before), image input for vision
models, and an off/on thinking toggle for reasoning models. The provider
sets llama.cpp-friendly compat flags.

models.json references ${LEMONADE_API_KEY} when a key is configured, which
launch exports to pi, and keeps the "lemonade" placeholder otherwise.
Launch warns when the selected model is not labeled tool-calling.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* feat(cli): add Lemonade MCP to pi with launch pi --mcp

--mcp adds a "lemonade" streamable HTTP server to pi's mcp.json and
--no-mcp removes it; other servers, top-level keys and user-set keys on
the entry are kept. An existing entry is refreshed on every launch so it
follows the current host, port and key. The Authorization header
references ${LEMONADE_API_KEY} and is omitted without a key, and tools use
direct exposure so the entry does not switch codemode on.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* feat(cli): add launch pi --codemode

--codemode passes --tools +codemode for that launch only, without changing
pi's settings. Combined with --mcp, codemode scripts can call Lemonade's
MCP tools, for example lemonade_generate_image, and show the result with
image().

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* test(cli): cover the JSON launch pi writes into pi's agent directory

Unit tests for the models.json provider block (llama.cpp compat, context
window, vision, reasoning) and for merging, refreshing and removing the
lemonade server in mcp.json.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* test(cli): cover launch pi metadata, key, MCP and codemode end to end

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* docs: describe launch pi MCP, codemode, images and the API key reference

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* refactor(cli): read pi settings.json with read_json_object

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* test(cli): pin pi's apiKey value and MCP header refresh in PiProfileTest

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): fall back to the default window for an auto ctx_size in launch

A saved ctx_size of -1 (auto) reached pi as -1, so no contextWindow was
written and pi used its own 128000-token default instead of Lemonade's
40960 fallback.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): use launch's --ctx-size for the selected model's agent window

launch loads the model with its own recipe options, but agent configs
were written from the saved ctx_size only, so pi (and opencode/junie)
could be told a window larger than the one the model runs with.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): give a not-yet-downloaded launch model its labels and window

The agent model list holds only downloaded models, so a selected model
that was not downloaded yet went in with no labels and the default
window: pi lost image input and the thinking toggle, and skipped the
tool-calling warning. launch now looks the model up with
GET /api/v1/models/<id> and builds its entry from the same parsing as
the list, falling back to a bare entry when the server does not know it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* docs: update pi's launch intro and window notes for the launch fixes

The intro listed only models.json with the selected model and
settings.json; it now lists all three files. The window notes cover
launch's --ctx-size and an automatic ctx_size, and cli.md names the
${LEMONADE_API_KEY} reference as it appears in models.json.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): drop stdio keys and keep user auth when refreshing pi's MCP entry

Refreshing an existing "lemonade" entry in pi's mcp.json now removes
command/args/env/cwd and any non-HTTP type, since pi rejects a url entry
with a stdio or sse type. A launch without an API key only removes the
Authorization header when it is Lemonade's own ${LEMONADE_API_KEY}
reference.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): use https in pi's config when the server is reached over TLS

build_agent_server_base_url always returned http://, so launching pi
against an https host wrote http URLs into models.json and mcp.json. It
now takes an optional is_ssl, which launch passes for pi only; the other
agents' URLs are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): leave thinking to the model and server in launch pi

Launch no longer writes reasoning, thinkingLevelMap or thinkingFormat
for pi's models, or supportsReasoningEffort for the provider. The
qwen-chat-template toggle only works for models whose chat template
reads enable_thinking, and the CLI cannot tell which ones do: the
reasoning label does not say, and the DeepSeek-R1 Qwen distills carry a
Qwen name without the toggle. Pi still shows a model's reasoning output,
since it reads reasoning_content for every model.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): drop supportsDeveloperRole from launch pi's provider

Pi only sends a developer message for models marked reasoning, and
launch no longer marks any, so the setting had no effect.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): warn when launch pi is given a model the server does not know

A mistyped --model started pi without any message: the selected model
went into models.json without labels, which also skipped the
tool-calling warning, and the background load failed silently. When the
server answers 404 for the model, launch pi now says so. Other lookup
failures and the other agents are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): drop pi's MCP credentials when launch points it at another server

Refreshing the lemonade entry in pi's mcp.json kept its headers, oauth
and auth settings when the url moved to a different server, so pi would
send credentials meant for the old server to the new one. They are now
removed when the url changes; a refresh against the same server keeps
them as before.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): stop launch pi when --no-mcp cannot remove the MCP server

When removing the lemonade entry from pi's mcp.json failed, launch only
warned and started pi with the server still enabled. Since the user
asked for the removal explicitly, launch now exits with an error
instead. --mcp failures and the automatic refresh still only warn.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): keep pi's mcp.json permissions and symlink when launch rewrites it

Launch rewrote mcp.json through a new temp file, so a private 0600 file
holding other servers' tokens became world-readable under the default
umask, and a symlinked mcp.json was replaced by a regular file. The
write now goes to the symlink's target and the temp file takes the
existing file's permissions. settings.json gets the same treatment.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* test(cli): pin that another form of pi's MCP url counts as another server

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): stop launch pi when a key is set and pi's config cannot be updated

Pi's config references ${LEMONADE_API_KEY}, which launch exports. When
models.json, or an existing lemonade entry in mcp.json, could not be
updated, launch warned and started pi anyway, so pi sent this server's
key to the server its old config still pointed at. With a key, launch
now exits with an error instead. Without a key it still warns and
continues, and other agents are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): stop launch pi with a key when pi's mcp.json cannot be read

Launch treated an mcp.json it could not parse as having no lemonade
entry, so it skipped the refresh and started pi with the key exported.
Pi reads the file with Node, which tolerates invalid UTF-8, so a stale
entry in such a file would get this server's key. With a key, launch
now stops when mcp.json exists but cannot be read. A missing file and
launches without a key are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* docs: note the pi versions launch pi --mcp and --codemode need

--mcp relies on pi's built-in MCP support and is ignored by pi before
1.0. --codemode passes --tools +codemode, and pi only accepts +name
entries in --tools from 1.1.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): give pi the auto-tuned context size of the launched model

With an automatic ctx_size, launch wrote the 40960 fallback to pi's
models.json, while the server sized the model at load, so pi compacted
by a window the model did not have. When the launched model's size is
automatic, launch now loads it before starting pi and writes the window
the server reports for the loaded model. If the load fails, pi gets the
fallback as before. Other agents are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): check pi is installed before launch loads a model for its window

Launch synced pi's config, which can now load the model to read its
auto-tuned window, before looking for the pi binary. With pi missing,
launch loaded the model, evicting others, and only then failed. Pi's
config sync now runs after the binary is found. Other agents keep their
order.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): warn when launch pi can't read the loaded model's context size

When the load succeeded but the server reported no context size, launch
gave pi the 40960 fallback without saying so, and a failed read was
reported as a failed load. Launch now names the step that failed, warns
when no size was reported, and says which size pi gets instead.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* docs: note that launch pi waits for the load when the context size is automatic

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): stop launch pi when the model it waits on fails to load

When launch loads the model to read its auto-tuned window and the load
fails, it now prints the server's error and exits without starting pi,
which would otherwise run on a model that can't answer. A load that
succeeds without a readable size still falls back to 40960 with a
warning. Launches with a known window keep loading in the background.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* docs: say launch pi with --model may wait for the load

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* feat(cli): check pi's version when launch pi gets --codemode or --mcp

--codemode passes `--tools +codemode`, which pi only reads as adding a
tool from 1.1, and pi ignores mcp.json before 1.0. When either flag is
passed, launch now runs `pi --version`: an older pi stops launch for
--codemode and gets a warning for --mcp. Output without a version is
not checked, so launch still starts pi.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(cli): skip launch's background load when pi's sync already loaded the model

When the launched model's context size is automatic, pi's config sync
loads it to read the window, and launch then sent the same load again in
the background. The router reused the loaded model, so the second request
did nothing. Launch now skips it after a sync load; other launches keep
loading in the background.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-19 17:41:54 +00:00

282 lines
12 KiB
C++

// Checks the JSON `lemonade launch pi` writes into pi's agent directory: the
// provider block in models.json and the "lemonade" server in mcp.json.
// Build with: cmake --build --preset default --target test_pi_profile
// Run with: ctest --test-dir build -R '^PiProfileTest$' --output-on-failure
#include "lemon_cli/agent_launcher.h"
#include "lemon_cli/pi_profile.h"
#include <nlohmann/json.hpp>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <string>
namespace fs = std::filesystem;
using nlohmann::json;
namespace {
int failures = 0;
void check(const std::string& what, bool ok) {
std::printf("%s %s\n", ok ? "PASS" : "FAIL", what.c_str());
if (!ok) ++failures;
}
std::string read_file(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
std::stringstream buffer;
buffer << in.rdbuf();
return buffer.str();
}
void write_file(const fs::path& path, const std::string& content) {
std::ofstream out(path, std::ios::binary | std::ios::trunc);
out << content;
}
void test_provider_block() {
const json provider = lemon_cli::pi_profile().build_provider_block(
"http://localhost:13305/v1", "",
{
{"Plain", "", 32768, {"chat"}},
{"Vision", "", 65536, {"chat", "vision"}},
{"Thinker", "", 40960, {"chat", "reasoning"}},
{"Unknown", "", 0, {"chat"}},
});
check("provider compat targets llama.cpp", provider["compat"] == json{
{"supportsStore", false},
{"maxTokensField", "max_tokens"},
});
check("plain model", provider["models"][0] == json{
{"id", "Plain"}, {"contextWindow", 32768}, {"maxTokens", 32768}, {"input", {"text"}},
});
check("vision model takes images", provider["models"][1]["input"] == json{"text", "image"});
check("reasoning model leaves thinking to the server", provider["models"][2] == json{
{"id", "Thinker"}, {"contextWindow", 40960}, {"maxTokens", 40960}, {"input", {"text"}},
});
check("unknown window is left to pi", provider["models"][3] == json{
{"id", "Unknown"}, {"input", {"text"}},
});
}
void test_api_key() {
const auto api_key_for = [](const std::string& key) {
return lemon_cli::pi_profile().build_provider_block(
"http://localhost:13305/v1", key, {{"Plain", "", 32768, {"chat"}}})["apiKey"];
};
check("no key writes the placeholder", api_key_for("") == "lemonade");
check("a key is referenced from the environment, never written",
api_key_for("real-secret-key") == "${LEMONADE_API_KEY}");
}
void test_server_origin() {
check("https server gets an https origin",
lemon_tray::build_agent_server_base_url("my.server", 443, true) ==
"https://my.server:443");
check("wildcard host keeps the scheme",
lemon_tray::build_agent_server_base_url("0.0.0.0", 13305, true) ==
"https://localhost:13305");
check("plain server stays http",
lemon_tray::build_agent_server_base_url("localhost", 13305, false) ==
"http://localhost:13305");
}
void test_pi_version() {
const auto parsed = [](const std::string& output, int major, int minor) {
int found_major = -1;
int found_minor = -1;
return lemon_cli::parse_pi_version(output, found_major, found_minor) &&
found_major == major && found_minor == minor;
};
check("pi --version output is parsed", parsed("1.1.0\n", 1, 1));
check("an older pi version is parsed", parsed("0.99.2", 0, 99));
check("a prefixed version is parsed", parsed("pi v1.0.4", 1, 0));
int major = 0;
int minor = 0;
check("output without a version is not parsed",
!lemon_cli::parse_pi_version("fake-agent-ok\n", major, minor) &&
!lemon_cli::parse_pi_version("", major, minor));
}
void test_mcp_server(const fs::path& mcp_path) {
std::string error;
write_file(mcp_path, R"({
"autoEnableCodemode": false,
"mcpServers": {
"other": {"url": "http://other/mcp"},
"lemonade": {"url": "http://localhost:13305/mcp", "enabled": false,
"headers": {"X-Trace": "1"}}
}
})");
lemon_cli::sync_pi_mcp_server("http://localhost:13305", true, error);
json mcp = json::parse(read_file(mcp_path));
json expected = json::parse(R"({
"autoEnableCodemode": false,
"mcpServers": {
"other": {"url": "http://other/mcp"},
"lemonade": {
"url": "http://localhost:13305/mcp",
"enabled": false,
"headers": {"X-Trace": "1", "Authorization": "Bearer ${LEMONADE_API_KEY}"},
"exposure": "direct"
}
}
})");
mcp["mcpServers"]["lemonade"].erase("description");
check("add keeps other servers, top-level keys and user-set keys", mcp == expected);
lemon_cli::sync_pi_mcp_server("http://localhost:13305", false, error);
mcp = json::parse(read_file(mcp_path));
check("refresh without a key drops only the key header",
mcp["mcpServers"]["lemonade"]["headers"] == json{{"X-Trace", "1"}});
// Credentials meant for the old server must not be sent to the new one.
mcp["mcpServers"]["lemonade"]["headers"]["Authorization"] = "Bearer token-for-old";
mcp["mcpServers"]["lemonade"]["oauth"] = {{"clientId", "old"}};
mcp["mcpServers"]["lemonade"]["auth"] = {{"provider", "old"}};
write_file(mcp_path, mcp.dump());
lemon_cli::sync_pi_mcp_server("http://127.0.0.1:9000", false, error);
mcp = json::parse(read_file(mcp_path));
const json& moved = mcp["mcpServers"]["lemonade"];
check("refresh to another server drops the old server's credentials",
moved["url"] == "http://127.0.0.1:9000/mcp" && !moved.contains("headers") &&
!moved.contains("oauth") && !moved.contains("auth") &&
moved["enabled"] == false);
mcp["mcpServers"]["lemonade"]["headers"] = {{"Authorization", "Bearer token-for-old"},
{"X-API-Key", "key-for-old"}};
write_file(mcp_path, mcp.dump());
lemon_cli::sync_pi_mcp_server("https://other.example:443", true, error);
mcp = json::parse(read_file(mcp_path));
check("refresh to another server with a key sends only the key reference",
mcp["mcpServers"]["lemonade"]["headers"] ==
json{{"Authorization", "Bearer ${LEMONADE_API_KEY}"}});
lemon_cli::remove_pi_mcp_server(error);
mcp = json::parse(read_file(mcp_path));
check("remove drops only the lemonade server",
mcp == json::parse(R"({"autoEnableCodemode": false,
"mcpServers": {"other": {"url": "http://other/mcp"}}})"));
// Pi rejects an entry whose type is not an HTTP one even when it has a url.
write_file(mcp_path, R"({"mcpServers": {"lemonade": {
"type": "stdio", "command": "npx", "args": ["lemonade-mcp"],
"env": {"A": "1"}, "cwd": "/tmp", "timeout": 30
}}})");
lemon_cli::sync_pi_mcp_server("http://localhost:13305", false, error);
mcp = json::parse(read_file(mcp_path));
const json& migrated = mcp["mcpServers"]["lemonade"];
check("refresh turns a stdio entry into an HTTP one and keeps user settings",
migrated["url"] == "http://localhost:13305/mcp" && !migrated.contains("type") &&
!migrated.contains("command") && !migrated.contains("args") &&
!migrated.contains("env") && !migrated.contains("cwd") &&
migrated["timeout"] == 30);
write_file(mcp_path, R"({"mcpServers": {"lemonade": {
"type": "streamable-http", "url": "http://old:1/mcp"
}}})");
lemon_cli::sync_pi_mcp_server("http://localhost:13305", false, error);
mcp = json::parse(read_file(mcp_path));
check("refresh keeps an HTTP type the user set",
mcp["mcpServers"]["lemonade"]["type"] == "streamable-http");
// Only the exact url launch writes counts as the same server.
write_file(mcp_path, R"({"mcpServers": {"lemonade": {
"url": "http://localhost:13305/mcp/", "headers": {"X-Trace": "1"}
}}})");
lemon_cli::sync_pi_mcp_server("http://localhost:13305", false, error);
mcp = json::parse(read_file(mcp_path));
check("refresh treats another form of the url as another server",
!mcp["mcpServers"]["lemonade"].contains("headers"));
write_file(mcp_path, R"({"mcpServers": {"lemonade": {
"url": "http://localhost:13305/mcp",
"headers": {"Authorization": "Bearer my-own-token"}
}}})");
lemon_cli::sync_pi_mcp_server("http://localhost:13305", false, error);
mcp = json::parse(read_file(mcp_path));
check("refresh to the same server without a key keeps the user's Authorization",
mcp["mcpServers"]["lemonade"]["headers"] ==
json{{"Authorization", "Bearer my-own-token"}});
write_file(mcp_path, "{ not json");
check("malformed mcp.json is refused and left untouched",
!lemon_cli::sync_pi_mcp_server("http://localhost:13305", false, error) &&
read_file(mcp_path) == "{ not json");
}
#ifndef _WIN32
// mcp.json can hold other servers' tokens, so rewriting it must not widen its
// permissions or replace a symlinked file with a regular one.
void test_mcp_file_kept(const fs::path& agent_dir) {
std::string error;
const fs::path mcp_path = agent_dir / "mcp.json";
const std::string content =
R"({"mcpServers": {"other": {"url": "https://x/mcp",
"headers": {"Authorization": "Bearer secret"}},
"lemonade": {"url": "http://localhost:13305/mcp"}}})";
write_file(mcp_path, content);
fs::permissions(mcp_path, fs::perms::owner_read | fs::perms::owner_write);
lemon_cli::sync_pi_mcp_server("http://localhost:13305", false, error);
check("refresh keeps a private mcp.json private",
fs::status(mcp_path).permissions() ==
(fs::perms::owner_read | fs::perms::owner_write));
write_file(mcp_path, content);
fs::permissions(mcp_path, fs::perms::owner_read | fs::perms::owner_write);
lemon_cli::remove_pi_mcp_server(error);
check("--no-mcp removal keeps a private mcp.json private",
fs::status(mcp_path).permissions() ==
(fs::perms::owner_read | fs::perms::owner_write));
const fs::path target = agent_dir / "dotfiles-mcp.json";
fs::remove(mcp_path);
write_file(target, content);
fs::create_symlink(target, mcp_path);
lemon_cli::sync_pi_mcp_server("http://127.0.0.1:9000", false, error);
check("refresh writes through a symlinked mcp.json",
fs::is_symlink(mcp_path) &&
json::parse(read_file(target))["mcpServers"]["lemonade"]["url"] ==
"http://127.0.0.1:9000/mcp");
fs::remove(mcp_path);
}
#endif
} // namespace
int main() {
const fs::path agent_dir = fs::temp_directory_path() /
("lemonade-pi-profile-test-" +
std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
fs::create_directories(agent_dir);
#ifdef _WIN32
_putenv_s("PI_CODING_AGENT_DIR", agent_dir.string().c_str());
#else
setenv("PI_CODING_AGENT_DIR", agent_dir.string().c_str(), 1);
#endif
test_provider_block();
test_api_key();
test_server_origin();
test_pi_version();
test_mcp_server(agent_dir / "mcp.json");
#ifndef _WIN32
test_mcp_file_kept(agent_dir);
#endif
std::error_code ec;
fs::remove_all(agent_dir, ec);
std::printf("%s (%d failure%s)\n", failures ? "FAILED" : "OK", failures, failures == 1 ? "" : "s");
return failures ? 1 : 0;
}