0df2bbac0a
* docs(plugins): draft Host data API proto (read + write DTOs) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(plugins): ADR + spec + plan for the Host data API Plugins access kandev data via capability-gated Host gRPC RPCs returning hand-mapped DTOs, never the DB directly. ADR 0042. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(plugins): add Host data API RPCs and DTOs to plugin proto Extends the existing service Host (per ADR 0042) with read RPCs (ListTasks/GetTask, ListWorkspaces, ListWorkflows, ListWorkflowSteps, ListAgentProfiles, ListRepositories, ListSessions, ListSessionCodeStats) and declares the deferred phase-2 write RPCs (CreateTask, UpdateTask, CreateComment) so the contract is stable for later tasks. Regenerates plugin.pb.go/plugin_grpc.pb.go via `make -C apps/backend proto`. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(plugins): Host data API SDK accessors + session LOC aggregation Wave 1-2 of ADR 0042: pkg/pluginsdk gains typed reader accessors (host.Tasks(), host.Sessions().CodeStats(), host.Workflows(), ...) over the extended Host gRPC service, with proto<->native DTO conversions and an UnimplementedHostData seam for the kandev-side impl. internal/analytics gains the per-session LOC aggregation those readers surface. Backend handlers + capability gating land in the next wave. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(plugins): capability-gated Host data read handlers (ADR 0042) Implement pluginHost Tasks/Sessions/Workspaces/Workflows/AgentProfiles/ Repositories readers: each gated on api_read:<resource> (PermissionDenied otherwise), backed by the service layer via narrow injected interfaces, and hand-mapped to the pluginsdk DTOs. Sessions().CodeStats routes through the analytics aggregation; acp_session_id preserves the metadata->resume_token fallback. Wired through plugins.Service.SetDataSources + backendapp. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(plugins): wire test for Host data reads + docs (ADR 0042 accepted) End-to-end test over the real go-plugin transport: session data round-trips, per-resource api_read gating returns PermissionDenied over the wire, cursor pagination. Document the Host data API + SDK accessors in GRPC-CONTRACT.md, reconcile the spec to shipped code, mark ADR 0042 accepted. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(plugins): full session history + snapshot profile name in data API Sessions().List now fetches tasks with includeArchived=true — an archived task's sessions are still real sessions, and CodeStats already made the same call at the SQL layer, so the two session reads were inconsistent (26 of 359 sessions visible on a real instance). Tasks().List keeps archived tasks excluded. Session gains agent_profile_name (proto field 10) sourced from the profile snapshot, so sessions of since-uninstalled agents keep a human label — the AgentProfiles registry only lists live agents. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(plugins): renumber Host data API ADR 0042 -> 0043 main merged its own ADR 0042 (project shell output); renumber this one to the next free slot and update all references. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(plugins): address Host data API review (perf, pagination, filters, proto) - paginate before DTO conversion so per-session ACP lookups run <=limit times - fetch all source pages (no silent 1000/workspace truncation); accurate HasMore - stable id tiebreaker on paginated sorts - AND SessionFilter.TaskIDs with WorkspaceIDs; exclude config-mode sessions from CodeStats (shared dialect.ExcludeConfigModePredicate) so List/CodeStats match - Get returns codes.NotFound consistently in-process and over the wire - wrap bare-DTO RPC responses (GetTaskResponse etc.) for Buf response uniqueness Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(plugins): mark Host data API plan tasks done --------- Co-authored-by: Kandev Agent <agent@kandev.dev> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
161 lines
6.4 KiB
Go
161 lines
6.4 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"github.com/kandev/kandev/internal/task/models"
|
|
)
|
|
|
|
// SessionReadyPollInterval is how often WaitForSessionReady polls session state.
|
|
const SessionReadyPollInterval = 1 * time.Second
|
|
|
|
// SessionReadyMaxWait is the maximum time WaitForSessionReady waits before timing out.
|
|
const SessionReadyMaxWait = 90 * time.Second
|
|
|
|
// WaitForSessionReady polls the session state until the agent is ready to accept
|
|
// prompts. Returns nil when the session reaches WAITING_FOR_INPUT, or an error if
|
|
// it transitions to FAILED/CANCELLED/COMPLETED, the context is cancelled, or the
|
|
// timeout is exceeded. Used after ResumeTaskSession to gate the prompt retry until
|
|
// the agent has actually finished booting.
|
|
func (s *Service) WaitForSessionReady(ctx context.Context, sessionID string) error {
|
|
deadline := time.Now().Add(SessionReadyMaxWait)
|
|
for {
|
|
if time.Now().After(deadline) {
|
|
return fmt.Errorf("timeout waiting for session to become ready after resume")
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-time.After(SessionReadyPollInterval):
|
|
}
|
|
session, err := s.sessions.GetTaskSession(ctx, sessionID)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to check session state: %w", err)
|
|
}
|
|
switch session.State {
|
|
case models.TaskSessionStateWaitingForInput:
|
|
return nil
|
|
case models.TaskSessionStateFailed:
|
|
errMsg := session.ErrorMessage
|
|
if errMsg == "" {
|
|
errMsg = "session failed during resume"
|
|
}
|
|
return fmt.Errorf("session failed after resume: %s", errMsg)
|
|
case models.TaskSessionStateCancelled, models.TaskSessionStateCompleted:
|
|
return fmt.Errorf("session in unexpected state after resume: %s", session.State)
|
|
default:
|
|
// STARTING or RUNNING — keep polling
|
|
}
|
|
}
|
|
}
|
|
|
|
// ListTaskSessions returns all sessions for a task.
|
|
func (s *Service) ListTaskSessions(ctx context.Context, taskID string) ([]*models.TaskSession, error) {
|
|
return s.sessions.ListTaskSessions(ctx, taskID)
|
|
}
|
|
|
|
// GetTaskSession returns a single session by ID.
|
|
func (s *Service) GetTaskSession(ctx context.Context, sessionID string) (*models.TaskSession, error) {
|
|
return s.sessions.GetTaskSession(ctx, sessionID)
|
|
}
|
|
|
|
// GetExecutorRunningBySessionID returns the live executor row for sessionID,
|
|
// or models.ErrExecutorRunningNotFound if the session has none (e.g. it
|
|
// never started, or has since completed and been cleaned up). Exposed at
|
|
// the service layer — rather than requiring callers to reach into
|
|
// repository.ExecutorRepository directly — for the Host data API's
|
|
// acp_session_id fallback (ADR 0043): a session's ACP conversation id is
|
|
// normally read from TaskSession.Metadata["acp"]["session_id"], but that key
|
|
// is only populated once the agent has emitted a session_info frame;
|
|
// executors_running.resume_token carries the same id and survives on
|
|
// sessions that never got that far.
|
|
func (s *Service) GetExecutorRunningBySessionID(ctx context.Context, sessionID string) (*models.ExecutorRunning, error) {
|
|
return s.executors.GetExecutorRunningBySessionID(ctx, sessionID)
|
|
}
|
|
|
|
func (s *Service) DismissLastAgentError(ctx context.Context, sessionID, stamp string) (*models.TaskSession, error) {
|
|
session, err := s.sessions.GetTaskSession(ctx, sessionID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
lastErr, ok := models.LoadLastAgentError(session.Metadata)
|
|
if !ok {
|
|
return session, nil
|
|
}
|
|
if stamp != "" && !lastErr.MatchesStamp(stamp) {
|
|
return session, nil
|
|
}
|
|
now := time.Now().UTC()
|
|
updated, err := s.sessions.DismissLastAgentError(context.WithoutCancel(ctx), sessionID, lastErr, now)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !updated {
|
|
return session, nil
|
|
}
|
|
return s.sessions.GetTaskSession(ctx, sessionID)
|
|
}
|
|
|
|
// GetPrimarySession returns the primary session for a task.
|
|
func (s *Service) GetPrimarySession(ctx context.Context, taskID string) (*models.TaskSession, error) {
|
|
return s.sessions.GetPrimarySessionByTaskID(ctx, taskID)
|
|
}
|
|
|
|
// GetPrimarySessionIDsForTasks returns a map of task ID to primary session ID for the given task IDs.
|
|
// Tasks without a primary session are not included in the result.
|
|
func (s *Service) GetPrimarySessionIDsForTasks(ctx context.Context, taskIDs []string) (map[string]string, error) {
|
|
return s.sessions.GetPrimarySessionIDsByTaskIDs(ctx, taskIDs)
|
|
}
|
|
|
|
// GetSessionCountsForTasks returns a map of task ID to session count for the given task IDs.
|
|
func (s *Service) GetSessionCountsForTasks(ctx context.Context, taskIDs []string) (map[string]int, error) {
|
|
return s.sessions.GetSessionCountsByTaskIDs(ctx, taskIDs)
|
|
}
|
|
|
|
// GetPrimarySessionInfoForTasks returns a map of task ID to primary session info for the given task IDs.
|
|
func (s *Service) GetPrimarySessionInfoForTasks(ctx context.Context, taskIDs []string) (map[string]*models.TaskSession, error) {
|
|
return s.sessions.GetPrimarySessionInfoByTaskIDs(ctx, taskIDs)
|
|
}
|
|
|
|
// GetPendingActionsForSessions returns pending user-action projections for
|
|
// sessions whose messages may not be loaded by list views.
|
|
func (s *Service) GetPendingActionsForSessions(ctx context.Context, sessionIDs []string) (map[string]models.TaskPendingAction, error) {
|
|
return s.messages.GetPendingActionsBySessionIDs(ctx, sessionIDs)
|
|
}
|
|
|
|
// BatchGetSessionsForTasks returns all sessions for the given task IDs grouped
|
|
// by task ID. Wraps the repository batch loader so callers in the handler
|
|
// layer can derive primary session, session count, and per-task session info
|
|
// from one round trip instead of three.
|
|
func (s *Service) BatchGetSessionsForTasks(ctx context.Context, taskIDs []string) (map[string][]*models.TaskSession, error) {
|
|
return s.sessions.BatchGetSessionsByTaskIDs(ctx, taskIDs)
|
|
}
|
|
|
|
// SetPrimarySession sets a session as the primary session for its task.
|
|
// This will unset any existing primary session for the same task.
|
|
func (s *Service) SetPrimarySession(ctx context.Context, sessionID string) error {
|
|
if err := s.sessions.SetSessionPrimary(ctx, sessionID); err != nil {
|
|
s.logger.Error("failed to set primary session",
|
|
zap.String("session_id", sessionID),
|
|
zap.Error(err))
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UpdateSessionReviewStatus updates the review status of a session.
|
|
func (s *Service) UpdateSessionReviewStatus(ctx context.Context, sessionID string, status string) error {
|
|
if err := s.sessions.UpdateSessionReviewStatus(ctx, sessionID, status); err != nil {
|
|
s.logger.Error("failed to update session review status",
|
|
zap.String("session_id", sessionID),
|
|
zap.String("status", status),
|
|
zap.Error(err))
|
|
return err
|
|
}
|
|
return nil
|
|
}
|