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-deepseek — DeepSeek AI 服务 (OpenAI 兼容)
# 依赖: http 服务 (查询), config 服务 (查询)
# ============================================================
add_library(plugin-deepseek SHARED
src/deepseek_plugin.cpp
)
target_include_directories(plugin-deepseek PRIVATE
${CMAKE_SOURCE_DIR}/dstalk-core/include
)
target_link_libraries(plugin-deepseek PRIVATE dstalk)
# Boost.JSON 用于构建/解析请求和响应
find_package(Boost REQUIRED CONFIG)
target_link_libraries(plugin-deepseek PRIVATE boost::boost)
target_compile_definitions(plugin-deepseek PRIVATE
BOOST_ALL_NO_LIB
BOOST_ERROR_CODE_HEADER_ONLY
BOOST_JSON_HEADER_ONLY
)
set_target_properties(plugin-deepseek PROPERTIES
PREFIX ""
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins"
)

View File

@@ -0,0 +1,475 @@
#include "dstalk/dstalk_host.h"
#include "dstalk/dstalk_services.h"
#include <boost/json.hpp>
#include <cstring>
#include <string>
namespace json = boost::json;
// ============================================================================
// 全局指针:从 on_init 获取
// ============================================================================
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;
// ============================================================================
// 配置数据(由 configure() 设置)
// ============================================================================
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;
// ============================================================================
// 辅助:从 base_url 提取 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;
}
// ============================================================================
// 辅助:构建 headers JSON 字符串
// ============================================================================
static std::string build_headers_json(const std::string& auth_header_value)
{
json::object h;
h["Authorization"] = "Bearer " + auth_header_value;
return json::serialize(h);
}
// ============================================================================
// 辅助dstalk_message_t[] -> boost::json::array
// ============================================================================
static void append_history(json::array& msgs,
const dstalk_message_t* history, int history_len)
{
for (int i = 0; i < history_len; ++i) {
const auto& m = history[i];
json::object obj;
obj["role"] = m.role ? m.role : "";
if (m.role && std::strcmp(m.role, "tool") == 0) {
obj["tool_call_id"] = m.tool_call_id ? m.tool_call_id : "";
obj["content"] = m.content ? m.content : "";
} else if (m.role && std::strcmp(m.role, "assistant") == 0 &&
m.tool_calls_json && m.tool_calls_json[0] != '\0') {
obj["content"] = m.content ? m.content : "";
obj["tool_calls"] = json::parse(m.tool_calls_json);
} else {
obj["content"] = m.content ? m.content : "";
}
msgs.push_back(obj);
}
}
// ============================================================================
// 构建 DeepSeek JSON 请求体
// ============================================================================
static std::string build_request_json(
const dstalk_message_t* history, int history_len,
const std::string& user_input,
const std::string& tools_json,
bool stream)
{
json::object root;
root["model"] = g_cfg.model;
root["max_tokens"] = g_cfg.max_tokens;
root["temperature"] = g_cfg.temperature;
root["stream"] = stream;
json::array msgs;
append_history(msgs, history, history_len);
// 追加当前用户输入
if (!user_input.empty()) {
json::object obj;
obj["role"] = "user";
obj["content"] = user_input;
msgs.push_back(obj);
}
root["messages"] = msgs;
// tools 定义
if (!tools_json.empty()) {
root["tools"] = json::parse(tools_json);
}
return json::serialize(root);
}
// ============================================================================
// 解析非流式 JSON 响应
// ============================================================================
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 choices = obj["choices"].as_array();
if (!choices.empty()) {
auto msg = choices[0].as_object()["message"].as_object();
std::string content = json::value_to<std::string>(msg["content"]);
r.content = g_host->strdup(content.c_str());
if (msg.contains("tool_calls")) {
std::string tc = json::serialize(msg["tool_calls"]);
r.tool_calls_json = g_host->strdup(tc.c_str());
} else {
r.tool_calls_json = nullptr;
}
r.ok = 1;
r.error = nullptr;
} 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 行解析OpenAI 兼容格式)
// ============================================================================
static bool parse_sse_line(const std::string& line, std::string& token_out)
{
if (line.rfind("data: ", 0) != 0) return false;
std::string data = line.substr(6);
if (data == "[DONE]") {
token_out.clear();
return true; // 流结束信号
}
try {
auto jv = json::parse(data);
auto obj = jv.as_object();
auto choices = obj["choices"].as_array();
if (!choices.empty()) {
auto delta = choices[0].as_object()["delta"].as_object();
if (delta.contains("content")) {
token_out = json::value_to<std::string>(delta["content"]);
return true;
}
}
} 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,
"[deepseek] 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 + "/chat/completions";
std::string body = build_request_json(history, history_len,
user_input ? user_input : "", tools_json ? tools_json : "", false);
std::string headers_json = build_headers_json(g_cfg.api_key);
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 streaming_ok = true;
};
// 行回调:解析 SSE line将 token 传递给用户回调
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);
std::string token;
if (!parse_sse_line(line_str, token)) return 1; // 非 data 行,继续
if (token.empty()) return 0; // [DONE],停止
ctx->accumulated += token;
if (ctx->user_cb) {
return ctx->user_cb(token.c_str(), ctx->userdata);
}
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 + "/chat/completions";
std::string body = build_request_json(history, history_len,
user_input ? user_input : "", "", true); // stream=true, no tools
std::string headers_json = build_headers_json(g_cfg.api_key);
StreamContext ctx;
ctx.host = g_host;
ctx.user_cb = cb;
ctx.userdata = userdata;
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;
// 检查传输层错误或非 2xx 状态
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()) {
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, "[deepseek] http service not found");
return -1;
}
if (g_host) g_host->log(DSTALK_LOG_INFO, "[deepseek] initializing DeepSeek AI plugin");
return host->register_service("ai.deepseek", 1, &g_service);
}
static void on_shutdown()
{
if (g_host) g_host->log(DSTALK_LOG_INFO, "[deepseek] shutdown");
g_http = nullptr;
g_config = nullptr;
g_host = nullptr;
}
// ============================================================================
// 插件描述符
// ============================================================================
static dstalk_plugin_info_t g_info = {
/* .name = */ "deepseek-ai",
/* .version = */ "1.0.0",
/* .description = */ "DeepSeek AI provider (OpenAI-compatible 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;
}