Skip to content

Fully autonomous AI Agents system capable of performing complex penetration testing tasks

feat: add assistant flow management tools and summarizer cache

Dmitry Ng5067e8f5a444
diff --git a/Dockerfile b/Dockerfile
index dc0664af..c1b1b818 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -159,6 +159,7 @@ COPY --from=api-builder /licenses/backend /opt/pentagi/licenses/backend
COPY --from=frontend-compiler /licenses/frontend /opt/pentagi/licenses/frontend
# Copy provider configuration files
+COPY examples/configs/azure-openai.provider.yml /opt/pentagi/conf/
COPY examples/configs/custom-openai.provider.yml /opt/pentagi/conf/
COPY examples/configs/deepinfra.provider.yml /opt/pentagi/conf/
COPY examples/configs/deepseek.provider.yml /opt/pentagi/conf/
diff --git a/backend/docs/flow_execution.md b/backend/docs/flow_execution.md
index e54b579e..0c0a56e0 100644
--- a/backend/docs/flow_execution.md
+++ b/backend/docs/flow_execution.md
@@ -14,11 +14,11 @@ This document describes the internal architecture and execution workflow of Flow
- **FlowWorker** - Manages the complete lifecycle of a Flow, coordinates Tasks
- **TaskWorker** - Executes individual Tasks, manages Subtask generation and refinement
- **SubtaskWorker** - Handles execution of specific Subtasks via AI agents
-- **AssistantWorker** - Manages interactive assistant mode within a Flow
+- **AssistantWorker** - Manages interactive assistant mode within a Flow; optionally controls the Flow's automation via injected `FlowWorker` reference
### Providers
- **FlowProvider** - Core interface for Flow execution, agent coordination and orchestration
-- **AssistantProvider** - Specialized provider for assistant mode interactions
+- **AssistantProvider** - Specialized provider for assistant mode interactions; receives `FlowWorker` via `SetFlowWorker()` after chain preparation to enable flow management tool callbacks
- **ProviderController** - Factory for creating and managing different LLM providers
### AI Agents
@@ -34,11 +34,11 @@ This document describes the internal architecture and execution workflow of Flow
- **Enricher Agent** - Enhances information from multiple sources
- **Adviser Agent** - Provides expert guidance and recommendations
- **Reflector Agent** - Corrects agents that return unstructured text instead of tool calls
-- **Assistant Agent** - Provides interactive assistance, operates autonomously within Flow independently from Task/Subtask (UseAgents flag controls delegation)
+- **Assistant Agent** - Provides interactive assistance, operates autonomously within Flow independently from Task/Subtask (UseAgents flag controls delegation); when FlowWorker is available, exposes `get_flow_status`, `stop_flow`, `submit_flow_input`, and `patch_flow_subtasks` tools for automation control
### Tools and Capabilities by Category
- **Environment Tools** - Terminal commands, file operations within Docker containers
- - `terminal` - Command execution (default: 5min if not specified, hard limit: 20min)
+ - `terminal` - Command execution (configurable via `TERMINAL_TOOL_TIMEOUT`, default: 1200s; hard limit: 3h/10800s; 0 or negative values are clamped to the hard limit)
- `file` - Read/write operations with absolute path requirements
- **Search Network Tools** - External information sources
@@ -68,6 +68,12 @@ This document describes the internal architecture and execution workflow of Flow
- **Barrier Tools** - Control flow termination
- `done` - Complete subtask, `ask` - Request user input (configurable via ASK_USER env)
+- **Flow Management Tools** - Assistant-only; available when FlowWorker is injected into AssistantProvider
+ - `get_flow_status` - Query flow state, tasks, subtasks, planned/running subtask with optional agent messages (verbose mode: 50 messages, execution context)
+ - `stop_flow` - Cancel the currently running task (15s timeout; reports actual post-stop state)
+ - `submit_flow_input` - Deliver text to a waiting flow: answers an `ask` checkpoint or creates a new task
+ - `patch_flow_subtasks` - Replace planned subtask list via delta operations (add/remove/modify/reorder); returns new IDs after recreation
+
### Execution Context
- **Message Chain** - Conversation history maintained for each agent interaction
- **Execution Context** - Comprehensive state including completed/planned Subtasks
@@ -310,6 +316,13 @@ sequenceDiagram
Note over AW: Message chain preserved in DB
AW->>AP: Continue conversation context
end
+
+ opt FlowWorker injected (flow management enabled)
+ Note over AP,AA: get_flow_status / stop_flow / submit_flow_input / patch_flow_subtasks available
+ AA->>AP: Call flow management tool
+ AP->>AP: buildFlowManagerHandlers() → stopAssistantFlow / sendAssistantFlowInput / patchAssistantFlowSubtasks
+ AP-->>AA: Tool result with actual flow state
+ end
```
### Vector Database (RAG) Integration
@@ -559,7 +572,7 @@ graph TB
subgraph "Tool Execution Environment"
WorkDir[Work Directory<br/>/work in container]
- Terminal[Terminal Tool<br/>5min default, 20min max]
+ Terminal[Terminal Tool<br/>default 1200s, hard limit 3h]
FileOps[File Operations<br/>Absolute paths required]
WebAccess[Web Access<br/>Separate scraper container]
end
@@ -853,12 +866,13 @@ Several mechanisms ensure efficient execution:
- **Search Action Economy** - Searcher limited to 3-5 actions per query
**Timeout Configuration**:
-- **Terminal Operations** - Default 5 minutes, hard limit 20 minutes
+- **Terminal Operations** - Configurable via `TERMINAL_TOOL_TIMEOUT` (default: 1200s); hard limit 3h/10800s; 0 or negative values clamped to hard limit
- **LLM API Calls** - 3 retries with 5-second delays between attempts
- **Vector Search** - Threshold 0.2, max 3 results per query
- **Tool Result Summarization** - Triggered at 16KB result size
- **Flow Input Processing** - 1 second timeout for input queueing
- **Assistant Input** - 2 second timeout for assistant input queueing
+- **Flow Management Operations** - 15 second timeout for `stop_flow` and `submit_flow_input` handlers
**Container Resource Management**:
- **Port Allocation** - 2 ports per Flow starting from base 28000
@@ -868,6 +882,7 @@ Several mechanisms ensure efficient execution:
**Memory Optimization**:
- **Message summarization** - Prevents context window overflow
+- **Summarizer result cache** - LRU cache per FlowProvider (1000 entries, 4h TTL); keyed by SHA-256 of input; skips LLM call for repeated identical content
- **Tool argument limits** - 1KB limit for individual argument values
- **Connection pooling** - Database connections are reused
- **Automatic cleanup** - Containers removed after Flow completion
@@ -1116,6 +1131,10 @@ graph TB
- `performMentor` method in `performer.go` - Coordinates mentor invocation for execution monitoring
- `performPlanner` method in `performers.go` - Generates execution plans via adviser
- `formatEnhancedToolResponse` function in `helpers.go` - Formats mentor analysis
+- `flowStatusTool`, `stopFlowTool`, `submitFlowInputTool`, `patchFlowSubtasksTool` in `tools/flow_manager.go` - Flow management tool implementations
+- `buildFlowManagerHandlers()` in `providers/assistant.go` - Builds handler closures from injected `FlowWorker`
+- `patchAssistantFlowSubtasks()` in `providers/assistant.go` - Applies subtask delta operations and recreates DB entries
+- Summarizer LRU cache on `flowProvider` (`providers/provider.go`) - 1000 entries, 4h TTL, SHA-256 key
- Template `question_execution_monitor.tmpl` - Question format for execution monitoring
- Template `question_task_planner.tmpl` - Question format for task planning
@@ -1155,7 +1174,7 @@ The Flow execution system represents a sophisticated orchestration platform that
### Operational Flexibility
- **Multi-provider LLM support** - Different models optimized for different agent types
-- **Assistant dual modes** - UseAgents flag enables delegation or direct tool access
+- **Assistant dual modes** - UseAgents flag enables delegation or direct tool access; FlowWorker injection enables 4 flow management tools for automation control
- **Flow continuity** - System can resume operations after interruptions
- **Real-time feedback** - Streaming responses provide immediate user visibility
- **Vector knowledge system** - 4 storage types with semantic search and metadata filtering
@@ -1171,6 +1190,13 @@ The Flow execution system represents a sophisticated orchestration platform that
- **Buffer Management**: Separate buffers for thinking/content with controlled updates
- **Real-time Distribution**: Immediate GraphQL subscription updates to frontend
+**Assistant Flow Management Architecture**:
+- **FlowWorker injection**: `SetFlowWorker(fw FlowWorker)` called after `getFlowProviderWorkers()` in `controller/assistant.go`
+- **Handler closures**: `buildFlowManagerHandlers()` produces `StopFlow`, `SendFlowInput`, `PatchSubtasks` callbacks
+- **Two-layer validation**: tool handlers (`tools/flow_manager.go`) perform primary checks; provider callbacks are safety nets
+- **Subtask patching**: delta operations applied via `applySubtaskOperations()`; all planned subtask IDs are recreated; new IDs returned in tool result
+- **State verification**: `stop_flow` re-queries `GetFlowTasks` after handler returns and reports actual state
+
**Message Chain Consistency**:
- **AST Processing**: Uses Chain Abstract Syntax Tree for structured message analysis
- **Fallback Content**: Unresponded tool calls get default responses via `cast.FallbackResponseContent`
diff --git a/backend/pkg/controller/assistant.go b/backend/pkg/controller/assistant.go
index 3f41906a..f49539f6 100644
--- a/backend/pkg/controller/assistant.go
+++ b/backend/pkg/controller/assistant.go
@@ -63,6 +63,7 @@ type newAssistantWorkerCtx struct {
prvname provider.ProviderName
prvtype provider.ProviderType
functions *tools.Functions
+ fw FlowWorker
flowWorkerCtx
}
@@ -70,6 +71,7 @@ type newAssistantWorkerCtx struct {
type assistantWorkerCtx struct {
userID int64
flowID int64
+ fw FlowWorker
flowWorkerCtx
}
@@ -200,6 +202,7 @@ func NewAssistantWorker(ctx context.Context, awc newAssistantWorkerCtx) (Assista
assistantProvider.SetAgentLogProvider(workers.alw)
assistantProvider.SetMsgLogProvider(aslw)
+ assistantProvider.SetFlowWorker(awc.fw)
executor.SetImage(container.Image)
executor.SetEmbedder(assistantProvider.Embedder())
@@ -338,6 +341,7 @@ func LoadAssistantWorker(
assistantProvider.SetAgentLogProvider(workers.alw)
assistantProvider.SetMsgLogProvider(aslw)
+ assistantProvider.SetFlowWorker(awc.fw)
executor.SetImage(container.Image)
executor.SetEmbedder(assistantProvider.Embedder())
diff --git a/backend/pkg/controller/flow.go b/backend/pkg/controller/flow.go
index e8909ffe..821721d4 100644
--- a/backend/pkg/controller/flow.go
+++ b/backend/pkg/controller/flow.go
@@ -420,6 +420,7 @@ func LoadFlowWorker(ctx context.Context, flow database.Flow, fwc flowWorkerCtx)
awc := assistantWorkerCtx{
userID: flow.UserID,
flowID: flow.ID,
+ fw: fw,
flowWorkerCtx: fwc,
}
for _, assistant := range assistants {
diff --git a/backend/pkg/controller/flows.go b/backend/pkg/controller/flows.go
index 6c9b2c1b..e73aac47 100644
--- a/backend/pkg/controller/flows.go
+++ b/backend/pkg/controller/flows.go
@@ -289,6 +289,7 @@ func (fc *flowController) CreateAssistant(
prvtype: prvtype,
useAgents: useAgents,
functions: functions,
+ fw: fw,
flowWorkerCtx: flowWorkerCtx,
})
if err != nil {
diff --git a/backend/pkg/providers/assistant.go b/backend/pkg/providers/assistant.go
index adb10dd6..551a6ff3 100644
--- a/backend/pkg/providers/assistant.go
+++ b/backend/pkg/providers/assistant.go
@@ -34,6 +34,7 @@ type AssistantProvider interface {
SetMsgChainID(msgChainID int64)
SetAgentLogProvider(agentLog tools.AgentLogProvider)
SetMsgLogProvider(msgLog tools.MsgLogProvider)
+ SetFlowWorker(flowWorker FlowWorker)
PrepareAgentChain(ctx context.Context) (int64, error)
PerformAgentChain(ctx context.Context) error
@@ -41,10 +42,19 @@ type AssistantProvider interface {
EnsureChainConsistency(ctx context.Context) error
}
+type FlowWorker interface {
+ GetTitle() string
+ GetStatus(ctx context.Context) (database.FlowStatus, error)
+ PutInput(ctx context.Context, input string, prv provider.Provider) error
+ Stop(ctx context.Context) error
+ Rename(ctx context.Context, title string) error
+}
+
type assistantProvider struct {
id int64
msgChainID int64
summarizer csum.Summarizer
+ flowWorker FlowWorker
fp flowProvider
}
@@ -84,6 +94,10 @@ func (ap *assistantProvider) SetMsgLogProvider(msgLog tools.MsgLogProvider) {
ap.fp.SetMsgLogProvider(msgLog)
}
+func (ap *assistantProvider) SetFlowWorker(flowWorker FlowWorker) {
+ ap.flowWorker = flowWorker
+}
+
func (ap *assistantProvider) PrepareAgentChain(ctx context.Context) (int64, error) {
ctx, span := obs.Observer.NewSpan(ctx, obs.SpanKindInternal, "providers.flowProvider.PrepareAssistantChain")
defer span.End()
@@ -194,14 +208,15 @@ func (ap *assistantProvider) PerformAgentChain(ctx context.Context) error {
ctx, _ = executorAgent.Observation(ctx)
cfg := tools.AssistantExecutorConfig{
- UseAgents: useAgents,
- Adviser: adviser,
- Coder: coder,
- Installer: installer,
- Memorist: memorist,
- Pentester: pentester,
- Searcher: searcher,
- Summarizer: ap.fp.GetSummarizeResultHandler(nil, nil),
+ UseAgents: useAgents,
+ Adviser: adviser,
+ Coder: coder,
+ Installer: installer,
+ Memorist: memorist,
+ Pentester: pentester,
+ Searcher: searcher,
+ Summarizer: ap.fp.GetSummarizeResultHandler(nil, nil),
+ FlowManager: ap.buildFlowManagerHandlers(),
}
executor, err := ap.fp.Executor().GetAssistantExecutor(cfg)
@@ -311,33 +326,38 @@ func (ap *assistantProvider) getAssistantSystemPrompt(ctx context.Context) (stri
}
systemAssistantTmpl, err := ap.fp.Prompter().RenderTemplate(templates.PromptTypeAssistant, map[string]any{
- "SearchToolName": tools.SearchToolName,
- "PentesterToolName": tools.PentesterToolName,
- "CoderToolName": tools.CoderToolName,
- "AdviceToolName": tools.AdviceToolName,
- "MemoristToolName": tools.MemoristToolName,
- "MaintenanceToolName": tools.MaintenanceToolName,
- "TerminalToolName": tools.TerminalToolName,
- "FileToolName": tools.FileToolName,
- "GoogleToolName": tools.GoogleToolName,
- "DuckDuckGoToolName": tools.DuckDuckGoToolName,
- "TavilyToolName": tools.TavilyToolName,
- "TraversaalToolName": tools.TraversaalToolName,
- "PerplexityToolName": tools.PerplexityToolName,
- "BrowserToolName": tools.BrowserToolName,
- "SearchInMemoryToolName": tools.SearchInMemoryToolName,
- "SearchGuideToolName": tools.SearchGuideToolName,
- "SearchAnswerToolName": tools.SearchAnswerToolName,
- "SearchCodeToolName": tools.SearchCodeToolName,
- "SummarizationToolName": cast.SummarizationToolName,
- "SummarizedContentPrefix": strings.ReplaceAll(csum.SummarizedContentPrefix, "\n", "\\n"),
- "UseAgents": useAgents,
- "DockerImage": ap.fp.Image(),
- "Cwd": docker.WorkFolderPathInContainer,
- "ContainerPorts": ap.fp.getContainerPortsDescription(),
- "ExecutionContext": executionContext,
- "Lang": ap.fp.Language(),
- "CurrentTime": getCurrentTime(),
+ "SearchToolName": tools.SearchToolName,
+ "PentesterToolName": tools.PentesterToolName,
+ "CoderToolName": tools.CoderToolName,
+ "AdviceToolName": tools.AdviceToolName,
+ "MemoristToolName": tools.MemoristToolName,
+ "MaintenanceToolName": tools.MaintenanceToolName,
+ "TerminalToolName": tools.TerminalToolName,
+ "FileToolName": tools.FileToolName,
+ "GoogleToolName": tools.GoogleToolName,
+ "DuckDuckGoToolName": tools.DuckDuckGoToolName,
+ "TavilyToolName": tools.TavilyToolName,
+ "TraversaalToolName": tools.TraversaalToolName,
+ "PerplexityToolName": tools.PerplexityToolName,
+ "BrowserToolName": tools.BrowserToolName,
+ "SearchInMemoryToolName": tools.SearchInMemoryToolName,
+ "SearchGuideToolName": tools.SearchGuideToolName,
+ "SearchAnswerToolName": tools.SearchAnswerToolName,
+ "SearchCodeToolName": tools.SearchCodeToolName,
+ "SummarizationToolName": cast.SummarizationToolName,
+ "SummarizedContentPrefix": strings.ReplaceAll(csum.SummarizedContentPrefix, "\n", "\\n"),
+ "UseAgents": useAgents,
+ "DockerImage": ap.fp.Image(),
+ "Cwd": docker.WorkFolderPathInContainer,
+ "ContainerPorts": ap.fp.getContainerPortsDescription(),
+ "ExecutionContext": executionContext,
+ "Lang": ap.fp.Language(),
+ "CurrentTime": getCurrentTime(),
+ "FlowManagerEnabled": ap.flowWorker != nil,
+ "GetFlowStatusToolName": tools.GetFlowStatusToolName,
+ "StopFlowToolName": tools.StopFlowToolName,
+ "SubmitFlowInputToolName": tools.SubmitFlowInputToolName,
+ "PatchFlowSubtasksToolName": tools.PatchFlowSubtasksToolName,
})
if err != nil {
logger.WithError(err).Error("failed to get system prompt for assistant template")
@@ -393,3 +413,277 @@ func (ap *assistantProvider) getAssistantExecutionContext(ctx context.Context) (
return executionContext, nil
}
+
+// buildFlowManagerHandlers constructs FlowManagerHandlers from the injected flowWorker.
+// Returns zero-value (no-op) handlers when flowWorker is nil, so the 4 flow-management
+// tools are simply not registered in the assistant executor.
+func (ap *assistantProvider) buildFlowManagerHandlers() tools.FlowManagerHandlers {
+ if ap.flowWorker == nil {
+ return tools.FlowManagerHandlers{}
+ }
+
+ return tools.FlowManagerHandlers{
+ StopFlow: ap.stopAssistantFlow,
+ SendFlowInput: ap.sendAssistantFlowInput,
+ PatchSubtasks: ap.patchAssistantFlowSubtasks,
+ }
+}
+
+func (ap *assistantProvider) stopAssistantFlow(ctx context.Context, reason string) error {
+ logger := logrus.WithContext(ctx).WithFields(logrus.Fields{
+ "provider": ap.fp.Type(),
+ "assistant_id": ap.id,
+ "flow_id": ap.fp.ID(),
+ "msg_chain_id": ap.msgChainID,
+ "reason": reason[:min(len(reason), 1000)],
+ })
+
+ logger.Debug("stopping assistant flow")
+
+ if ap.flowWorker == nil {
+ logger.Error("flow worker is not set")
+ return fmt.Errorf("flow worker is not set")
+ }
+
+ status, err := ap.flowWorker.GetStatus(ctx)
+ if err != nil {
+ logger.WithError(err).Error("failed to get flow status")
+ return fmt.Errorf("failed to get flow status: %w", err)
+ }
+
+ if status != database.FlowStatusRunning {
+ logger.Debug("flow is not running, skipping stop")
+ return nil
+ }
+
+ err = ap.flowWorker.Stop(ctx)
+
+ level := langfuse.ObservationLevelDefault
+ statusMsg := "success"
+ if err != nil {
+ level = langfuse.ObservationLevelError
+ statusMsg = err.Error()
+ }
+
+ _, observation := obs.Observer.NewObservation(ctx)
+ observation.Event(
+ langfuse.WithEventName("stopping flow by assistant"),
+ langfuse.WithEventInput(map[string]any{
+ "reason": reason,
+ }),
+ langfuse.WithEventMetadata(langfuse.Metadata{
+ "provider": ap.fp.Type(),
+ "assistant_id": ap.id,
+ "flow_id": ap.fp.ID(),
+ "msg_chain_id": ap.msgChainID,
+ }),
+ langfuse.WithEventLevel(level),
+ langfuse.WithEventStatus(statusMsg),
+ )
+
+ if err != nil {
+ logger.WithError(err).Error("failed to stop flow")
+ return fmt.Errorf("failed to stop flow: %w", err)
+ }
+
+ return nil
+}
+
+func (ap *assistantProvider) sendAssistantFlowInput(ctx context.Context, input string) error {
+ logger := logrus.WithContext(ctx).WithFields(logrus.Fields{
+ "provider": ap.fp.Type(),
+ "assistant_id": ap.id,
+ "flow_id": ap.fp.ID(),
+ "msg_chain_id": ap.msgChainID,
+ "input": input[:min(len(input), 1000)],
+ })
+
+ logger.Debug("sending input to flow from assistant")
+
+ if ap.flowWorker == nil {
+ logger.Error("flow worker is not set")
+ return fmt.Errorf("flow worker is not set")
+ }
+
+ status, err := ap.flowWorker.GetStatus(ctx)
+ if err != nil {
+ logger.WithError(err).Error("failed to get flow status")
+ return fmt.Errorf("failed to get flow status: %w", err)
+ }
+
+ if status != database.FlowStatusWaiting {
+ logger.Error("flow is not waiting, cannot send input")
+ return fmt.Errorf("flow is not in 'waiting' state (current: %s); cannot submit input", status)
+ }
+
+ err = ap.flowWorker.PutInput(ctx, input, nil)
+
+ level := langfuse.ObservationLevelDefault
+ statusMsg := "success"
+ if err != nil {
+ level = langfuse.ObservationLevelError
+ statusMsg = err.Error()
+ }
+
+ _, observation := obs.Observer.NewObservation(ctx)
+ observation.Event(
+ langfuse.WithEventName("sending input to flow by assistant"),
+ langfuse.WithEventInput(map[string]any{
+ "input": input,
+ }),
+ langfuse.WithEventMetadata(langfuse.Metadata{
+ "provider": ap.fp.Type(),
+ "assistant_id": ap.id,
+ "flow_id": ap.fp.ID(),
+ "msg_chain_id": ap.msgChainID,
+ }),
+ langfuse.WithEventLevel(level),
+ langfuse.WithEventStatus(statusMsg),
+ )
+
+ if err != nil {
+ logger.WithError(err).Error("failed to put flow input")
+ return fmt.Errorf("failed to put flow input: %w", err)
+ }
+
+ return nil
+}
+
+func (ap *assistantProvider) patchAssistantFlowSubtasks(
+ ctx context.Context,
+ taskID int64,
+ patch tools.SubtaskPatch,
+) error {
+ logger := logrus.WithContext(ctx).WithFields(logrus.Fields{
+ "provider": ap.fp.Type(),
+ "assistant_id": ap.id,
+ "flow_id": ap.fp.ID(),
+ "msg_chain_id": ap.msgChainID,
+ "task_id": taskID,
+ "ops_count": len(patch.Operations),
+ })
+
+ logger.Debug("patching flow subtasks from assistant")
+
+ if ap.flowWorker == nil {
+ logger.Error("flow worker is not set")
+ return fmt.Errorf("flow worker is not set")
+ }
+
+ status, err := ap.flowWorker.GetStatus(ctx)
+ if err != nil {
+ logger.WithError(err).Error("failed to get flow status")
+ return fmt.Errorf("failed to get flow status: %w", err)
+ }
+
+ if status == database.FlowStatusRunning {
+ logger.Error("flow is running, cannot patch subtasks")
+ return fmt.Errorf("flow is in 'running' state; patching is not allowed while a task is executing")
+ }
+
+ db := ap.fp.DB()
+
+ tasksInfo, err := ap.fp.getTasksInfo(ctx, taskID)
+ if err != nil {
+ logger.WithError(err).Error("failed to get tasks info")
+ return fmt.Errorf("failed to get tasks info: %w", err)
+ }
+
+ if tasksInfo.Task.ID != taskID {
+ logger.Error("task is not found in the flow tasks")
+
+ if len(tasksInfo.Tasks) == 0 {
+ logger.Warn("no tasks found for the flow")
+ return fmt.Errorf("task ID %d not found: the flow has no tasks yet; submit input to create the first task", taskID)
+ }
+
+ return fmt.Errorf("task ID %d not found in this flow", taskID)
+ }
+
+ subtasksInfo := ap.fp.getSubtasksInfo(taskID, tasksInfo.Subtasks)
+
+ // The current active subtask is normally untouchable by a patch.
+ // We include it only when the agent explicitly references it by ID — meaning
+ // it consciously wants to remove or modify it, accepting the state reset to created.
+ patchableSubs := make([]database.Subtask, 0, len(subtasksInfo.Planned)+1)
+
+ if subtasksInfo.Subtask != nil && slices.ContainsFunc(patch.Operations, func(op tools.SubtaskOperation) bool {
+ return op.ID != nil && *op.ID == subtasksInfo.Subtask.ID
+ }) {
+ patchableSubs = append(patchableSubs, *subtasksInfo.Subtask)
+ }
+
+ patchableSubs = append(patchableSubs, subtasksInfo.Planned...)
+
+ logger.WithField("patchable_count", len(patchableSubs)).Debug("built patchable subtask list")
+
+ result, err := applySubtaskOperations(patchableSubs, patch, logger)
+ if err != nil {
+ return fmt.Errorf("failed to apply subtask operations for task %d: %w", taskID, err)
+ }
+
+ idsToDelete := make([]int64, 0, len(patchableSubs))
+ for _, st := range patchableSubs {
+ idsToDelete = append(idsToDelete, st.ID)
+ }
+
+ if len(idsToDelete) > 0 {
+ if err := db.DeleteSubtasks(ctx, idsToDelete); err != nil {
+ return fmt.Errorf("failed to delete subtasks for task %d: %w", taskID, err)
+ }
+ }
+
+ // result contains only entries that were in patchableSubs (minus removed ones)
+ // plus any new entries from add operations — all safe to create unconditionally.
+ for _, info := range result {
+ if _, err := db.CreateSubtask(ctx, database.CreateSubtaskParams{
+ Status: database.SubtaskStatusCreated,
+ TaskID: taskID,
+ Title: info.Title,
+ Description: info.Description,
+ }); err != nil {
+ return fmt.Errorf("failed to create subtask %q for task %d: %w", info.Title, taskID, err)
+ }
+ }
+
+ subtasksResult := convertSubtaskInfoPatch(result)
+ _, _ = ap.fp.putAgentLog(
+ ctx,
+ database.MsgchainTypeAssistant,
+ database.MsgchainTypePrimaryAgent,
+ patch.Message,
+ ap.fp.subtasksToMarkdown(subtasksResult),
+ &taskID,
+ nil,
+ )
+
+ level := langfuse.ObservationLevelDefault
+ statusMsg := fmt.Sprintf(
+ "patched %d planned subtasks for task %d: %d ops applied",
+ len(result), taskID, len(patch.Operations),
+ )
+
+ _, observation := obs.Observer.NewObservation(ctx)
+ observation.Event(
+ langfuse.WithEventName("patching flow subtasks by assistant"),
+ langfuse.WithEventInput(map[string]any{
+ "task_id": taskID,
+ "operations": patch.Operations,
+ "message": patch.Message,
+ "subtasks": patchableSubs,
+ }),
+ langfuse.WithEventOutput(map[string]any{
+ "subtasks": subtasksResult,
+ }),
+ langfuse.WithEventMetadata(langfuse.Metadata{
+ "provider": ap.fp.Type(),
+ "assistant_id": ap.id,
+ "flow_id": ap.fp.ID(),
+ "msg_chain_id": ap.msgChainID,
+ }),
+ langfuse.WithEventLevel(level),
+ langfuse.WithEventStatus(statusMsg),
+ )
+
+ return nil
+}
diff --git a/backend/pkg/providers/handlers.go b/backend/pkg/providers/handlers.go
index 4a177834..4883e77f 100644
--- a/backend/pkg/providers/handlers.go
+++ b/backend/pkg/providers/handlers.go
@@ -2,6 +2,7 @@ package providers
import (
"context"
+ "crypto/sha256"
"encoding/json"
"fmt"
"strings"
@@ -854,6 +855,14 @@ func (fp *flowProvider) GetSummarizeResultHandler(taskID, subtaskID *int64) tool
ctx, span := obs.Observer.NewSpan(ctx, obs.SpanKindInternal, "providers.flowProvider.getSummarizeResultHandler")
defer span.End()
+ // Return cached summary for identical input without calling the LLM.
+ cacheKey := sha256.Sum256([]byte(result))
+ if fp.summarizerCache != nil {
+ if cached, ok := fp.summarizerCache.Get(cacheKey); ok {
+ return cached, nil
+ }
+ }
+
ctx, observation := obs.Observer.NewObservation(ctx)
summarizerAgent := observation.Agent(
langfuse.WithAgentName("chain summarizer"),
@@ -899,6 +908,10 @@ func (fp *flowProvider) GetSummarizeResultHandler(taskID, subtaskID *int64) tool
langfuse.WithAgentLevel(langfuse.ObservationLevelDebug),
)
+ if fp.summarizerCache != nil {
+ fp.summarizerCache.Add(cacheKey, summary)
+ }
+
return summary, nil
}
}
diff --git a/backend/pkg/providers/helpers_test.go b/backend/pkg/providers/helpers_test.go
index 88a610ca..eb9bd40c 100644
--- a/backend/pkg/providers/helpers_test.go
+++ b/backend/pkg/providers/helpers_test.go
@@ -9,6 +9,7 @@ import (
"pentagi/pkg/cast"
+ lru "github.com/hashicorp/golang-lru/v2/expirable"
"github.com/stretchr/testify/assert"
"github.com/vxcontrol/langchaingo/llms"
)
@@ -198,6 +199,7 @@ func cloneChain(chain []llms.MessageContent) []llms.MessageContent {
func newFlowProvider() *flowProvider {
return &flowProvider{
mx: &sync.RWMutex{},
+ summarizerCache: lru.NewLRU[[32]byte, string](summarizerCacheMaxSize, nil, summarizerCacheTTL),
callCounter: &atomic.Int64{},
maxGACallsLimit: maxGeneralAgentChainIterations,
maxLACallsLimit: maxLimitedAgentChainIterations,
diff --git a/backend/pkg/providers/performers.go b/backend/pkg/providers/performers.go
index ce76cfbe..d9748a82 100644
--- a/backend/pkg/providers/performers.go
+++ b/backend/pkg/providers/performers.go
@@ -291,7 +291,7 @@ func (fp *flowProvider) performSubtasksRefiner(
logger.WithError(err).Error("failed to unmarshal subtask patch")
return "", fmt.Errorf("failed to unmarshal subtask patch: %w", err)
}
- if err := ValidateSubtaskPatch(subtaskPatch); err != nil {
+ if err := subtaskPatch.Validate(); err != nil {
logger.WithError(err).Error("invalid subtask patch")
return "", fmt.Errorf("invalid subtask patch: %w", err)
}
diff --git a/backend/pkg/providers/provider.go b/backend/pkg/providers/provider.go
index e13abc68..c18680ae 100644
--- a/backend/pkg/providers/provider.go
+++ b/backend/pkg/providers/provider.go
@@ -20,6 +20,7 @@ import (
"pentagi/pkg/templates"
"pentagi/pkg/tools"
+ lru "github.com/hashicorp/golang-lru/v2/expirable"
"github.com/sirupsen/logrus"
"github.com/vxcontrol/langchaingo/llms"
"github.com/vxcontrol/langchaingo/llms/reasoning"
@@ -34,7 +35,7 @@ const (
msgGeneratorSizeLimit = 150 * 1024 // 150 KB
msgRefinerSizeLimit = 100 * 1024 // 100 KB
msgReporterSizeLimit = 100 * 1024 // 100 KB
- msgSummarizerLimit = 16 * 1024 // 16 KB
+ msgSummarizerLimit = 32 * 1024 // 32 KB
)
const textTruncateMessage = "\n\n[...truncated]"
@@ -153,6 +154,8 @@ type flowProvider struct {
summarizer csum.Summarizer
+ summarizerCache *lru.LRU[[32]byte, string]
+
maxGACallsLimit int
maxLACallsLimit int
buildMonitor executionMonitorBuilder
diff --git a/backend/pkg/providers/providers.go b/backend/pkg/providers/providers.go
index 9a9a5a7d..47b9cdc6 100644
--- a/backend/pkg/providers/providers.go
+++ b/backend/pkg/providers/providers.go
@@ -36,6 +36,7 @@ import (
"pentagi/pkg/templates"
"pentagi/pkg/tools"
+ lru "github.com/hashicorp/golang-lru/v2/expirable"
"github.com/sirupsen/logrus"
)
@@ -43,6 +44,11 @@ const deltaCallCounter = 10000
const defaultTestParallelWorkersNumber = 16
+const (
+ summarizerCacheMaxSize = 1000
+ summarizerCacheTTL = 4 * time.Hour
+)
+
const pentestDockerImage = "vxcontrol/kali-linux"
type ProviderController interface {
@@ -460,6 +466,7 @@ func (pc *providerController) NewFlowProvider(
prompter: prompter,
executor: executor,
summarizer: pc.summarizerAgent,
+ summarizerCache: lru.NewLRU[[32]byte, string](summarizerCacheMaxSize, nil, summarizerCacheTTL),
Provider: prv,
maxGACallsLimit: pc.cfg.MaxGeneralAgentToolCalls,
maxLACallsLimit: pc.cfg.MaxLimitedAgentToolCalls,
@@ -510,6 +517,7 @@ func (pc *providerController) LoadFlowProvider(
prompter: prompter,
executor: executor,
summarizer: pc.summarizerAgent,
+ summarizerCache: lru.NewLRU[[32]byte, string](summarizerCacheMaxSize, nil, summarizerCacheTTL),
Provider: prv,
maxGACallsLimit: pc.cfg.MaxGeneralAgentToolCalls,
maxLACallsLimit: pc.cfg.MaxLimitedAgentToolCalls,
@@ -604,6 +612,7 @@ func (pc *providerController) NewAssistantProvider(
executor: executor,
streamCb: streamCb,
summarizer: pc.summarizerAgent,
+ summarizerCache: lru.NewLRU[[32]byte, string](summarizerCacheMaxSize, nil, summarizerCacheTTL),
Provider: prv,
maxGACallsLimit: pc.cfg.MaxGeneralAgentToolCalls,
maxLACallsLimit: pc.cfg.MaxLimitedAgentToolCalls,
@@ -657,6 +666,7 @@ func (pc *providerController) LoadAssistantProvider(
executor: executor,
streamCb: streamCb,
summarizer: pc.summarizerAgent,
+ summarizerCache: lru.NewLRU[[32]byte, string](summarizerCacheMaxSize, nil, summarizerCacheTTL),
Provider: prv,
maxGACallsLimit: pc.cfg.MaxGeneralAgentToolCalls,
maxLACallsLimit: pc.cfg.MaxLimitedAgentToolCalls,
diff --git a/backend/pkg/providers/subtask_patch.go b/backend/pkg/providers/subtask_patch.go
index 1857ab59..ae468452 100644
--- a/backend/pkg/providers/subtask_patch.go
+++ b/backend/pkg/providers/subtask_patch.go
@@ -335,36 +335,3 @@ func fixSubtaskPatch(planned []database.Subtask, patch tools.SubtaskPatch) tools
return newPatch
}
-
-// ValidateSubtaskPatch validates the operations in a SubtaskPatch
-func ValidateSubtaskPatch(patch tools.SubtaskPatch) error {
- for i, op := range patch.Operations {
- switch op.Op {
- case tools.SubtaskOpAdd:
- if op.Title == "" {
- return fmt.Errorf("operation %d: add requires title", i)
- }
- if op.Description == "" {
- return fmt.Errorf("operation %d: add requires description", i)
- }
- case tools.SubtaskOpRemove:
- if op.ID == nil {
- return fmt.Errorf("operation %d: remove requires id", i)
- }
- case tools.SubtaskOpModify:
- if op.ID == nil {
- return fmt.Errorf("operation %d: modify requires id", i)
- }
- if op.Title == "" && op.Description == "" {
- return fmt.Errorf("operation %d: modify requires at least title or description", i)
- }
- case tools.SubtaskOpReorder:
- if op.ID == nil {
- return fmt.Errorf("operation %d: reorder requires id", i)
- }
- default:
- return fmt.Errorf("operation %d: unknown operation type %q", i, op.Op)
- }
- }
- return nil
-}
diff --git a/backend/pkg/providers/subtask_patch_test.go b/backend/pkg/providers/subtask_patch_test.go
index 56fb0f9a..d3724d37 100644
--- a/backend/pkg/providers/subtask_patch_test.go
+++ b/backend/pkg/providers/subtask_patch_test.go
@@ -612,7 +612,7 @@ func TestValidateSubtaskPatch_ValidOperations(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- err := ValidateSubtaskPatch(tt.patch)
+ err := tt.patch.Validate()
assert.NoError(t, err)
})
}
@@ -693,7 +693,7 @@ func TestValidateSubtaskPatch_InvalidOperations(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- err := ValidateSubtaskPatch(tt.patch)
+ err := tt.patch.Validate()
require.Error(t, err)
assert.Contains(t, err.Error(), tt.expectedError)
})
diff --git a/backend/pkg/templates/prompts/assistant.tmpl b/backend/pkg/templates/prompts/assistant.tmpl
index d64f5412..4c3302aa 100644
--- a/backend/pkg/templates/prompts/assistant.tmpl
+++ b/backend/pkg/templates/prompts/assistant.tmpl
@@ -266,6 +266,82 @@ IMPORTANT:
- Mentor may review progress periodically and help prevent loops and incorrect approaches
</mentor_availability>
+{{if .FlowManagerEnabled}}
+## AUTOMATION FLOW MANAGEMENT
+
+You have tools to observe and control the automation flow running alongside this session.
+
+<flow_status_reference>
+Flow states and what each allows:
+
+- **running** — a task is actively executing subtasks; only `{{.GetFlowStatusToolName}}` and `{{.StopFlowToolName}}` are available
+- **waiting (no tasks)** — the flow exists but no tasks have been created yet; only `{{.SubmitFlowInputToolName}}` is meaningful here — it creates the first task
+- **waiting (ask checkpoint)** — a subtask paused at an `ask` call and is waiting for the user's reply; `{{.SubmitFlowInputToolName}}` delivers that reply and execution resumes
+- **waiting (between tasks)** — all current subtasks are finished; `{{.SubmitFlowInputToolName}}` starts a new task, or you can first adjust the remaining planned subtasks with `{{.PatchFlowSubtasksToolName}}`
+- **finished / failed** — terminal; inspection via `{{.GetFlowStatusToolName}}` is still available but no further automation will start
+</flow_status_reference>
+
+<flow_management_tools>
+**`{{.GetFlowStatusToolName}}`** — query the flow state at any time.
+- `detail=summary` — overall health: status, task/subtask counts, active task and subtask IDs
+- `detail=tasks` — all tasks with ID, status, title; add `verbose=true` for inputs and results
+- `detail=subtasks` — all subtasks, optionally filtered with `task_id`; add `verbose=true` for descriptions and results
+- `detail=running` — full Task→Subtask execution chain with task input, subtask description, and recent agent messages; add `verbose=true` for 50 messages and execution context
+- `detail=planned` — subtasks with status `created` (not yet started), optionally filtered with `task_id`; add `verbose=true` for full descriptions
+
+**`{{.StopFlowToolName}}`** — cancel the currently running task.
+- Only effective when flow is `running`; returns an informational message when already `waiting`
+- The response includes the actual state the flow reached after the stop — rely on that, no extra status check needed
+
+**`{{.SubmitFlowInputToolName}}`** — deliver text to the flow; rejected when flow is `running`.
+- Ask checkpoint → delivers the user's reply; the subtask resumes immediately
+- No tasks / between tasks → creates a new task via the full generator cycle; write a self-contained description with all context
+
+**`{{.PatchFlowSubtasksToolName}}`** — rewrite the planned subtask list for a task; rejected when flow is `running`.
+- Requires an existing task — cannot be used when there are no tasks yet
+- Targets subtasks with status `created`; you can also explicitly include the ID of the currently active subtask to modify or remove it, which resets it to `created`
+- After patching, the response lists the new subtask IDs — use those IDs for any subsequent references
+- Obtain the `task_id` via `{{.GetFlowStatusToolName}}` with `detail=tasks`
+</flow_management_tools>
+
+<flow_management_protocols>
+**User asks what is happening in the automation:**
+1. `{{.GetFlowStatusToolName}}` with `detail=summary`
+2. Drill deeper as needed: `detail=running` for the active chain, `detail=tasks` or `detail=subtasks` for history
+
+**User asks what was found or accomplished:**
+1. `{{.GetFlowStatusToolName}}` with `detail=subtasks` to see completed work with results
+2. Use `{{.MemoristToolName}}` to retrieve findings stored in long-term memory
+
+**User asks to stop the automation:**
+1. Call `{{.StopFlowToolName}}` — the response confirms whether the flow reached `waiting` state
+
+**User wants to send new instructions while automation is running:**
+1. `{{.GetFlowStatusToolName}}` with `detail=summary` to confirm current state
+2. If `running`: explain the flow is active; offer to stop it
+3. If `waiting`: use `{{.SubmitFlowInputToolName}}` directly
+
+**User wants to modify the execution plan:**
+1. If `running`: call `{{.StopFlowToolName}}` and confirm the response shows `waiting`
+2. If there are no tasks yet: use `{{.SubmitFlowInputToolName}}` to create the first task instead — `{{.PatchFlowSubtasksToolName}}` requires an existing task
+3. `{{.GetFlowStatusToolName}}` with `detail=tasks` → obtain the target `task_id`
+4. `{{.GetFlowStatusToolName}}` with `detail=planned` and `task_id=N` → review planned subtasks with their current IDs
+5. `{{.PatchFlowSubtasksToolName}}` with the desired operations
+6. `{{.SubmitFlowInputToolName}}` to trigger execution of the updated plan
+
+**Choosing the right mode for `{{.SubmitFlowInputToolName}}`:**
+- **New task**: write a complete, self-contained description — goals, targets, constraints, scope — because the generator decomposes it into subtasks without asking follow-up questions
+- **Answer to ask checkpoint**: send only the direct reply to the agent's question; do not mix in unrelated instructions
+</flow_management_protocols>
+
+<flow_management_constraints>
+- `{{.SubmitFlowInputToolName}}` and `{{.PatchFlowSubtasksToolName}}` are rejected when flow is `running` — stop first
+- `{{.PatchFlowSubtasksToolName}}` requires at least one existing task — if no tasks exist yet, use `{{.SubmitFlowInputToolName}}` to create the first one
+- `{{.PatchFlowSubtasksToolName}}` recreates the planned subtask list with new IDs — always use the IDs from the response for any further operations on those subtasks
+- `finished` and `failed` are terminal states — no tool can restart the flow; report the final state to the user
+</flow_management_constraints>
+{{end}}
+
## COMPLETION REQUIREMENTS
1. You MUST communicate with the user in their preferred language ({{.Lang}})
diff --git a/backend/pkg/templates/templates.go b/backend/pkg/templates/templates.go
index 5ac89414..8ad23038 100644
--- a/backend/pkg/templates/templates.go
+++ b/backend/pkg/templates/templates.go
@@ -114,6 +114,11 @@ var PromptVariables = map[PromptType][]string{
"ExecutionContext",
"Lang",
"CurrentTime",
+ "FlowManagerEnabled",
+ "GetFlowStatusToolName",
+ "StopFlowToolName",
+ "SubmitFlowInputToolName",
+ "PatchFlowSubtasksToolName",
},
PromptTypePentester: {
"HackResultToolName",
diff --git a/backend/pkg/templates/validator/testdata.go b/backend/pkg/templates/validator/testdata.go
index b1d3f27c..15385c45 100644
--- a/backend/pkg/templates/validator/testdata.go
+++ b/backend/pkg/templates/validator/testdata.go
@@ -62,6 +62,10 @@ func CreateDummyTemplateData() map[string]any {
"SubtaskPatchToolName": tools.SubtaskPatchToolName,
"AskUserToolName": tools.AskUserToolName,
"AskUserEnabled": true,
+ "GetFlowStatusToolName": tools.GetFlowStatusToolName,
+ "StopFlowToolName": tools.StopFlowToolName,
+ "SubmitFlowInputToolName": tools.SubmitFlowInputToolName,
+ "PatchFlowSubtasksToolName": tools.PatchFlowSubtasksToolName,
// Summarization related - using constants from proper packages
"SummarizationToolName": cast.SummarizationToolName,
@@ -70,6 +74,7 @@ func CreateDummyTemplateData() map[string]any {
// Boolean flags
"UseAgents": true,
"IsDefaultDockerImage": false,
+ "FlowManagerEnabled": true,
// Docker and environment
"DockerImage": "vxcontrol/kali-linux:latest",
diff --git a/backend/pkg/tools/args.go b/backend/pkg/tools/args.go
index a04ad05d..6d242b27 100644
--- a/backend/pkg/tools/args.go
+++ b/backend/pkg/tools/args.go
@@ -240,6 +240,77 @@ type HackResult struct {
Message string `json:"message" jsonschema:"required,title=Hack result message" jsonschema_description:"Not so long message with the result and path to reach goal to send to the user in user's language only"`
}
+// FlowStatusDetail controls the level of detail returned by get_flow_status.
+type FlowStatusDetail string
+
+const (
+ FlowStatusDetailSummary FlowStatusDetail = "summary"
+ FlowStatusDetailTasks FlowStatusDetail = "tasks"
+ FlowStatusDetailSubtasks FlowStatusDetail = "subtasks"
+ FlowStatusDetailRunning FlowStatusDetail = "running"
+ FlowStatusDetailPlanned FlowStatusDetail = "planned"
+)
+
+// GetFlowStatusAction defines arguments for the get_flow_status tool.
+type GetFlowStatusAction struct {
+ Detail FlowStatusDetail `json:"detail" jsonschema:"required,enum=summary,enum=tasks,enum=subtasks,enum=running,enum=planned" jsonschema_description:"Level of detail: 'summary' - flow health snapshot with status and counts; 'tasks' - all tasks with ID/status/title; 'subtasks' - all subtasks optionally filtered by task_id; 'running' - full Task→Subtask execution chain including task input and recent agent messages; 'planned' - only subtasks with status 'created' (not yet started), optionally filtered by task_id"`
+ TaskID *Int64 `json:"task_id,omitempty" jsonschema:"title=Task ID,type=integer" jsonschema_description:"Optional task ID filter. Applies to detail=subtasks and detail=planned to narrow results to a specific task."`
+ Verbose Bool `json:"verbose,omitempty" jsonschema:"type=boolean" jsonschema_description:"Set to true for deeper investigation: includes descriptions, inputs, results, and execution context per entry; shows up to 50 recent agent messages instead of 10."`
+ Message string `json:"message" jsonschema:"required,title=Status message" jsonschema_description:"Short description of what you are requesting, to show the user."`
+}
+
+// StopFlowAction defines arguments for the stop_flow tool.
+type StopFlowAction struct {
+ Reason string `json:"reason" jsonschema:"required" jsonschema_description:"Brief explanation of why the automation is being stopped. Included in logs and shown to the user."`
+ Message string `json:"message" jsonschema:"required,title=Stop message" jsonschema_description:"Short message to show the user explaining that the automation is being stopped."`
+}
+
+// SubmitFlowInputAction defines arguments for the submit_flow_input tool.
+type SubmitFlowInputAction struct {
+ Input string `json:"input" jsonschema:"required" jsonschema_description:"Text to deliver to the automation flow. If a subtask is waiting at an 'ask' checkpoint, this is delivered as the user's answer and execution resumes. If the flow is waiting with no active subtask, this becomes the goal for a new task — include complete context, targets, and constraints because the generator will decompose it into subtasks without further clarification."`
+ Message string `json:"message" jsonschema:"required,title=Input message" jsonschema_description:"Short message to show the user describing what is being submitted to the automation."`
+}
+
+// PatchFlowSubtasksAction defines arguments for the patch_flow_subtasks tool.
+type PatchFlowSubtasksAction struct {
+ TaskID int64 `json:"task_id" jsonschema:"required,type=integer" jsonschema_description:"ID of the task whose subtask plan to modify. Obtain this from get_flow_status with detail='tasks'."`
+ Operations []SubtaskOperation `json:"operations" jsonschema:"required" jsonschema_description:"Delta operations to apply: add (insert new subtask at a position), remove (delete by ID), modify (update title/description), reorder (move to different position). Empty array returns the current plan unchanged."`
+ Message string `json:"message" jsonschema:"required,title=Patch summary" jsonschema_description:"Short message to show the user describing what changes are being made to the plan."`
+}
+
+// ValidateSubtaskPatch validates the operations in a SubtaskPatch
+func (sp SubtaskPatch) Validate() error {
+ for i, op := range sp.Operations {
+ switch op.Op {
+ case SubtaskOpAdd:
+ if op.Title == "" {
+ return fmt.Errorf("operation %d: add requires title", i)
+ }
+ if op.Description == "" {
+ return fmt.Errorf("operation %d: add requires description", i)
+ }
+ case SubtaskOpRemove:
+ if op.ID == nil {
+ return fmt.Errorf("operation %d: remove requires id", i)
+ }
+ case SubtaskOpModify:
+ if op.ID == nil {
+ return fmt.Errorf("operation %d: modify requires id", i)
+ }
+ if op.Title == "" && op.Description == "" {
+ return fmt.Errorf("operation %d: modify requires at least title or description", i)
+ }
+ case SubtaskOpReorder:
+ if op.ID == nil {
+ return fmt.Errorf("operation %d: reorder requires id", i)
+ }
+ default:
+ return fmt.Errorf("operation %d: unknown operation type %q", i, op.Op)
+ }
+ }
+ return nil
+}
+
type Bool bool
func (b *Bool) UnmarshalJSON(data []byte) error {
diff --git a/backend/pkg/tools/flow_manager.go b/backend/pkg/tools/flow_manager.go
new file mode 100644
index 00000000..c28d415e
--- /dev/null
+++ b/backend/pkg/tools/flow_manager.go
@@ -0,0 +1,841 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "pentagi/pkg/database"
+)
+
+// flowStatusTool implements get_flow_status — reads flow/task/subtask state from DB.
+type flowStatusTool struct {
+ flowID int64
+ db database.Querier
+ summarizer SummarizeHandler
+}
+
+func NewFlowStatusTool(flowID int64, db database.Querier, summarizer SummarizeHandler) *flowStatusTool {
+ return &flowStatusTool{flowID: flowID, db: db, summarizer: summarizer}
+}
+
+const (
+ msgLogLimitNormal = 10
+ msgLogLimitVerbose = 50
+ flowOperationTimeout = 15 * time.Second
+ taskReadyPollInterval = 5 * time.Second
+ taskReadyPollTimeout = 2 * time.Minute
+ msgLogsLimit = 16 * 1024 // 16 KB
+ summaryLimit = 32 * 1024 // 32 KB
+ taskListLimit = 32 * 1024 // 32 KB
+ subtasksListLimit = 48 * 1024 // 48 KB
+ plannedListLimit = 32 * 1024 // 32 KB
+ runningInfoLimit = 48 * 1024 // 48 KB
+ inputLimit = 8 * 1024 // 8 KB
+ descriptionLimit = 4 * 1024 // 4 KB
+ resultLimit = 8 * 1024 // 8 KB
+ summarizationLimit = 128 * 1024 // 128 KB hard limit
+)
+
+func (t *flowStatusTool) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+ var action GetFlowStatusAction
+ if err := json.Unmarshal(args, &action); err != nil {
+ return "", fmt.Errorf("failed to parse get_flow_status args: %w", err)
+ }
+
+ verbose := action.Verbose.Bool()
+
+ switch action.Detail {
+ case FlowStatusDetailSummary:
+ return t.buildSummary(ctx, verbose)
+ case FlowStatusDetailTasks:
+ return t.buildTasksList(ctx, verbose)
+ case FlowStatusDetailSubtasks:
+ return t.buildSubtasksList(ctx, action.TaskID.PtrInt64(), verbose)
+ case FlowStatusDetailRunning:
+ return t.buildRunningInfo(ctx, verbose)
+ case FlowStatusDetailPlanned:
+ return t.buildPlannedList(ctx, action.TaskID.PtrInt64(), verbose)
+ default:
+ return "", fmt.Errorf("unknown detail level %q; use one of: summary, tasks, subtasks, running, planned", action.Detail)
+ }
+}
+
+func (t *flowStatusTool) buildSummary(ctx context.Context, verbose bool) (string, error) {
+ tasks, err := t.db.GetFlowTasks(ctx, t.flowID)
+ if err != nil {
+ return "", fmt.Errorf("failed to get flow tasks: %w", err)
+ }
+
+ subtasks, err := t.db.GetFlowSubtasks(ctx, t.flowID)
+ if err != nil {
+ return "", fmt.Errorf("failed to get flow subtasks: %w", err)
+ }
+
+ taskCounts := map[string]int{"created": 0, "running": 0, "waiting": 0, "finished": 0, "failed": 0}
+ var activeTask *database.Task
+ for i, task := range tasks {
+ taskCounts[string(task.Status)]++
+ if task.Status == database.TaskStatusRunning || task.Status == database.TaskStatusWaiting {
+ activeTask = &tasks[i]
+ }
+ }
+
+ stCounts := map[string]int{"created": 0, "running": 0, "waiting": 0, "finished": 0, "failed": 0}
+ var activeST *database.Subtask
+ for i, st := range subtasks {
+ stCounts[string(st.Status)]++
+ if st.Status == database.SubtaskStatusRunning || st.Status == database.SubtaskStatusWaiting {
+ activeST = &subtasks[i]
+ }
+ }
+
+ sb := &strings.Builder{}
+ fmt.Fprintf(sb, "Flow ID: %d\n", t.flowID)
+ fmt.Fprintf(sb, "Flow status: %s\n", inferFlowStatus(tasks))
+ fmt.Fprintf(sb, "Tasks — total: %d, running: %d, waiting: %d, finished: %d, failed: %d, planned: %d\n",
+ len(tasks), taskCounts["running"], taskCounts["waiting"], taskCounts["finished"], taskCounts["failed"], taskCounts["created"])
+ fmt.Fprintf(sb, "Subtasks — total: %d, running: %d, waiting: %d, finished: %d, failed: %d, planned: %d\n",
+ len(subtasks), stCounts["running"], stCounts["waiting"], stCounts["finished"], stCounts["failed"], stCounts["created"])
+
+ if activeTask != nil {
+ fmt.Fprintf(sb, "\nActive task: ID=%-6d | %-8s | %s\n", activeTask.ID, activeTask.Status, activeTask.Title)
+ if verbose && activeTask.Input != "" {
+ input, err := t.getInputText(ctx, activeTask.Input)
+ if err != nil {
+ return "", fmt.Errorf("failed to get active task input: %w", err)
+ }
+ fmt.Fprintf(sb, " Input: %s\n", input)
+ }
+ }
+ if activeST != nil {
+ fmt.Fprintf(sb, "Active subtask: ID=%-6d | %-8s | %s\n", activeST.ID, activeST.Status, activeST.Title)
+ if verbose && activeST.Description != "" {
+ description, err := t.getDescriptionText(ctx, activeST.Description)
+ if err != nil {
+ return "", fmt.Errorf("failed to get active subtask description: %w", err)
+ }
+ fmt.Fprintf(sb, " Description: %s\n", description)
+ }
+ }
+
+ if len(tasks) == 0 {
+ fmt.Fprintf(sb, "\nNo tasks yet. Flow is waiting for first input.\n")
+ }
+
+ summary := sb.String()
+ if t.summarizer != nil && len(summary) > summaryLimit {
+ summary, err = t.summarizer(ctx, truncateText(summary, summarizationLimit))
+ if err != nil {
+ return "", fmt.Errorf("failed to summarize summary: %w", err)
+ }
+ }
+
+ return summary, nil
+}
+
+func (t *flowStatusTool) buildTasksList(ctx context.Context, verbose bool) (string, error) {
+ tasks, err := t.db.GetFlowTasks(ctx, t.flowID)
+ if err != nil {
+ return "", fmt.Errorf("failed to get flow tasks: %w", err)
+ }
+
+ if len(tasks) == 0 {
+ return "No tasks found for this flow.", nil
+ }
+
+ sb := &strings.Builder{}
+ fmt.Fprintf(sb, "Tasks for flow %d:\n\n", t.flowID)
+ for _, task := range tasks {
+ fmt.Fprintf(sb, "Task ID: %d | Status: %s | Title: %s\n", task.ID, task.Status, task.Title)
+ if verbose {
+ if task.Input != "" {
+ input, err := t.getInputText(ctx, task.Input)
+ if err != nil {
+ return "", fmt.Errorf("failed to get task input: %w", err)
+ }
+ fmt.Fprintf(sb, " Input: %s\n", input)
+ }
+ if task.Result != "" {
+ result, err := t.getResultText(ctx, task.Result)
+ if err != nil {
+ return "", fmt.Errorf("failed to get task result: %w", err)
+ }
+ fmt.Fprintf(sb, " Result: %s\n", result)
+ }
+ }
+ }
+
+ taskList := sb.String()
+ if t.summarizer != nil && len(taskList) > taskListLimit {
+ taskList, err = t.summarizer(ctx, truncateText(taskList, summarizationLimit))
+ if err != nil {
+ return "", fmt.Errorf("failed to summarize task list: %w", err)
+ }
+ }
+
+ return taskList, nil
+}
+
+func (t *flowStatusTool) buildSubtasksList(ctx context.Context, taskID *int64, verbose bool) (string, error) {
+ var subtasks []database.Subtask
+ var err error
+
+ if taskID != nil && *taskID > 0 {
+ subtasks, err = t.db.GetFlowTaskSubtasks(ctx, database.GetFlowTaskSubtasksParams{
+ FlowID: t.flowID,
+ TaskID: *taskID,
+ })
+ } else {
+ subtasks, err = t.db.GetFlowSubtasks(ctx, t.flowID)
+ }
+
+ if err != nil {
+ return "", fmt.Errorf("failed to get subtasks: %w", err)
+ }
+
+ if len(subtasks) == 0 {
+ return "No subtasks found.", nil
+ }
+
+ sb := &strings.Builder{}
+ if taskID != nil && *taskID > 0 {
+ fmt.Fprintf(sb, "Subtasks for task %d:\n\n", *taskID)
+ } else {
+ fmt.Fprintf(sb, "All subtasks for flow %d:\n\n", t.flowID)
+ }
+ for _, st := range subtasks {
+ fmt.Fprintf(sb, "Subtask ID: %d | Task ID: %d | Status: %s | Title: %s\n",
+ st.ID, st.TaskID, st.Status, st.Title)
+ if verbose {
+ if st.Description != "" {
+ description, err := t.getDescriptionText(ctx, st.Description)
+ if err != nil {
+ return "", fmt.Errorf("failed to get subtask description: %w", err)
+ }
+ fmt.Fprintf(sb, " Description: %s\n", description)
+ }
+ if st.Result != "" {
+ result, err := t.getResultText(ctx, st.Result)
+ if err != nil {
+ return "", fmt.Errorf("failed to get subtask result: %w", err)
+ }
+ fmt.Fprintf(sb, " Result: %s\n", result)
+ }
+ }
+ }
+
+ subtasksList := sb.String()
+ if t.summarizer != nil && len(subtasksList) > subtasksListLimit {
+ subtasksList, err = t.summarizer(ctx, truncateText(subtasksList, summarizationLimit))
+ if err != nil {
+ return "", fmt.Errorf("failed to summarize subtasks list: %w", err)
+ }
+ }
+
+ return subtasksList, nil
+}
+
+func (t *flowStatusTool) buildRunningInfo(ctx context.Context, verbose bool) (string, error) {
+ subtasks, err := t.db.GetFlowSubtasks(ctx, t.flowID)
+ if err != nil {
+ return "", fmt.Errorf("failed to get subtasks: %w", err)
+ }
+
+ for _, st := range subtasks {
+ if st.Status != database.SubtaskStatusRunning && st.Status != database.SubtaskStatusWaiting {
+ continue
+ }
+
+ // Load the parent task to give the full Task→Subtask chain.
+ tasks, err := t.db.GetFlowTasks(ctx, t.flowID)
+ if err != nil {
+ return "", fmt.Errorf("failed to get flow tasks: %w", err)
+ }
+ var activeTask *database.Task
+ for i, task := range tasks {
+ if task.ID == st.TaskID {
+ activeTask = &tasks[i]
+ break
+ }
+ }
+
+ sb := &strings.Builder{}
+
+ if activeTask != nil {
+ fmt.Fprintf(sb, "=== Active Task ===\n")
+ fmt.Fprintf(sb, "Task ID: %d | Status: %s | Title: %s\n", activeTask.ID, activeTask.Status, activeTask.Title)
+ if activeTask.Input != "" {
+ input, err := t.getInputText(ctx, activeTask.Input)
+ if err != nil {
+ return "", fmt.Errorf("failed to get active task input: %w", err)
+ }
+ fmt.Fprintf(sb, "Input:\n%s\n", input)
+ }
+ if activeTask.Result != "" {
+ result, err := t.getResultText(ctx, activeTask.Result)
+ if err != nil {
+ return "", fmt.Errorf("failed to get active task result: %w", err)
+ }
+ fmt.Fprintf(sb, "Result so far:\n%s\n", result)
+ }
+ }
+
+ fmt.Fprintf(sb, "\n=== Active Subtask ===\n")
+ fmt.Fprintf(sb, "Subtask ID: %d | Status: %s | Title: %s\n", st.ID, st.Status, st.Title)
+ description, err := t.getDescriptionText(ctx, st.Description)
+ if err != nil {
+ return "", fmt.Errorf("failed to get subtask description: %w", err)
+ }
+ fmt.Fprintf(sb, "Description:\n%s\n", description)
+ if st.Result != "" {
+ result, err := t.getResultText(ctx, st.Result)
+ if err != nil {
+ return "", fmt.Errorf("failed to get subtask result: %w", err)
+ }
+ fmt.Fprintf(sb, "Result so far:\n%s\n", result)
+ }
+ if verbose && st.Context != "" {
+ execContext, err := t.getDescriptionText(ctx, st.Context)
+ if err != nil {
+ return "", fmt.Errorf("failed to get subtask context: %w", err)
+ }
+ fmt.Fprintf(sb, "\nExecution context:\n%s\n", execContext)
+ }
+ if st.Status == database.SubtaskStatusWaiting {
+ fmt.Fprintf(sb, "\nNote: subtask is waiting for user input (ask state).\n")
+ fmt.Fprintf(sb, "Use %s to provide the answer and resume execution.\n", SubmitFlowInputToolName)
+ }
+
+ msgLimit := msgLogLimitNormal
+ if verbose {
+ msgLimit = msgLogLimitVerbose
+ }
+ msgLogs, err := t.appendSubtaskMsgLogs(ctx, st.ID, msgLimit)
+ if err != nil {
+ return "", fmt.Errorf("failed to get subtask msg logs: %w", err)
+ }
+ sb.WriteString(msgLogs)
+
+ runningInfo := sb.String()
+ if t.summarizer != nil && len(runningInfo) > runningInfoLimit {
+ runningInfo, err = t.summarizer(ctx, truncateText(runningInfo, summarizationLimit))
+ if err != nil {
+ return "", fmt.Errorf("failed to summarize running info: %w", err)
+ }
+ }
+
+ return runningInfo, nil
+ }
+
+ return "No running or waiting subtask found. Flow is idle (waiting for next input).", nil
+}
+
+func (t *flowStatusTool) buildPlannedList(ctx context.Context, taskID *int64, verbose bool) (string, error) {
+ var subtasks []database.Subtask
+ var err error
+
+ if taskID != nil && *taskID > 0 {
+ subtasks, err = t.db.GetTaskPlannedSubtasks(ctx, *taskID)
+ if err != nil {
+ return "", fmt.Errorf("failed to get planned subtasks: %w", err)
+ }
+ } else {
+ all, err2 := t.db.GetFlowSubtasks(ctx, t.flowID)
+ if err2 != nil {
+ return "", fmt.Errorf("failed to get flow subtasks: %w", err2)
+ }
+ for _, st := range all {
+ if st.Status == database.SubtaskStatusCreated {
+ subtasks = append(subtasks, st)
+ }
+ }
+ }
+
+ if len(subtasks) == 0 {
+ return "No planned (created) subtasks found. All subtasks have been started or completed.", nil
+ }
+
+ sb := &strings.Builder{}
+ if taskID != nil && *taskID > 0 {
+ fmt.Fprintf(sb, "Planned subtasks for task %d:\n\n", *taskID)
+ } else {
+ fmt.Fprintf(sb, "All planned subtasks for flow %d:\n\n", t.flowID)
+ }
+ for _, st := range subtasks {
+ fmt.Fprintf(sb, "Subtask ID: %d | Task ID: %d | Title: %s\n", st.ID, st.TaskID, st.Title)
+ if st.Description != "" {
+ if verbose {
+ description, err := t.getDescriptionText(ctx, st.Description)
+ if err != nil {
+ return "", fmt.Errorf("failed to get subtask description: %w", err)
+ }
+ fmt.Fprintf(sb, " Description: %s\n", description)
+ } else {
+ fmt.Fprintf(sb, " Description: %s\n", truncateText(st.Description, 200))
+ }
+ }
+ }
+
+ plannedList := sb.String()
+ if t.summarizer != nil && len(plannedList) > plannedListLimit {
+ plannedList, err = t.summarizer(ctx, truncateText(plannedList, summarizationLimit))
+ if err != nil {
+ return "", fmt.Errorf("failed to summarize planned list: %w", err)
+ }
+ }
+
+ return plannedList, nil
+}
+
+// appendSubtaskMsgLogs appends the last `limit` agent messages for a subtask to the builder.
+func (t *flowStatusTool) appendSubtaskMsgLogs(ctx context.Context, subtaskID int64, limit int) (string, error) {
+ nullID := database.Int64ToNullInt64(&subtaskID)
+ logs, err := t.db.GetSubtaskMsgLogs(ctx, nullID)
+ if err != nil {
+ return "", fmt.Errorf("failed to get subtask msg logs: %w", err)
+ }
+
+ if len(logs) == 0 {
+ return fmt.Sprintf("No agent messages found for subtask %d.", subtaskID), nil
+ }
+
+ start := 0
+ if len(logs) > limit {
+ start = len(logs) - limit
+ }
+ logs = logs[start:]
+
+ sb := &strings.Builder{}
+ fmt.Fprintf(sb, "\n=== Last %d agent messages ===\n", len(logs))
+ for _, log := range logs {
+ fmt.Fprintf(sb, "[%s] %s\n", log.Type, truncateText(log.Message, 1024))
+ if log.Result != "" {
+ fmt.Fprintf(sb, " → %s\n", truncateText(log.Result, 300))
+ }
+ }
+
+ logsList := sb.String()
+ if t.summarizer != nil && len(logsList) > msgLogsLimit {
+ logsList, err = t.summarizer(ctx, truncateText(logsList, summarizationLimit))
+ if err != nil {
+ return "", fmt.Errorf("failed to summarize msg logs: %w", err)
+ }
+ }
+
+ return logsList, nil
+}
+
+func (t *flowStatusTool) getInputText(ctx context.Context, input string) (string, error) {
+ if input == "" {
+ return "", nil
+ }
+
+ if t.summarizer != nil && len(input) > 2*inputLimit {
+ summarized, err := t.summarizer(ctx, truncateText(input, summarizationLimit))
+ if err != nil {
+ return "", fmt.Errorf("failed to summarize input: %w", err)
+ }
+ return summarized, nil
+ }
+
+ return truncateText(input, inputLimit), nil
+}
+
+func (t *flowStatusTool) getDescriptionText(ctx context.Context, description string) (string, error) {
+ if description == "" {
+ return "", nil
+ }
+
+ if t.summarizer != nil && len(description) > 2*descriptionLimit {
+ summarized, err := t.summarizer(ctx, truncateText(description, summarizationLimit))
+ if err != nil {
+ return "", fmt.Errorf("failed to summarize description: %w", err)
+ }
+ return summarized, nil
+ }
+
+ return truncateText(description, descriptionLimit), nil
+}
+
+func (t *flowStatusTool) getResultText(ctx context.Context, result string) (string, error) {
+ if result == "" {
+ return "", nil
+ }
+
+ if t.summarizer != nil && len(result) > 2*resultLimit {
+ summarized, err := t.summarizer(ctx, truncateText(result, summarizationLimit))
+ if err != nil {
+ return "", fmt.Errorf("failed to summarize result: %w", err)
+ }
+ return summarized, nil
+ }
+
+ return truncateText(result, resultLimit), nil
+}
+
+// inferFlowStatus derives a human-readable flow status from the task list.
+func inferFlowStatus(tasks []database.Task) string {
+ for _, task := range tasks {
+ if task.Status == database.TaskStatusRunning {
+ return "running"
+ }
+ }
+ for _, task := range tasks {
+ if task.Status == database.TaskStatusWaiting {
+ return "waiting (subtask asking for user input)"
+ }
+ }
+ return "waiting (ready for next input)"
+}
+
+func truncateText(s string, maxLen int) string {
+ if len(s) <= maxLen {
+ return s
+ }
+ return s[:maxLen] + "..."
+}
+
+// stopFlowTool implements stop_flow.
+type stopFlowTool struct {
+ flowID int64
+ db database.Querier
+ handler func(ctx context.Context, reason string) error
+}
+
+func NewStopFlowTool(flowID int64, db database.Querier, handler func(ctx context.Context, reason string) error) *stopFlowTool {
+ return &stopFlowTool{flowID: flowID, db: db, handler: handler}
+}
+
+func (t *stopFlowTool) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+ var action StopFlowAction
+ if err := json.Unmarshal(args, &action); err != nil {
+ return "", fmt.Errorf("failed to parse stop_flow args: %w", err)
+ }
+
+ tasks, err := t.db.GetFlowTasks(ctx, t.flowID)
+ if err != nil {
+ return "", fmt.Errorf("failed to check flow status: %w", err)
+ }
+
+ isRunning := false
+ for _, task := range tasks {
+ if task.Status == database.TaskStatusRunning {
+ isRunning = true
+ break
+ }
+ }
+
+ if !isRunning {
+ return "No running task found — the flow is already in 'waiting' state and ready to accept input.", nil
+ }
+
+ stopCtx, stopCancel := context.WithTimeout(ctx, flowOperationTimeout)
+ defer stopCancel()
+
+ if err := t.handler(stopCtx, action.Reason); err != nil {
+ if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
+ return "", fmt.Errorf(
+ "stop timed out after %s — the task may still be winding down. "+
+ "Call %s to check the current state before proceeding",
+ flowOperationTimeout, GetFlowStatusToolName)
+ }
+ return "", fmt.Errorf("failed to stop flow: %w", err)
+ }
+
+ // Re-query task statuses to report the actual state the flow reached.
+ newTasks, err := t.db.GetFlowTasks(ctx, t.flowID)
+ if err != nil {
+ // Stop succeeded but we cannot verify the new state — return a safe partial message.
+ return fmt.Sprintf(
+ "Flow stop initiated (reason: %s). Could not verify new status: %s. "+
+ "Call %s to confirm before proceeding.",
+ action.Reason, err, GetFlowStatusToolName), nil
+ }
+
+ for _, task := range newTasks {
+ if task.Status == database.TaskStatusRunning {
+ return fmt.Sprintf(
+ "Stop requested (reason: %s), but a task is still running — the flow has not reached 'waiting' yet. "+
+ "Call %s to confirm before making further changes.",
+ action.Reason, GetFlowStatusToolName), nil
+ }
+ }
+
+ return fmt.Sprintf(
+ "Flow stopped successfully (reason: %s). The flow is now in 'waiting' state and ready to accept new input or subtask patches.",
+ action.Reason), nil
+}
+
+// submitFlowInputTool implements submit_flow_input.
+type submitFlowInputTool struct {
+ flowID int64
+ db database.Querier
+ handler func(ctx context.Context, input string) error
+ pollInterval time.Duration
+ pollTimeout time.Duration
+}
+
+func NewSubmitFlowInputTool(flowID int64, db database.Querier, handler func(ctx context.Context, input string) error) *submitFlowInputTool {
+ return &submitFlowInputTool{
+ flowID: flowID,
+ db: db,
+ handler: handler,
+ pollInterval: taskReadyPollInterval,
+ pollTimeout: taskReadyPollTimeout,
+ }
+}
+
+func (t *submitFlowInputTool) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+ var action SubmitFlowInputAction
+ if err := json.Unmarshal(args, &action); err != nil {
+ return "", fmt.Errorf("failed to parse %s args: %w", SubmitFlowInputToolName, err)
+ }
+
+ if action.Input == "" {
+ return "", fmt.Errorf("input must not be empty")
+ }
+
+ tasks, err := t.db.GetFlowTasks(ctx, t.flowID)
+ if err != nil {
+ return "", fmt.Errorf("failed to check flow status: %w", err)
+ }
+
+ for _, task := range tasks {
+ if task.Status == database.TaskStatusRunning {
+ return "", fmt.Errorf(
+ "task %q (ID: %d) is currently running; "+
+ "cannot submit input while a task is executing. "+
+ "Call %s first to cancel it, then retry %s",
+ task.Title, task.ID, StopFlowToolName, SubmitFlowInputToolName)
+ }
+ }
+
+ // Determine mode for better response message
+ waitingForAsk := false
+ subtasks, err := t.db.GetFlowSubtasks(ctx, t.flowID)
+ if err == nil {
+ for _, st := range subtasks {
+ if st.Status == database.SubtaskStatusWaiting {
+ waitingForAsk = true
+ break
+ }
+ }
+ }
+
+ inputCtx, inputCancel := context.WithTimeout(ctx, flowOperationTimeout)
+ defer inputCancel()
+
+ if err := t.handler(inputCtx, action.Input); err != nil {
+ if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
+ return "", fmt.Errorf(
+ "submit timed out after %s — the flow may not have received the input. "+
+ "Call %s to check the current state before retrying",
+ flowOperationTimeout, GetFlowStatusToolName)
+ }
+ // A missing message chain means the waiting subtask's execution context was lost
+ // (most likely after a system restart or database cleanup while the subtask was at an ask checkpoint).
+ // The subtask can no longer be resumed; the flow must be stopped and restarted.
+ if strings.Contains(err.Error(), "no rows in result set") {
+ return "", fmt.Errorf(
+ "the waiting subtask's execution context is no longer available in the database — "+
+ "this typically happens after a system restart when the subtask was paused at an ask checkpoint. "+
+ "Recovery: (1) call %s to cancel the stale task; "+
+ "(2) call %s with a fresh description of what to do next; "+
+ "if the flow already has planned subtasks that should still run, "+
+ "use %s to inspect the remaining plan and %s to patch it before resuming",
+ StopFlowToolName, SubmitFlowInputToolName,
+ GetFlowStatusToolName, PatchFlowSubtasksToolName)
+ }
+ return "", fmt.Errorf("failed to submit flow input: %w", err)
+ }
+
+ if waitingForAsk {
+ return "Input delivered as the answer to the waiting subtask's question. The subtask will resume execution.", nil
+ }
+
+ // Input triggered task creation — wait for the generator to produce a running task.
+ return t.waitForTaskReady(ctx)
+}
+
+// waitForTaskReady polls GetFlowTasks every pollInterval until a running or waiting
+// task appears or pollTimeout is reached. It is called after submit_flow_input
+// triggers new task creation so the LLM gets confirmation that the generator finished.
+func (t *submitFlowInputTool) waitForTaskReady(ctx context.Context) (string, error) {
+ deadline := time.Now().Add(t.pollTimeout)
+ ticker := time.NewTicker(t.pollInterval)
+ defer ticker.Stop()
+
+ for {
+ tasks, err := t.db.GetFlowTasks(ctx, t.flowID)
+ if err == nil {
+ for _, task := range tasks {
+ if task.Status == database.TaskStatusRunning || task.Status == database.TaskStatusWaiting {
+ return fmt.Sprintf(
+ "Input accepted. Task %q (ID: %d) is now running — the generator has produced its subtask plan. "+
+ "Call %s with detail='running' to see what the agent is doing.",
+ task.Title, task.ID, GetFlowStatusToolName), nil
+ }
+ }
+ }
+
+ if time.Now().After(deadline) {
+ break
+ }
+
+ select {
+ case <-ctx.Done():
+ return "", fmt.Errorf(
+ "context cancelled while waiting for task to start. "+
+ "Call %s to check whether a task was created",
+ GetFlowStatusToolName)
+ case <-ticker.C:
+ }
+ }
+
+ return fmt.Sprintf(
+ "Input accepted but no running task appeared within %s. "+
+ "The generator may still be working. Call %s to check the current state.",
+ t.pollTimeout, GetFlowStatusToolName), nil
+}
+
+// patchFlowSubtasksTool implements patch_flow_subtasks.
+type patchFlowSubtasksTool struct {
+ flowID int64
+ db database.Querier
+ handler func(ctx context.Context, taskID int64, patch SubtaskPatch) error
+}
+
+func NewPatchFlowSubtasksTool(
+ flowID int64,
+ db database.Querier,
+ handler func(ctx context.Context, taskID int64, patch SubtaskPatch) error,
+) *patchFlowSubtasksTool {
+ return &patchFlowSubtasksTool{flowID: flowID, db: db, handler: handler}
+}
+
+func (t *patchFlowSubtasksTool) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+ var action PatchFlowSubtasksAction
+ if err := json.Unmarshal(args, &action); err != nil {
+ return "", fmt.Errorf("failed to parse patch_flow_subtasks args: %w", err)
+ }
+
+ if action.TaskID <= 0 {
+ return "", fmt.Errorf("task_id must be a positive integer")
+ }
+
+ // Validate flow is not running
+ tasks, err := t.db.GetFlowTasks(ctx, t.flowID)
+ if err != nil {
+ return "", fmt.Errorf("failed to check flow status: %w", err)
+ }
+
+ for _, task := range tasks {
+ if task.Status == database.TaskStatusRunning {
+ return "", fmt.Errorf(
+ "task %q (ID: %d) is currently running; "+
+ "patching is not allowed while a task is executing. "+
+ "Call %s first, then retry %s",
+ task.Title, task.ID, StopFlowToolName, PatchFlowSubtasksToolName)
+ }
+ }
+
+ // Verify task_id belongs to this flow.
+ taskBelongsToFlow := false
+ for _, task := range tasks {
+ if task.ID == action.TaskID {
+ taskBelongsToFlow = true
+ break
+ }
+ }
+ if !taskBelongsToFlow {
+ return "", fmt.Errorf(
+ "task ID %d was not found in this flow; "+
+ "obtain a valid task ID from %s with detail='tasks'",
+ action.TaskID, GetFlowStatusToolName)
+ }
+
+ // Verify there are planned subtasks to patch.
+ planned, err := t.db.GetTaskPlannedSubtasks(ctx, action.TaskID)
+ if err != nil {
+ return "", fmt.Errorf("failed to get planned subtasks for task %d: %w", action.TaskID, err)
+ }
+
+ if len(planned) == 0 && len(action.Operations) > 0 {
+ subtasks, err := t.db.GetFlowSubtasks(ctx, t.flowID)
+ if err != nil {
+ return "", fmt.Errorf("failed to check subtask state for task %d: %w", action.TaskID, err)
+ }
+
+ for _, st := range subtasks {
+ if st.TaskID != action.TaskID {
+ continue
+ }
+ switch st.Status {
+ case database.SubtaskStatusWaiting:
+ return "", fmt.Errorf(
+ "task %d has a subtask (ID: %d, %q) waiting for user input. "+
+ "Only 'created' subtasks can be patched, but you can include the waiting subtask's ID in your operations to modify or remove it. "+
+ "Alternatively, answer it via %s first",
+ action.TaskID, st.ID, st.Title, SubmitFlowInputToolName)
+ case database.SubtaskStatusRunning:
+ return "", fmt.Errorf(
+ "task %d has a subtask (ID: %d, %q) currently running. "+
+ "Call %s first, then retry",
+ action.TaskID, st.ID, st.Title, StopFlowToolName)
+ }
+ }
+
+ return "", fmt.Errorf(
+ "no 'created' subtasks found for task %d; "+
+ "all subtasks have been executed or the task has no plan yet. "+
+ "Use %s to create a new task instead",
+ action.TaskID, SubmitFlowInputToolName)
+ }
+
+ patch := SubtaskPatch{
+ Operations: action.Operations,
+ Message: action.Message,
+ }
+
+ if err := patch.Validate(); err != nil {
+ return "", fmt.Errorf("invalid subtask patch: %w", err)
+ }
+
+ if len(action.Operations) == 0 {
+ return fmt.Sprintf("No operations provided — the subtask plan for task %d is unchanged.", action.TaskID), nil
+ }
+
+ if err := t.handler(ctx, action.TaskID, patch); err != nil {
+ return "", fmt.Errorf("failed to patch subtasks for task %d: %w", action.TaskID, err)
+ }
+
+ // Query the new subtask list so the LLM can correlate the patched entries with their new IDs.
+ newPlanned, err := t.db.GetTaskPlannedSubtasks(ctx, action.TaskID)
+ if err != nil {
+ // Not fatal — operations were applied; just warn and skip the list.
+ return fmt.Sprintf(
+ "%d operation(s) applied to the subtask plan for task %d. "+
+ "Could not retrieve updated subtask list: %s. "+
+ "Call %s with detail='planned' and task_id=%d to verify.",
+ len(action.Operations), action.TaskID, err,
+ GetFlowStatusToolName, action.TaskID), nil
+ }
+
+ sb := &strings.Builder{}
+ fmt.Fprintf(sb,
+ "%d operation(s) applied to the subtask plan for task %d. "+
+ "Updated planned subtasks (new IDs assigned after recreation):\n",
+ len(action.Operations), action.TaskID)
+ for _, st := range newPlanned {
+ fmt.Fprintf(sb, " ID: %d | %s\n", st.ID, st.Title)
+ }
+ fmt.Fprintf(sb,
+ "Call %s to start execution with the updated plan.",
+ SubmitFlowInputToolName)
+
+ return sb.String(), nil
+}
diff --git a/backend/pkg/tools/flow_manager_test.go b/backend/pkg/tools/flow_manager_test.go
new file mode 100644
index 00000000..89aef9d9
--- /dev/null
+++ b/backend/pkg/tools/flow_manager_test.go
@@ -0,0 +1,1382 @@
+package tools
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "pentagi/pkg/database"
+)
+
+// mockQuerier satisfies database.Querier by embedding the interface;
+// only the methods used by flow_manager are overridden via function fields.
+type mockQuerier struct {
+ database.Querier
+ getFlowTasksFn func(ctx context.Context, flowID int64) ([]database.Task, error)
+ getFlowSubtasksFn func(ctx context.Context, flowID int64) ([]database.Subtask, error)
+ getFlowTaskSubtasksFn func(ctx context.Context, arg database.GetFlowTaskSubtasksParams) ([]database.Subtask, error)
+ getTaskPlannedFn func(ctx context.Context, taskID int64) ([]database.Subtask, error)
+ getSubtaskMsgLogsFn func(ctx context.Context, subtaskID sql.NullInt64) ([]database.Msglog, error)
+}
+
+func (m *mockQuerier) GetFlowTasks(ctx context.Context, flowID int64) ([]database.Task, error) {
+ if m.getFlowTasksFn != nil {
+ return m.getFlowTasksFn(ctx, flowID)
+ }
+ return nil, nil
+}
+
+func (m *mockQuerier) GetFlowSubtasks(ctx context.Context, flowID int64) ([]database.Subtask, error) {
+ if m.getFlowSubtasksFn != nil {
+ return m.getFlowSubtasksFn(ctx, flowID)
+ }
+ return nil, nil
+}
+
+func (m *mockQuerier) GetFlowTaskSubtasks(ctx context.Context, arg database.GetFlowTaskSubtasksParams) ([]database.Subtask, error) {
+ if m.getFlowTaskSubtasksFn != nil {
+ return m.getFlowTaskSubtasksFn(ctx, arg)
+ }
+ return nil, nil
+}
+
+func (m *mockQuerier) GetTaskPlannedSubtasks(ctx context.Context, taskID int64) ([]database.Subtask, error) {
+ if m.getTaskPlannedFn != nil {
+ return m.getTaskPlannedFn(ctx, taskID)
+ }
+ return nil, nil
+}
+
+func (m *mockQuerier) GetSubtaskMsgLogs(ctx context.Context, subtaskID sql.NullInt64) ([]database.Msglog, error) {
+ if m.getSubtaskMsgLogsFn != nil {
+ return m.getSubtaskMsgLogsFn(ctx, subtaskID)
+ }
+ return nil, nil
+}
+
+// ------------------------------------------------------------------
+// Helpers
+
+func makeTasks(statuses ...database.TaskStatus) []database.Task {
+ tasks := make([]database.Task, len(statuses))
+ for i, s := range statuses {
+ tasks[i] = database.Task{ID: int64(i + 1), Status: s, Title: fmt.Sprintf("task-%d", i+1)}
+ }
+ return tasks
+}
+
+func makeSubtasks(statuses ...database.SubtaskStatus) []database.Subtask {
+ subs := make([]database.Subtask, len(statuses))
+ for i, s := range statuses {
+ subs[i] = database.Subtask{ID: int64(i + 1), Status: s, Title: fmt.Sprintf("subtask-%d", i+1), TaskID: 1}
+ }
+ return subs
+}
+
+// ------------------------------------------------------------------
+// Pure function tests
+
+func TestInferFlowStatus(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ statuses []database.TaskStatus
+ want string
+ }{
+ {
+ name: "no tasks",
+ want: "waiting (ready for next input)",
+ },
+ {
+ name: "running task takes priority",
+ statuses: []database.TaskStatus{database.TaskStatusWaiting, database.TaskStatusRunning, database.TaskStatusFinished},
+ want: "running",
+ },
+ {
+ name: "waiting task, no running",
+ statuses: []database.TaskStatus{database.TaskStatusFinished, database.TaskStatusWaiting},
+ want: "waiting (subtask asking for user input)",
+ },
+ {
+ name: "all finished",
+ statuses: []database.TaskStatus{database.TaskStatusFinished, database.TaskStatusFinished},
+ want: "waiting (ready for next input)",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ tasks := makeTasks(tt.statuses...)
+ got := inferFlowStatus(tasks)
+ if got != tt.want {
+ t.Errorf("inferFlowStatus() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestTruncateText(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ input string
+ maxLen int
+ want string
+ }{
+ {name: "shorter than max", input: "hello", maxLen: 10, want: "hello"},
+ {name: "exactly max", input: "hello", maxLen: 5, want: "hello"},
+ {name: "longer than max — appends ellipsis", input: "hello world", maxLen: 5, want: "hello..."},
+ {name: "empty string", input: "", maxLen: 5, want: ""},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ got := truncateText(tt.input, tt.maxLen)
+ if got != tt.want {
+ t.Errorf("truncateText() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+// ------------------------------------------------------------------
+// flowStatusTool.Handle dispatch
+
+func TestFlowStatusToolHandle(t *testing.T) {
+ t.Parallel()
+
+ db := &mockQuerier{
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) { return nil, nil },
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) { return nil, nil },
+ }
+ tool := NewFlowStatusTool(1, db, nil)
+ ctx := context.Background()
+
+ tests := []struct {
+ name string
+ args string
+ wantErr bool
+ check func(t *testing.T, result string)
+ }{
+ {
+ name: "invalid JSON returns error",
+ args: `{bad json}`,
+ wantErr: true,
+ },
+ {
+ name: "unknown detail returns error",
+ args: `{"detail":"nonexistent","message":"x"}`,
+ wantErr: true,
+ },
+ {
+ name: "summary detail dispatches correctly",
+ args: `{"detail":"summary","message":"x"}`,
+ check: func(t *testing.T, result string) {
+ t.Helper()
+ if !strings.Contains(result, "Flow ID:") {
+ t.Errorf("summary result should contain 'Flow ID:', got: %s", result)
+ }
+ },
+ },
+ {
+ name: "tasks detail dispatches correctly",
+ args: `{"detail":"tasks","message":"x"}`,
+ check: func(t *testing.T, result string) {
+ t.Helper()
+ if result == "" {
+ t.Error("tasks result should not be empty")
+ }
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ result, err := tool.Handle(ctx, "get_flow_status", json.RawMessage(tt.args))
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("Handle() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ if tt.check != nil {
+ tt.check(t, result)
+ }
+ })
+ }
+}
+
+// ------------------------------------------------------------------
+// buildSummary
+
+func TestBuildSummary(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+
+ t.Run("db error on GetFlowTasks", func(t *testing.T) {
+ t.Parallel()
+ db := &mockQuerier{getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) {
+ return nil, errors.New("db down")
+ }}
+ _, err := NewFlowStatusTool(1, db, nil).buildSummary(ctx, false)
+ if err == nil {
+ t.Fatal("expected error, got nil")
+ }
+ })
+
+ t.Run("db error on GetFlowSubtasks", func(t *testing.T) {
+ t.Parallel()
+ db := &mockQuerier{
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) { return nil, nil },
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) { return nil, errors.New("db down") },
+ }
+ _, err := NewFlowStatusTool(1, db, nil).buildSummary(ctx, false)
+ if err == nil {
+ t.Fatal("expected error, got nil")
+ }
+ })
+
+ t.Run("empty tasks emits no-tasks notice", func(t *testing.T) {
+ t.Parallel()
+ db := &mockQuerier{
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) { return nil, nil },
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) { return nil, nil },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildSummary(ctx, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(result, "No tasks yet") {
+ t.Errorf("expected 'No tasks yet' in result, got: %s", result)
+ }
+ })
+
+ t.Run("status counts are correct", func(t *testing.T) {
+ t.Parallel()
+ tasks := makeTasks(
+ database.TaskStatusRunning,
+ database.TaskStatusWaiting,
+ database.TaskStatusFinished,
+ database.TaskStatusFailed,
+ database.TaskStatusCreated,
+ )
+ subs := makeSubtasks(
+ database.SubtaskStatusRunning,
+ database.SubtaskStatusFinished,
+ database.SubtaskStatusFinished,
+ )
+ db := &mockQuerier{
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) { return tasks, nil },
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) { return subs, nil },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildSummary(ctx, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(result, "total: 5") {
+ t.Errorf("expected 'total: 5' tasks in result, got: %s", result)
+ }
+ if !strings.Contains(result, "total: 3") {
+ t.Errorf("expected 'total: 3' subtasks in result, got: %s", result)
+ }
+ })
+
+ t.Run("active task identified and shown", func(t *testing.T) {
+ t.Parallel()
+ tasks := makeTasks(database.TaskStatusFinished, database.TaskStatusRunning)
+ db := &mockQuerier{
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) { return tasks, nil },
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) { return nil, nil },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildSummary(ctx, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(result, "Active task:") {
+ t.Errorf("expected 'Active task:' in result, got: %s", result)
+ }
+ if !strings.Contains(result, "task-2") {
+ t.Errorf("expected active task 'task-2' in result, got: %s", result)
+ }
+ })
+
+ t.Run("summarizer called when output exceeds summaryLimit", func(t *testing.T) {
+ t.Parallel()
+ largeTasks := make([]database.Task, 1)
+ largeTasks[0] = database.Task{ID: 1, Status: database.TaskStatusRunning, Title: strings.Repeat("x", summaryLimit+1)}
+ db := &mockQuerier{
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) { return largeTasks, nil },
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) { return nil, nil },
+ }
+ summarizerCalled := false
+ summarizer := func(_ context.Context, _ string) (string, error) {
+ summarizerCalled = true
+ return "summarized", nil
+ }
+ result, err := NewFlowStatusTool(1, db, summarizer).buildSummary(ctx, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !summarizerCalled {
+ t.Error("expected summarizer to be called, but it was not")
+ }
+ if result != "summarized" {
+ t.Errorf("expected summarizer output, got: %s", result)
+ }
+ })
+}
+
+// ------------------------------------------------------------------
+// buildTasksList
+
+func TestBuildTasksList(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+
+ tests := []struct {
+ name string
+ tasks []database.Task
+ tasksErr error
+ verbose bool
+ wantErr bool
+ wantSubstr string
+ }{
+ {
+ name: "no tasks returns specific message",
+ wantSubstr: "No tasks found",
+ },
+ {
+ name: "db error propagated",
+ tasksErr: errors.New("db fail"),
+ wantErr: true,
+ },
+ {
+ name: "tasks listed with IDs and titles",
+ tasks: makeTasks(database.TaskStatusFinished, database.TaskStatusRunning),
+ wantSubstr: "task-1",
+ },
+ {
+ name: "verbose: result field included when set",
+ verbose: true,
+ tasks: []database.Task{
+ {ID: 1, Status: database.TaskStatusFinished, Title: "t1", Result: "my-result"},
+ },
+ wantSubstr: "my-result",
+ },
+ {
+ name: "non-verbose: result field NOT included",
+ verbose: false,
+ tasks: []database.Task{
+ {ID: 1, Status: database.TaskStatusFinished, Title: "t1", Result: "secret-result"},
+ },
+ wantSubstr: "", // will be checked via absence
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ db := &mockQuerier{getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) {
+ return tt.tasks, tt.tasksErr
+ }}
+ result, err := NewFlowStatusTool(1, db, nil).buildTasksList(ctx, tt.verbose)
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("buildTasksList() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ if tt.wantErr {
+ return
+ }
+ if tt.wantSubstr != "" && !strings.Contains(result, tt.wantSubstr) {
+ t.Errorf("expected %q in result, got: %s", tt.wantSubstr, result)
+ }
+ // non-verbose check: result field must not appear
+ if !tt.verbose && len(tt.tasks) > 0 && tt.tasks[0].Result != "" {
+ if strings.Contains(result, tt.tasks[0].Result) {
+ t.Errorf("non-verbose mode should not include result field, got: %s", result)
+ }
+ }
+ })
+ }
+}
+
+// ------------------------------------------------------------------
+// buildSubtasksList
+
+func TestBuildSubtasksList(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+
+ t.Run("without taskID uses GetFlowSubtasks", func(t *testing.T) {
+ t.Parallel()
+ flowSubtasksCalled := false
+ db := &mockQuerier{
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) {
+ flowSubtasksCalled = true
+ return makeSubtasks(database.SubtaskStatusFinished), nil
+ },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildSubtasksList(ctx, nil, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !flowSubtasksCalled {
+ t.Error("expected GetFlowSubtasks to be called")
+ }
+ if !strings.Contains(result, "All subtasks for flow") {
+ t.Errorf("expected flow-level header, got: %s", result)
+ }
+ })
+
+ t.Run("with valid taskID uses GetFlowTaskSubtasks", func(t *testing.T) {
+ t.Parallel()
+ taskSubtasksCalled := false
+ taskID := int64(42)
+ db := &mockQuerier{
+ getFlowTaskSubtasksFn: func(_ context.Context, arg database.GetFlowTaskSubtasksParams) ([]database.Subtask, error) {
+ taskSubtasksCalled = true
+ if arg.TaskID != taskID {
+ return nil, fmt.Errorf("unexpected taskID %d", arg.TaskID)
+ }
+ return makeSubtasks(database.SubtaskStatusRunning), nil
+ },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildSubtasksList(ctx, &taskID, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !taskSubtasksCalled {
+ t.Error("expected GetFlowTaskSubtasks to be called")
+ }
+ if !strings.Contains(result, "Subtasks for task 42") {
+ t.Errorf("expected task-level header, got: %s", result)
+ }
+ })
+
+ t.Run("empty subtasks returns no-subtasks message", func(t *testing.T) {
+ t.Parallel()
+ db := &mockQuerier{
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) { return nil, nil },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildSubtasksList(ctx, nil, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(result, "No subtasks found") {
+ t.Errorf("expected 'No subtasks found', got: %s", result)
+ }
+ })
+
+ t.Run("db error propagated", func(t *testing.T) {
+ t.Parallel()
+ db := &mockQuerier{
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) {
+ return nil, errors.New("db fail")
+ },
+ }
+ _, err := NewFlowStatusTool(1, db, nil).buildSubtasksList(ctx, nil, false)
+ if err == nil {
+ t.Fatal("expected error, got nil")
+ }
+ })
+}
+
+// ------------------------------------------------------------------
+// buildRunningInfo
+
+func TestBuildRunningInfo(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+
+ t.Run("no active subtasks — flow is idle", func(t *testing.T) {
+ t.Parallel()
+ db := &mockQuerier{
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) {
+ return makeSubtasks(database.SubtaskStatusFinished, database.SubtaskStatusFailed), nil
+ },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildRunningInfo(ctx, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(result, "No running or waiting subtask found") {
+ t.Errorf("expected idle message, got: %s", result)
+ }
+ })
+
+ t.Run("running subtask shows parent task chain", func(t *testing.T) {
+ t.Parallel()
+ tasks := []database.Task{
+ {ID: 1, Status: database.TaskStatusRunning, Title: "main-task"},
+ }
+ subs := []database.Subtask{
+ {ID: 10, Status: database.SubtaskStatusRunning, Title: "active-sub", TaskID: 1},
+ }
+ db := &mockQuerier{
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) { return subs, nil },
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) { return tasks, nil },
+ getSubtaskMsgLogsFn: func(_ context.Context, _ sql.NullInt64) ([]database.Msglog, error) {
+ return nil, nil
+ },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildRunningInfo(ctx, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(result, "Active Task") {
+ t.Errorf("expected 'Active Task' section, got: %s", result)
+ }
+ if !strings.Contains(result, "main-task") {
+ t.Errorf("expected parent task title 'main-task', got: %s", result)
+ }
+ if !strings.Contains(result, "active-sub") {
+ t.Errorf("expected subtask title 'active-sub', got: %s", result)
+ }
+ })
+
+ t.Run("waiting subtask shows ask note and submit tool name", func(t *testing.T) {
+ t.Parallel()
+ subs := []database.Subtask{
+ {ID: 5, Status: database.SubtaskStatusWaiting, Title: "ask-sub", TaskID: 2},
+ }
+ db := &mockQuerier{
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) { return subs, nil },
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) { return nil, nil },
+ getSubtaskMsgLogsFn: func(_ context.Context, _ sql.NullInt64) ([]database.Msglog, error) {
+ return nil, nil
+ },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildRunningInfo(ctx, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(result, "waiting for user input") {
+ t.Errorf("expected waiting note, got: %s", result)
+ }
+ if !strings.Contains(result, SubmitFlowInputToolName) {
+ t.Errorf("expected SubmitFlowInputToolName in result, got: %s", result)
+ }
+ })
+ t.Run("verbose shows result and execution context", func(t *testing.T) {
+ t.Parallel()
+ subs := []database.Subtask{
+ {ID: 7, Status: database.SubtaskStatusRunning, Title: "verbose-sub", TaskID: 1,
+ Result: "partial-result", Context: "exec-context-data"},
+ }
+ db := &mockQuerier{
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) { return subs, nil },
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) { return nil, nil },
+ getSubtaskMsgLogsFn: func(_ context.Context, _ sql.NullInt64) ([]database.Msglog, error) {
+ return nil, nil
+ },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildRunningInfo(ctx, true)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(result, "partial-result") {
+ t.Errorf("verbose: expected subtask result in output, got: %s", result)
+ }
+ if !strings.Contains(result, "exec-context-data") {
+ t.Errorf("verbose: expected execution context in output, got: %s", result)
+ }
+ })
+
+ t.Run("non-verbose hides execution context", func(t *testing.T) {
+ t.Parallel()
+ subs := []database.Subtask{
+ {ID: 8, Status: database.SubtaskStatusRunning, Title: "quiet-sub", TaskID: 1,
+ Context: "secret-context"},
+ }
+ db := &mockQuerier{
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) { return subs, nil },
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) { return nil, nil },
+ getSubtaskMsgLogsFn: func(_ context.Context, _ sql.NullInt64) ([]database.Msglog, error) {
+ return nil, nil
+ },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildRunningInfo(ctx, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if strings.Contains(result, "secret-context") {
+ t.Errorf("non-verbose: execution context should be hidden, got: %s", result)
+ }
+ })
+}
+
+func TestBuildPlannedList(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+
+ t.Run("with taskID uses GetTaskPlannedSubtasks", func(t *testing.T) {
+ t.Parallel()
+ plannedCalled := false
+ taskID := int64(7)
+ db := &mockQuerier{
+ getTaskPlannedFn: func(_ context.Context, id int64) ([]database.Subtask, error) {
+ plannedCalled = true
+ if id != taskID {
+ return nil, fmt.Errorf("unexpected taskID %d", id)
+ }
+ return makeSubtasks(database.SubtaskStatusCreated), nil
+ },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildPlannedList(ctx, &taskID, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !plannedCalled {
+ t.Error("expected GetTaskPlannedSubtasks to be called")
+ }
+ if !strings.Contains(result, "Planned subtasks for task 7") {
+ t.Errorf("expected task-level header, got: %s", result)
+ }
+ })
+
+ t.Run("without taskID filters created subtasks from flow", func(t *testing.T) {
+ t.Parallel()
+ subs := []database.Subtask{
+ {ID: 1, Status: database.SubtaskStatusCreated, Title: "planned-sub", TaskID: 1},
+ {ID: 2, Status: database.SubtaskStatusFinished, Title: "done-sub", TaskID: 1},
+ }
+ db := &mockQuerier{
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) { return subs, nil },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildPlannedList(ctx, nil, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(result, "planned-sub") {
+ t.Errorf("expected created subtask 'planned-sub', got: %s", result)
+ }
+ if strings.Contains(result, "done-sub") {
+ t.Errorf("finished subtask 'done-sub' should not appear in planned list, got: %s", result)
+ }
+ })
+
+ t.Run("all subtasks executed returns specific message", func(t *testing.T) {
+ t.Parallel()
+ db := &mockQuerier{
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) {
+ return makeSubtasks(database.SubtaskStatusFinished, database.SubtaskStatusFailed), nil
+ },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).buildPlannedList(ctx, nil, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(result, "No planned") {
+ t.Errorf("expected 'No planned' message, got: %s", result)
+ }
+ })
+}
+
+// ------------------------------------------------------------------
+// waitForTaskReady — context cancellation
+
+func TestWaitForTaskReadyContextCancelled(t *testing.T) {
+ t.Parallel()
+
+ db := &mockQuerier{
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) {
+ // Always return no running task so the loop keeps spinning.
+ return makeTasks(database.TaskStatusCreated), nil
+ },
+ }
+ tool := NewSubmitFlowInputTool(1, db, nil)
+ tool.pollInterval = 1 * time.Millisecond
+ tool.pollTimeout = 1 * time.Hour // would hang without ctx cancellation
+
+ ctx, cancel := context.WithCancel(context.Background())
+ // Cancel immediately so the first ticker tick triggers ctx.Done().
+ cancel()
+
+ _, err := tool.waitForTaskReady(ctx)
+ if err == nil {
+ t.Fatal("expected error from cancelled context, got nil")
+ }
+ if !strings.Contains(err.Error(), "context cancelled") {
+ t.Errorf("expected 'context cancelled' in error, got: %v", err)
+ }
+}
+
+// ------------------------------------------------------------------
+// appendSubtaskMsgLogs
+
+func TestAppendSubtaskMsgLogs(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+
+ t.Run("db error returns error", func(t *testing.T) {
+ t.Parallel()
+ db := &mockQuerier{
+ getSubtaskMsgLogsFn: func(_ context.Context, _ sql.NullInt64) ([]database.Msglog, error) {
+ return nil, errors.New("db down")
+ },
+ }
+ _, err := NewFlowStatusTool(1, db, nil).appendSubtaskMsgLogs(ctx, 5, 10)
+ if err == nil {
+ t.Fatal("expected error on DB failure, got nil")
+ }
+ })
+
+ t.Run("no logs returns specific message", func(t *testing.T) {
+ t.Parallel()
+ db := &mockQuerier{
+ getSubtaskMsgLogsFn: func(_ context.Context, _ sql.NullInt64) ([]database.Msglog, error) {
+ return nil, nil
+ },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).appendSubtaskMsgLogs(ctx, 5, 10)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(result, "No agent messages") {
+ t.Errorf("expected 'No agent messages', got: %s", result)
+ }
+ })
+
+ t.Run("fewer logs than limit — all shown", func(t *testing.T) {
+ t.Parallel()
+ logs := []database.Msglog{
+ {ID: 1, Message: "msg-alpha"},
+ {ID: 2, Message: "msg-beta"},
+ }
+ db := &mockQuerier{
+ getSubtaskMsgLogsFn: func(_ context.Context, _ sql.NullInt64) ([]database.Msglog, error) {
+ return logs, nil
+ },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).appendSubtaskMsgLogs(ctx, 1, 10)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(result, "msg-alpha") || !strings.Contains(result, "msg-beta") {
+ t.Errorf("expected all messages in result, got: %s", result)
+ }
+ })
+
+ t.Run("more logs than limit — only tail shown", func(t *testing.T) {
+ t.Parallel()
+ logs := make([]database.Msglog, 5)
+ for i := range logs {
+ logs[i] = database.Msglog{ID: int64(i + 1), Message: fmt.Sprintf("msg-%d", i+1)}
+ }
+ db := &mockQuerier{
+ getSubtaskMsgLogsFn: func(_ context.Context, _ sql.NullInt64) ([]database.Msglog, error) {
+ return logs, nil
+ },
+ }
+ result, err := NewFlowStatusTool(1, db, nil).appendSubtaskMsgLogs(ctx, 1, 2)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ // Only last 2 (msg-4, msg-5) should appear; msg-1 through msg-3 should not.
+ for _, absent := range []string{"msg-1", "msg-2", "msg-3"} {
+ if strings.Contains(result, absent) {
+ t.Errorf("old message %q should have been dropped by limit, got: %s", absent, result)
+ }
+ }
+ for _, present := range []string{"msg-4", "msg-5"} {
+ if !strings.Contains(result, present) {
+ t.Errorf("recent message %q should appear in result, got: %s", present, result)
+ }
+ }
+ })
+
+ t.Run("summarizer called when logs exceed msgLogsLimit", func(t *testing.T) {
+ t.Parallel()
+ // Each message is capped to 1024 chars in the output; to exceed msgLogsLimit (16 KB)
+ // we need enough log entries so their combined formatted size exceeds the limit.
+ numLogs := msgLogsLimit/1024 + 2
+ logs := make([]database.Msglog, numLogs)
+ for i := range logs {
+ logs[i] = database.Msglog{ID: int64(i + 1), Message: strings.Repeat("x", 1024)}
+ }
+ db := &mockQuerier{
+ getSubtaskMsgLogsFn: func(_ context.Context, _ sql.NullInt64) ([]database.Msglog, error) {
+ return logs, nil
+ },
+ }
+ summarizerCalled := false
+ summarizer := func(_ context.Context, _ string) (string, error) {
+ summarizerCalled = true
+ return "summarized-logs", nil
+ }
+ result, err := NewFlowStatusTool(1, db, summarizer).appendSubtaskMsgLogs(ctx, 1, numLogs+10)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !summarizerCalled {
+ t.Error("expected summarizer to be called for oversized logs output")
+ }
+ if result != "summarized-logs" {
+ t.Errorf("expected summarizer output, got: %s", result)
+ }
+ })
+}
+
+// ------------------------------------------------------------------
+// Text helper methods
+
+func TestGetTextHelpers(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+
+ tool := NewFlowStatusTool(1, &mockQuerier{}, nil)
+
+ tests := []struct {
+ name string
+ call func(string) (string, error)
+ limit int
+ twoLimit int
+ }{
+ {
+ name: "getInputText",
+ call: func(s string) (string, error) { return tool.getInputText(ctx, s) },
+ limit: inputLimit,
+ twoLimit: 2 * inputLimit,
+ },
+ {
+ name: "getDescriptionText",
+ call: func(s string) (string, error) { return tool.getDescriptionText(ctx, s) },
+ limit: descriptionLimit,
+ twoLimit: 2 * descriptionLimit,
+ },
+ {
+ name: "getResultText",
+ call: func(s string) (string, error) { return tool.getResultText(ctx, s) },
+ limit: resultLimit,
+ twoLimit: 2 * resultLimit,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name+"/empty returns empty", func(t *testing.T) {
+ t.Parallel()
+ got, err := tt.call("")
+ if err != nil || got != "" {
+ t.Errorf("empty input: got (%q, %v), want (\"\", nil)", got, err)
+ }
+ })
+
+ t.Run(tt.name+"/short text truncated to limit", func(t *testing.T) {
+ t.Parallel()
+ text := strings.Repeat("a", tt.limit+10)
+ got, err := tt.call(text)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if len(got) > tt.limit+3 { // +3 for "..."
+ t.Errorf("expected text to be truncated to ~%d chars, got len=%d", tt.limit, len(got))
+ }
+ })
+
+ t.Run(tt.name+"/oversized text triggers summarizer", func(t *testing.T) {
+ t.Parallel()
+ summarizerCalled := false
+ toolWithSummarizer := NewFlowStatusTool(1, &mockQuerier{}, func(_ context.Context, _ string) (string, error) {
+ summarizerCalled = true
+ return "summarized", nil
+ })
+ text := strings.Repeat("b", tt.twoLimit+1)
+ // Call the correct method on the tool with summarizer
+ var got string
+ var err error
+ switch tt.name {
+ case "getInputText":
+ got, err = toolWithSummarizer.getInputText(ctx, text)
+ case "getDescriptionText":
+ got, err = toolWithSummarizer.getDescriptionText(ctx, text)
+ case "getResultText":
+ got, err = toolWithSummarizer.getResultText(ctx, text)
+ }
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !summarizerCalled {
+ t.Error("expected summarizer to be called for oversized text")
+ }
+ if got != "summarized" {
+ t.Errorf("expected summarizer output, got: %s", got)
+ }
+ })
+ }
+}
+
+// ------------------------------------------------------------------
+// stopFlowTool.Handle
+
+func TestStopFlowToolHandle(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+
+ tests := []struct {
+ name string
+ args string
+ tasks []database.Task
+ tasksErr error
+ handler func(context.Context, string) error
+ newTasks []database.Task
+ newTaskErr error
+ wantErr bool
+ wantSubstr string
+ wantErrSubstr string
+ }{
+ {
+ name: "invalid JSON returns error",
+ args: `{bad}`,
+ wantErr: true,
+ },
+ {
+ name: "no running tasks — already waiting",
+ args: `{"reason":"test","message":"x"}`,
+ tasks: makeTasks(database.TaskStatusFinished, database.TaskStatusWaiting),
+ wantSubstr: "already in 'waiting' state",
+ },
+ {
+ name: "running task — handler succeeds — confirms stopped",
+ args: `{"reason":"test","message":"x"}`,
+ tasks: makeTasks(database.TaskStatusRunning),
+ handler: func(_ context.Context, _ string) error { return nil },
+ newTasks: makeTasks(database.TaskStatusFinished),
+ wantSubstr: "stopped successfully",
+ },
+ {
+ name: "running task — handler error — propagated",
+ args: `{"reason":"test","message":"x"}`,
+ tasks: makeTasks(database.TaskStatusRunning),
+ handler: func(_ context.Context, _ string) error { return errors.New("stop failed") },
+ wantErr: true,
+ },
+ {
+ name: "running task — handler deadline exceeded — timeout message",
+ args: `{"reason":"test","message":"x"}`,
+ tasks: makeTasks(database.TaskStatusRunning),
+ handler: func(_ context.Context, _ string) error {
+ return context.DeadlineExceeded
+ },
+ wantErr: true,
+ wantErrSubstr: "timed out",
+ },
+ {
+ name: "running task — handler context cancelled — timeout message",
+ args: `{"reason":"test","message":"x"}`,
+ tasks: makeTasks(database.TaskStatusRunning),
+ handler: func(_ context.Context, _ string) error {
+ return context.Canceled
+ },
+ wantErr: true,
+ wantErrSubstr: "timed out",
+ },
+ {
+ name: "running task — after stop task still running — warns",
+ args: `{"reason":"test","message":"x"}`,
+ tasks: makeTasks(database.TaskStatusRunning),
+ handler: func(_ context.Context, _ string) error { return nil },
+ newTasks: makeTasks(database.TaskStatusRunning),
+ wantSubstr: "has not reached 'waiting'",
+ },
+ {
+ name: "stop succeeds but re-query fails — partial message returned",
+ args: `{"reason":"test","message":"x"}`,
+ tasks: makeTasks(database.TaskStatusRunning),
+ handler: func(_ context.Context, _ string) error { return nil },
+ newTaskErr: errors.New("db fail"),
+ wantSubstr: "Could not verify new status",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ callCount := 0
+ db := &mockQuerier{
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) {
+ callCount++
+ if callCount == 1 {
+ return tt.tasks, tt.tasksErr
+ }
+ return tt.newTasks, tt.newTaskErr
+ },
+ }
+ tool := NewStopFlowTool(1, db, tt.handler)
+ result, err := tool.Handle(ctx, "stop_flow", json.RawMessage(tt.args))
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("Handle() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ if tt.wantErr {
+ if tt.wantErrSubstr != "" && (err == nil || !strings.Contains(err.Error(), tt.wantErrSubstr)) {
+ t.Errorf("expected %q in error, got: %v", tt.wantErrSubstr, err)
+ }
+ return
+ }
+ if tt.wantSubstr != "" && !strings.Contains(result, tt.wantSubstr) {
+ t.Errorf("expected %q in result, got: %s", tt.wantSubstr, result)
+ }
+ })
+ }
+}
+
+// ------------------------------------------------------------------
+// submitFlowInputTool.Handle
+
+func TestSubmitFlowInputToolHandle(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+
+ tests := []struct {
+ name string
+ args string
+ tasks []database.Task
+ subtasks []database.Subtask
+ handler func(context.Context, string) error
+ newTasks []database.Task
+ wantErr bool
+ wantSubstr string
+ wantErrSubstr string
+ }{
+ {
+ name: "invalid JSON returns error",
+ args: `{bad}`,
+ wantErr: true,
+ },
+ {
+ name: "empty input returns error",
+ args: `{"input":"","message":"x"}`,
+ wantErr: true,
+ },
+ {
+ name: "running task blocks submission",
+ args: `{"input":"hello","message":"x"}`,
+ tasks: makeTasks(database.TaskStatusRunning),
+ wantErr: true,
+ },
+ {
+ name: "waiting subtask — delivered as ask answer",
+ args: `{"input":"my answer","message":"x"}`,
+ tasks: makeTasks(database.TaskStatusWaiting),
+ subtasks: makeSubtasks(database.SubtaskStatusWaiting),
+ handler: func(_ context.Context, _ string) error { return nil },
+ wantSubstr: "answer to the waiting subtask",
+ },
+ {
+ name: "idle flow — handler error propagated",
+ args: `{"input":"do something","message":"x"}`,
+ handler: func(_ context.Context, _ string) error { return errors.New("submit failed") },
+ wantErr: true,
+ },
+ {
+ name: "idle flow — stale message chain after restart — actionable error",
+ args: `{"input":"do something","message":"x"}`,
+ handler: func(_ context.Context, _ string) error {
+ return fmt.Errorf("failed to put flow input: failed to get message chain 63247: sql: no rows in result set")
+ },
+ wantErr: true,
+ wantErrSubstr: "no longer available in the database",
+ },
+ {
+ name: "idle flow — handler deadline exceeded — timeout message",
+ args: `{"input":"do something","message":"x"}`,
+ handler: func(_ context.Context, _ string) error {
+ return context.DeadlineExceeded
+ },
+ wantErr: true,
+ wantErrSubstr: "timed out",
+ },
+ {
+ name: "idle flow — handler context cancelled — timeout message",
+ args: `{"input":"do something","message":"x"}`,
+ handler: func(_ context.Context, _ string) error {
+ return context.Canceled
+ },
+ wantErr: true,
+ wantErrSubstr: "timed out",
+ },
+ {
+ name: "idle flow — new task now running",
+ args: `{"input":"do something","message":"x"}`,
+ handler: func(_ context.Context, _ string) error { return nil },
+ newTasks: []database.Task{{ID: 5, Status: database.TaskStatusRunning, Title: "new-task"}},
+ wantSubstr: "new-task",
+ },
+ {
+ name: "idle flow — no running task after submit",
+ args: `{"input":"do something","message":"x"}`,
+ handler: func(_ context.Context, _ string) error { return nil },
+ newTasks: makeTasks(database.TaskStatusCreated),
+ wantSubstr: "generator may still be working",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ taskCallCount := 0
+ db := &mockQuerier{
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) {
+ taskCallCount++
+ if taskCallCount == 1 {
+ return tt.tasks, nil
+ }
+ return tt.newTasks, nil
+ },
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) {
+ return tt.subtasks, nil
+ },
+ }
+ tool := NewSubmitFlowInputTool(1, db, tt.handler)
+ // Shorten polling so tests don't hang.
+ tool.pollInterval = 1 * time.Millisecond
+ tool.pollTimeout = 20 * time.Millisecond
+
+ result, err := tool.Handle(ctx, "submit_flow_input", json.RawMessage(tt.args))
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("Handle() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ if tt.wantErr {
+ if tt.wantErrSubstr != "" && (err == nil || !strings.Contains(err.Error(), tt.wantErrSubstr)) {
+ t.Errorf("expected %q in error, got: %v", tt.wantErrSubstr, err)
+ }
+ return
+ }
+ if tt.wantSubstr != "" && !strings.Contains(result, tt.wantSubstr) {
+ t.Errorf("expected %q in result, got: %s", tt.wantSubstr, result)
+ }
+ })
+ }
+}
+
+// ------------------------------------------------------------------
+// patchFlowSubtasksTool.Handle
+
+func TestPatchFlowSubtasksToolHandle(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+
+ validOp := SubtaskOperation{Op: SubtaskOpAdd, Title: "new sub", Description: "do thing"}
+ invalidOp := SubtaskOperation{Op: SubtaskOpRemove} // remove without ID
+
+ tests := []struct {
+ name string
+ args string
+ tasks []database.Task
+ planned []database.Subtask
+ allSubtasks []database.Subtask
+ plannedErr error
+ handler func(context.Context, int64, SubtaskPatch) error
+ newPlanned []database.Subtask
+ wantErr bool
+ wantSubstr string
+ }{
+ {
+ name: "invalid JSON returns error",
+ args: `{bad}`,
+ wantErr: true,
+ },
+ {
+ name: "task_id zero returns error",
+ args: `{"task_id":0,"operations":[],"message":"x"}`,
+ wantErr: true,
+ },
+ {
+ name: "running task blocks patching",
+ args: `{"task_id":1,"operations":[],"message":"x"}`,
+ tasks: makeTasks(database.TaskStatusRunning),
+ wantErr: true,
+ },
+ {
+ name: "task not in flow returns error",
+ args: `{"task_id":99,"operations":[],"message":"x"}`,
+ tasks: makeTasks(database.TaskStatusFinished),
+ wantErr: true,
+ },
+ {
+ name: "empty operations returns unchanged message",
+ args: `{"task_id":1,"operations":[],"message":"x"}`,
+ tasks: makeTasks(database.TaskStatusFinished),
+ planned: makeSubtasks(database.SubtaskStatusCreated),
+ wantSubstr: "unchanged",
+ },
+ {
+ name: "invalid patch operation returns validation error",
+ args: buildPatchArgs(1, invalidOp),
+ tasks: makeTasks(database.TaskStatusFinished),
+ planned: makeSubtasks(database.SubtaskStatusCreated),
+ wantErr: true,
+ },
+ {
+ name: "valid patch applied — reports count and new IDs",
+ args: buildPatchArgs(1, validOp),
+ tasks: makeTasks(database.TaskStatusFinished),
+ planned: makeSubtasks(database.SubtaskStatusCreated),
+ handler: func(_ context.Context, _ int64, _ SubtaskPatch) error { return nil },
+ newPlanned: []database.Subtask{{ID: 100, Status: database.SubtaskStatusCreated, Title: "new sub", TaskID: 1}},
+ wantSubstr: "1 operation(s) applied",
+ },
+ {
+ name: "no planned subtasks + operations + waiting subtask — descriptive error",
+ args: buildPatchArgs(1, validOp),
+ tasks: makeTasks(database.TaskStatusFinished),
+ planned: nil,
+ allSubtasks: []database.Subtask{{ID: 2, Status: database.SubtaskStatusWaiting, Title: "ask-sub", TaskID: 1}},
+ wantErr: true,
+ },
+ {
+ name: "no planned subtasks + operations + running subtask — descriptive error",
+ args: buildPatchArgs(1, validOp),
+ tasks: makeTasks(database.TaskStatusFinished),
+ planned: nil,
+ allSubtasks: []database.Subtask{{ID: 3, Status: database.SubtaskStatusRunning, Title: "run-sub", TaskID: 1}},
+ wantErr: true,
+ },
+ {
+ name: "no planned subtasks + operations + no active subtasks — generic error",
+ args: buildPatchArgs(1, validOp),
+ tasks: makeTasks(database.TaskStatusFinished),
+ planned: nil,
+ allSubtasks: makeSubtasks(database.SubtaskStatusFinished),
+ wantErr: true,
+ },
+ {
+ name: "handler error propagated",
+ args: buildPatchArgs(1, validOp),
+ tasks: makeTasks(database.TaskStatusFinished),
+ planned: makeSubtasks(database.SubtaskStatusCreated),
+ handler: func(_ context.Context, _ int64, _ SubtaskPatch) error { return errors.New("patch failed") },
+ wantErr: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ plannedCallCount := 0
+ db := &mockQuerier{
+ getFlowTasksFn: func(_ context.Context, _ int64) ([]database.Task, error) {
+ return tt.tasks, nil
+ },
+ getTaskPlannedFn: func(_ context.Context, _ int64) ([]database.Subtask, error) {
+ plannedCallCount++
+ if plannedCallCount == 1 {
+ return tt.planned, tt.plannedErr
+ }
+ return tt.newPlanned, nil
+ },
+ getFlowSubtasksFn: func(_ context.Context, _ int64) ([]database.Subtask, error) {
+ return tt.allSubtasks, nil
+ },
+ }
+ tool := NewPatchFlowSubtasksTool(1, db, tt.handler)
+ result, err := tool.Handle(ctx, "patch_flow_subtasks", json.RawMessage(tt.args))
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("Handle() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ if tt.wantSubstr != "" && !strings.Contains(result, tt.wantSubstr) {
+ t.Errorf("expected %q in result, got: %s", tt.wantSubstr, result)
+ }
+ })
+ }
+}
+
+func buildPatchArgs(taskID int64, ops ...SubtaskOperation) string {
+ opsJSON, _ := json.Marshal(ops)
+ return fmt.Sprintf(`{"task_id":%d,"operations":%s,"message":"x"}`, taskID, opsJSON)
+}
+
+// ------------------------------------------------------------------
+// SubtaskPatch.Validate (logic coverage)
+
+func TestSubtaskPatchValidate(t *testing.T) {
+ t.Parallel()
+
+ id := int64(1)
+
+ tests := []struct {
+ name string
+ ops []SubtaskOperation
+ wantErr bool
+ }{
+ {
+ name: "valid add operation",
+ ops: []SubtaskOperation{{Op: SubtaskOpAdd, Title: "t", Description: "d"}},
+ wantErr: false,
+ },
+ {
+ name: "add missing title",
+ ops: []SubtaskOperation{{Op: SubtaskOpAdd, Description: "d"}},
+ wantErr: true,
+ },
+ {
+ name: "add missing description",
+ ops: []SubtaskOperation{{Op: SubtaskOpAdd, Title: "t"}},
+ wantErr: true,
+ },
+ {
+ name: "remove with id",
+ ops: []SubtaskOperation{{Op: SubtaskOpRemove, ID: &id}},
+ wantErr: false,
+ },
+ {
+ name: "remove without id",
+ ops: []SubtaskOperation{{Op: SubtaskOpRemove}},
+ wantErr: true,
+ },
+ {
+ name: "modify with id and title",
+ ops: []SubtaskOperation{{Op: SubtaskOpModify, ID: &id, Title: "new title"}},
+ wantErr: false,
+ },
+ {
+ name: "modify without id",
+ ops: []SubtaskOperation{{Op: SubtaskOpModify, Title: "t"}},
+ wantErr: true,
+ },
+ {
+ name: "modify without title or description",
+ ops: []SubtaskOperation{{Op: SubtaskOpModify, ID: &id}},
+ wantErr: true,
+ },
+ {
+ name: "reorder with id",
+ ops: []SubtaskOperation{{Op: SubtaskOpReorder, ID: &id}},
+ wantErr: false,
+ },
+ {
+ name: "reorder without id",
+ ops: []SubtaskOperation{{Op: SubtaskOpReorder}},
+ wantErr: true,
+ },
+ {
+ name: "unknown operation type",
+ ops: []SubtaskOperation{{Op: "unknown"}},
+ wantErr: true,
+ },
+ {
+ name: "empty operations list is valid",
+ ops: []SubtaskOperation{},
+ wantErr: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ patch := SubtaskPatch{Operations: tt.ops}
+ err := patch.Validate()
+ if (err != nil) != tt.wantErr {
+ t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ })
+ }
+}
diff --git a/backend/pkg/tools/registry.go b/backend/pkg/tools/registry.go
index 6e1ef657..9cf8296a 100644
--- a/backend/pkg/tools/registry.go
+++ b/backend/pkg/tools/registry.go
@@ -44,6 +44,10 @@ const (
SubtaskPatchToolName = "subtask_patch"
TerminalToolName = "terminal"
FileToolName = "file"
+ GetFlowStatusToolName = "get_flow_status"
+ StopFlowToolName = "stop_flow"
+ SubmitFlowInputToolName = "submit_flow_input"
+ PatchFlowSubtasksToolName = "patch_flow_subtasks"
)
type ToolType int
@@ -124,6 +128,10 @@ var toolsTypeMapping = map[string]ToolType{
SubtaskPatchToolName: StoreAgentResultToolType,
TerminalToolName: EnvironmentToolType,
FileToolName: EnvironmentToolType,
+ GetFlowStatusToolName: EnvironmentToolType,
+ StopFlowToolName: EnvironmentToolType,
+ SubmitFlowInputToolName: EnvironmentToolType,
+ PatchFlowSubtasksToolName: EnvironmentToolType,
}
var reflector = &jsonschema.Reflector{
@@ -374,6 +382,42 @@ var registryDefinitions = map[string]llms.FunctionDefinition{
Description: "If you need to finish the task with success or failure, use this tool",
Parameters: reflector.Reflect(&Done{}),
},
+ GetFlowStatusToolName: {
+ Name: GetFlowStatusToolName,
+ Description: "Return structured information about the automation flow. " +
+ "Choose the detail level based on what you need to know:\n" +
+ " 'summary' — flow health snapshot: status, task counts, subtask counts, active task/subtask IDs. Best first call.\n" +
+ " 'tasks' — all tasks with ID, status, title. Add verbose=true for inputs and results.\n" +
+ " 'subtasks' — all subtasks, optionally filtered by task_id. Add verbose=true for descriptions and results.\n" +
+ " 'running' — full Task→Subtask execution chain: task input, subtask description, partial result, and recent agent messages (10 default, 50 with verbose=true). Use when you need to understand what is happening right now.\n" +
+ " 'planned' — subtasks with status 'created' (not yet started), optionally filtered by task_id. Add verbose=true for full descriptions.",
+ Parameters: reflector.Reflect(&GetFlowStatusAction{}),
+ },
+ StopFlowToolName: {
+ Name: StopFlowToolName,
+ Description: "Cancel the currently executing automation task. " +
+ "If a task is actively running its execution context is cancelled; the flow transitions to 'waiting' state and can accept new input or subtask patches. " +
+ "If no task is running the tool returns an informational message and takes no further action. " +
+ "After calling this tool, verify the flow reached 'waiting' state before making further changes.",
+ Parameters: reflector.Reflect(&StopFlowAction{}),
+ },
+ SubmitFlowInputToolName: {
+ Name: SubmitFlowInputToolName,
+ Description: "Deliver text to the automation flow. The behaviour depends on the current flow state:\n" +
+ " Subtask at 'ask' checkpoint — the text is delivered as the user's answer and the subtask resumes immediately.\n" +
+ " Flow waiting with no active subtask — the text becomes the goal for a new task; the generator and refiner agents decompose it into a subtask list. Write a complete, detailed description with all context the automation needs.\n" +
+ "Returns an error if a task is currently running — cancel the running task first.",
+ Parameters: reflector.Reflect(&SubmitFlowInputAction{}),
+ },
+ PatchFlowSubtasksToolName: {
+ Name: PatchFlowSubtasksToolName,
+ Description: "Replace the planned (not-yet-started) subtask list for a specific task using delta operations. " +
+ "Supported operations: add (insert a new subtask at a position), remove (delete a planned subtask by ID), modify (update title or description), reorder (move to a different position). " +
+ "The currently executing or waiting subtask can also be targeted by including its ID in an operation; doing so resets it to 'created' status. " +
+ "After patching, submit new input to trigger execution of the updated plan. " +
+ "Returns an error if a task is currently running — cancel it first.",
+ Parameters: reflector.Reflect(&PatchFlowSubtasksAction{}),
+ },
}
func getMessageType(name string) database.MsglogType {
diff --git a/backend/pkg/tools/tools.go b/backend/pkg/tools/tools.go
index a900aa23..7760bbdc 100644
--- a/backend/pkg/tools/tools.go
+++ b/backend/pkg/tools/tools.go
@@ -177,14 +177,23 @@ type CustomExecutorConfig struct {
}
type AssistantExecutorConfig struct {
- UseAgents bool
- Adviser ExecutorHandler
- Coder ExecutorHandler
- Installer ExecutorHandler
- Memorist ExecutorHandler
- Pentester ExecutorHandler
- Searcher ExecutorHandler
- Summarizer SummarizeHandler
+ UseAgents bool
+ Adviser ExecutorHandler
+ Coder ExecutorHandler
+ Installer ExecutorHandler
+ Memorist ExecutorHandler
+ Pentester ExecutorHandler
+ Searcher ExecutorHandler
+ Summarizer SummarizeHandler
+ FlowManager FlowManagerHandlers
+}
+
+// FlowManagerHandlers holds optional callbacks for automation flow control.
+// When StopFlow is non-nil all four flow-management tools are registered.
+type FlowManagerHandlers struct {
+ StopFlow func(ctx context.Context, reason string) error
+ SendFlowInput func(ctx context.Context, input string) error
+ PatchSubtasks func(ctx context.Context, taskID int64, patch SubtaskPatch) error
}
type PrimaryExecutorConfig struct {
@@ -686,6 +695,28 @@ func (fte *flowToolsExecutor) GetAssistantExecutor(cfg AssistantExecutorConfig)
}
}
+ flowStatus := NewFlowStatusTool(fte.flowID, fte.db, cfg.Summarizer)
+ definitions = append(definitions, registryDefinitions[GetFlowStatusToolName])
+ handlers[GetFlowStatusToolName] = flowStatus.Handle
+
+ if cfg.FlowManager.StopFlow != nil {
+ stopFlow := NewStopFlowTool(fte.flowID, fte.db, cfg.FlowManager.StopFlow)
+ definitions = append(definitions, registryDefinitions[StopFlowToolName])
+ handlers[StopFlowToolName] = stopFlow.Handle
+ }
+
+ if cfg.FlowManager.SendFlowInput != nil {
+ submitInput := NewSubmitFlowInputTool(fte.flowID, fte.db, cfg.FlowManager.SendFlowInput)
+ definitions = append(definitions, registryDefinitions[SubmitFlowInputToolName])
+ handlers[SubmitFlowInputToolName] = submitInput.Handle
+ }
+
+ if cfg.FlowManager.PatchSubtasks != nil {
+ patchSubtasks := NewPatchFlowSubtasksTool(fte.flowID, fte.db, cfg.FlowManager.PatchSubtasks)
+ definitions = append(definitions, registryDefinitions[PatchFlowSubtasksToolName])
+ handlers[PatchFlowSubtasksToolName] = patchSubtasks.Handle
+ }
+
ce := &customExecutor{
flowID: fte.flowID,
mlp: fte.mlp,