agent

package
v0.0.0-...-8acab51 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 36 Imported by: 0

Documentation

Overview

Package agent provides autonomous task execution for Blue.

Index

Constants

View Source
const (
	StateUpdateKindFSObservation = "fs_observation"
	StateUpdateKindFSMutation    = "fs_mutation"
	StateUpdateKindCommand       = "command_history"
	StateUpdateKindEvidence      = "evidence"
)
View Source
const (
	GroundingStatusGrounded = "grounded"
	GroundingStatusUnknown  = "unknown"
	GroundingStatusFallback = "fallback"
	GroundingStatusRejected = "rejected"
)
View Source
const MaxConcurrentTasks = 32

MaxConcurrentTasks is the default limit of concurrent agent tasks per user.

View Source
const MaxToolRoundsPerStep = 50

MaxToolRoundsPerStep is the max tool rounds within a single plan step.

Variables

This section is empty.

Functions

func BuildGroundStateSummary

func BuildGroundStateSummary(state *GroundTruthState) string

func EvaluateAssertions

func EvaluateAssertions(state *GroundTruthState, assertions []PlannerAssertion) []string

func MarshalPlan

func MarshalPlan(steps []PlanStep) string

MarshalPlan serializes plan steps to JSON for storage.

Types

type AgentQuestion

type AgentQuestion struct {
	ID          string           `json:"id"`
	Question    string           `json:"question"`
	Detail      string           `json:"detail,omitempty"`
	Header      string           `json:"header"` // short tab label (max 12 chars)
	Type        string           `json:"type,omitempty"`
	Options     []QuestionOption `json:"options,omitempty"`
	MultiSelect bool             `json:"multi_select,omitempty"` // true = checkboxes, false = radio
	Required    bool             `json:"required,omitempty"`
}

AgentQuestion is a question the agent asks the user during execution.

type CapabilityInfo

type CapabilityInfo struct {
	Name             string         `json:"name"`
	Kind             CapabilityKind `json:"kind"`
	RiskLevel        string         `json:"risk_level"`
	DeterminismScore float64        `json:"determinism_score"`
	Idempotent       bool           `json:"idempotent"`
	LatencyProfile   string         `json:"latency_profile,omitempty"`
	CostProfile      string         `json:"cost_profile,omitempty"`
}

CapabilityInfo standardizes call metadata for deterministic routing/auditing.

type CapabilityKind

type CapabilityKind string

CapabilityKind identifies where a call is routed.

const (
	CapabilityKindTool  CapabilityKind = "tool"
	CapabilityKindSkill CapabilityKind = "skill"
	CapabilityKindMCP   CapabilityKind = "mcp"
)

type CreateTaskRequest

type CreateTaskRequest struct {
	Goal           string `json:"goal"`
	ConversationID string `json:"conversation_id,omitempty"`
	Context        string `json:"context,omitempty"` // recent conversation context for the agent
}

CreateTaskRequest is the API request to create a new agent task.

type CriterionResult

type CriterionResult struct {
	Criterion string `json:"criterion"`
	Status    string `json:"status"`
	Evidence  string `json:"evidence,omitempty"`
}

type GroundTruthState

type GroundTruthState struct {
	Files    map[string]GroundedFileFact    `json:"files,omitempty"`
	Commands map[string]GroundedCommandFact `json:"commands,omitempty"`
	Calls    map[string]GroundedToolCall    `json:"calls,omitempty"`
	Results  map[string]GroundedToolResult  `json:"results,omitempty"`
}

func NewGroundTruthState

func NewGroundTruthState() *GroundTruthState

type GroundTruthStateStore

type GroundTruthStateStore struct{}

func NewGroundTruthStateStore

func NewGroundTruthStateStore() *GroundTruthStateStore

func (*GroundTruthStateStore) ApplyExecution

func (s *GroundTruthStateStore) ApplyExecution(state *GroundTruthState, exec *GroundedExecution)

func (*GroundTruthStateStore) DeriveStateUpdates

func (s *GroundTruthStateStore) DeriveStateUpdates(call GroundedToolCall, result GroundedToolResult) []StateUpdate

type GroundedCommandFact

type GroundedCommandFact struct {
	ToolCallID string    `json:"tool_call_id"`
	Tool       string    `json:"tool"`
	Command    string    `json:"command,omitempty"`
	ArgsHash   string    `json:"args_hash,omitempty"`
	ExitCode   int       `json:"exit_code"`
	OutputHash string    `json:"output_hash,omitempty"`
	ObservedAt time.Time `json:"observed_at"`
}

type GroundedExecution

type GroundedExecution struct {
	Call    GroundedToolCall   `json:"call"`
	Result  GroundedToolResult `json:"result"`
	Updates []StateUpdate      `json:"updates,omitempty"`
}

type GroundedExecutor

type GroundedExecutor struct {
	// contains filtered or unexported fields
}

func NewGroundedExecutor

func NewGroundedExecutor(executor *tools.Executor, registry *tools.Registry, stateStore *GroundTruthStateStore, secret []byte, askHandler func(ctx context.Context, task *Task, argsJSON string) string) *GroundedExecutor

func (*GroundedExecutor) Execute

func (e *GroundedExecutor) Execute(ctx context.Context, task *Task, stepIndex, plannerRound int, nextTool PlannerToolCall) (*GroundedExecution, error)

func (*GroundedExecutor) SetToolGateway

func (e *GroundedExecutor) SetToolGateway(gateway *tools.ToolGateway)

func (*GroundedExecutor) VerifyResult

func (e *GroundedExecutor) VerifyResult(result GroundedToolResult) bool

type GroundedFileFact

type GroundedFileFact struct {
	Path           string    `json:"path"`
	Exists         bool      `json:"exists"`
	Size           int64     `json:"size,omitempty"`
	ContentSHA256  string    `json:"content_sha256,omitempty"`
	LastObservedBy string    `json:"last_observed_by,omitempty"`
	LastMutatedBy  string    `json:"last_mutated_by,omitempty"`
	ObservedAt     time.Time `json:"observed_at,omitempty"`
}

type GroundedPlanner

type GroundedPlanner struct {
	// contains filtered or unexported fields
}

func NewGroundedPlanner

func NewGroundedPlanner(llm LLMCaller) *GroundedPlanner

func (*GroundedPlanner) Decide

type GroundedResponse

type GroundedResponse struct {
	Summary string          `json:"summary"`
	Claims  []ResponseClaim `json:"claims"`
}

type GroundedRuntime

type GroundedRuntime struct {
	// contains filtered or unexported fields
}

func NewGroundedRuntime

func NewGroundedRuntime(cfg GroundedRuntimeConfig) *GroundedRuntime

func (*GroundedRuntime) ExecuteStep

func (r *GroundedRuntime) ExecuteStep(ctx context.Context, task *Task, step PlanStep, plan []PlanStep, maxToolRounds int) (*GroundedStepResult, error)

func (*GroundedRuntime) VerifyTask

func (r *GroundedRuntime) VerifyTask(task *Task) (*VerificationResult, string, error)

type GroundedRuntimeConfig

type GroundedRuntimeConfig struct {
	PlannerLLM        LLMCaller
	ResponderLLM      LLMCaller
	Registry          *tools.Registry
	Executor          *tools.Executor
	Store             *Store
	StateStore        *GroundTruthStateStore
	Planner           *GroundedPlanner
	GroundedExecutor  *GroundedExecutor
	Verifier          *GroundedVerifier
	AskHandler        func(ctx context.Context, task *Task, argsJSON string) string
	ConfirmToolCall   func(ctx context.Context, task *Task, step PlanStep, nextTool PlannerToolCall) error
	KnowledgeResolver LoopKnowledgeResolver
	KnowledgeTrace    func(task *Task, trace loopKnowledgeTrace)
	Secret            []byte
	MaxPlannerRounds  int
}

type GroundedStepResult

type GroundedStepResult struct {
	Output             string
	VerifiedOutput     string
	GroundingStatus    string
	VerificationErrors []string
}

type GroundedToolCall

type GroundedToolCall struct {
	ToolCallID   string         `json:"tool_call_id"`
	TaskID       string         `json:"task_id"`
	StepIndex    int            `json:"step_index"`
	PlannerRound int            `json:"planner_round"`
	Tool         string         `json:"tool"`
	Args         map[string]any `json:"args"`
	CreatedAt    time.Time      `json:"created_at"`
}

type GroundedToolResult

type GroundedToolResult struct {
	ToolCallID string    `json:"tool_call_id"`
	Tool       string    `json:"tool"`
	ExitCode   int       `json:"exit_code"`
	OK         bool      `json:"ok"`
	Result     any       `json:"result,omitempty"`
	Stderr     string    `json:"stderr,omitempty"`
	AuthTag    string    `json:"auth_tag"`
	StartedAt  time.Time `json:"started_at"`
	FinishedAt time.Time `json:"finished_at"`
}

type GroundedVerifier

type GroundedVerifier struct {
	// contains filtered or unexported fields
}

func NewGroundedVerifier

func NewGroundedVerifier(verifyResult func(GroundedToolResult) bool) *GroundedVerifier

func (*GroundedVerifier) Respond

func (v *GroundedVerifier) Respond(ctx context.Context, llmCaller LLMCaller, input ResponderInput) (*GroundedResponse, error)

func (*GroundedVerifier) Verify

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler provides REST API for agent tasks.

func NewHandler

func NewHandler(store *Store, runner *Runner) *Handler

NewHandler creates a new agent handler.

func (*Handler) CancelTask

func (h *Handler) CancelTask(c echo.Context) error

CancelTask handles POST /api/v1/agent/tasks/:id/cancel

func (*Handler) CreateTask

func (h *Handler) CreateTask(c echo.Context) error

CreateTask handles POST /api/v1/agent/tasks

func (*Handler) DeleteTask

func (h *Handler) DeleteTask(c echo.Context) error

DeleteTask handles DELETE /api/v1/agent/tasks/:id

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(g *echo.Group)

RegisterRoutes registers agent API routes.

func (*Handler) SendMessage

func (h *Handler) SendMessage(c echo.Context) error

SendMessage handles POST /api/v1/agent/tasks/:id/message Enqueues a user message for injection into a running task.

func (*Handler) SubmitAnswer

func (h *Handler) SubmitAnswer(c echo.Context) error

SubmitAnswer handles POST /api/v1/agent/tasks/:id/answer Delivers user answers to a pending ask_user call.

type LLMCaller

type LLMCaller interface {
	Chat(ctx context.Context, req llm.ChatRequest) (*llm.ChatResponse, error)
}

LLMCaller abstracts LLM calls so the runner doesn't depend on proxybridge directly.

type LoopKnowledgeResolver

type LoopKnowledgeResolver interface {
	ResolveLoopContext(ctx context.Context, req knowledge.LoopContextRequest) (*knowledge.LoopContextResult, error)
}

type MemoryRecaller

type MemoryRecaller interface {
	Recall(ctx context.Context, query string, limit int) ([]MemoryResult, error)
}

MemoryRecaller abstracts memory recall so the runner doesn't depend on memory package directly.

type MemoryResult

type MemoryResult struct {
	Content  string
	Score    float32
	Metadata map[string]string
}

MemoryResult is a simplified memory search result for the agent runner.

type PlanStep

type PlanStep struct {
	Index       int        `json:"index"`
	Description string     `json:"description"`
	Status      StepStatus `json:"status"`
	Output      string     `json:"output,omitempty"`
	StartedAt   *time.Time `json:"started_at,omitempty"`
	CompletedAt *time.Time `json:"completed_at,omitempty"`
}

PlanStep represents a single step in the agent's plan.

func UnmarshalPlan

func UnmarshalPlan(data string) []PlanStep

UnmarshalPlan deserializes plan steps from JSON.

type PlannerAssertion

type PlannerAssertion struct {
	Type string `json:"type"`
	Path string `json:"path,omitempty"`
	Tool string `json:"tool,omitempty"`
}

type PlannerDecision

type PlannerDecision struct {
	Status     PlannerDecisionStatus `json:"status"`
	Reason     string                `json:"reason"`
	NextTool   *PlannerToolCall      `json:"next_tool,omitempty"`
	Assertions []PlannerAssertion    `json:"assertions,omitempty"`
}

type PlannerDecisionStatus

type PlannerDecisionStatus string
const (
	PlannerDecisionContinue PlannerDecisionStatus = "continue"
	PlannerDecisionComplete PlannerDecisionStatus = "complete"
	PlannerDecisionBlocked  PlannerDecisionStatus = "blocked"
	PlannerDecisionUnknown  PlannerDecisionStatus = "unknown"
)

type PlannerInput

type PlannerInput struct {
	Model              string
	Goal               string
	PlanSummary        string
	Step               PlanStep
	PlannerRound       int
	MaxRounds          int
	GroundState        *GroundTruthState
	ToolCatalog        []llm.Tool
	PriorToolCallIDs   []string
	PreviousViolations []string
	KnowledgeContext   string
	RoutingContract    string
	CoordinationCtx    string
}

type PlannerToolCall

type PlannerToolCall struct {
	Tool string         `json:"tool"`
	Args map[string]any `json:"args"`
}

type ProgressSignatureState

type ProgressSignatureState struct {
	// contains filtered or unexported fields
}

func (*ProgressSignatureState) Observe

func (s *ProgressSignatureState) Observe(toolSig, decision string, toolSummaries []string) bool

func (*ProgressSignatureState) ObserveDetailed

func (s *ProgressSignatureState) ObserveDetailed(toolSig, decision string, toolSummaries []string) tools.ToolLoopDetection

type QuestionAnswer

type QuestionAnswer struct {
	QuestionID string   `json:"question_id"`
	Values     []string `json:"values"` // selected option values or free text
	OtherText  string   `json:"other_text,omitempty"`
}

QuestionAnswer is the user's answer to a question.

type QuestionOption

type QuestionOption struct {
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
	Value       string `json:"value"`
}

QuestionOption is a selectable option for a question.

type ResponderInput

type ResponderInput struct {
	Model              string
	Goal               string
	Step               PlanStep
	GroundState        *GroundTruthState
	PriorToolCallIDs   []string
	PreviousViolations []string
}

type ResponseClaim

type ResponseClaim struct {
	Type        ResponseClaimType `json:"type"`
	Text        string            `json:"text,omitempty"`
	ToolCallIDs []string          `json:"tool_call_ids,omitempty"`
	Path        string            `json:"path,omitempty"`
	Value       string            `json:"value,omitempty"`
	Excerpt     string            `json:"excerpt,omitempty"`
}

type ResponseClaimType

type ResponseClaimType string
const (
	ClaimTypeFSExists           ResponseClaimType = "fs_exists"
	ClaimTypeFSSize             ResponseClaimType = "fs_size"
	ClaimTypeFileContentExcerpt ResponseClaimType = "file_content_excerpt"
	ClaimTypeCommandExcerpt     ResponseClaimType = "command_output_excerpt"
	ClaimTypeToolOutput         ResponseClaimType = "tool_output"
	ClaimTypeUnknown            ResponseClaimType = "unknown"
)

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner executes agent tasks in the background.

func NewRunner

func NewRunner(store *Store, llmCaller LLMCaller, registry *tools.Registry, executor *tools.Executor, broker *sse.Broker, config RunnerConfig) *Runner

NewRunner creates a new agent runner.

func (*Runner) AskUser

func (r *Runner) AskUser(ctx context.Context, taskID string, questions []AgentQuestion, stepIndex int) ([]QuestionAnswer, error)

AskUser sends questions to the user and blocks until answers are received or ctx is cancelled. Sets task status to waiting_input while blocked, then restores the prior running status.

func (*Runner) Cancel

func (r *Runner) Cancel(taskID string) bool

Cancel cancels a running task.

func (*Runner) EnqueueMessage

func (r *Runner) EnqueueMessage(taskID, message string) bool

EnqueueMessage adds a user message to a running task's queue. Returns false if the task is not running.

func (*Runner) SetAskTimeoutActionFunc

func (r *Runner) SetAskTimeoutActionFunc(fn func() string)

SetAskTimeoutActionFunc sets dynamic timeout action getter ("error" | "default").

func (*Runner) SetAskTimeoutFunc

func (r *Runner) SetAskTimeoutFunc(fn func() time.Duration)

SetAskTimeoutFunc sets a dynamic timeout getter (takes precedence over static timeout when >0).

func (*Runner) SetAutoReflectFunc

func (r *Runner) SetAutoReflectFunc(fn func() bool)

SetAutoReflectFunc sets a dynamic auto-reflect toggle getter.

func (*Runner) SetEventObserver

func (r *Runner) SetEventObserver(observer TaskEventObserver)

SetEventObserver wires an optional observer for task SSE events.

func (*Runner) SetExecPathGuard

func (r *Runner) SetExecPathGuard(guard tools.ExecPathGuard)

SetExecPathGuard wires runtime-specific exec path protection into exec-style tools.

func (*Runner) SetKnowledgeResolver

func (r *Runner) SetKnowledgeResolver(resolver LoopKnowledgeResolver)

func (*Runner) SetMaxToolRoundsPerStepFunc

func (r *Runner) SetMaxToolRoundsPerStepFunc(fn func() int)

SetMaxToolRoundsPerStepFunc sets a dynamic max-tool-round getter.

func (*Runner) SetMemory

func (r *Runner) SetMemory(m MemoryRecaller)

SetMemory sets the memory recaller for context injection.

func (*Runner) SetReflector

func (r *Runner) SetReflector(reflector SelfReflector)

SetReflector sets the post-task reflection engine.

func (*Runner) SetSubagentExecutor

func (r *Runner) SetSubagentExecutor(executor tools.SubagentExecutor)

SetSubagentExecutor wires harness-backed child-run execution into the agent runtime.

func (*Runner) SetToolApprover

func (r *Runner) SetToolApprover(approver tools.ToolApprover)

SetToolApprover wires runtime tool approval enforcement into the agent's shared tool gateway.

func (*Runner) SetToolEventObserver

func (r *Runner) SetToolEventObserver(observer tools.RuntimeEventObserver)

SetToolEventObserver wires runtime tool lifecycle observation into the shared tool gateway.

func (*Runner) SetToolMetricsRecorder

func (r *Runner) SetToolMetricsRecorder(recorder interface {
	RecordCounter(name string, value int64, tags map[string]string)
})

SetToolMetricsRecorder wires runtime counter recording into the shared tool gateway.

func (*Runner) SetWritePathGuard

func (r *Runner) SetWritePathGuard(guard tools.WritePathGuard)

SetWritePathGuard wires runtime-specific direct-write protection into file mutation tools.

func (*Runner) Shutdown

func (r *Runner) Shutdown()

Shutdown cancels all running tasks and waits for goroutines to exit.

func (*Runner) Submit

func (r *Runner) Submit(ctx context.Context, userID, goal, conversationID, conversationCtx string) (*Task, error)

Submit creates and starts a new agent task. Returns the task immediately.

func (*Runner) SubmitAnswers

func (r *Runner) SubmitAnswers(taskID string, answers []QuestionAnswer) bool

SubmitAnswers delivers user answers to a pending AskUser call. Returns false if no question is pending for this task.

func (*Runner) SubmitTask

func (r *Runner) SubmitTask(ctx context.Context, task *Task, conversationCtx string) (*Task, error)

SubmitTask starts a caller-provided task ID through the normal runner flow.

type RunnerConfig

type RunnerConfig struct {
	MaxConcurrent int
	TaskTimeout   time.Duration
	AskTimeout    time.Duration
	AutoReflect   bool
	// AskTimeoutAction controls timeout behavior: "error" (default) | "default".
	AskTimeoutAction string
	// MaxToolRoundsPerStep controls tool loop budget per plan step.
	MaxToolRoundsPerStep int
}

RunnerConfig configures the agent runner.

type RuntimeAuditEvent

type RuntimeAuditEvent struct {
	Timestamp  time.Time       `json:"timestamp"`
	From       RuntimeState    `json:"from,omitempty"`
	To         RuntimeState    `json:"to,omitempty"`
	Reason     string          `json:"reason,omitempty"`
	Capability *CapabilityInfo `json:"capability,omitempty"`
	Error      string          `json:"error,omitempty"`
}

RuntimeAuditEvent records deterministic state transitions and routing decisions.

type RuntimeEvent

type RuntimeEvent struct {
	ID           string    `json:"id"`
	TaskID       string    `json:"task_id"`
	StepIndex    int       `json:"step_index"`
	PlannerRound int       `json:"planner_round"`
	EventType    string    `json:"event_type"`
	PayloadJSON  string    `json:"payload_json"`
	CreatedAt    time.Time `json:"created_at"`
}

type RuntimeState

type RuntimeState string

RuntimeState represents the explicit orchestrator FSM state.

const (
	RuntimeStateIntake      RuntimeState = "INTAKE"
	RuntimeStateClarify     RuntimeState = "CLARIFY"
	RuntimeStatePlan        RuntimeState = "PLAN"
	RuntimeStateConfirmGate RuntimeState = "CONFIRM_GATE"
	RuntimeStateExecute     RuntimeState = "EXECUTE"
	RuntimeStateVerify      RuntimeState = "VERIFY"
	RuntimeStateReflect     RuntimeState = "REFLECT"
	RuntimeStateReport      RuntimeState = "REPORT"
	RuntimeStateRecover     RuntimeState = "RECOVER"
	RuntimeStateDone        RuntimeState = "DONE"
	RuntimeStateAborted     RuntimeState = "ABORTED"
)

type SelfReflector

type SelfReflector interface {
	Reflect(ctx context.Context, input selfreflect.Input) (*selfreflect.Result, error)
}

type StateUpdate

type StateUpdate struct {
	UpdateID      string         `json:"update_id"`
	ToolCallID    string         `json:"tool_call_id"`
	Kind          string         `json:"kind"`
	Path          string         `json:"path,omitempty"`
	Exists        bool           `json:"exists,omitempty"`
	Size          int64          `json:"size,omitempty"`
	ContentSHA256 string         `json:"content_sha256,omitempty"`
	ObservedAt    time.Time      `json:"observed_at"`
	Metadata      map[string]any `json:"metadata,omitempty"`
}

type StepStatus

type StepStatus string

StepStatus represents the status of a plan step.

const (
	StepStatusPending   StepStatus = "pending"
	StepStatusRunning   StepStatus = "running"
	StepStatusCompleted StepStatus = "completed"
	StepStatusFailed    StepStatus = "failed"
	StepStatusSkipped   StepStatus = "skipped"
)

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store persists agent tasks in SQLite.

func NewStore

func NewStore(db *sql.DB) (*Store, error)

NewStore creates a new agent task store.

func NewStoreWithReadDB

func NewStoreWithReadDB(writeDB, readDB *sql.DB) (*Store, error)

NewStoreWithReadDB creates a new agent task store with separate write and read database handles.

func (*Store) AppendRuntimeEvent

func (s *Store) AppendRuntimeEvent(ctx context.Context, event RuntimeEvent) error

func (*Store) Cleanup

func (s *Store) Cleanup(ctx context.Context, olderThan time.Duration) (int64, error)

Cleanup removes tasks older than the given duration.

func (*Store) CountRunning

func (s *Store) CountRunning(ctx context.Context, userID string) (int, error)

CountRunning returns the number of running tasks for a user.

func (*Store) Create

func (s *Store) Create(ctx context.Context, task *Task) error

Create inserts a new task.

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, id string, userID ...string) error

Delete removes a task.

func (*Store) Get

func (s *Store) Get(ctx context.Context, id string, userID ...string) (*Task, error)

Get retrieves a task by ID.

func (*Store) ListByUser

func (s *Store) ListByUser(ctx context.Context, userID string, limit int) ([]*Task, error)

ListByUser returns tasks for a user, ordered by creation time descending.

func (*Store) ListRuntimeEvents

func (s *Store) ListRuntimeEvents(ctx context.Context, taskID string) ([]RuntimeEvent, error)

func (*Store) RecoverStaleTasks

func (s *Store) RecoverStaleTasks(ctx context.Context) (int64, error)

RecoverStaleTasks marks any tasks stuck in running states as failed. Call this on startup to clean up tasks from a previous crash.

func (*Store) SetStatus

func (s *Store) SetStatus(ctx context.Context, id string, status TaskStatus, errMsg string, userID ...string) error

SetStatus is a convenience method to update just the status.

func (*Store) Update

func (s *Store) Update(ctx context.Context, task *Task, userID ...string) error

Update updates a task's mutable fields.

type Task

type Task struct {
	ID                 string                 `json:"id"`
	UserID             string                 `json:"user_id"`
	ConversationID     string                 `json:"conversation_id,omitempty"`
	Goal               string                 `json:"goal"`
	Plan               []PlanStep             `json:"plan,omitempty"`
	Status             TaskStatus             `json:"status"`
	RuntimeState       RuntimeState           `json:"runtime_state,omitempty"`
	RuntimeAudit       []RuntimeAuditEvent    `json:"runtime_audit,omitempty"`
	SuccessCriteria    []string               `json:"success_criteria,omitempty"`
	FallbackPlan       []string               `json:"fallback_plan,omitempty"`
	CurrentStep        int                    `json:"current_step"`
	Progress           int                    `json:"progress"` // 0-100
	Result             string                 `json:"result,omitempty"`
	VerifiedOutput     string                 `json:"verified_output,omitempty"`
	VerificationErrors []string               `json:"verification_errors,omitempty"`
	GroundingStatus    string                 `json:"grounding_status,omitempty"`
	Metadata           map[string]interface{} `json:"metadata,omitempty"`
	Error              string                 `json:"error,omitempty"`
	CreatedAt          time.Time              `json:"created_at"`
	UpdatedAt          time.Time              `json:"updated_at"`
	WorkspaceRoot      string                 `json:"-"`

	GroundState *GroundTruthState `json:"-"`
}

Task represents an autonomous agent task.

type TaskEvent

type TaskEvent struct {
	TaskID     string          `json:"task_id"`
	EventType  string          `json:"event_type"` // task_created, task_planning, task_progress, task_step_completed, task_reflection_started, task_reflection_completed, task_completed, task_failed, task_question
	StepIndex  int             `json:"step_index,omitempty"`
	Progress   int             `json:"progress,omitempty"`
	Message    string          `json:"message,omitempty"`
	Output     string          `json:"output,omitempty"`
	DurationMs int64           `json:"duration_ms,omitempty"` // step execution time in milliseconds
	Questions  []AgentQuestion `json:"questions,omitempty"`   // for task_question events
	FromState  RuntimeState    `json:"from_state,omitempty"`
	ToState    RuntimeState    `json:"to_state,omitempty"`
}

TaskEvent is an SSE event for task progress.

type TaskEventObserver

type TaskEventObserver interface {
	HandleTaskEvent(event TaskEvent)
}

type TaskKind

type TaskKind string
const (
	TaskKindCode     TaskKind = "code"
	TaskKindDocs     TaskKind = "docs"
	TaskKindResearch TaskKind = "research"
	TaskKindOps      TaskKind = "ops"
	TaskKindGeneric  TaskKind = "generic"
)

type TaskStatus

type TaskStatus string

TaskStatus represents the status of an agent task.

const (
	TaskStatusPending      TaskStatus = "pending"
	TaskStatusPlanning     TaskStatus = "planning"
	TaskStatusExecuting    TaskStatus = "executing"
	TaskStatusWaitingInput TaskStatus = "waiting_input" // blocked on ask_user
	TaskStatusAborted      TaskStatus = "aborted"
	TaskStatusCompleted    TaskStatus = "completed"
	TaskStatusFailed       TaskStatus = "failed"
	TaskStatusCancelled    TaskStatus = "cancelled"
)

type VerificationContext

type VerificationContext struct {
	TaskKind        TaskKind
	Goal            string
	SuccessCriteria []string
	FallbackPlan    []string
	PlannedSteps    []string
}

type VerificationDecision

type VerificationDecision struct {
	Valid      bool
	Violations []string
	Status     string
	Output     string
}

type VerificationResult

type VerificationResult struct {
	Status            string            `json:"status"`
	Summary           string            `json:"summary"`
	CriteriaResults   []CriterionResult `json:"criteria_results"`
	SuggestedRecovery string            `json:"suggested_recovery,omitempty"`
	ExecutedChecks    []string          `json:"executed_checks"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL