279e15b318
* feat(plugins): implement Host data API write RPCs (CreateTask/UpdateTask/CreateComment) The api_write manifest capability was a stored no-op. Wire the deferred phase-2 write RPCs (ADR 0043) so closed-loop plugins (Sentry->task, Slack slash-command task creation, refactor fan-out) can create and update tasks and post comments. - SDK: Host.Tasks() gains Create/Update; new Host.Comments() writer; CreateTaskInput/UpdateTaskInput/Comment DTOs (pkg/pluginsdk). - Gating: api_write:tasks gates Create/UpdateTask, api_write:comments gates CreateComment; undeclared -> gRPC PermissionDenied, per-method and independent of the read caps on the same resource. - Writes route through the first-party service layer (task service for tasks, office service for comments) via backendapp adapters, never a repository -- so task.*/comment-created events fire and WS updates. Server stamps source="plugin:<id>"; CreateTask resolves workspace/ workflow defaults and best-effort honors start_agent; UpdateTask uses a conservative title/description/state/workflow_step_id mask. - Fixture plugins exercise a CreateTask+CreateComment round-trip; in-process, real-broker wire, and subprocess tests cover the round-trip and per-capability denial. - Docs: spec, GRPC-CONTRACT, HOST-DATA-API.proto, proto comments moved writes deferred -> implemented; ADR 0043 amended with the concrete service-layer routing decision. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(plugins): send a message to a task session via Host SendMessage (replaces CreateComment) The office TaskComment write was the wrong primitive — it's an office/ dashboard construct, not a way to message the agent working a task, and it only did anything under office reactivity. Replace the CreateComment write RPC with SendMessage, which delivers a prompt to a task session through the orchestrator's real delivery path (the same one message_task uses). - Proto: swap CreateComment/Comment for SendMessage(SendMessageRequest) returns SendMessageResponse{session_id, status}; regenerated stubs. - SDK: Host.Comments() removed; Host.Messages().Send(taskID, sessionID, text) added (pairs with Messages().List), returning MessageDispatch. - Gating: api_write:comments dropped; SendMessage gated api_write:messages (independent of api_read:messages on the same accessor, like Tasks()). - Delivery: a new pluginsTaskMessengerAdapter (backendapp) resolves the target session (explicit id verified against the task, or the primary session), records a user message stamped source="plugin:<id>", then dispatches by state — running → queue; idle/completed → prompt (resume if the agent process is gone); never-started → launch; failed dispatch deletes the recorded message. Wired via SetWriteDeps (live-read). - Tests: adapter state-machine unit tests (queue/start/prompt/resume/ delete-on-failure/belongs-to-task/no-primary/terminal); SDK, in-process gating, wire, and subprocess round-trips updated to SendMessage. - Docs: spec, GRPC-CONTRACT, HOST-DATA-API.proto, proto comments, and the ADR 0043 amendment updated from comment-create to message-send. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(plugins): address PR review — nil guards, detached contexts, state validation Follow-up fixes from the #1970 review (Claude + CodeRabbit bots): - grpcHostServer.CreateTask/UpdateTask/SendMessage: nil-guard the returned value before toProto() so a custom/test Host returning (nil, nil) yields a gRPC Internal error, not a server panic (matches GetTask's pattern). - host.go: fix stale server doc comment (Comments()/CreateComment → Messages()/SendMessage). - startTaskBestEffort and the post-resume wait+retry now run on context.WithoutCancel(ctx): the task/resume is already committed, so a plugin's incoming deadline must not silently abort the launch/resume. - pluginsTaskWriterAdapter.UpdateTask validates the state string against the known task-state enum (excluding orchestrator-owned SCHEDULING) and returns InvalidArgument, so a plugin typo can't forward a bogus state to the service. - Tests: add the resume-wait-timeout path (message deleted so a retry can't duplicate), and a dedicated pluginsTaskWriterAdapter test covering source→metadata mapping and state validation (both adapters now depend on narrow interfaces for testability). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(plugins): launch start_agent asynchronously so CreateTask doesn't block Review nit follow-up: startTaskBestEffort called StartTask synchronously, so with the detached context the plugin's CreateTask RPC blocked on the orchestrator's full inline launch path (office lookup, state update, workflow step move, task fetch) with no bound — and the "asynchronous" comment was wrong. Move the fire-and-forget into pluginsTaskStarterAdapter (backendapp, no goleak), mirroring MCP's launchAutoStartTask: the launch runs in a goroutine on a context.WithTimeout(context.WithoutCancel(ctx), AgentLaunchTimeout), and StartTask returns immediately. The plugin host stays a simple synchronous call (its taskStarter contract now documents "returns promptly, launches async"). Adds adapters_plugin_starter_test.go: launch invoked, returns before the launch completes, detaches from a cancelled caller context, and swallows launch errors. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(plugins): document write validation + SendMessage rollback; harden starter test cleanup Addresses the final PR #1970 review nits: - adapters_plugin_starter_test.go: register the block-channel release via t.Cleanup (sync.Once-guarded) before the goroutine can block, per AGENTS.md. - GRPC-CONTRACT.md: document CreateTask/UpdateTask validation + error rules (title required, id required, NotFound on missing task, invalid-state reject). - spec.md: document that a failed SendMessage dispatch deletes the recorded message, plus the required-field/NotFound/terminal-session rules. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Kandev Agent <agent@kandev.dev> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
876 lines
32 KiB
Go
876 lines
32 KiB
Go
package backendapp
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"github.com/kandev/kandev/internal/agent/discovery"
|
|
"github.com/kandev/kandev/internal/agent/hostutility"
|
|
"github.com/kandev/kandev/internal/agent/registry"
|
|
agentsettingscontroller "github.com/kandev/kandev/internal/agent/settings/controller"
|
|
agentctlutil "github.com/kandev/kandev/internal/agentctl/server/utility"
|
|
analyticsservice "github.com/kandev/kandev/internal/analytics/service"
|
|
"github.com/kandev/kandev/internal/automation"
|
|
"github.com/kandev/kandev/internal/azuredevops"
|
|
"github.com/kandev/kandev/internal/common/config"
|
|
"github.com/kandev/kandev/internal/common/logger"
|
|
"github.com/kandev/kandev/internal/db"
|
|
editorservice "github.com/kandev/kandev/internal/editors/service"
|
|
"github.com/kandev/kandev/internal/events/bus"
|
|
"github.com/kandev/kandev/internal/github"
|
|
"github.com/kandev/kandev/internal/gitlab"
|
|
"github.com/kandev/kandev/internal/integrations/secretadapter"
|
|
"github.com/kandev/kandev/internal/jira"
|
|
"github.com/kandev/kandev/internal/linear"
|
|
"github.com/kandev/kandev/internal/plugins"
|
|
promptservice "github.com/kandev/kandev/internal/prompts/service"
|
|
"github.com/kandev/kandev/internal/secrets"
|
|
"github.com/kandev/kandev/internal/sentry"
|
|
"github.com/kandev/kandev/internal/slack"
|
|
systemsettings "github.com/kandev/kandev/internal/system/settings"
|
|
taskmodels "github.com/kandev/kandev/internal/task/models"
|
|
taskservice "github.com/kandev/kandev/internal/task/service"
|
|
"github.com/kandev/kandev/internal/task/share"
|
|
userservice "github.com/kandev/kandev/internal/user/service"
|
|
utilityservice "github.com/kandev/kandev/internal/utility/service"
|
|
wfmodels "github.com/kandev/kandev/internal/workflow/models"
|
|
workflowservice "github.com/kandev/kandev/internal/workflow/service"
|
|
"github.com/kandev/kandev/internal/workflowsync"
|
|
v1 "github.com/kandev/kandev/pkg/api/v1"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
func provideServices(cfg *config.Config, log *logger.Logger, repos *Repositories, dbPool *db.Pool, eventBus bus.EventBus, agentRegistry *registry.Registry, version string) (*Services, *agentsettingscontroller.Controller, error) {
|
|
// Load custom TUI agents from DB into registry before discovery
|
|
loadCustomTUIAgents(context.Background(), repos, agentRegistry, log)
|
|
|
|
discoveryRegistry, err := discovery.LoadRegistry(context.Background(), agentRegistry, log)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
agentSettingsController := agentsettingscontroller.NewController(repos.AgentSettings, discoveryRegistry, agentRegistry, repos.Task, log)
|
|
|
|
userSvc := userservice.NewService(repos.User, eventBus, log)
|
|
editorSvc := editorservice.NewService(repos.Editor, repos.Task, userSvc)
|
|
promptSvc := promptservice.NewService(repos.Prompts)
|
|
utilitySvc := utilityservice.NewService(repos.Utility)
|
|
workflowSvc := workflowservice.NewService(repos.Workflow, log)
|
|
taskSvc := taskservice.NewService(
|
|
taskservice.Repos{
|
|
Workspaces: repos.Task,
|
|
Tasks: repos.Task,
|
|
TaskRepos: repos.Task,
|
|
WorkspaceFolders: repos.Task,
|
|
Workflows: repos.Task,
|
|
Messages: repos.Task,
|
|
Turns: repos.Task,
|
|
Sessions: repos.Task,
|
|
GitSnapshots: repos.Task,
|
|
RepoEntities: repos.Task,
|
|
RepositoryCleanup: repos.Task,
|
|
Executors: repos.Task,
|
|
Environments: repos.Task,
|
|
TaskEnvironments: repos.Task,
|
|
Reviews: repos.Task,
|
|
ResourceCleanups: repos.Task,
|
|
},
|
|
eventBus,
|
|
log,
|
|
taskservice.RepositoryDiscoveryConfig{
|
|
Roots: cfg.RepositoryDiscovery.Roots,
|
|
MaxDepth: cfg.RepositoryDiscovery.MaxDepth,
|
|
TaskWorktreeRoots: []string{filepath.Join(cfg.ResolvedHomeDir(), "tasks")},
|
|
},
|
|
)
|
|
|
|
// Wire workflow step creator to task service for board creation
|
|
taskSvc.SetWorkflowStepCreator(workflowSvc)
|
|
// Standard Kanban workspace creation is coordinated by the task SQLite
|
|
// repository so workspace, workflow, and steps share one transaction.
|
|
taskSvc.SetWorkspaceBootstrapper(repos.Task)
|
|
|
|
// Wire workflow step getter to task service for MoveTask
|
|
taskSvc.SetWorkflowStepGetter(&workflowStepGetterAdapter{svc: workflowSvc})
|
|
|
|
// Wire start step resolver to task service for CreateTask
|
|
taskSvc.SetStartStepResolver(&startStepResolverAdapter{svc: workflowSvc})
|
|
|
|
// Wire workflow provider to workflow service for export/import
|
|
workflowSvc.SetWorkflowProvider(&workflowProviderAdapter{svc: taskSvc})
|
|
|
|
// Wire agent profile resolver/matcher for workflow export/import
|
|
workflowSvc.SetAgentProfileFuncs(
|
|
buildAgentProfileResolver(repos),
|
|
buildAgentProfileMatcher(repos),
|
|
)
|
|
|
|
githubSvc := initGitHubService(cfg, dbPool, eventBus, repos.Secrets, log)
|
|
if githubSvc != nil {
|
|
githubSvc.SetPromptResolver(promptSvc)
|
|
if brokerErr := githubSvc.ConfigureCredentialBroker(&githubBrokerScopeAuthorizer{repo: repos.Task}); brokerErr != nil {
|
|
log.Warn("GitHub credential broker initialization failed", zap.Error(brokerErr))
|
|
}
|
|
}
|
|
gitlabSvc := initGitLabService(dbPool, eventBus, repos.Secrets, log)
|
|
azureDevOpsSvc := initAzureDevOpsService(dbPool, eventBus, repos.Secrets, log)
|
|
if azureDevOpsSvc != nil {
|
|
azureDevOpsSvc.SetRepositoryLookup(&repositoryLookupAdapter{svc: taskSvc})
|
|
}
|
|
jiraSvc := initJiraService(dbPool, eventBus, repos.Secrets, log)
|
|
linearSvc := initLinearService(dbPool, eventBus, repos.Secrets, log)
|
|
sentrySvc := initSentryService(dbPool, eventBus, repos.Secrets, log)
|
|
slackSvc := initSlackService(dbPool, repos.Secrets, log)
|
|
workflowSyncSvc := initWorkflowSyncService(dbPool, githubSvc, workflowSvc, taskSvc, log)
|
|
pluginsSvc := initPluginsService(cfg, dbPool, eventBus, repos.Secrets, log)
|
|
if pluginsSvc != nil {
|
|
pluginsSvc.SetDataSources(taskSvc, taskSvc, workflowSvc, agentSettingsController, analyticsservice.New(repos.Analytics), taskSvc, pluginsTaskWriterAdapter{svc: taskSvc})
|
|
}
|
|
shareHTTP := initShareHandlers(dbPool, repos.Task, githubSvc, log, version)
|
|
|
|
// Plumb GitHub branch listing into the task service so provider-backed
|
|
// ("Remote") repos serve branches from the GitHub API rather than relying
|
|
// on a local clone that may not exist yet (or ever - some executors clone
|
|
// inside their own container).
|
|
if githubSvc != nil {
|
|
taskSvc.SetRemoteBranchLister(githubBranchListerAdapter{svc: githubSvc})
|
|
taskSvc.SetPRTaskResolver(githubSvc)
|
|
githubSvc.SetWorkspaceAuthorizer(taskSvc.AuthorizeWorkspaceAccess)
|
|
}
|
|
|
|
// Initialize Automation service
|
|
automationComponents, automationErr := automation.Provide(dbPool.Writer(), dbPool.Reader(), eventBus, githubSvc, log)
|
|
if automationErr != nil {
|
|
log.Warn("Automation service initialization failed (non-fatal)", zap.Error(automationErr))
|
|
}
|
|
if automationComponents != nil {
|
|
automationComponents.Service.SetTaskDeleter(&automationTaskDeleterAdapter{svc: taskSvc})
|
|
// Per-user workspace scoping for the automation HTTP/WS surface.
|
|
automationComponents.Service.SetWorkspaceAuthorizer(taskSvc.AuthorizeWorkspaceAccess)
|
|
}
|
|
|
|
services := &Services{
|
|
Task: taskSvc,
|
|
User: userSvc,
|
|
Editor: editorSvc,
|
|
Prompts: promptSvc,
|
|
Utility: utilitySvc,
|
|
Workflow: workflowSvc,
|
|
GitHub: githubSvc,
|
|
GitLab: gitlabSvc,
|
|
AzureDevOps: azureDevOpsSvc,
|
|
Jira: jiraSvc,
|
|
Linear: linearSvc,
|
|
Sentry: sentrySvc,
|
|
Slack: slackSvc,
|
|
WorkflowSync: workflowSyncSvc,
|
|
Share: shareHTTP,
|
|
Automation: automationComponents,
|
|
Plugins: pluginsSvc,
|
|
// Office is constructed later in initOfficeServices once all
|
|
// of its dependencies (config loader, task integrations, etc.) are available.
|
|
Office: nil,
|
|
// Notification service is initialized after gateway is available.
|
|
Notification: nil,
|
|
}
|
|
mentionComponents, err := newMentionComponents(
|
|
taskSvc,
|
|
taskSvc,
|
|
builtinMentionProviders(services, repos.Task)...,
|
|
)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
services.Mentions = mentionComponents
|
|
return services, agentSettingsController, nil
|
|
}
|
|
|
|
type githubBrokerScopeAuthorizer struct {
|
|
repo interface {
|
|
GetTask(context.Context, string) (*taskmodels.Task, error)
|
|
GetTaskSession(context.Context, string) (*taskmodels.TaskSession, error)
|
|
GetRepository(context.Context, string) (*taskmodels.Repository, error)
|
|
ListTaskRepositories(context.Context, string) ([]*taskmodels.TaskRepository, error)
|
|
}
|
|
}
|
|
|
|
func (a *githubBrokerScopeAuthorizer) AuthorizeGitHubRepository(
|
|
ctx context.Context,
|
|
workspaceID, taskID, sessionID, repositoryID, owner, repoName string,
|
|
) error {
|
|
if a == nil || a.repo == nil {
|
|
return fmt.Errorf("task repository is unavailable")
|
|
}
|
|
if err := a.authorizeTaskSession(ctx, workspaceID, taskID, sessionID); err != nil {
|
|
return err
|
|
}
|
|
if err := a.authorizeTaskRepository(ctx, taskID, repositoryID); err != nil {
|
|
return err
|
|
}
|
|
return a.authorizeRepositoryIdentity(ctx, workspaceID, repositoryID, owner, repoName)
|
|
}
|
|
|
|
func (a *githubBrokerScopeAuthorizer) authorizeTaskSession(
|
|
ctx context.Context,
|
|
workspaceID, taskID, sessionID string,
|
|
) error {
|
|
task, err := a.repo.GetTask(ctx, taskID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if task == nil || task.WorkspaceID != workspaceID {
|
|
return fmt.Errorf("task does not belong to workspace")
|
|
}
|
|
session, err := a.repo.GetTaskSession(ctx, sessionID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if session == nil || session.TaskID != taskID {
|
|
return fmt.Errorf("session does not belong to task")
|
|
}
|
|
switch session.State {
|
|
case taskmodels.TaskSessionStateCompleted,
|
|
taskmodels.TaskSessionStateFailed,
|
|
taskmodels.TaskSessionStateCancelled:
|
|
return fmt.Errorf("session is terminal")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *githubBrokerScopeAuthorizer) authorizeTaskRepository(
|
|
ctx context.Context,
|
|
taskID, repositoryID string,
|
|
) error {
|
|
links, err := a.repo.ListTaskRepositories(ctx, taskID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
linked := false
|
|
for _, link := range links {
|
|
if link != nil && link.RepositoryID == repositoryID {
|
|
linked = true
|
|
break
|
|
}
|
|
}
|
|
if !linked {
|
|
return fmt.Errorf("repository is not linked to task")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *githubBrokerScopeAuthorizer) authorizeRepositoryIdentity(
|
|
ctx context.Context,
|
|
workspaceID, repositoryID, owner, repoName string,
|
|
) error {
|
|
repository, err := a.repo.GetRepository(ctx, repositoryID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if repository == nil || repository.WorkspaceID != workspaceID ||
|
|
!strings.EqualFold(repository.Provider, "github") ||
|
|
!strings.EqualFold(repository.ProviderOwner, owner) ||
|
|
!strings.EqualFold(repository.ProviderName, repoName) {
|
|
return fmt.Errorf("repository identity does not match lease scope")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// loadCustomTUIAgents loads user-defined TUI agents from the database into the registry.
|
|
// Non-fatal: logs warnings but continues if any individual agent fails.
|
|
func loadCustomTUIAgents(ctx context.Context, repos *Repositories, agentRegistry *registry.Registry, log *logger.Logger) {
|
|
tuiAgents, err := repos.AgentSettings.ListTUIAgents(ctx)
|
|
if err != nil {
|
|
log.Warn("failed to load custom TUI agents from database", zap.Error(err))
|
|
return
|
|
}
|
|
for _, agent := range tuiAgents {
|
|
if agent.TUIConfig == nil {
|
|
continue
|
|
}
|
|
cfg := agent.TUIConfig
|
|
if regErr := agentRegistry.RegisterCustomTUIAgent(
|
|
agent.Name, cfg.DisplayName, cfg.Command, cfg.Description, cfg.Model, cfg.CommandArgs,
|
|
); regErr != nil {
|
|
log.Warn("failed to register custom TUI agent",
|
|
zap.String("name", agent.Name), zap.Error(regErr))
|
|
}
|
|
}
|
|
}
|
|
|
|
// workflowStepGetterAdapter adapts workflow service to task service's WorkflowStepGetter interface.
|
|
// Since task service now uses wfmodels.WorkflowStep directly, the adapter simply delegates to the service.
|
|
type workflowStepGetterAdapter struct {
|
|
svc *workflowservice.Service
|
|
}
|
|
|
|
// GetStep implements taskservice.WorkflowStepGetter.
|
|
func (a *workflowStepGetterAdapter) GetStep(ctx context.Context, stepID string) (*wfmodels.WorkflowStep, error) {
|
|
return a.svc.GetStep(ctx, stepID)
|
|
}
|
|
|
|
// GetNextStepByPosition implements taskservice.WorkflowStepGetter.
|
|
func (a *workflowStepGetterAdapter) GetNextStepByPosition(ctx context.Context, boardID string, currentPosition int) (*wfmodels.WorkflowStep, error) {
|
|
return a.svc.GetNextStepByPosition(ctx, boardID, currentPosition)
|
|
}
|
|
|
|
// startStepResolverAdapter adapts workflow service to task service's StartStepResolver interface.
|
|
type startStepResolverAdapter struct {
|
|
svc *workflowservice.Service
|
|
}
|
|
|
|
// ResolveStartStep implements taskservice.StartStepResolver.
|
|
func (a *startStepResolverAdapter) ResolveStartStep(ctx context.Context, workflowID string) (string, error) {
|
|
step, err := a.svc.ResolveStartStep(ctx, workflowID)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return step.ID, nil
|
|
}
|
|
|
|
// ResolveFirstStep implements taskservice.StartStepResolver.
|
|
func (a *startStepResolverAdapter) ResolveFirstStep(ctx context.Context, workflowID string) (string, error) {
|
|
step, err := a.svc.ResolveFirstStep(ctx, workflowID)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return step.ID, nil
|
|
}
|
|
|
|
// githubSecretAdapter adapts secrets.SecretStore to github.SecretProvider and github.SecretManager.
|
|
type githubSecretAdapter struct {
|
|
store secrets.SecretStore
|
|
}
|
|
|
|
func (a *githubSecretAdapter) List(ctx context.Context) ([]*github.SecretListItem, error) {
|
|
items, err := a.store.List(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
result := make([]*github.SecretListItem, len(items))
|
|
for i, item := range items {
|
|
result[i] = &github.SecretListItem{
|
|
ID: item.ID,
|
|
Name: item.Name,
|
|
HasValue: item.HasValue,
|
|
}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func (a *githubSecretAdapter) Reveal(ctx context.Context, id string) (string, error) {
|
|
return a.store.Reveal(ctx, id)
|
|
}
|
|
|
|
// Create creates a new secret with the given name and value.
|
|
func (a *githubSecretAdapter) Create(ctx context.Context, name, value string) (string, error) {
|
|
secret := &secrets.SecretWithValue{
|
|
Secret: secrets.Secret{Name: name},
|
|
Value: value,
|
|
}
|
|
if err := a.store.Create(ctx, secret); err != nil {
|
|
return "", err
|
|
}
|
|
return secret.ID, nil
|
|
}
|
|
|
|
// Update updates an existing secret's value.
|
|
func (a *githubSecretAdapter) Update(ctx context.Context, id, value string) error {
|
|
return a.store.Update(ctx, id, &secrets.UpdateSecretRequest{Value: &value})
|
|
}
|
|
|
|
// Delete removes a secret by ID.
|
|
func (a *githubSecretAdapter) Delete(ctx context.Context, id string) error {
|
|
return a.store.Delete(ctx, id)
|
|
}
|
|
|
|
// initGitHubService wires up the GitHub integration. Failures are non-fatal:
|
|
// the rest of the backend still boots without GitHub configured.
|
|
func initGitHubService(
|
|
cfg *config.Config,
|
|
dbPool *db.Pool,
|
|
eventBus bus.EventBus,
|
|
secretsStore secrets.SecretStore,
|
|
log *logger.Logger,
|
|
) *github.Service {
|
|
adapter := &githubSecretAdapter{store: secretsStore}
|
|
svc, _, err := github.Provide(dbPool.Writer(), dbPool.Reader(), adapter, eventBus, log)
|
|
if err != nil {
|
|
log.Warn("GitHub service initialization failed (non-fatal)", zap.Error(err))
|
|
}
|
|
if svc != nil {
|
|
// GitHub takes both a SecretProvider (read-only) and a SecretManager
|
|
// (mutating) — same adapter satisfies both interfaces, but the
|
|
// service needs the mutating one wired explicitly.
|
|
svc.SetSecretManager(adapter)
|
|
svc.SetConnectionSecretStore(secretadapter.New(secretsStore))
|
|
if authErr := svc.InitializeAppRegistrationLifecycle(); authErr != nil {
|
|
log.Warn("GitHub App registration lifecycle failed to initialize", zap.Error(authErr))
|
|
}
|
|
if authErr := svc.InitializeAppRegistrationRuntimes(context.Background()); authErr != nil {
|
|
log.Warn("one or more GitHub App registrations failed to initialize", zap.Error(authErr))
|
|
}
|
|
}
|
|
return svc
|
|
}
|
|
|
|
// gitlabSecretAdapter adapts secrets.SecretStore to the GitLab integration's
|
|
// SecretProvider and SecretManager interfaces. Mirrors githubSecretAdapter
|
|
// — kept separate so the two packages can evolve independently.
|
|
type gitlabSecretAdapter struct {
|
|
store secrets.SecretStore
|
|
}
|
|
|
|
func (a *gitlabSecretAdapter) List(ctx context.Context) ([]*gitlab.SecretListItem, error) {
|
|
items, err := a.store.List(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
result := make([]*gitlab.SecretListItem, len(items))
|
|
for i, item := range items {
|
|
result[i] = &gitlab.SecretListItem{
|
|
ID: item.ID,
|
|
Name: item.Name,
|
|
HasValue: item.HasValue,
|
|
}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func (a *gitlabSecretAdapter) Reveal(ctx context.Context, id string) (string, error) {
|
|
return a.store.Reveal(ctx, id)
|
|
}
|
|
|
|
func (a *gitlabSecretAdapter) Create(ctx context.Context, name, value string) (string, error) {
|
|
secret := &secrets.SecretWithValue{
|
|
Secret: secrets.Secret{Name: name},
|
|
Value: value,
|
|
}
|
|
if err := a.store.Create(ctx, secret); err != nil {
|
|
return "", err
|
|
}
|
|
return secret.ID, nil
|
|
}
|
|
|
|
func (a *gitlabSecretAdapter) Update(ctx context.Context, id, value string) error {
|
|
return a.store.Update(ctx, id, &secrets.UpdateSecretRequest{Value: &value})
|
|
}
|
|
|
|
func (a *gitlabSecretAdapter) Delete(ctx context.Context, id string) error {
|
|
return a.store.Delete(ctx, id)
|
|
}
|
|
|
|
const gitlabHostSettingKey = "gitlab_host"
|
|
|
|
type gitlabHostStore struct {
|
|
settings *systemsettings.Store
|
|
}
|
|
|
|
func newGitLabHostStore(dbPool *db.Pool) (gitlab.HostStore, error) {
|
|
settingsStore, err := systemsettings.NewStore(dbPool)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &gitlabHostStore{settings: settingsStore}, nil
|
|
}
|
|
|
|
func (s *gitlabHostStore) GetHost(ctx context.Context) (string, error) {
|
|
raw, found, err := s.settings.Get(ctx, gitlabHostSettingKey)
|
|
if err != nil || !found {
|
|
return "", err
|
|
}
|
|
return string(raw), nil
|
|
}
|
|
|
|
func (s *gitlabHostStore) SetHost(ctx context.Context, host string) error {
|
|
return s.settings.Save(ctx, gitlabHostSettingKey, []byte(host))
|
|
}
|
|
|
|
// initGitLabService wires up the GitLab integration. Failures are non-fatal:
|
|
// the rest of the backend still boots without GitLab configured.
|
|
func initGitLabService(dbPool *db.Pool, eventBus bus.EventBus, secretsStore secrets.SecretStore, log *logger.Logger) *gitlab.Service {
|
|
adapter := &gitlabSecretAdapter{store: secretsStore}
|
|
hostStore, hostStoreErr := newGitLabHostStore(dbPool)
|
|
if hostStoreErr != nil {
|
|
log.Warn("GitLab host store unavailable (non-fatal)", zap.Error(hostStoreErr))
|
|
return nil
|
|
}
|
|
svc, _, err := gitlab.Provide(context.Background(), adapter, hostStore, log)
|
|
if err != nil {
|
|
log.Warn("GitLab service initialization failed (non-fatal)", zap.Error(err))
|
|
}
|
|
if svc != nil {
|
|
svc.SetSecretManager(adapter)
|
|
svc.SetWorkspaceSecretStore(secretadapter.New(secretsStore))
|
|
svc.SetEventBus(eventBus)
|
|
if store, storeErr := gitlab.NewStore(dbPool.Writer(), dbPool.Reader()); storeErr == nil {
|
|
svc.SetStore(store)
|
|
if migrationErr := gitlab.MigrateLegacyConnection(
|
|
context.Background(), store, secretadapter.New(secretsStore), adapter, adapter, hostStore, log,
|
|
); migrationErr != nil {
|
|
log.Warn("GitLab legacy connection migration failed (non-fatal)", zap.Error(migrationErr))
|
|
}
|
|
} else {
|
|
log.Warn("GitLab task-mr store unavailable (non-fatal)", zap.Error(storeErr))
|
|
}
|
|
}
|
|
return svc
|
|
}
|
|
|
|
// initJiraService wires up the Jira integration. Failures are non-fatal.
|
|
func initJiraService(dbPool *db.Pool, eventBus bus.EventBus, secretsStore secrets.SecretStore, log *logger.Logger) *jira.Service {
|
|
svc, _, err := jira.Provide(dbPool.Writer(), dbPool.Reader(), secretadapter.New(secretsStore), eventBus, log)
|
|
if err != nil {
|
|
log.Warn("JIRA service initialization failed (non-fatal)", zap.Error(err))
|
|
}
|
|
return svc
|
|
}
|
|
|
|
// initAzureDevOpsService wires the workspace-scoped Azure integration.
|
|
// Failures are non-fatal so unrelated providers and the backend keep working.
|
|
func initAzureDevOpsService(
|
|
dbPool *db.Pool,
|
|
eventBus bus.EventBus,
|
|
secretsStore secrets.SecretStore,
|
|
log *logger.Logger,
|
|
) *azuredevops.Service {
|
|
svc, _, err := azuredevops.Provide(
|
|
dbPool.Writer(), dbPool.Reader(), secretadapter.New(secretsStore), eventBus, log,
|
|
)
|
|
if err != nil {
|
|
log.Warn("Azure DevOps service initialization failed (non-fatal)", zap.Error(err))
|
|
return nil
|
|
}
|
|
return svc
|
|
}
|
|
|
|
// initWorkflowSyncService wires the GitHub workflow-sync service. Failures
|
|
// are non-fatal; the service is nil when GitHub is unavailable.
|
|
func initWorkflowSyncService(dbPool *db.Pool, githubSvc *github.Service, workflowSvc *workflowservice.Service, taskSvc *taskservice.Service, log *logger.Logger) *workflowsync.Service {
|
|
if githubSvc == nil {
|
|
log.Warn("workflow sync disabled: GitHub service unavailable")
|
|
return nil
|
|
}
|
|
workflowSvc.SetSyncWorkflowOps(taskSvc)
|
|
svc, _, err := workflowsync.Provide(dbPool.Writer(), dbPool.Reader(), githubSvc, workflowSvc, log)
|
|
if err != nil {
|
|
log.Warn("workflow sync service initialization failed (non-fatal)", zap.Error(err))
|
|
return nil
|
|
}
|
|
return svc
|
|
}
|
|
|
|
// initLinearService wires up the Linear integration. Failures are non-fatal.
|
|
func initLinearService(dbPool *db.Pool, eventBus bus.EventBus, secretsStore secrets.SecretStore, log *logger.Logger) *linear.Service {
|
|
svc, _, err := linear.Provide(dbPool.Writer(), dbPool.Reader(), secretadapter.New(secretsStore), eventBus, log)
|
|
if err != nil {
|
|
log.Warn("Linear service initialization failed (non-fatal)", zap.Error(err))
|
|
}
|
|
return svc
|
|
}
|
|
|
|
// initSentryService wires up the Sentry integration. Failures are non-fatal.
|
|
func initSentryService(dbPool *db.Pool, eventBus bus.EventBus, secretsStore secrets.SecretStore, log *logger.Logger) *sentry.Service {
|
|
svc, _, err := sentry.Provide(dbPool.Writer(), dbPool.Reader(), secretadapter.New(secretsStore), eventBus, log)
|
|
if err != nil {
|
|
log.Warn("Sentry service initialization failed (non-fatal)", zap.Error(err))
|
|
}
|
|
return svc
|
|
}
|
|
|
|
// initShareHandlers wires up the public-share-links HTTP surface. Failures
|
|
// are non-fatal: the rest of the backend boots without the share endpoints.
|
|
// GitHub access resolves from the owning task workspace on every operation.
|
|
func initShareHandlers(
|
|
dbPool *db.Pool,
|
|
taskRepo share.TaskReader,
|
|
githubSvc *github.Service,
|
|
log *logger.Logger,
|
|
version string,
|
|
) *share.HTTPHandlers {
|
|
h, _, err := share.Provide(
|
|
dbPool.Writer(), dbPool.Reader(), taskRepo, githubSvc, log,
|
|
share.Config{KandevVersion: version},
|
|
)
|
|
if err != nil {
|
|
log.Warn("Share handlers initialization failed (non-fatal)", zap.Error(err))
|
|
return nil
|
|
}
|
|
return h
|
|
}
|
|
|
|
// initSlackService wires up the Slack integration. Failures are non-fatal.
|
|
// The agent runner is wired post-construction by main.go once hostutility +
|
|
// utility services exist.
|
|
func initSlackService(dbPool *db.Pool, secretsStore secrets.SecretStore, log *logger.Logger) *slack.Service {
|
|
svc, _, err := slack.Provide(dbPool.Writer(), dbPool.Reader(), secretadapter.New(secretsStore), log)
|
|
if err != nil {
|
|
log.Warn("Slack service initialization failed (non-fatal)", zap.Error(err))
|
|
}
|
|
return svc
|
|
}
|
|
|
|
// initPluginsService wires up the plugin system's core Service
|
|
// (registration registry, config, plugin_state store). Failures are
|
|
// non-fatal: the rest of the backend still boots without plugins.
|
|
//
|
|
// This only constructs the Service — event delivery (delivery.Deliverer)
|
|
// and health monitoring (plugins.HealthMonitor) are wired separately by
|
|
// startPluginsSubsystems (plugins.go), once addCleanup and ctx are
|
|
// available, mirroring how the Jira/Linear/Sentry pollers are started in
|
|
// startAgentInfrastructure rather than inside their init*Service functions.
|
|
func initPluginsService(cfg *config.Config, dbPool *db.Pool, eventBus bus.EventBus, secretsStore secrets.SecretStore, log *logger.Logger) *plugins.Service {
|
|
svc, _, err := plugins.Provide(cfg, dbPool, secretadapter.New(secretsStore), eventBus, log)
|
|
if err != nil {
|
|
log.Warn("Plugins service initialization failed (non-fatal)", zap.Error(err))
|
|
return nil
|
|
}
|
|
return svc
|
|
}
|
|
|
|
// buildKandevMCPURL is the URL passed to the Slack triage agent for the
|
|
// Kandev MCP server. The MCP server is mounted on the same port as the rest
|
|
// of the backend's HTTP API; this just centralises the path so it stays in
|
|
// sync with internal/mcp/server's mount point ("/mcp").
|
|
func buildKandevMCPURL(port int) string {
|
|
if port == 0 {
|
|
port = portsBackendDefault
|
|
}
|
|
return fmt.Sprintf("http://localhost:%d/mcp", port)
|
|
}
|
|
|
|
// portsBackendDefault is the default backend HTTP port. We don't import
|
|
// internal/common/ports here to avoid pulling its transitive deps into
|
|
// services.go's import graph; the value is duplicated only as a fallback for
|
|
// when cfg.Server.Port is left at zero (which shouldn't happen in practice).
|
|
const portsBackendDefault = 38429
|
|
|
|
// slackHostUtilityAdapter adapts *hostutility.Manager to slack.HostUtilityRunner.
|
|
// The slack package can't import hostutility without a transitive cycle (it
|
|
// would need to import agentctl + lifecycle), so we shim through the agentctl
|
|
// utility DTO here in the cmd package where both are already imported.
|
|
type slackHostUtilityAdapter struct {
|
|
mgr *hostutility.Manager
|
|
}
|
|
|
|
func (a slackHostUtilityAdapter) ExecutePromptWithMCP(
|
|
ctx context.Context,
|
|
agentType, model, mode, prompt string,
|
|
mcpServers []agentctlutil.MCPServerDTO,
|
|
) (slack.HostPromptResult, error) {
|
|
res, err := a.mgr.ExecutePromptWithMCP(ctx, agentType, model, mode, prompt, mcpServers)
|
|
if err != nil {
|
|
return slack.HostPromptResult{}, err
|
|
}
|
|
return slack.HostPromptResult{
|
|
Response: res.Response,
|
|
Model: res.Model,
|
|
PromptTokens: res.PromptTokens,
|
|
ResponseTokens: res.ResponseTokens,
|
|
DurationMs: res.DurationMs,
|
|
}, nil
|
|
}
|
|
|
|
// pluginsHostUtilityAdapter adapts *hostutility.Manager to the plugins
|
|
// package's utilityRunner interface (Host.InvokeUtilityAgent, ADR 0048),
|
|
// returning just the response text. Lives here for the same cycle-avoidance
|
|
// reason as slackHostUtilityAdapter — internal/plugins must not import the
|
|
// agent runtime.
|
|
type pluginsHostUtilityAdapter struct {
|
|
mgr *hostutility.Manager
|
|
}
|
|
|
|
func (a pluginsHostUtilityAdapter) ExecutePrompt(ctx context.Context, agentType, model, mode, prompt string) (string, error) {
|
|
res, err := a.mgr.ExecutePrompt(ctx, agentType, model, mode, prompt)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return res.Response, nil
|
|
}
|
|
|
|
type pluginsUtilityAgentAdapter struct {
|
|
svc *utilityservice.Service
|
|
}
|
|
|
|
func (a pluginsUtilityAgentAdapter) GetAgentByID(ctx context.Context, id string) (*plugins.UtilityAgent, error) {
|
|
agent, err := a.svc.GetAgentByID(ctx, id)
|
|
if err != nil {
|
|
if errors.Is(err, utilityservice.ErrAgentNotFound) {
|
|
return nil, plugins.ErrUtilityAgentNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
return &plugins.UtilityAgent{Name: agent.Name, AgentID: agent.AgentID, Model: agent.Model, Enabled: agent.Enabled}, nil
|
|
}
|
|
|
|
// pluginsTaskWriterAdapter adapts the task service to the plugins package's
|
|
// taskWriter interface (Host data API CreateTask/UpdateTask write RPCs, ADR
|
|
// 0043 phase 2). It translates the plugins-local TaskCreateInput/TaskUpdateInput
|
|
// — which internal/plugins can't express as service.CreateTaskRequest without
|
|
// an import cycle — into the real service requests, so writes route through the
|
|
// same task.*-event-publishing service methods the REST/MCP API uses. The
|
|
// plugin's provenance is stamped into task metadata (`source`), since the Task
|
|
// model has no dedicated source column.
|
|
// pluginTaskWriteService is the narrow slice of the task service the write
|
|
// adapter needs, so the adapter's field mapping + state validation are
|
|
// unit-testable with a fake. *taskservice.Service satisfies it.
|
|
type pluginTaskWriteService interface {
|
|
CreateTask(ctx context.Context, req *taskservice.CreateTaskRequest) (*taskmodels.Task, error)
|
|
UpdateTask(ctx context.Context, id string, req *taskservice.UpdateTaskRequest) (*taskmodels.Task, error)
|
|
}
|
|
|
|
type pluginsTaskWriterAdapter struct {
|
|
svc pluginTaskWriteService
|
|
}
|
|
|
|
func (a pluginsTaskWriterAdapter) CreateTask(ctx context.Context, in plugins.TaskCreateInput) (*taskmodels.Task, error) {
|
|
var metadata map[string]interface{}
|
|
if in.Source != "" {
|
|
metadata = map[string]interface{}{"source": in.Source}
|
|
}
|
|
return a.svc.CreateTask(ctx, &taskservice.CreateTaskRequest{
|
|
WorkspaceID: in.WorkspaceID,
|
|
WorkflowID: in.WorkflowID,
|
|
WorkflowStepID: in.WorkflowStepID,
|
|
Title: in.Title,
|
|
Description: in.Description,
|
|
ParentID: in.ParentID,
|
|
Metadata: metadata,
|
|
})
|
|
}
|
|
|
|
func (a pluginsTaskWriterAdapter) UpdateTask(ctx context.Context, in plugins.TaskUpdateInput) (*taskmodels.Task, error) {
|
|
req := &taskservice.UpdateTaskRequest{
|
|
Title: in.Title,
|
|
Description: in.Description,
|
|
WorkflowStepID: in.WorkflowStepID,
|
|
}
|
|
if in.State != nil {
|
|
// v1.TaskState is a string type, so the cast can't fail — validate the
|
|
// value against the known enum here (the REST/MCP path validates state
|
|
// at its HTTP handler) so a plugin typo can't forward a bogus state to
|
|
// the service and risk persisting it.
|
|
state := v1.TaskState(*in.State)
|
|
if !validPluginTaskState(state) {
|
|
return nil, status.Errorf(codes.InvalidArgument, "invalid task state %q", *in.State)
|
|
}
|
|
req.State = &state
|
|
}
|
|
return a.svc.UpdateTask(ctx, in.ID, req)
|
|
}
|
|
|
|
// validPluginTaskState reports whether state is a state a plugin may set via
|
|
// UpdateTask. SCHEDULING is intentionally excluded — it is an orchestrator-owned
|
|
// transient state, not a value a plugin should assign directly.
|
|
func validPluginTaskState(state v1.TaskState) bool {
|
|
switch state {
|
|
case v1.TaskStateTODO, v1.TaskStateCreated, v1.TaskStateInProgress,
|
|
v1.TaskStateReview, v1.TaskStateBlocked, v1.TaskStateWaitingForInput,
|
|
v1.TaskStateCompleted, v1.TaskStateFailed, v1.TaskStateCancelled:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
// workflowProviderAdapter adapts task service to workflow service's WorkflowProvider interface.
|
|
type workflowProviderAdapter struct {
|
|
svc *taskservice.Service
|
|
}
|
|
|
|
// ListWorkflows implements workflowservice.WorkflowProvider.
|
|
func (a *workflowProviderAdapter) ListWorkflows(ctx context.Context, workspaceID string, includeHidden bool) ([]*taskmodels.Workflow, error) {
|
|
return a.svc.ListWorkflows(ctx, workspaceID, includeHidden)
|
|
}
|
|
|
|
// GetWorkflow implements workflowservice.WorkflowProvider.
|
|
func (a *workflowProviderAdapter) GetWorkflow(ctx context.Context, id string) (*taskmodels.Workflow, error) {
|
|
return a.svc.GetWorkflow(ctx, id)
|
|
}
|
|
|
|
// CreateWorkflow implements workflowservice.WorkflowProvider.
|
|
func (a *workflowProviderAdapter) CreateWorkflow(ctx context.Context, workspaceID, name, description string) (*taskmodels.Workflow, error) {
|
|
return a.svc.CreateWorkflow(ctx, &taskservice.CreateWorkflowRequest{
|
|
WorkspaceID: workspaceID,
|
|
Name: name,
|
|
Description: description,
|
|
})
|
|
}
|
|
|
|
// UpdateWorkflow implements workflowservice.WorkflowProvider.
|
|
func (a *workflowProviderAdapter) UpdateWorkflow(ctx context.Context, workflow *taskmodels.Workflow) error {
|
|
_, err := a.svc.UpdateWorkflow(ctx, workflow.ID, &taskservice.UpdateWorkflowRequest{
|
|
Name: &workflow.Name,
|
|
Description: &workflow.Description,
|
|
AgentProfileID: &workflow.AgentProfileID,
|
|
})
|
|
return err
|
|
}
|
|
|
|
// buildAgentProfileResolver creates a resolver that converts profile IDs to portable form for export.
|
|
func buildAgentProfileResolver(repos *Repositories) wfmodels.AgentProfileResolver {
|
|
return func(profileID string) *wfmodels.AgentProfilePortable {
|
|
if profileID == "" {
|
|
return nil
|
|
}
|
|
profile, err := repos.AgentSettings.GetAgentProfile(context.Background(), profileID)
|
|
if err != nil || profile == nil {
|
|
return nil
|
|
}
|
|
return &wfmodels.AgentProfilePortable{
|
|
AgentName: profile.AgentDisplayName,
|
|
Model: profile.Model,
|
|
Mode: profile.Mode,
|
|
}
|
|
}
|
|
}
|
|
|
|
// buildAgentProfileMatcher creates a matcher that finds profiles by agent name, model, and mode for import.
|
|
func buildAgentProfileMatcher(repos *Repositories) wfmodels.AgentProfileMatcher {
|
|
return func(agentName, model, mode string) string {
|
|
agents, err := repos.AgentSettings.ListAgents(context.Background())
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
for _, agent := range agents {
|
|
profiles, pErr := repos.AgentSettings.ListAgentProfiles(context.Background(), agent.ID)
|
|
if pErr != nil {
|
|
continue
|
|
}
|
|
for _, p := range profiles {
|
|
if p.AgentDisplayName == agentName && p.Model == model && p.Mode == mode {
|
|
return p.ID
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
}
|
|
|
|
// githubBranchListerAdapter bridges github.Service to the task service's
|
|
// RemoteBranchLister interface. It maps github.RepoBranch into the task
|
|
// service's Branch shape with Type="remote" so the dialog renders branches
|
|
// the same way URL-mode does - bare names without an "origin/" prefix, since
|
|
// there is no checked-out clone whose tracking config could disambiguate.
|
|
type githubBranchListerAdapter struct {
|
|
svc *github.Service
|
|
}
|
|
|
|
func (a githubBranchListerAdapter) ListRepoBranches(
|
|
ctx context.Context, workspaceID, owner, repo string,
|
|
) ([]taskservice.Branch, error) {
|
|
remote, err := a.svc.ListRepoBranchesForWorkspace(ctx, workspaceID, owner, repo)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]taskservice.Branch, 0, len(remote))
|
|
for _, b := range remote {
|
|
out = append(out, taskservice.Branch{Name: b.Name, Type: "remote"})
|
|
}
|
|
return out, nil
|
|
}
|