Refactor to plugin architecture with B3 CLI UX, C2 smoke tests, C3 CI scripts

Architecture overhaul (Wave 1-4 collaborative work):
- Migrated dstalk-core from monolithic api.cpp to plugin-based design with
  host/service_registry/event_bus/plugin_loader and topological initialization.
- Split public headers into dstalk_host.h / dstalk_services.h /
  dstalk_lsp.h / dstalk_types.h; deleted obsolete dstalk_api.h and inlined
  TLS/file/net code now provided by plugins.
- Added 9 plugins: deepseek, anthropic, network, session, context, tools,
  config, file-io, lsp; AI plugins register as "ai.<provider>" services.

B3 CLI interaction enhancement:
- Prompt now shows current model name (A1).
- /status command prints model/base_url/api_key (sanitized: shown only
  as set/unset)/services readiness (A2).
- SIGINT/Ctrl+C handled on POSIX (signal) and Windows (SetConsoleCtrlHandler);
  /quit no longer std::exit(0) but sets a quit flag so dstalk_shutdown runs
  exactly once via natural control flow (B1+B2).
- Cross-DLL free fixed: print_file uses dstalk_free instead of std::free (B4).
- --batch mode plus isatty auto-detection for piped stdin (C1).
- fgets truncation detection with friendly error and stdin draining (C3).
- Distinct exit codes (init/AI/service-unavailable) (C4).
- /model rejects empty model name (C5).

C2 smoke test extension:
- 4 new test blocks: null-safety (file_io/session/tools/config),
  escape-boundary round-trip, tools->execute call chain, session robustness
  (add(nullptr), clear -> token_count == 0).

C3 CI build scripts:
- scripts/ci-build.sh and scripts/ci-build.bat invoke cmake configure +
  parallel build + ctest, suitable for GitHub Actions.

Build verified: dstalk-cli compiles, smoke test passes via ctest.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-05-27 05:12:56 +08:00
parent 3e9ba04df5
commit e6f24f00f1
53 changed files with 6450 additions and 1360 deletions

View File

@@ -0,0 +1,32 @@
cmake_minimum_required(VERSION 3.21)
# ============================================================
# plugin-anthropic — Anthropic Claude AI 服务
# 依赖: http 服务 (查询), config 服务 (查询)
# ============================================================
add_library(plugin-anthropic SHARED
src/anthropic_plugin.cpp
)
target_include_directories(plugin-anthropic PRIVATE
${CMAKE_SOURCE_DIR}/dstalk-core/include
)
target_link_libraries(plugin-anthropic PRIVATE dstalk)
# Boost.JSON 用于构建/解析请求和响应
find_package(Boost REQUIRED CONFIG)
target_link_libraries(plugin-anthropic PRIVATE boost::boost)
target_compile_definitions(plugin-anthropic PRIVATE
BOOST_ALL_NO_LIB
BOOST_ERROR_CODE_HEADER_ONLY
BOOST_JSON_HEADER_ONLY
)
set_target_properties(plugin-anthropic PROPERTIES
PREFIX ""
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins"
)

View File

@@ -0,0 +1,486 @@
#include "dstalk/dstalk_host.h"
#include "dstalk/dstalk_services.h"
#include <boost/json.hpp>
#include <cstring>
#include <string>
namespace json = boost::json;
// ============================================================================
// 全局指针
// ============================================================================
static const dstalk_host_api_t* g_host = nullptr;
static dstalk_http_service_t* g_http = nullptr;
static dstalk_config_service_t* g_config = nullptr;
// ============================================================================
// 配置数据
// ============================================================================
struct PluginConfig {
std::string provider;
std::string base_url;
std::string api_key;
std::string model;
int max_tokens = 4096;
double temperature = 0.7;
};
static PluginConfig g_cfg;
// ============================================================================
// 辅助:提取 host / target
// ============================================================================
static bool extract_host_port(const std::string& url,
std::string& scheme_out, std::string& host_out,
std::string& port_out, std::string& target_out)
{
size_t scheme_end = url.find("://");
if (scheme_end == std::string::npos) return false;
scheme_out = url.substr(0, scheme_end);
std::string rest = url.substr(scheme_end + 3);
size_t slash = rest.find('/');
std::string authority = (slash != std::string::npos) ? rest.substr(0, slash) : rest;
target_out = (slash != std::string::npos) ? rest.substr(slash) : "/";
size_t colon = authority.rfind(':');
if (colon != std::string::npos) {
host_out = authority.substr(0, colon);
port_out = authority.substr(colon + 1);
} else {
host_out = authority;
port_out = (scheme_out == "https") ? "443" : "80";
}
return true;
}
// ============================================================================
// 构建 Anthropic headers JSON
// ============================================================================
static std::string build_headers_json()
{
json::object h;
h["x-api-key"] = g_cfg.api_key;
h["anthropic-version"] = "2023-06-01";
return json::serialize(h);
}
// ============================================================================
// 构建 Anthropic JSON 请求体
// ============================================================================
static std::string build_request_json(
const dstalk_message_t* history, int history_len,
const std::string& user_input,
bool stream)
{
json::object root;
root["model"] = g_cfg.model;
root["max_tokens"] = g_cfg.max_tokens;
root["stream"] = stream;
// 提取 system 消息作为顶层字段
std::string system_prompt;
json::array msgs;
for (int i = 0; i < history_len; ++i) {
const auto& m = history[i];
if (m.role && std::strcmp(m.role, "system") == 0) {
if (!system_prompt.empty()) system_prompt += "\n\n";
system_prompt += m.content ? m.content : "";
continue;
}
json::object obj;
obj["role"] = m.role ? m.role : "";
obj["content"] = m.content ? m.content : "";
msgs.push_back(obj);
}
// 追加当前用户输入
{
json::object obj;
obj["role"] = "user";
obj["content"] = user_input;
msgs.push_back(obj);
}
root["messages"] = msgs;
if (!system_prompt.empty()) {
root["system"] = system_prompt;
}
if (g_cfg.temperature >= 0.0 && g_cfg.temperature <= 1.0) {
root["temperature"] = g_cfg.temperature;
}
return json::serialize(root);
}
// ============================================================================
// 解析非流式响应
// ============================================================================
static void parse_response(const char* body, int http_status,
dstalk_chat_result_t& r)
{
r.http_status = http_status;
if (http_status < 200 || http_status >= 300) {
r.ok = 0;
try {
auto jv = json::parse(body ? body : "{}");
auto obj = jv.as_object();
if (obj.contains("error")) {
auto err = obj["error"].as_object();
r.error = g_host->strdup(
json::value_to<std::string>(err["message"]).c_str());
}
} catch (...) {
std::string msg = "HTTP " + std::to_string(http_status);
r.error = g_host->strdup(msg.c_str());
}
if (!r.error) {
std::string msg = "HTTP " + std::to_string(http_status);
r.error = g_host->strdup(msg.c_str());
}
r.content = nullptr;
r.tool_calls_json = nullptr;
return;
}
try {
auto jv = json::parse(body ? body : "{}");
auto obj = jv.as_object();
auto content = obj["content"].as_array();
if (!content.empty()) {
// 取第一个 text block
for (const auto& block : content) {
auto bobj = block.as_object();
if (bobj.contains("type") &&
json::value_to<std::string>(bobj["type"]) == "text") {
std::string text = json::value_to<std::string>(bobj["text"]);
r.content = g_host->strdup(text.c_str());
r.ok = 1;
r.error = nullptr;
r.tool_calls_json = nullptr;
return;
}
}
r.ok = 0;
r.error = g_host->strdup("no text content block found");
} else {
r.ok = 0;
r.error = g_host->strdup("empty response");
}
r.content = nullptr;
r.tool_calls_json = nullptr;
} catch (std::exception& e) {
r.ok = 0;
std::string msg = std::string("json parse: ") + e.what();
r.error = g_host->strdup(msg.c_str());
r.content = nullptr;
r.tool_calls_json = nullptr;
} catch (...) {
r.ok = 0;
r.error = g_host->strdup("json parse error");
r.content = nullptr;
r.tool_calls_json = nullptr;
}
}
// ============================================================================
// SSE 事件解析Anthropic 格式: event/content_block_delta)
// ============================================================================
// 状态机:记录当前正在处理的事件类型
// 简化版:直接从 data: 行解析,不依赖 event: 行
static bool parse_sse_data(const std::string& data, std::string& token_out)
{
try {
auto jv = json::parse(data);
auto obj = jv.as_object();
auto* type_ptr = obj.if_contains("type");
if (!type_ptr || !type_ptr->is_string()) return false;
std::string type = json::value_to<std::string>(*type_ptr);
if (type == "content_block_delta") {
auto* delta = obj.if_contains("delta");
if (!delta || !delta->is_object()) return false;
auto& dobj = delta->as_object();
auto* dtype = dobj.if_contains("type");
if (!dtype || !dtype->is_string()) return false;
std::string delta_type = json::value_to<std::string>(*dtype);
if (delta_type == "text_delta") {
auto* text = dobj.if_contains("text");
if (text && text->is_string()) {
token_out = json::value_to<std::string>(*text);
return true;
}
}
} else if (type == "message_stop") {
token_out.clear();
return true; // 流结束
}
// 忽略: message_start, content_block_start, content_block_stop, ping, message_delta
} catch (...) {
// 解析失败忽略
}
return false;
}
// ============================================================================
// configure
// ============================================================================
static int my_configure(const char* provider, const char* base_url,
const char* api_key, const char* model,
int max_tokens, double temperature)
{
if (provider) g_cfg.provider = provider;
if (base_url) g_cfg.base_url = base_url;
if (api_key) g_cfg.api_key = api_key;
if (model) g_cfg.model = model;
g_cfg.max_tokens = max_tokens;
g_cfg.temperature = temperature;
if (g_host) {
g_host->log(DSTALK_LOG_INFO,
"[anthropic] configured: model=%s base_url=%s max_tokens=%d temperature=%.2f",
g_cfg.model.c_str(), g_cfg.base_url.c_str(),
g_cfg.max_tokens, g_cfg.temperature);
}
return 0;
}
// ============================================================================
// chat
// ============================================================================
static dstalk_chat_result_t my_chat(
const dstalk_message_t* history, int history_len,
const char* user_input,
const char* /*tools_json*/)
{
dstalk_chat_result_t r = {};
r.ok = 0;
if (!g_http) {
r.error = g_host->strdup("http service not available");
return r;
}
std::string scheme, host, port, target;
extract_host_port(g_cfg.base_url, scheme, host, port, target);
std::string target_path = target + "/v1/messages";
std::string body = build_request_json(history, history_len,
user_input ? user_input : "", false);
std::string headers_json = build_headers_json();
char* response_body = nullptr;
int status_code = 0;
int ret = g_http->post_json(
host.c_str(), port.c_str(), target_path.c_str(), body.c_str(),
headers_json.c_str(), &response_body, &status_code);
if (ret != 0) {
r.error = g_host->strdup("http request failed");
return r;
}
parse_response(response_body, status_code, r);
if (response_body) {
g_host->free(response_body);
}
return r;
}
// ============================================================================
// chat_stream
// ============================================================================
struct StreamContext {
const dstalk_host_api_t* host;
dstalk_stream_cb user_cb;
void* userdata;
std::string accumulated;
bool saw_data_line = false;
};
// 行回调
static int sse_line_callback(const char* line, void* userdata)
{
auto* ctx = static_cast<StreamContext*>(userdata);
if (!line || !line[0]) return 1; // 空行,继续
std::string line_str(line);
// SSE 格式: "data: <json>"
if (line_str.rfind("data: ", 0) == 0) {
std::string data = line_str.substr(6);
std::string token;
if (parse_sse_data(data, token)) {
ctx->saw_data_line = true;
if (token.empty()) {
// message_stop
return 0;
}
ctx->accumulated += token;
if (ctx->user_cb) {
return ctx->user_cb(token.c_str(), ctx->userdata);
}
}
}
// "event: ..." 行和其他 -> 忽略
return 1;
}
static dstalk_chat_result_t my_chat_stream(
const dstalk_message_t* history, int history_len,
const char* user_input,
dstalk_stream_cb cb, void* userdata)
{
dstalk_chat_result_t r = {};
r.ok = 0;
if (!g_http) {
r.error = g_host->strdup("http service not available");
return r;
}
std::string scheme, host, port, target;
extract_host_port(g_cfg.base_url, scheme, host, port, target);
std::string target_path = target + "/v1/messages";
std::string body = build_request_json(history, history_len,
user_input ? user_input : "", true);
std::string headers_json = build_headers_json();
StreamContext ctx;
ctx.host = g_host;
ctx.user_cb = cb;
ctx.userdata = userdata;
ctx.saw_data_line = false;
char* response_body = nullptr;
int status_code = 0;
int ret = g_http->post_stream(
host.c_str(), port.c_str(), target_path.c_str(), body.c_str(),
headers_json.c_str(),
sse_line_callback, &ctx,
&response_body, &status_code);
r.http_status = status_code;
// 检查错误状态
if (status_code < 200 || status_code >= 300) {
r.ok = 0;
if (response_body && response_body[0]) {
try {
auto jv = json::parse(response_body);
auto obj = jv.as_object();
if (obj.contains("error")) {
auto err = obj["error"].as_object();
r.error = g_host->strdup(
json::value_to<std::string>(err["message"]).c_str());
}
} catch (...) {}
}
if (!r.error) {
if (status_code <= 0)
r.error = g_host->strdup("transport error");
else
r.error = g_host->strdup(
("HTTP " + std::to_string(status_code)).c_str());
}
if (response_body) g_host->free(response_body);
r.content = nullptr;
r.tool_calls_json = nullptr;
return r;
}
if (response_body) g_host->free(response_body);
if (ctx.accumulated.empty() && !ctx.saw_data_line) {
r.ok = 0;
r.error = g_host->strdup("no content received");
r.content = nullptr;
r.tool_calls_json = nullptr;
} else {
r.ok = 1;
r.error = nullptr;
r.content = g_host->strdup(ctx.accumulated.c_str());
r.tool_calls_json = nullptr;
}
return r;
}
// ============================================================================
// free_result
// ============================================================================
static void my_free_result(dstalk_chat_result_t* result)
{
if (!result || !g_host) return;
if (result->content) { g_host->free((void*)result->content); result->content = nullptr; }
if (result->error) { g_host->free((void*)result->error); result->error = nullptr; }
if (result->tool_calls_json) { g_host->free((void*)result->tool_calls_json); result->tool_calls_json = nullptr; }
}
// ============================================================================
// 服务 vtable
// ============================================================================
static dstalk_ai_service_t g_service = {
&my_configure,
&my_chat,
&my_chat_stream,
&my_free_result,
};
// ============================================================================
// 生命周期
// ============================================================================
static int on_init(const dstalk_host_api_t* host)
{
g_host = host;
g_http = (dstalk_http_service_t*)host->query_service("http", 1);
g_config = (dstalk_config_service_t*)host->query_service("config", 1);
if (!g_http) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[anthropic] http service not found");
return -1;
}
if (g_host) g_host->log(DSTALK_LOG_INFO, "[anthropic] initializing Anthropic AI plugin");
return host->register_service("ai.anthropic", 1, &g_service);
}
static void on_shutdown()
{
if (g_host) g_host->log(DSTALK_LOG_INFO, "[anthropic] shutdown");
g_http = nullptr;
g_config = nullptr;
g_host = nullptr;
}
// ============================================================================
// 插件描述符
// ============================================================================
static dstalk_plugin_info_t g_info = {
/* .name = */ "anthropic-ai",
/* .version = */ "1.0.0",
/* .description = */ "Anthropic Claude AI provider (Messages API)",
/* .api_version = */ DSTALK_API_VERSION,
/* .dependencies = */ { "http", "config", NULL },
/* .on_init = */ on_init,
/* .on_shutdown = */ on_shutdown,
/* .on_event = */ nullptr,
};
extern "C" DSTALK_PLUGIN_EXPORT dstalk_plugin_info_t* dstalk_plugin_init(void)
{
return &g_info;
}