Files
archie/internal/app/archiegateway/tools.go
T

235 lines
8.2 KiB
Go

package archiegateway
import (
"context"
"log/slog"
"os"
"path/filepath"
"strings"
"time"
"github.com/samcharles93/ai-sdk/provider/minimax"
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/applystatus"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/gateway"
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/infrastructure/taskmcp"
"github.com/samcharles93/archie-core/internal/plugin"
"github.com/samcharles93/archie-core/internal/tools/mcp"
minimaxtool "github.com/samcharles93/archie-core/internal/tools/minimax"
toolprovider "github.com/samcharles93/archie-core/internal/tools/provider"
builtintoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/builtin"
"github.com/samcharles93/archie-core/internal/tools/sendfile"
"github.com/samcharles93/archie-core/internal/tools/webfetch"
)
func (b *server) registerTools() error {
cfg, log := b.cfgHolder.Get(), b.log
b.providerRegistry = toolprovider.NewRegistry(b.toolReg)
b.mcpMu.Lock()
b.mcpApplied = make(map[string]appliedMCPServer, len(cfg.Tools.MCPServers))
b.mcpMu.Unlock()
if workspace := cfg.Chat.Workspace; workspace != "" {
unrestricted := cfg.Chat.UnrestrictedFilesystem
// A workspace chosen in the dashboard names a directory nobody has
// created yet; every file tool would fail on it.
if err := os.MkdirAll(workspace, 0o700); err != nil {
log.Error("create chat workspace", "workspace", workspace, "err", err)
}
if err := b.providerRegistry.Register(builtintoolprovider.New(workspace, unrestricted)); err != nil {
log.Error("workspace tool provider registration failed", "err", err)
return err
}
log.Info("workspace tools enabled",
"workspace", workspace, "unrestricted_filesystem", unrestricted)
} else {
log.Info("workspace tools disabled (chat.workspace is unset)")
}
for _, srv := range cfg.Tools.MCPServers {
provider, err := b.buildMCPProvider(srv)
if err != nil {
log.Warn("mcp tool provider skipped", "name", srv.Name, "err", err)
continue
}
if err := b.providerRegistry.RegisterOptional(provider); err != nil {
log.Warn("mcp tool provider skipped", "name", srv.Name, "err", err)
continue
}
b.mcpMu.Lock()
b.mcpApplied[strings.TrimSpace(srv.Name)] = appliedMCPServer{server: srv, id: provider.Manifest().ID}
b.mcpMu.Unlock()
}
if err := b.capabilityHost.Register(b.providerRegistry); err != nil {
log.Error("tool-provider capability registration failed", "err", err)
return err
}
return nil
}
func (b *server) registerStandaloneTools(ctx context.Context) {
cfg, log := b.cfg, b.log
if spillDir := cfg.Tools.Policy.SpillDir; spillDir != "" {
if err := toolLimits(cfg).EnsureSpillDir(); err != nil {
log.Warn("tool spill directory unavailable; large results will be truncated instead", "err", err)
} else if ws := cfg.Chat.Workspace; ws != "" && !cfg.Chat.UnrestrictedFilesystem && !isWithin(ws, spillDir) {
log.Warn("tool spill directory is outside chat.workspace; the model cannot read back what is spilled there",
"spill_dir", spillDir, "workspace", ws)
}
}
b.registerWebFetchTool(cfg)
if entry := sendfile.Tool(cfg.Chat.Workspace); entry != nil {
if err := b.toolReg.Register(*entry); err != nil {
log.Warn("send_file registration failed", "err", err)
} else {
log.Info("file sending enabled", "workspace", cfg.Chat.Workspace)
}
} else {
log.Info("file sending disabled (chat.workspace is unset)")
}
b.registerMinimaxTool(cfg, log)
b.registerWorkflowTools(ctx)
}
// registerWorkflowTools puts the workflow and integration tools in the shared
// registry, so chat turns and Kit harnesses (through the task-tool RPCs) both
// reach them, each in its own caller's org.
func (b *server) registerWorkflowTools(ctx context.Context) {
authz := infraaccess.StartLive(ctx, b.stateStore.ListPolicies, applystatus.RestampInterval, b.log)
workflows := controlplanerpc.NewWorkflows(b.stateStore.ControlPlane())
entries := append(gateway.WorkflowTools(workflows, authz), gateway.IntegrationTools(integrationSource{Workflows: workflows, store: b.stateStore}, authz)...)
for _, entry := range entries {
if err := b.toolReg.Register(entry); err != nil {
b.log.Warn("workflow tool registration failed", "tool", entry.Name, "err", err)
}
}
}
// integrationSource reads settings through the control plane and event types,
// bindings and access policies through the State Store.
type integrationSource struct {
controlplanerpc.Workflows
store *staterpc.Client
}
func (s integrationSource) EventTypes(ctx context.Context) ([]eventtype.EventType, error) {
return s.store.ListEventTypes(ctx)
}
func (s integrationSource) Bindings(ctx context.Context) ([]binding.Binding, error) {
return s.store.ListBindings(ctx)
}
func (s integrationSource) Policies(ctx context.Context) ([]access.Policy, error) {
return s.store.ListPolicies(ctx)
}
func (b *server) registerWebFetchTool(cfg config.Config) {
log := b.log
entry := webfetch.Tool(webfetch.Config{
Enabled: cfg.Tools.WebFetch.IsEnabled(),
Timeout: cfg.Tools.WebFetch.Timeout.Std(),
MaxBytes: cfg.Tools.WebFetch.MaxBytes,
AllowPrivateNetworks: cfg.Tools.WebFetch.AllowPrivateNetworks,
})
if entry == nil {
log.Info("web fetch disabled")
return
}
if err := b.toolReg.Register(*entry); err != nil {
log.Warn("web_fetch registration failed", "err", err)
return
}
log.Info("web fetch enabled",
"allow_private_networks", cfg.Tools.WebFetch.AllowPrivateNetworks)
}
func (b *server) registerMinimaxTool(cfg config.Config, log *slog.Logger) {
if !cfg.Tools.Minimax.IsEnabled() {
log.Info("minimax video generation disabled")
return
}
apiKey, err := b.secrets.Resolve(cfg.Tools.Minimax.APIKey)
if err != nil {
log.Warn("minimax video generation enabled but the API key failed to resolve; tool not registered", "err", err)
return
}
if apiKey == "" {
log.Warn("minimax video generation enabled but no API key is configured; tool not registered")
return
}
provider, err := minimax.New(minimax.Config{APIKey: apiKey, BaseURL: cfg.Tools.Minimax.BaseURL})
if err != nil {
log.Warn("minimax video generation enabled but the provider could not be built; tool not registered", "err", err)
return
}
entry := minimaxtool.Tool(provider)
if entry == nil {
return
}
if err := b.toolReg.Register(*entry); err != nil {
log.Warn("generate_video registration failed", "err", err)
return
}
log.Info("minimax video generation enabled")
}
// toolLimits reads the configured per-turn result limits.
func toolLimits(cfg config.Config) modelloop.ToolLimits {
return modelloop.ToolLimits{
MaxResultChars: cfg.Tools.Policy.MaxResultChars,
SpillDir: cfg.Tools.Policy.SpillDir,
}
}
// isWithin reports whether target sits inside base.
func isWithin(base, target string) bool {
absBase, err := filepath.Abs(base)
if err != nil {
return false
}
absTarget, err := filepath.Abs(target)
if err != nil {
return false
}
rel, err := filepath.Rel(absBase, absTarget)
if err != nil {
return false
}
return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
func configuredMCPProvider(server config.MCPServer, workDir string, sampling mcp.SamplingHandler) (toolprovider.Engine, error) {
cacheDir := ""
if workDir != "" {
cacheDir = filepath.Join(workDir, "mcp-npm-cache")
}
provider, _, err := taskmcp.NewProvider(server, sampling, cacheDir)
return provider, err
}
func shutdownCapabilityHost(ctx context.Context, capabilityHost *plugin.Host, log *slog.Logger) func() {
return func() {
stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
if err := capabilityHost.Stop(stopCtx); err != nil {
log.Error("capability host shutdown", "err", err)
}
}
}