Files
drharness/src/tool_registry.cpp
T

83 lines
2.3 KiB
C++

#include "tool_registry.hpp"
#include "encoding.hpp"
std::expected<void, std::string> ToolRegistry::register_tool(Tool tool) {
if (tools_.count(tool.name))
return std::unexpected("duplicate tool: " + tool.name);
order_.push_back(tool.name);
tools_.emplace(tool.name, std::move(tool));
return {};
}
std::optional<const Tool*> ToolRegistry::find(const std::string& name) const {
auto it = tools_.find(name);
if (it == tools_.end()) return std::nullopt;
return &it->second;
}
std::vector<Tool> ToolRegistry::tools() const {
std::vector<Tool> ret{};
for (auto const& x : tool_names())
{
ret.push_back(**this->find(x));
}
return ret;
}
// helper type for the visitor
template<class... Ts>
struct overloads : Ts... { using Ts::operator()...; };
Content ToolRegistry::invoke(const std::string& name,
const nlohmann::json& args) const {
auto it = tools_.find(name);
if (it == tools_.end())
return "Error: unknown tool: " + name;
auto ret = it->second.execute(args);
ret = std::visit(overloads{
[](std::string const& x) -> Content { return ensure_utf8(x.c_str()); },
[](std::vector<ContentPart> const& x) -> Content {
std::vector<ContentPart> ret = x;
for (auto& i : ret)
{
if (i.text)
{
std::string valid = ensure_utf8(i.text->c_str());
i.text = valid;
}
}
return ret;
},
}, ret);
return ret;
}
std::expected<ToolRegistry, std::string> ToolRegistry::create_subregistry(std::vector<std::string> const& names) const
{
ToolRegistry sub_registry;
for (const auto& tool_name : names) {
auto found = this->find(tool_name);
if (found) {
auto reg_result = sub_registry.register_tool(**found);
if (!reg_result) {
return std::unexpected(reg_result.error());
}
} else {
return std::unexpected("Could not find tool: " + tool_name);
}
}
return sub_registry;
}
std::vector<std::string> const& ToolRegistry::tool_names() const
{
return this->order_;
}