Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat: add durable team task orchestration
trohitg228c286283ad
diff --git a/CLAUDE.md b/CLAUDE.mdindex 44690d97..bbcb85e1 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1109,7 +1109,7 @@ AI Agent (`aiAgent`) and Chat Agent / Zeenie (`chatAgent`) run the same plain-as**`max_iterations` precedence (highest->lowest): per-node `parameters.max_iterations` > `UserSettings.agent_recursion_limit` > env `AGENT_RECURSION_LIMIT` (default 200) > `llm_defaults.json:agent.recursion_limit`.**-Full reference — agent loop, skill injection, tool building, input/auto-prompt fallback (message>text>content>str), handle topology, spec-driven `AIAgentNode`, async delegation (F4.B child-workflow + legacy fire-and-forget), specialized-agent routing — in [docs-internal/agent_architecture.md](./docs-internal/agent_architecture.md); delegation deep-dive in [agent_delegation.md](./docs-internal/agent_delegation.md), team leads in [agent_teams.md](./docs-internal/agent_teams.md).+Full reference — agent loop, skill injection, tool building, input/auto-prompt fallback (message>text>content>str), handle topology, spec-driven `AIAgentNode`, durable Task Manager delegation (Temporal child workflows plus the legacy bridge), and specialized-agent routing — in [docs-internal/agent_architecture.md](./docs-internal/agent_architecture.md); low-level compatibility mechanics in [agent_delegation.md](./docs-internal/agent_delegation.md), and the authoritative team-lead contract in [agent_teams.md](./docs-internal/agent_teams.md).## Architecture Patterns- **Plugin-first (Wave 11).** One folder per plugin under [`server/nodes/<group>/<plugin>/`](./server/nodes/) rooted at `__init__.py`, subclassing `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode`. Auto-registers via `__init_subclass__`. See [`docs-internal/plugin_system.md`](./docs-internal/plugin_system.md).@@ -1429,7 +1429,11 @@ class MyTool(ToolNode): # or SpecializedAgentBase for an agent`BaseNode.__init_subclass__` registers the class into `_NODE_CLASS_REGISTRY` (first), then into `NODE_METADATA`, `_DIRECT_MODELS`, `NODE_OUTPUT_SCHEMAS`, and `_HANDLER_REGISTRY` on import. The class-registry-first order matters: `_metadata_dict` calls `get_plugin_icon_path(cls.type)` which goes through `get_node_class()`. NodeSpec emits at `GET /api/schemas/nodes/<type>/spec.json`. The frontend auto-discovers via `useNodeSpec` + `componentKind` dispatch (see "Spec-driven component design" above). Icon goes in `<plugin>/icon.svg` (or `visuals.json` for emoji / library brand); color goes in `<plugin>/meta.json` (or `visuals.json` legacy fallback).**Cross-cutting edits that are still required (small):**-- New specialized agent: add the agent's `type` string to the delegation-check tuple in [`server/services/handlers/tools.py:execute_tool()`](./server/services/handlers/tools.py) (~line 224) so the parent agent's `delegate_to_*` tool finds it. Also update `AI_AGENT_TYPES` frozenset in [`server/constants.py`](./server/constants.py) — used for legacy delegation checks. Both are flagged as tech debt; see "remaining tribal arrays" note.+- New specialized agent: update `AI_AGENT_TYPES` and the canonical teammate+ discovery/validation surfaces so a team lead can authorize it through+ `input-teammates`. Team leads delegate with Task Manager; `delegate_to_*`+ remains an internal/legacy dispatch identity and must not be taught as the+ model-facing team contract.- Brand-new uiHint flag: add to `INodeUIHints` in [`client/src/types/INodeProperties.ts`](./client/src/types/INodeProperties.ts) AND to the `known` set in `test_ui_hints_only_carry_known_flags` (`server/tests/test_node_spec.py`).**No edits needed:** any TypeScript node definition file, `_get_tool_schema()`, `AGENT_CONFIGS`, `AGENT_WITH_SKILLS_TYPES`, `aiAgentTypes`, `Dashboard.tsx`, `MiddleSection.tsx`, `InputSection.tsx`, or any of the other arrays the pre-Wave-11 docs listed.@@ -1448,7 +1452,7 @@ Tool nodes display execution status via the standard node status system:| calculatorTool | CalculatorSchema | `_execute_calculator()` | Math operations || currentTimeTool | CurrentTimeSchema | `_execute_current_time()` | Date/time with timezone || duckduckgoSearch | DuckDuckGoSearchSchema | `_execute_duckduckgo_search()` | DuckDuckGo web search (free) |-| taskManager | TaskManagerSchema | `_execute_task_manager()` | Task creation and management |+| taskManager | `TaskManagerParams` | `_execute_task_manager()` | Intrinsic durable team assignment, review, retry/reassignment, cancellation, and acceptance || writeTodos | WriteTodosSchema | `execute_write_todos()` / `handle_write_todos()` | Structured task list planning with checklist rendering || braveSearch | BraveSearchSchema | `handle_brave_search()` | Brave Search API web results || serperSearch | SerperSearchSchema | `handle_serper_search()` | Google SERP via Serper API |diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 929fdcf8..2acbbfaa 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -36,7 +36,7 @@ Deep dives: [DESIGN.md](docs-internal/DESIGN.md) - [TEMPORAL_ARCHITECTURE.md](do[](https://raw.githubusercontent.com/zeenie-ai/OpenCompany/main/docs/diagrams/ai-agent-routing.svg)-AI execution splits into two paths. `execute_chat()` for direct chat completions delegates every provider to the native SDK layer in [services/llm/](server/services/llm/) via `ChatUnifier` (12 providers, lazy imports, normalized `LLMResponse`; Groq, Cerebras, and the local servers ride the OpenAI-compatible client with a custom `base_url` — the old chat-path LangChain fallback is retired). `execute_agent()` and `execute_chat_agent()` build a LangChain chat model (`ChatOpenAI` / `ChatAnthropic` / etc.) and drive it through `_run_agent_loop` — a plain async `for iteration in range(max):` that calls `chat_model.ainvoke`, dispatches any `tool_calls`, appends `ToolMessage` results, and loops. Team leads (`orchestrator_agent`, `ai_employee`) auto-inject `delegate_to_<type>` tools for every agent connected to their `input-teammates` handle. The RLM Agent uses a REPL-based recursive language model pattern. Long-running activities (browser automation, claude_code_agent) stay alive across Temporal's 2-minute heartbeat window via per-message `activity.heartbeat()` calls in the WebSocket read loop.+AI execution splits into two paths. `execute_chat()` for direct chat completions delegates every provider to the native SDK layer in [services/llm/](server/services/llm/) via `ChatUnifier` (12 providers, lazy imports, normalized `LLMResponse`; Groq, Cerebras, and the local servers ride the OpenAI-compatible client with a custom `base_url` — the old chat-path LangChain fallback is retired). `execute_agent()` and `execute_chat_agent()` build a LangChain chat model (`ChatOpenAI` / `ChatAnthropic` / etc.) and drive it through `_run_agent_loop`. Team leads (`orchestrator_agent`, `ai_employee`) receive an intrinsic Task Manager and may assign only agents connected to their `input-teammates` handle. Delegate descriptors stay internal for dispatch; the model calls `task_manager(assign_task)` and reviews `submitted` work before acceptance. Temporal batches same-turn assignments under the root-wide concurrency coordinator; legacy execution reuses the same durable task record. The RLM Agent uses a REPL-based recursive language model pattern. Long-running activities remain alive through activity heartbeats.Deep dives: [agent_architecture.md](docs-internal/agent_architecture.md) - [native_llm_sdk.md](docs-internal/native_llm_sdk.md) - [agent_teams.md](docs-internal/agent_teams.md) - [memory_compaction.md](docs-internal/memory_compaction.md) - [cli_agent_framework.md](docs-internal/cli_agent_framework.md)diff --git a/README.md b/README.mdindex 617f9a34..75c411d4 100644--- a/README.md+++ b/README.md@@ -68,7 +68,7 @@ Three example workflows load automatically on first launch. Open them on the can## What You Can Build- **Personal AI assistants that remember.** A chat assistant that knows your calendar, reads your inbox, and follows up on tasks. Conversations are saved as readable markdown you can edit; long-term memory uses vector search so years of context stay accessible.-- **Agent teams that delegate.** Hire an **AI Employee** as a team lead, connect specialist agents (coding, web, productivity...), and the lead automatically exposes each one as a `delegate_to_*` tool — the AI decides who gets which subtask.+- **Durable agent teams.** Hire an **AI Employee** or Orchestrator as a team lead, connect specialist agents through `input-teammates`, and the lead assigns bounded work through its built-in Task Manager. Tasks are durably queued, run up to three descendants in parallel, require lead acceptance, and remain visible in the read-only Team Monitor.- **Automations that run themselves.** Recurring jobs ("every weekday at 9 AM, summarize my unread emails"), event-driven replies ("when a customer texts on WhatsApp, draft a response"), and multi-step background pipelines. Any workflow can also expose a live `/webhook/{path}` HTTP endpoint that fires on GET, POST, PUT, DELETE, or PATCH.- **Email, calendar, and document workflows.** Send and search Gmail, manage Calendar, Drive, Sheets, Tasks, and Contacts. Read any inbox over IMAP (Gmail, Outlook, Yahoo, iCloud, ProtonMail, Fastmail, or custom servers) — including a polling trigger that fires a workflow on every new message.- **Messaging bots.** Send and receive on **WhatsApp** (groups, contacts, newsletter channels), **Telegram** (bots with owner detection), and **Twitter/X** (post, reply, search). A unified social node normalizes incoming messages into one format so the same workflow handles them all.diff --git a/client/src/components/TeamMonitorNode.tsx b/client/src/components/TeamMonitorNode.tsxindex 19f79437..a4b96825 100644--- a/client/src/components/TeamMonitorNode.tsx+++ b/client/src/components/TeamMonitorNode.tsx@@ -13,7 +13,7 @@ const TEAM_LEAD_TYPES = ['ai_employee', 'orchestrator_agent'];interface TeamTask {id: string;title: string;- status: 'pending' | 'in_progress' | 'completed' | 'failed' | 'skipped';+ status: 'blocked' | 'queued' | 'running' | 'submitted' | 'accepted' | 'failed' | 'cancelled' | 'pending' | 'in_progress' | 'completed' | 'skipped';assigned_to?: string;}@@ -21,6 +21,7 @@ interface TeamMember {agent_node_id: string;agent_type: string;status: string;+ label?: string;}interface TeamStatus {@@ -65,6 +66,29 @@ const TeamMonitorNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnreturn null;}, [edges, nodes, id]);+ const connectedTeammates = useMemo<TeamMember[]>(() => {+ if (!connectedTeamLead) return [];+ return edges+ .filter((edge) => edge.target === connectedTeamLead.id && edge.targetHandle === 'input-teammates')+ .map((edge) => nodes.find((node) => node.id === edge.source))+ .filter((node): node is NonNullable<typeof node> => !!node)+ .map((node) => ({+ agent_node_id: node.id,+ agent_type: node.type || 'aiAgent',+ label: String((node.data as NodeData | undefined)?.label || node.type || 'Agent'),+ status: 'connected',+ }));+ }, [connectedTeamLead, edges, nodes]);++ const visibleMembers = useMemo(() => {+ const persisted = teamStatus?.members || [];+ const byId = new Map(persisted.map((member) => [member.agent_node_id, member]));+ for (const member of connectedTeammates) {+ byId.set(member.agent_node_id, { ...member, ...(byId.get(member.agent_node_id) || {}) });+ }+ return [...byId.values()].filter((member) => member.agent_node_id !== connectedTeamLead?.id);+ }, [connectedTeamLead?.id, connectedTeammates, teamStatus?.members]);+// Fetch team statusconst fetchTeamStatus = useCallback(async () => {// Use explicit teamId from data, or get from connected node's workflow context@@ -118,9 +142,14 @@ const TeamMonitorNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnconst getStatusColor = (status: string) => {switch (status) {+ case 'accepted':case 'completed': return 'var(--success)';+ case 'submitted': return 'var(--node-agent)';+ case 'running':case 'in_progress': return 'var(--info)';case 'failed': return 'var(--destructive)';+ case 'blocked':+ case 'queued':case 'pending': return 'var(--warning)';default: return theme.colors.textSecondary;}@@ -166,7 +195,7 @@ const TeamMonitorNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConn}}><div style={{ textAlign: 'center' }}><div style={{ fontSize: 12, fontWeight: 'bold', color: 'var(--node-agent)' }}>- {teamStatus?.members?.length || 0}+ {visibleMembers.length}</div><div style={{ fontSize: 8, color: theme.colors.textSecondary }}>Team</div></div>@@ -196,6 +225,20 @@ const TeamMonitorNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConn</div></div>+ {/* Connected teammates */}+ {visibleMembers.length > 0 && (+ <div style={{ padding: '4px 6px', borderBottom: `1px solid ${theme.colors.border}` }}>+ {visibleMembers.slice(0, 4).map((member) => (+ <div key={member.agent_node_id} title={member.agent_type} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '2px 0', fontSize: 9 }}>+ <span style={{ width: 6, height: 6, borderRadius: '50%', backgroundColor: member.status === 'working' ? 'var(--info)' : 'var(--success)', flexShrink: 0 }} />+ <span style={{ color: theme.colors.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{member.label || member.agent_type}</span>+ <span style={{ marginLeft: 'auto', color: theme.colors.textSecondary }}>{member.status}</span>+ </div>+ ))}+ {visibleMembers.length > 4 && <div style={{ color: theme.colors.textSecondary, fontSize: 8 }}>+{visibleMembers.length - 4} more</div>}+ </div>+ )}+{/* Active Tasks */}<div style={{ padding: '4px 6px', maxHeight: 80, overflow: 'auto' }}>{!data?.teamId && !connectedTeamLead ? (diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsxindex c0609a38..1520322a 100644--- a/client/src/components/parameterPanel/MiddleSection.tsx+++ b/client/src/components/parameterPanel/MiddleSection.tsx@@ -29,6 +29,8 @@ import { ActionButton } from '@/components/ui/action-button';import ParameterRenderer from '../ParameterRenderer';import MasterSkillEditor from './MasterSkillEditor';import TodoEditor from './TodoEditor';+import TaskManagerPanel from './TaskManagerPanel';+import TeamMonitorPanel from './TeamMonitorPanel';import { useAppStore } from '../../store/useAppStore';import { useWebSocket, CompactionStats } from '../../contexts/WebSocketContext';import { useUserSettingsQuery } from '../../hooks/useUserSettingsQuery';@@ -183,6 +185,8 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({// it's now permanently dead.const isSkillNode = false;const isTodoEditorNode = hints.isTodoEditor === true;+ const isTaskManagerNode = hints.isTaskManagerPanel === true;+ const isMonitorNode = hints.isMonitorPanel === true;const isAgentWithSkills = hints.hasSkills === true;const { data: userSettings } = useUserSettingsQuery();@@ -518,7 +522,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({<div className="relative flex h-full flex-1 flex-col overflow-hidden">{/* Description - hide for code editor nodes (Python, Skill), masterSkill,and the todo editor (each renders its own full-panel header). */}- {!needsCodeEditorLayout && !isMasterSkillNode && !isTodoEditorNode && (+ {!needsCodeEditorLayout && !isMasterSkillNode && !isTodoEditorNode && !isTaskManagerNode && !isMonitorNode && (<div className="shrink-0 border-b border-border-default bg-bg-panel px-6 pt-4 pb-2"><p className="m-0 text-base leading-[1.5] text-fg-muted">{nodeDefinition.description}@@ -541,6 +545,20 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({</div>) : isTodoEditorNode ? (<TodoEditor nodeId={nodeId} />+ ) : isTaskManagerNode ? (+ <TaskManagerPanel+ nodeId={nodeId}+ workflowId={currentWorkflow?.id}+ nodes={currentWorkflow?.nodes || []}+ edges={currentWorkflow?.edges || []}+ />+ ) : isMonitorNode ? (+ <TeamMonitorPanel+ nodeId={nodeId}+ workflowId={currentWorkflow?.id}+ nodes={currentWorkflow?.nodes || []}+ edges={currentWorkflow?.edges || []}+ />) : (<>{/* Parameters */}diff --git a/client/src/components/parameterPanel/TaskManagerPanel.tsx b/client/src/components/parameterPanel/TaskManagerPanel.tsxnew file mode 100644index 00000000..897bf42d--- /dev/null+++ b/client/src/components/parameterPanel/TaskManagerPanel.tsx@@ -0,0 +1,286 @@+import React, { useCallback, useEffect, useMemo, useState } from 'react';+import { Eye, Filter, RefreshCw, Search } from 'lucide-react';+import { toast } from 'sonner';+import type { Edge, Node } from 'reactflow';++import { useWebSocket } from '@/contexts/WebSocketContext';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Textarea } from '@/components/ui/textarea';+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';+import {+ AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,+ AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,+} from '@/components/ui/alert-dialog';+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { cn } from '@/lib/utils';++export type TeamTaskStatus = 'blocked' | 'queued' | 'running' | 'submitted' | 'accepted' | 'failed' | 'cancelled';++export interface TeamTaskAttempt {+ id: string;+ attempt_number: number;+ assignee_node_id?: string;+ status: string;+ result?: unknown;+ error?: string;+ started_at?: string;+ completed_at?: string;+}++export interface TeamTaskView {+ id: string;+ title: string;+ mission?: string;+ description?: string;+ context?: unknown;+ acceptance_criteria?: string | string[];+ status: TeamTaskStatus | string;+ assigned_to?: string;+ assignee_label?: string;+ assignee_type?: string;+ queue_position?: number;+ queue_sequence?: number;+ depends_on?: string[];+ current_attempt?: number;+ retry_count?: number;+ revision?: number;+ result?: unknown;+ error?: string;+ usage?: { input_tokens?: number; output_tokens?: number; total_tokens?: number; cost?: number };+ trace_id?: string;+ child_workflow_id?: string;+ child_run_id?: string;+ created_at?: string;+ started_at?: string;+ completed_at?: string;+ attempts?: TeamTaskAttempt[];+ allowed_actions?: string[];+}++interface TeamExecution {+ execution_id: string;+ label?: string;+ status?: string;+ created_at?: string;+}++interface TeamStatusView {+ team_id?: string;+ execution_id?: string;+ root_execution_id?: string;+ status?: string;+ tasks?: TeamTaskView[];+ active_tasks?: TeamTaskView[];+ archived_executions?: TeamExecution[];+ max_concurrent_subagents?: number;+ active_count?: number;+ [key: string]: unknown;+}++type PendingAction = { operation: string; task?: TeamTaskView; label: string } | null;++const STATUSES: TeamTaskStatus[] = ['blocked', 'queued', 'running', 'submitted', 'accepted', 'failed', 'cancelled'];+const STATUS_STYLES: Record<string, string> = {+ blocked: 'border-fg-muted/30 bg-bg-panel text-fg-muted',+ queued: 'border-warning/30 bg-warning/10 text-warning',+ running: 'border-info/30 bg-info/10 text-info',+ submitted: 'border-node-agent/30 bg-node-agent/10 text-node-agent',+ accepted: 'border-success/30 bg-success/10 text-success',+ failed: 'border-destructive/30 bg-destructive/10 text-destructive',+ cancelled: 'border-fg-muted/30 bg-bg-panel text-fg-muted',+};++const jsonText = (value: unknown): string => {+ if (value == null) return '';+ if (typeof value === 'string') return value;+ try { return JSON.stringify(value, null, 2); } catch { return String(value); }+};++const elapsed = (task: TeamTaskView): string => {+ const start = task.started_at || task.created_at;+ if (!start) return '—';+ const end = task.completed_at ? new Date(task.completed_at).getTime() : Date.now();+ const seconds = Math.max(0, Math.round((end - new Date(start).getTime()) / 1000));+ if (seconds < 60) return `${seconds}s`;+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;+ return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;+};++const taskTokens = (task: TeamTaskView): number => task.usage?.total_tokens+ ?? ((task.usage?.input_tokens || 0) + (task.usage?.output_tokens || 0));++interface Props { nodeId: string; workflowId?: string; nodes: Node[]; edges: Edge[] }++const TaskManagerPanel: React.FC<Props> = ({ nodeId, workflowId, nodes, edges }) => {+ const { sendRequest, addEventListener } = useWebSocket();+ const [status, setStatus] = useState<TeamStatusView | null>(null);+ const [loading, setLoading] = useState(false);+ const [search, setSearch] = useState('');+ const [filter, setFilter] = useState('all');+ const [executionId, setExecutionId] = useState<string>('active');+ const [selected, setSelected] = useState<TeamTaskView | null>(null);+ const [pending, setPending] = useState<PendingAction>(null);+ const [actionText, setActionText] = useState('');+ const [assignee, setAssignee] = useState('');+ const [busy, setBusy] = useState(false);+ const [page, setPage] = useState(0);+ const pageSize = 25;++ const connectedLead = useMemo(() => {+ const selected = nodes.find((node) => node.id === nodeId);+ if (selected && ['orchestrator_agent', 'ai_employee'].includes(selected.type || '')) return selected;+ const edge = edges.find((candidate) => candidate.source === nodeId && candidate.targetHandle === 'input-tools');+ return edge ? nodes.find((node) => node.id === edge.target) : undefined;+ }, [edges, nodeId, nodes]);++ const teammates = useMemo(() => {+ if (!connectedLead) return [];+ return edges+ .filter((edge) => edge.target === connectedLead.id && edge.targetHandle === 'input-teammates')+ .map((edge) => nodes.find((node) => node.id === edge.source))+ .filter((node): node is Node => !!node);+ }, [connectedLead, edges, nodes]);++ const fetchStatus = useCallback(async (quiet = false) => {+ if (!workflowId || !connectedLead) return;+ if (!quiet) setLoading(true);+ try {+ const scope = {+ workflow_id: workflowId,+ team_lead_node_id: connectedLead.id,+ ...(executionId !== 'active' ? { execution_id: executionId } : {}),+ };+ const [response, taskResponse] = await Promise.all([+ sendRequest<{ status?: TeamStatusView }>('get_team_status', scope),+ sendRequest<{ tasks?: TeamTaskView[] }>('get_team_tasks', scope),+ ]);+ setStatus(response?.status ? { ...response.status, tasks: taskResponse?.tasks || response.status.tasks || [] } : null);+ } catch (error) {+ if (!quiet) toast.error(error instanceof Error ? error.message : 'Unable to load team tasks');+ } finally {+ if (!quiet) setLoading(false);+ }+ }, [connectedLead, executionId, sendRequest, workflowId]);++ useEffect(() => { void fetchStatus(); }, [fetchStatus]);+ useEffect(() => {+ const refresh = (event: any) => {+ const eventTeamId = event?.team_id ?? event?.data?.team_id;+ if (!eventTeamId || !status?.team_id || eventTeamId === status.team_id) void fetchStatus(true);+ };+ const unsubscribers = ['team_event', 'task_added', 'task_claimed', 'task_completed', 'task_failed',+ 'team.task.submitted', 'team.task.requeued', 'team.task.failed', 'team.task.cancelled', 'team.task.accepted']+ .map((name) => addEventListener(name, refresh));+ return () => unsubscribers.forEach((unsubscribe) => unsubscribe());+ }, [addEventListener, fetchStatus, status?.team_id]);+ useEffect(() => {+ const interval = window.setInterval(() => void fetchStatus(true), 15_000);+ return () => window.clearInterval(interval);+ }, [fetchStatus]);++ const tasks = useMemo(() => {+ const full = status?.tasks?.length ? status.tasks : (status?.active_tasks || []);+ return full.filter((task) => {+ if (filter !== 'all' && task.status !== filter) return false;+ const haystack = `${task.title} ${task.mission || task.description || ''} ${task.assignee_label || task.assigned_to || ''}`.toLowerCase();+ return haystack.includes(search.toLowerCase());+ });+ }, [filter, search, status]);+ const counts = useMemo(() => Object.fromEntries(STATUSES.map((name) => [name,+ (status?.tasks || []).filter((task) => task.status === name).length || Number(status?.[`${name}_count`] || 0),+ ])), [status]);+ const active = Number(status?.active_count ?? counts.running ?? 0);+ const limit = Number(status?.max_concurrent_subagents || 3);+ const pages = Math.max(1, Math.ceil(tasks.length / pageSize));+ const visible = tasks.slice(page * pageSize, (page + 1) * pageSize);++ useEffect(() => setPage(0), [filter, search, executionId]);++ const runAction = async () => {+ if (!pending || !workflowId || !connectedLead) return;+ setBusy(true);+ try {+ const isFinish = pending.operation === 'finish';+ const response = await sendRequest<{ success?: boolean; error?: string }>(isFinish ? 'finish_team' : 'manage_team_task', {+ ...(!isFinish ? { operation: pending.operation } : {}),+ workflow_id: workflowId,+ team_lead_node_id: connectedLead.id,+ execution_id: status?.execution_id,+ task_id: pending.task?.id,+ revision: pending.task?.revision,+ reason: actionText || undefined,+ mission: pending.operation === 'modify' ? actionText : undefined,+ assignee_node_id: pending.operation === 'reassign' ? assignee : undefined,+ });+ if (response?.success === false || response?.error) throw new Error(response.error || 'Action rejected');+ toast.success(`${pending.label} requested`);+ setPending(null); setActionText(''); setAssignee('');+ await fetchStatus(true);+ } catch (error) {+ toast.error(error instanceof Error ? error.message : 'Task changed before this action could be applied');+ await fetchStatus(true);+ } finally { setBusy(false); }+ };++ const openAction = (operation: string, label: string, task?: TeamTaskView) => {+ setActionText(operation === 'modify' ? (task?.mission || task?.description || '') : '');+ setAssignee('');+ setPending({ operation, label, task });+ };+ const actionsFor = (task: TeamTaskView) => task.allowed_actions || ({+ blocked: ['modify', 'cancel'], queued: ['modify', 'cancel'], running: ['cancel'],+ submitted: ['accept', 'retry', 'reassign'], failed: ['retry', 'reassign'],+ cancelled: ['retry', 'reassign'], accepted: [],+ }[task.status] || []);++ if (!connectedLead) return <div className="flex h-full items-center justify-center p-8 text-center text-fg-muted">Connect Task Manager to a team lead’s Tools handle to inspect its tasks.</div>;++ return <div className="flex h-full min-h-0 flex-col bg-bg-panel">+ <div className="shrink-0 border-b border-border-default px-5 py-4">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div><h2 className="text-lg font-semibold text-fg-default">Team tasks</h2><p className="text-sm text-fg-muted">{connectedLead.data?.label || 'Team lead'} · {status?.status || 'No active team'}</p></div>+ <div className="flex items-center gap-2">+ {(status?.archived_executions?.length || 0) > 0 && <Select value={executionId} onValueChange={setExecutionId}><SelectTrigger className="w-48" aria-label="Execution"><SelectValue /></SelectTrigger><SelectContent><SelectItem value="active">Current execution</SelectItem>{status!.archived_executions!.map((run) => <SelectItem key={run.execution_id} value={run.execution_id}>{run.label || run.execution_id.slice(0, 12)}</SelectItem>)}</SelectContent></Select>}+ <Button variant="outline" size="sm" onClick={() => void fetchStatus()} disabled={loading}><RefreshCw className={cn('h-4 w-4', loading && 'animate-spin')} /> Refresh</Button>+ <Button size="sm" disabled={!status?.team_id} onClick={() => openAction('finish', 'Finish team')}>Finish team</Button>+ </div>+ </div>+ <div className="mt-4 grid grid-cols-4 gap-2 lg:grid-cols-8">+ <button className="rounded-md border border-border-default bg-bg-elevated p-2 text-left" onClick={() => setFilter('running')}><span className="text-xs text-fg-muted">Concurrency</span><div className="font-semibold tabular-nums text-info">{active} / {limit}</div></button>+ {STATUSES.map((name) => <button key={name} className={cn('rounded-md border p-2 text-left', STATUS_STYLES[name], filter === name && 'ring-2 ring-node-agent')} onClick={() => setFilter(filter === name ? 'all' : name)}><span className="text-xs capitalize">{name}</span><div className="font-semibold tabular-nums">{counts[name] || 0}</div></button>)}+ </div>+ </div>+ <div className="flex min-h-0 flex-1 flex-col p-4">+ <div className="mb-3 flex gap-2"><div className="relative flex-1"><Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-fg-muted" /><Input className="pl-9" value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search tasks, missions, or assignees" /></div><Select value={filter} onValueChange={setFilter}><SelectTrigger className="w-40"><Filter className="h-4 w-4" /><SelectValue /></SelectTrigger><SelectContent><SelectItem value="all">All statuses</SelectItem>{STATUSES.map((name) => <SelectItem key={name} value={name} className="capitalize">{name}</SelectItem>)}</SelectContent></Select></div>+ <div className="min-h-0 flex-1 overflow-auto rounded-md border border-border-default bg-bg-elevated">+ <table className="w-full min-w-[900px] border-collapse text-sm"><thead className="sticky top-0 z-10 bg-bg-panel text-left text-xs text-fg-muted"><tr>{['Task','Assignee','Status','Queue','Attempt','Elapsed','Tokens',''].map((h) => <th key={h} className="border-b border-border-default px-3 py-2 font-medium">{h}</th>)}</tr></thead><tbody>+ {visible.map((task) => <tr key={task.id} className="border-b border-border-default/70 hover:bg-bg-panel"><td className="max-w-[320px] px-3 py-3"><button className="block w-full text-left" onClick={() => setSelected(task)}><span className="block truncate font-medium text-fg-default">{task.title}</span><span className="block truncate text-xs text-fg-muted">{task.mission || task.description || 'No mission provided'}</span></button></td><td className="px-3 py-3"><span className="block">{task.assignee_label || task.assigned_to || 'Unassigned'}</span><span className="text-xs text-fg-muted">{task.assignee_type || ''}</span></td><td className="px-3 py-3"><Badge variant="outline" className={cn('capitalize', STATUS_STYLES[task.status])}>{task.status}</Badge></td><td className="px-3 py-3 tabular-nums">{task.queue_position ?? task.queue_sequence ?? '—'}</td><td className="px-3 py-3 tabular-nums">{task.current_attempt ?? 0}{task.retry_count ? ` (+${task.retry_count})` : ''}</td><td className="px-3 py-3 tabular-nums">{elapsed(task)}</td><td className="px-3 py-3 tabular-nums">{taskTokens(task).toLocaleString()}</td><td className="px-3 py-3"><Button variant="ghost" size="sm" onClick={() => setSelected(task)} aria-label={`Inspect ${task.title}`}><Eye className="h-4 w-4" /></Button></td></tr>)}+ {!loading && visible.length === 0 && <tr><td colSpan={8} className="p-12 text-center text-fg-muted">No tasks match this view.</td></tr>}+ </tbody></table>+ </div>+ {pages > 1 && <div className="mt-3 flex items-center justify-end gap-2 text-sm text-fg-muted"><Button variant="outline" size="sm" disabled={page === 0} onClick={() => setPage(page - 1)}>Previous</Button><span>{page + 1} / {pages}</span><Button variant="outline" size="sm" disabled={page + 1 >= pages} onClick={() => setPage(page + 1)}>Next</Button></div>}+ </div>++ <Dialog open={!!selected} onOpenChange={(open) => !open && setSelected(null)}><DialogContent className="max-h-[85vh] max-w-3xl overflow-y-auto"><DialogHeader><DialogTitle>{selected?.title}</DialogTitle></DialogHeader>{selected && <div className="space-y-5 text-sm">+ <div className="flex flex-wrap items-center gap-2"><Badge variant="outline" className={cn('capitalize', STATUS_STYLES[selected.status])}>{selected.status}</Badge><span className="text-fg-muted">Revision {selected.revision ?? 0} · Attempt {selected.current_attempt ?? 0} · {elapsed(selected)}</span></div>+ <section><h3 className="mb-1 font-medium">Mission</h3><p className="whitespace-pre-wrap text-fg-muted">{selected.mission || selected.description || '—'}</p></section>+ <section><h3 className="mb-1 font-medium">Acceptance criteria</h3><pre className="whitespace-pre-wrap rounded bg-bg-panel p-3 text-fg-muted">{jsonText(selected.acceptance_criteria) || '—'}</pre></section>+ <section><h3 className="mb-1 font-medium">Context</h3><pre className="max-h-48 overflow-auto whitespace-pre-wrap rounded bg-bg-panel p-3 text-xs text-fg-muted">{jsonText(selected.context) || '—'}</pre></section>+ {(selected.result != null || selected.error) && <section><h3 className="mb-1 font-medium">Result</h3><pre className={cn('max-h-64 overflow-auto whitespace-pre-wrap rounded p-3 text-xs', selected.error ? 'bg-destructive/10 text-destructive' : 'bg-success/10')}>{selected.error || jsonText(selected.result)}</pre></section>}+ <section><h3 className="mb-2 font-medium">Attempt history</h3><div className="space-y-2">{(selected.attempts || []).map((attempt) => <div key={attempt.id} className="rounded border border-border-default p-3"><div className="flex justify-between"><span>Attempt {attempt.attempt_number} · {attempt.assignee_node_id || 'Unassigned'}</span><Badge variant="outline">{attempt.status}</Badge></div>{attempt.error && <p className="mt-2 text-destructive">{attempt.error}</p>}</div>)}{!selected.attempts?.length && <p className="text-fg-muted">No previous attempts.</p>}</div></section>+ <section className="grid grid-cols-2 gap-2 rounded border border-border-default p-3 text-xs text-fg-muted"><span>Trace: {selected.trace_id || '—'}</span><span>Child workflow: {selected.child_workflow_id || '—'}</span><span>Child run: {selected.child_run_id || '—'}</span><span>Dependencies: {selected.depends_on?.join(', ') || 'None'}</span></section>+ <div className="flex flex-wrap justify-end gap-2">{actionsFor(selected).map((action) => <Button key={action} variant={action === 'cancel' ? 'destructive' : action === 'accept' ? 'default' : 'outline'} onClick={() => { setSelected(null); openAction(action.replace('_task', ''), action.replace('_task','').replace('_',' '), selected); }}>{action.replace('_task','').replace('_',' ')}</Button>)}</div>+ </div>}</DialogContent></Dialog>++ <AlertDialog open={!!pending} onOpenChange={(open) => !open && setPending(null)}><AlertDialogContent><AlertDialogHeader><AlertDialogTitle className="capitalize">{pending?.label}</AlertDialogTitle><AlertDialogDescription>{pending?.task ? `Apply this action to “${pending.task.title}”? The latest task revision will be checked.` : 'Finish this team only if every required task is resolved.'}</AlertDialogDescription></AlertDialogHeader>+ {pending?.operation === 'modify' && <Textarea value={actionText} onChange={(e) => setActionText(e.target.value)} placeholder="Updated mission" rows={5} />}+ {pending?.operation === 'reassign' && <Select value={assignee} onValueChange={setAssignee}><SelectTrigger><SelectValue placeholder="Choose a connected teammate" /></SelectTrigger><SelectContent>{teammates.map((node) => <SelectItem key={node.id} value={node.id}>{node.data?.label || node.type || node.id}</SelectItem>)}</SelectContent></Select>}+ {['cancel','retry','accept','finish'].includes(pending?.operation || '') && <Textarea value={actionText} onChange={(e) => setActionText(e.target.value)} placeholder="Reason or review note (optional)" rows={3} />}+ <AlertDialogFooter><AlertDialogCancel disabled={busy}>Cancel</AlertDialogCancel><AlertDialogAction disabled={busy || (pending?.operation === 'reassign' && !assignee) || (pending?.operation === 'modify' && !actionText.trim())} onClick={(event) => { event.preventDefault(); void runAction(); }}>{busy ? 'Applying…' : 'Confirm'}</AlertDialogAction></AlertDialogFooter>+ </AlertDialogContent></AlertDialog>+ </div>;+};++export default TaskManagerPanel;diff --git a/client/src/components/parameterPanel/TeamMonitorPanel.tsx b/client/src/components/parameterPanel/TeamMonitorPanel.tsxnew file mode 100644index 00000000..d10c3fdf--- /dev/null+++ b/client/src/components/parameterPanel/TeamMonitorPanel.tsx@@ -0,0 +1,103 @@+import React, { useCallback, useEffect, useMemo, useState } from 'react';+import { RefreshCw, Users } from 'lucide-react';+import type { Edge, Node } from 'reactflow';++import { useWebSocket } from '@/contexts/WebSocketContext';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { cn } from '@/lib/utils';++const LEAD_TYPES = new Set(['orchestrator_agent', 'ai_employee']);+const STATUS_STYLE: Record<string, string> = {+ blocked: 'text-fg-muted', queued: 'text-warning', running: 'text-info',+ submitted: 'text-node-agent', accepted: 'text-success', failed: 'text-destructive',+ cancelled: 'text-fg-muted', working: 'text-info', idle: 'text-success', connected: 'text-success',+};++interface Props { nodeId: string; workflowId?: string; nodes: Node[]; edges: Edge[] }+interface Member { agent_node_id: string; agent_type?: string; label?: string; status?: string }+interface Task { id: string; title: string; status: string; assigned_to?: string; assignee_label?: string; queue_position?: number }++const TeamMonitorPanel: React.FC<Props> = ({ nodeId, workflowId, nodes, edges }) => {+ const { sendRequest, addEventListener } = useWebSocket();+ const [status, setStatus] = useState<Record<string, any> | null>(null);+ const [tasks, setTasks] = useState<Task[]>([]);+ const [loading, setLoading] = useState(false);++ const lead = useMemo(() => {+ const incoming = edges.filter((edge) => edge.target === nodeId);+ return incoming.map((edge) => nodes.find((node) => node.id === edge.source))+ .find((node) => node && LEAD_TYPES.has(node.type || ''));+ }, [edges, nodeId, nodes]);++ const connected = useMemo<Member[]>(() => {+ if (!lead) return [];+ return edges.filter((edge) => edge.target === lead.id && edge.targetHandle === 'input-teammates')+ .map((edge) => nodes.find((node) => node.id === edge.source))+ .filter((node): node is Node => !!node)+ .map((node) => ({+ agent_node_id: node.id, agent_type: node.type,+ label: String((node.data as any)?.label || node.type || 'Agent'), status: 'connected',+ }));+ }, [edges, lead, nodes]);++ const members = useMemo(() => {+ const merged = new Map(connected.map((member) => [member.agent_node_id, member]));+ for (const member of (status?.members || []) as Member[]) {+ if (member.agent_node_id === lead?.id) continue;+ merged.set(member.agent_node_id, { ...merged.get(member.agent_node_id), ...member });+ }+ return [...merged.values()];+ }, [connected, lead?.id, status?.members]);++ const refresh = useCallback(async (quiet = false) => {+ if (!workflowId || !lead) return;+ if (!quiet) setLoading(true);+ try {+ const scope = { workflow_id: workflowId, team_lead_node_id: lead.id };+ const [teamResponse, taskResponse] = await Promise.all([+ sendRequest<{ status?: Record<string, any> }>('get_team_status', scope),+ sendRequest<{ tasks?: Task[] }>('get_team_tasks', scope),+ ]);+ setStatus(teamResponse.status || null);+ setTasks(taskResponse.tasks || []);+ } finally { if (!quiet) setLoading(false); }+ }, [lead, sendRequest, workflowId]);++ useEffect(() => { void refresh(); }, [refresh]);+ useEffect(() => {+ const update = () => void refresh(true);+ const removers = ['team_event', 'team.task.queued', 'team.task.running', 'team.task.submitted',+ 'team.task.accepted', 'team.task.failed', 'team.task.cancelled'].map((event) => addEventListener(event, update));+ return () => removers.forEach((remove) => remove());+ }, [addEventListener, refresh]);++ if (!lead) return <div className="flex h-full items-center justify-center p-8 text-center text-fg-muted">Connect an Orchestrator Agent or AI Employee to Team Monitor.</div>;++ const counts = ['blocked', 'queued', 'running', 'submitted', 'accepted', 'failed', 'cancelled']+ .map((name) => ({ name, value: tasks.filter((task) => task.status === name).length }));++ return <div className="flex h-full min-h-0 flex-col bg-bg-panel">+ <div className="shrink-0 border-b border-border-default px-6 py-4">+ <div className="flex items-center justify-between gap-3">+ <div><h2 className="text-lg font-semibold text-fg-default">Team Monitor</h2><p className="text-sm text-fg-muted">{String((lead.data as any)?.label || lead.type)} · {status?.status || 'Not running'}</p></div>+ <Button variant="outline" size="sm" onClick={() => void refresh()} disabled={loading}><RefreshCw className={cn('h-4 w-4', loading && 'animate-spin')} /> Refresh</Button>+ </div>+ <div className="mt-4 grid grid-cols-4 gap-2 lg:grid-cols-7">+ {counts.map(({ name, value }) => <div key={name} className="rounded-md border border-border-default bg-bg-elevated p-2"><div className="text-xs capitalize text-fg-muted">{name}</div><div className={cn('text-lg font-semibold tabular-nums', STATUS_STYLE[name])}>{value}</div></div>)}+ </div>+ </div>+ <div className="grid min-h-0 flex-1 grid-cols-1 gap-4 overflow-auto p-4 lg:grid-cols-[minmax(220px,0.75fr)_minmax(0,2fr)]">+ <section className="rounded-md border border-border-default bg-bg-elevated">+ <div className="flex items-center gap-2 border-b border-border-default px-4 py-3 font-medium"><Users className="h-4 w-4" /> Connected agents <Badge variant="outline">{members.length}</Badge></div>+ <div className="divide-y divide-border-default/70">{members.map((member) => <div key={member.agent_node_id} className="flex items-center gap-3 px-4 py-3"><span className={cn('h-2 w-2 rounded-full bg-current', STATUS_STYLE[member.status || 'connected'])} /><div className="min-w-0 flex-1"><div className="truncate font-medium text-fg-default">{member.label || member.agent_type}</div><div className="truncate text-xs text-fg-muted">{member.agent_type}</div></div><span className="text-xs capitalize text-fg-muted">{member.status || 'connected'}</span></div>)}{members.length === 0 && <div className="p-6 text-center text-sm text-fg-muted">No teammates connected.</div>}</div>+ </section>+ <section className="min-w-0 rounded-md border border-border-default bg-bg-elevated">+ <div className="border-b border-border-default px-4 py-3 font-medium">Current execution tasks</div>+ <div className="divide-y divide-border-default/70">{tasks.map((task) => <div key={task.id} className="grid grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-4 px-4 py-3"><div className="truncate font-medium text-fg-default">{task.title}</div><span className="text-xs text-fg-muted">{task.assignee_label || task.assigned_to || 'Unassigned'}</span><Badge variant="outline" className={cn('capitalize', STATUS_STYLE[task.status])}>{task.status}{task.queue_position ? ` #${task.queue_position}` : ''}</Badge></div>)}{tasks.length === 0 && <div className="p-8 text-center text-sm text-fg-muted">No tasks in this execution.</div>}</div>+ </section>+ </div>+ </div>;+};++export default TeamMonitorPanel;diff --git a/client/src/components/parameterPanel/__tests__/TaskManagerPanel.test.tsx b/client/src/components/parameterPanel/__tests__/TaskManagerPanel.test.tsxnew file mode 100644index 00000000..28f4185d--- /dev/null+++ b/client/src/components/parameterPanel/__tests__/TaskManagerPanel.test.tsx@@ -0,0 +1,90 @@+import { fireEvent, screen, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { renderWithProviders as render } from '../../../test/providers';++const { wsMock, listeners } = vi.hoisted(() => ({+ listeners: new Map<string, (data: any) => void>(),+ wsMock: {+ sendRequest: vi.fn(),+ addEventListener: vi.fn((name: string, handler: (data: any) => void) => {+ listeners.set(name, handler);+ return vi.fn();+ }),+ },+}));++vi.mock('../../../contexts/WebSocketContext', () => ({ useWebSocket: () => wsMock }));++import TaskManagerPanel from '../TaskManagerPanel';++const nodes: any[] = [+ { id: 'manager', type: 'taskManager', data: { label: 'Tasks' }, position: { x: 0, y: 0 } },+ { id: 'lead', type: 'orchestrator_agent', data: { label: 'Lead' }, position: { x: 1, y: 1 } },+ { id: 'worker', type: 'coding_agent', data: { label: 'Coder' }, position: { x: 2, y: 2 } },+];+const edges: any[] = [+ { id: 'tool', source: 'manager', target: 'lead', targetHandle: 'input-tools' },+ { id: 'mate', source: 'worker', target: 'lead', targetHandle: 'input-teammates' },+];+const task = {+ id: 'task-1', title: 'Implement feature', mission: 'Build it', status: 'submitted',+ assigned_to: 'worker', assignee_label: 'Coder', revision: 4, current_attempt: 1,+ result: { summary: 'done' }, usage: { total_tokens: 120 },+};++describe('TaskManagerPanel', () => {+ beforeEach(() => {+ vi.clearAllMocks(); listeners.clear();+ wsMock.sendRequest.mockImplementation((type: string) => {+ if (type === 'get_team_status') return Promise.resolve({ status: { team_id: 'team-1', execution_id: 'run-1', status: 'active', active_count: 2, max_concurrent_subagents: 3 } });+ if (type === 'get_team_tasks') return Promise.resolve({ tasks: [task] });+ return Promise.resolve({ success: true });+ });+ });++ it('derives team scope from the connected lead and renders the execution task table', async () => {+ render(<TaskManagerPanel nodeId="manager" workflowId="workflow-1" nodes={nodes} edges={edges} />);+ expect(await screen.findByText('Implement feature')).toBeInTheDocument();+ expect(screen.getByText('2 / 3')).toBeInTheDocument();+ expect(screen.getByText('Coder')).toBeInTheDocument();+ expect(wsMock.sendRequest).toHaveBeenCalledWith('get_team_tasks', {+ workflow_id: 'workflow-1', team_lead_node_id: 'lead',+ });+ });++ it('is intrinsically scoped when opened directly on a team lead', async () => {+ render(<TaskManagerPanel nodeId="lead" workflowId="workflow-1" nodes={nodes} edges={edges} />);+ expect(await screen.findByText('Implement feature')).toBeInTheDocument();+ expect(wsMock.sendRequest).toHaveBeenCalledWith('get_team_tasks', {+ workflow_id: 'workflow-1', team_lead_node_id: 'lead',+ });+ });++ it('subscribes to team lifecycle events and refreshes scoped tasks', async () => {+ render(<TaskManagerPanel nodeId="manager" workflowId="workflow-1" nodes={nodes} edges={edges} />);+ await screen.findByText('Implement feature');+ const callsBefore = wsMock.sendRequest.mock.calls.filter(([name]) => name === 'get_team_tasks').length;+ listeners.get('team.task.submitted')?.({ team_id: 'team-1' });+ await waitFor(() => expect(wsMock.sendRequest.mock.calls.filter(([name]) => name === 'get_team_tasks').length).toBeGreaterThan(callsBefore));+ });++ it('sends revision-scoped accept actions and never sends a browser-provided team id', async () => {+ render(<TaskManagerPanel nodeId="manager" workflowId="workflow-1" nodes={nodes} edges={edges} />);+ await screen.findByText('Implement feature');+ fireEvent.click(screen.getByRole('button', { name: 'Inspect Implement feature' }));+ fireEvent.click(await screen.findByRole('button', { name: 'accept' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Confirm' }));+ await waitFor(() => expect(wsMock.sendRequest).toHaveBeenCalledWith('manage_team_task', expect.objectContaining({+ operation: 'accept', workflow_id: 'workflow-1', team_lead_node_id: 'lead',+ execution_id: 'run-1', task_id: 'task-1', revision: 4,+ })));+ const mutation = wsMock.sendRequest.mock.calls.find(([name]) => name === 'manage_team_task')?.[1];+ expect(mutation).not.toHaveProperty('team_id');+ });++ it('shows a connection instruction when no lead owns the tool', () => {+ render(<TaskManagerPanel nodeId="manager" workflowId="workflow-1" nodes={nodes} edges={[]} />);+ expect(screen.getByText(/Connect Task Manager to a team lead/)).toBeInTheDocument();+ });+});diff --git a/client/src/components/parameterPanel/__tests__/TeamMonitorPanel.test.tsx b/client/src/components/parameterPanel/__tests__/TeamMonitorPanel.test.tsxnew file mode 100644index 00000000..3b1cf93d--- /dev/null+++ b/client/src/components/parameterPanel/__tests__/TeamMonitorPanel.test.tsx@@ -0,0 +1,50 @@+import { screen, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { renderWithProviders as render } from '../../../test/providers';++const wsMock = vi.hoisted(() => ({ sendRequest: vi.fn(), addEventListener: vi.fn(() => vi.fn()) }));+vi.mock('../../../contexts/WebSocketContext', () => ({ useWebSocket: () => wsMock }));++import TeamMonitorPanel from '../TeamMonitorPanel';++const nodes: any[] = [+ { id: 'monitor', type: 'teamMonitor', data: { label: 'Monitor' }, position: { x: 0, y: 0 } },+ { id: 'lead', type: 'orchestrator_agent', data: { label: 'Lead' }, position: { x: 1, y: 0 } },+ { id: 'coder', type: 'coding_agent', data: { label: 'Coder' }, position: { x: 2, y: 0 } },+];+const edges: any[] = [+ { id: 'monitor-edge', source: 'lead', target: 'monitor' },+ { id: 'team-edge', source: 'coder', target: 'lead', targetHandle: 'input-teammates' },+];++describe('TeamMonitorPanel', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ wsMock.sendRequest.mockImplementation((type: string) => {+ if (type === 'get_team_status') return Promise.resolve({ status: { status: 'active', members: [{ agent_node_id: 'coder', agent_type: 'coding_agent', label: 'Coder', status: 'working' }] } });+ return Promise.resolve({ tasks: [{ id: 'task-1', title: 'Build API', status: 'running', assigned_to: 'coder' }] });+ });+ });++ it('renders connected teammates and current execution tasks in one middle panel', async () => {+ render(<TeamMonitorPanel nodeId="monitor" workflowId="workflow-1" nodes={nodes} edges={edges} />);+ expect(await screen.findByText('Build API')).toBeInTheDocument();+ expect(screen.getByText('Coder')).toBeInTheDocument();+ expect(screen.getByText('working')).toBeInTheDocument();+ expect(wsMock.sendRequest).toHaveBeenCalledWith('get_team_status', { workflow_id: 'workflow-1', team_lead_node_id: 'lead' });+ });++ it('shows graph teammates even before a persisted execution exists', async () => {+ wsMock.sendRequest.mockResolvedValueOnce({ status: {} }).mockResolvedValueOnce({ tasks: [] });+ render(<TeamMonitorPanel nodeId="monitor" workflowId="workflow-1" nodes={nodes} edges={edges} />);+ expect(await screen.findByText('Coder')).toBeInTheDocument();+ expect(screen.getByText('connected')).toBeInTheDocument();+ });++ it('requires a team-lead connection', async () => {+ render(<TeamMonitorPanel nodeId="monitor" workflowId="workflow-1" nodes={nodes} edges={[]} />);+ expect(screen.getByText(/Connect an Orchestrator Agent or AI Employee/)).toBeInTheDocument();+ await waitFor(() => expect(wsMock.sendRequest).not.toHaveBeenCalled());+ });+});diff --git a/client/src/hooks/useReactFlowNodes.ts b/client/src/hooks/useReactFlowNodes.tsindex 3396e1f0..58306e2b 100644--- a/client/src/hooks/useReactFlowNodes.ts+++ b/client/src/hooks/useReactFlowNodes.ts@@ -166,10 +166,11 @@ export const useReactFlowNodes = ({ setNodes, setEdges }: UseReactFlowNodesPropsconst onNodesDelete = useCallback((deleted: Node[]) => {- setNodes((nds) => nds.filter((node) => !deleted.find((d) => d.id === node.id)));+ const removable = deleted.filter((node) => node.type !== 'taskManager');+ setNodes((nds) => nds.filter((node) => !removable.find((d) => d.id === node.id)));// Clear selected node if it was deleted- if (selectedNode && deleted.find((d) => d.id === selectedNode.id)) {+ if (selectedNode && removable.find((d) => d.id === selectedNode.id)) {setSelectedNode(null);}},@@ -188,4 +189,4 @@ export const useReactFlowNodes = ({ setNodes, setEdges }: UseReactFlowNodesPropsonNodesDelete,onEdgesDelete,};-};\ No newline at end of file+};diff --git a/client/src/types/INodeProperties.ts b/client/src/types/INodeProperties.tsindex fc7b7571..8a40d83c 100644--- a/client/src/types/INodeProperties.ts+++ b/client/src/types/INodeProperties.ts@@ -204,6 +204,8 @@ export interface INodeUIHints {isTodoEditor?: boolean;/** MiddleSection: render the team-monitor panel. */isMonitorPanel?: boolean;+ /** MiddleSection: render the execution-scoped team task control panel. */+ isTaskManagerPanel?: boolean;/** Special-case panel for gmaps_create with map preview. */showLocationPanel?: boolean;/** ConsolePanel: this node is a chat-message target. */diff --git a/docs-internal/agent_architecture.md b/docs-internal/agent_architecture.mdindex 444a632b..59c692b6 100644--- a/docs-internal/agent_architecture.md+++ b/docs-internal/agent_architecture.md@@ -336,7 +336,8 @@ Patterns covered in the canonical doc:- Database tool-schema override via ToolSchema model + Tool Schema Editor UI- Direct tool pattern (each Android service connects to the agent independently)- Direct Android service tools (16 entries, skip the toolkit)-- Agent delegation (`delegate_to_*` fire-and-forget background tasks)+- Durable team delegation through Task Manager; `delegate_to_*` identities are+ retained internally for compatibility dispatch- Per-type Temporal activity dispatch (F4.A, when TEMPORAL_PER_TYPE_DISPATCH=true)- Auto-skill edges (writeTodos, WhatsApp tools bundle a default skill)@@ -529,7 +530,7 @@ Handle layouts are declared in `server/nodes/agent/_handles.py` (local to `nodes| `output-main` | output | right | 50% | main || `output-top` | output | top | — | main |-**`team_lead_agent_handles()`** — `orchestrator_agent` and `ai_employee` only; adds an `input-teammates` handle (bottom, 80%) and shifts the bottom skill/tool offsets to 20%/50%. Connected agents become `delegate_to_<type>` tools via `collect_teammate_connections()` (in `server/services/plugin/edge_walker.py`). Team leads are also listed in `TEAM_LEAD_TYPES` in [`client/src/components/TeamMonitorNode.tsx`](../client/src/components/TeamMonitorNode.tsx) (frontend tribal array, flagged as tech debt). See [agent_teams.md](agent_teams.md).+**`team_lead_agent_handles()`** — `orchestrator_agent` and `ai_employee` only; adds an `input-teammates` handle (bottom, 80%) and shifts the bottom skill/tool offsets to 20%/50%. Connected agents become authorized Task Manager assignees via `collect_teammate_connections()` (in `server/services/plugin/edge_walker.py`); their delegate identities are hidden from the model and retained for trusted child dispatch. See [agent_teams.md](agent_teams.md).`AIAgentNode.tsx` is type-agnostic: it calls `useNodeSpec(type)` and renders whatever handles / icon / color the spec returns — there is no `AGENT_CONFIGS` map (retired Wave 10.D). Specialized-agent visuals all come from the NodeSpec; per-type display name / subtitle / description live on the plugin class, icon from `<plugin>/icon.svg` (visuals.json emoji fallback), color from `<plugin>/meta.json`. Glob `server/nodes/agent/` for the authoritative agent list — do not hand-maintain one.diff --git a/docs-internal/agent_delegation.md b/docs-internal/agent_delegation.mdindex ecda1352..e6f3c3a3 100644--- a/docs-internal/agent_delegation.md+++ b/docs-internal/agent_delegation.md@@ -1,5 +1,11 @@# Agent-to-Agent Delegation (Nested Agents)+> **Team-lead contract:** Orchestrator and AI Employee models do not call+> `delegate_to_*` directly. They create durable work through the intrinsic+> `task_manager(assign_task)` interface described in+> [agent_teams.md](agent_teams.md). Delegate names below are internal dispatch+> identities or legacy/non-team-lead compatibility mechanics.+How memory, parameters, and execution context flow when one AI agent delegates work to another agent connected as a tool.> **Related docs:** [tool_building_pipeline.md](./tool_building_pipeline.md) for the underlying `_build_tool_from_node` + `execute_tool` pipeline that backs `delegate_to_*` (delegation tools share the same StructuredTool construction path as other AI tools — what makes them special is the fire-and-forget background task and the `{"status": "delegated"}` lifecycle opt-out documented there).diff --git a/docs-internal/agent_teams.md b/docs-internal/agent_teams.mdindex 7cd02b9a..cf37a65f 100644--- a/docs-internal/agent_teams.md+++ b/docs-internal/agent_teams.md@@ -1,244 +1,124 @@-# Agent Teams Pattern--This document describes the Claude SDK Agent Teams pattern implementation in OpenCompany, enabling multi-agent coordination through AI Employee and Orchestrator nodes.--## Overview--The Agent Teams pattern allows a "team lead" agent to coordinate multiple specialized agents. Instead of blindly delegating to all connected agents, the team lead uses its AI capabilities to decide when and how to delegate based on the user's request.--## Team Lead Node Types--Two node types support the Agent Teams pattern:--| Node Type | Display Name | Description |-|-----------|--------------|-------------|-| `orchestrator_agent` | Orchestrator Agent | Coordinates multiple agents for complex workflows |-| `ai_employee` | AI Employee | Team lead for intelligent task delegation |--Both are defined in `TEAM_LEAD_TYPES` in [`server/nodes/agent/_inline.py`](../server/nodes/agent/_inline.py).--## Architecture--```- ┌─────────────────┐- │ AI Employee │- │ (Team Lead) │- └────────┬────────┘- │ input-teammates- ┌─────────────────┼─────────────────┐- │ │ │- ┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐- │ Web Agent │ │Coding Agent │ │ Task Agent │- └─────────────┘ └─────────────┘ └─────────────┘-```--### How It Works--1. **User sends prompt** to AI Employee (e.g., "Write a Python script and search the web for documentation")--2. **Team lead collects teammates** via the `input-teammates` handle using `collect_teammate_connections()` ([`server/services/plugin/edge_walker.py`](../server/services/plugin/edge_walker.py)), invoked from `prepare_agent_call` in [`_inline.py`](../server/nodes/agent/_inline.py)--3. **Teammates become delegation tools** - each connected agent becomes a `delegate_to_*` tool:- - `coding_agent` → `delegate_to_coding_agent` tool- - `web_agent` → `delegate_to_web_agent` tool- - `task_agent` → `delegate_to_task_agent` tool--4. **AI decides whether to delegate** - the team lead's LLM analyzes the request and decides:- - For "hi" or simple questions → responds directly (no delegation)- - For complex tasks → uses appropriate delegation tools--5. **Delegated agents execute** via the standard `_execute_delegated_agent()` flow in `handlers/tools.py` (legacy / F4.A path), OR — when the parent runs as a Temporal `AgentWorkflow` under F4.B and the child type is in `AGENT_WORKFLOW_TYPES` — as a child `AgentWorkflow` spawned via `workflow.execute_child_workflow` with `parent_node_id` plumbed through `child_context` so the parent canvas badge mirrors child progress. See [agent_delegation.md](./agent_delegation.md#overview) for both paths.--## Input Handles--Team lead agents have an additional handle compared to standard specialized agents:--| Handle | Position | Description |-|--------|----------|-------------|-| `input-main` | Left 30% | Main data input |-| `input-memory` | Left 55% | Memory node connection |-| `input-task` | Left 85% | Task completion events |-| `input-skill` | Bottom 25% | Skill nodes |-| `input-teammates` | Bottom 50% | **Specialized agents for delegation** |-| `input-tools` | Bottom 75% | Tool nodes |-| `output-top` | Top | Output |--## Backend Implementation--Wave 11 deleted `server/services/handlers/ai.py` (and `handle_chat_agent`). Agent execution now flows through each agent plugin's `execute_op` under `server/nodes/agent/<plugin>/__init__.py` (`ai_agent`, `chat_agent`) or [`server/nodes/agent/_specialized.py`](../server/nodes/agent/_specialized.py) (the 13 specialized agents share one execution body). All of them call the shared pre-dispatch helper `prepare_agent_call` in [`server/nodes/agent/_inline.py`](../server/nodes/agent/_inline.py), which (1) collects standard connections via `collect_agent_connections`, (2) injects task context, (3) auto-prompts from upstream input, and (4) for team-lead types, appends teammates as delegation tools. The prepared kwargs are then splatted into `AIService.execute_chat_agent(...)`.--### Pre-dispatch Logic ([`server/nodes/agent/_inline.py`](../server/nodes/agent/_inline.py))--```python-# Team-lead agent types where teammates become delegation tools.-TEAM_LEAD_TYPES = frozenset({"orchestrator_agent", "ai_employee"})--async def prepare_agent_call(*, node_id, node_type, parameters, context, database, ...):- # 5-tuple standard connection collection- memory_data, skill_data, tool_data, input_data, task_data = (- await collect_agent_connections(node_id, context, database, log_prefix=log_prefix)- )-- # ... task-context injection + auto-prompt fallback ...-- # Team-lead detection - add teammates as delegation tools- if node_type in TEAM_LEAD_TYPES:- teammates = await collect_teammate_connections(node_id, context, database)- if teammates:- tool_data = tool_data or []- for tm in teammates:- # Each teammate's own input-tools edges are walked into- # `child_tools` so the delegation tool's description lists- # what that teammate can actually do.- tool_data.append({- "node_id": tm["node_id"],- "node_type": tm["node_type"],- "label": tm["label"],- "parameters": tm.get("parameters", {}),- "child_tools": child_tools,- })- logger.info(f"[Teams] Added {len(teammates)} teammates as delegation tools")-- return {"parameters": parameters, "tool_data": tool_data or None, ...}-```--Note: `collect_agent_connections` ([`server/services/plugin/edge_walker.py`](../server/services/plugin/edge_walker.py)) returns a **5-tuple** — `(memory_data, skill_data, tool_data, input_data, task_data)`.--### Teammate Collection (`collect_teammate_connections`)--Lives in [`server/services/plugin/edge_walker.py`](../server/services/plugin/edge_walker.py):--```python-async def collect_teammate_connections(node_id, context, database):- """Walk input-teammates edges and return connected agents.-- Used by orchestrator_agent / ai_employee.- """- nodes = context.get("nodes", [])- edges = context.get("edges", [])- teammates = []-- for edge in edges:- if edge.get("target") != node_id or edge.get("targetHandle") != "input-teammates":- continue- source_id = edge.get("source")- source_node = next((n for n in nodes if n.get("id") == source_id), None)- if not source_node:- continue- node_type = source_node.get("type", "")- if node_type not in AI_AGENT_TYPES:- continue- params = await database.get_node_parameters(source_id) or {}- teammates.append({- "node_id": source_id,- "node_type": node_type,- "label": source_node.get("data", {}).get("label", node_type),- "parameters": params,- })-- return teammates-```--## Delegation Tools--When teammates are connected, the AI service builds delegation tools via `_build_tool_from_node()` in [`server/services/ai.py`](../server/services/ai.py).--The `delegate_to_<type>` tool name is **auto-derived**, not maintained as a static map. `BaseNode.__init_subclass__` ([`server/services/plugin/base.py`](../server/services/plugin/base.py)) sets `cls.tool_name = f"delegate_to_{cls.type}"` for every plugin whose `component_kind == "agent"` that doesn't declare its own (e.g. `coding_agent` -> `delegate_to_coding_agent`). Subclasses with a distinct delegation contract (`autonomous_agent`, `orchestrator_agent`, `ai_employee`, `rlm_agent`, `claude_code_agent`) override `tool_description` on the class.--When `_build_tool_from_node` sees an agent node type listed in `_AGENT_DELEGATION_TYPES`, it exposes the `(task, context)` delegation schema instead of the agent's own Params (which would leak provider/model/prompt into the parent LLM):--```python-# server/services/ai.py-class DelegateToAgentSchema(BaseModel):- task: str = Field(description="The mission directive for the agent (becomes its system message)")- context: Optional[str] = Field(default=None, description="Input data / details the agent needs (becomes its user prompt)")+# Durable Agent Teams++OpenCompany team leads (`orchestrator_agent` and `ai_employee`) coordinate+agents connected to their canonical `input-teammates` handle. The topology is+the authorization boundary: ordinary tool edges and agents belonging to other+leads cannot receive team tasks.++## Runtime model++1. `build_teammate_descriptors()` expands connected agents into stable+ identities containing node ID, type, label, capability description,+ provider/model configuration, and the child's connected tools and skills.+2. Task Manager is intrinsically and non-removably bound to every team lead.+ It is not a palette node or an Agent Builder-addable tool.+3. The lead delegates only by calling `task_manager` with+ `operation="assign_task"`, a bounded mission, context, acceptance criteria,+ and an exact connected `assignee_node_id`.+4. Delegate tool identities remain internal to the workflow. They resolve the+ selected teammate after persistence but are hidden from the lead's LLM.+5. Temporal and legacy execution share the durable task lifecycle and use the+ same precreated task ID; neither path creates a second tracking record.++## Topology++```text+ input-teammates+ Coding Agent ───────────┐+ Web Agent ──────────────┼──> Orchestrator / AI Employee+ Custom aiAgent ─────────┘ │+ ├── intrinsic Task Manager+ └── output-main -> Team Monitor```-The AI receives tools like:-- `delegate_to_coding_agent(task="Write a Python script...")`-- `delegate_to_web_agent(task="Search for React documentation...")`--## Team Tracking Service+Only `aiAgent` may repeat within one team. Specialized agent types are unique.+Validation rejects invalid endpoints, ambiguous delegate names, cycles, and+delegation depth beyond two child layers.-The `AgentTeamService` (`server/services/agent_team.py`) provides optional team tracking:+## Durable task lifecycle-```python-class AgentTeamService:- async def create_team(team_lead_node_id, teammate_node_ids, workflow_id, config)- async def add_task(team_id, title, description, created_by, priority)- async def claim_task(team_id, task_id, agent_node_id)- async def complete_task(team_id, task_id, result)- async def fail_task(team_id, task_id, error)- async def get_team_status(team_id)+```text+blocked -> queued -> running -> submitted -> accepted+ | |+ +-> failed +-> retry/reassign -> queued+ +-> cancelled```-### Database Tables--| Table | Description |-|-------|-------------|-| `agent_teams` | Team metadata (id, workflow_id, team_lead_node_id, status) |-| `team_members` | Team membership (agent_node_id, role, status) |-| `team_tasks` | Shared task list with dependencies |-| `agent_messages` | Inter-agent communication |--## Team Monitor Node--The `teamMonitor` node displays real-time team operations:--- **Stats Grid**: Member count, task counts (total/done/active/pending)-- **Active Tasks Panel**: Currently executing tasks-- **Event Stream**: Real-time log of task completions and messages--Connect Team Monitor to a team lead's output to visualize team activity.--## Example Workflow--```-┌─────────────┐ ┌─────────────────┐ ┌─────────────┐-│Chat Trigger │────▶│ AI Employee │────▶│Team Monitor │-└─────────────┘ └────────┬────────┘ └─────────────┘- │ input-teammates- ┌──────────────┼──────────────┐- │ │ │- ┌──────▼──────┐ ┌─────▼─────┐ ┌──────▼──────┐- │ Coding Agent│ │ Web Agent │ │ Task Agent │- │ + Python │ │ + HTTP │ │ │- └─────────────┘ └───────────┘ └─────────────┘-```--**User says**: "Search for React best practices and write a summary script"--**AI Employee decides**:-1. Calls `delegate_to_web_agent(task="Search for React best practices")`-2. Waits for result via `check_delegated_tasks`-3. Calls `delegate_to_coding_agent(task="Write a Python script to summarize: {web_result}")`-4. Synthesizes final response--**User says**: "Hello!"--**AI Employee decides**: Responds directly with greeting (no delegation needed)--## Key Files--| File | Description |-|------|-------------|-| [`server/nodes/agent/_inline.py`](../server/nodes/agent/_inline.py) | `TEAM_LEAD_TYPES`, `prepare_agent_call()` pre-dispatch (teammate -> delegation-tool injection) |-| [`server/services/plugin/edge_walker.py`](../server/services/plugin/edge_walker.py) | `collect_teammate_connections()` (input-teammates walk) + `collect_agent_connections()` (5-tuple) |-| [`server/services/plugin/base.py`](../server/services/plugin/base.py) | `BaseNode.__init_subclass__` auto-derives `tool_name = f"delegate_to_{type}"` for `component_kind=="agent"` |-| [`server/services/agent_team.py`](../server/services/agent_team.py) | `AgentTeamService` for team tracking |-| [`server/services/handlers/tools.py`](../server/services/handlers/tools.py) | `_execute_delegated_agent()` for actual delegation |-| [`server/services/ai.py`](../server/services/ai.py) | `_build_tool_from_node()` builds delegate_to_* tools, `DelegateToAgentSchema` |-| [`client/src/components/AIAgentNode.tsx`](../client/src/components/AIAgentNode.tsx) | Agent node rendering with `input-teammates` handle |-| [`client/src/components/TeamMonitorNode.tsx`](../client/src/components/TeamMonitorNode.tsx) | Team monitoring UI |--## Design Decisions--1. **AI-Driven Delegation**: The team lead's AI decides when to delegate, not automatic forwarding to all teammates--2. **Tool-Based Pattern**: Teammates become `delegate_to_*` tools, leveraging the existing agent-loop tool calling--3. **Fire-and-Forget**: Delegated agents run as background tasks; team lead can check status via `check_delegated_tasks`--4. **API Key Inheritance**: Teammates inherit provider/model from team lead if not configured; API keys injected via the standard `_inject_api_keys` flow in [`server/services/node_executor.py`](../server/services/node_executor.py)--5. **Standard Execution Path**: Team leads use the same `execute_chat_agent` flow as other agents, just with additional delegation tools+- `submitted` means the worker finished and the lead must review the result.+- `accepted` is the completed/Done state shown by Team Monitor.+- `failed` is unresolved until retried, reassigned, or intentionally cancelled.+- `finish_team` succeeds only when every task is accepted or cancelled.++Mutations are optimistic and execution-scoped. Callers pass `task_id` and+`expected_revision`; the service verifies team ownership and current state.+When exactly one task is submitted, `accept_task` may safely infer its ID and+current revision. It never guesses among multiple submissions.++## Parallel scheduling++The default root-wide limit is three active descendants, including+grandchildren and excluding the root lead. Assignments persist before children+start. Eligible tasks enter a deterministic FIFO queue, dependencies remain+blocked, and one sibling failure does not cancel successful siblings. Multiple+`assign_task` calls in one Temporal turn are preflighted and started+concurrently while their results are appended in original tool-call order.++Each child receives an isolated AgentWorkflow context containing only its+bounded mission, relevant context, and its own connected tools, skills, and+memory. The parent receives a compact result; full child output remains+inspectable through task attempts and execution traces.++## Completion and events++After durable persistence, lifecycle transitions emit deterministic events such+as `team.task.submitted`, `team.task.accepted`, `team.task.failed`, and+`team.task.cancelled`. A canonical task completion CloudEvent also feeds+`taskTrigger` for downstream automation. Temporal child completion returns to+the owning lead for review; `taskTrigger` is not the lead-resume mechanism.++## Human interfaces++### Task Manager++Selecting a team lead opens its full-height operational middle panel. It shows+all current-execution tasks, queue positions, attempts, results, errors, usage,+and authorized accept/retry/reassign/modify/cancel/finish controls. Archived+executions are selectable without aggregating unrelated runs.++### Team Monitor++Team Monitor is read-only and uses only the middle parameter-panel section.+Connect the lead's output to it. It shows graph-connected teammates immediately,+then merges persisted `working`/`idle` state, lifecycle counts, and current+execution tasks. Its Done count includes accepted tasks, not submitted work.++## Public Task Manager operations++| Operation | Purpose |+|---|---|+| `assign_task` | Persist and dispatch work to a connected teammate |+| `list_tasks` / `get_task` | Inspect state, result, attempts, and revision |+| `modify_task` | Edit blocked or queued work |+| `cancel_task` | Stop queued or running work |+| `retry_task` | Queue a new attempt |+| `reassign_task` | Queue a new attempt on another connected teammate |+| `accept_task` | Approve submitted work |+| `finish_team` | Complete a fully resolved team execution |++`mark_done` is a deprecated alias for `accept_task` and never deletes history.++## Key files++- `server/services/plugin/edge_walker.py` — canonical teammate discovery and+ intrinsic Task Manager binding.+- `server/nodes/tool/task_manager/__init__.py` — model-facing contract.+- `server/services/agent_team.py` and `server/core/database.py` — authorized+ durable service and persistence.+- `server/services/temporal/agent_workflow.py` — concurrent child orchestration.+- `server/services/handlers/tools.py` — legacy execution bridge.+- `client/src/components/parameterPanel/TaskManagerPanel.tsx` — operational UI.+- `client/src/components/parameterPanel/TeamMonitorPanel.tsx` — read-only UI.++See [agent_delegation.md](agent_delegation.md) for low-level compatibility+delegation mechanics. Direct `delegate_to_*` calls documented there are not the+team-lead model-facing contract.diff --git a/docs-internal/node-logic-flows/ai_agents/aiAgent.md b/docs-internal/node-logic-flows/ai_agents/aiAgent.mdindex 8d29e3dd..0d123764 100644--- a/docs-internal/node-logic-flows/ai_agents/aiAgent.md+++ b/docs-internal/node-logic-flows/ai_agents/aiAgent.md@@ -115,8 +115,8 @@ flowchart TDor `input_data.content` (first truthy wins) and assigns it to `prompt`. If theinput is not a dict the whole value is stringified.- **Team-lead delegation**: for `orchestrator_agent` / `ai_employee`,- teammates connected via `input-teammates` are appended to `tool_data` as- `delegate_to_*` tools (not applicable to `aiAgent` itself).+ teammates connected via `input-teammates` become Task Manager assignees+ (not applicable to `aiAgent` itself unless it is used as a teammate).- **Delegation to AIService**: `execute_op` returns `response.get("result")`on success; a `success=False` envelope raises `RuntimeError`. Typed openaiSDK failures surface as `NodeUserError` from inside `execute_agent`.diff --git a/docs-internal/node-logic-flows/ai_agents/chatAgent.md b/docs-internal/node-logic-flows/ai_agents/chatAgent.mdindex 34b4bbc5..8eb5e70b 100644--- a/docs-internal/node-logic-flows/ai_agents/chatAgent.md+++ b/docs-internal/node-logic-flows/ai_agents/chatAgent.md@@ -33,7 +33,7 @@ own plugin folder; there is no `functools.partial` wiring anymore.| `input-memory` | main | no | `simpleMemory` node for conversation history. || `input-tools` | main | no | Tool nodes bound to the LLM via `chat_model.bind_tools`. || `input-task` | main | no | `taskTrigger` output - formatted and prepended to the prompt. |-| `input-teammates` | main | no | **Team-lead only** (`orchestrator_agent`, `ai_employee`). Agents on this handle become `delegate_to_<name>` tools. |+| `input-teammates` | main | no | **Team-lead only** (`orchestrator_agent`, `ai_employee`). Agents on this handle become authorized Task Manager assignees. |## Parameters@@ -91,7 +91,7 @@ flowchart TDdatabase)` to find nodes wired to `input-teammates`. Each teammate isappended to `tool_data` as a synthetic entry (with `child_tools` describingits own `input-tools` neighbours). The AIService then exposes them to the LLM- as `delegate_to_<type>` tools (see [Agent Teams](../../agent_teams.md)).+ as durable Task Manager assignees (see [Agent Teams](../../agent_teams.md)).## Side Effectsdiff --git a/docs-internal/node-logic-flows/ai_tools/taskManager.md b/docs-internal/node-logic-flows/ai_tools/taskManager.mdindex 8ef18d74..7b82b03d 100644--- a/docs-internal/node-logic-flows/ai_tools/taskManager.md+++ b/docs-internal/node-logic-flows/ai_tools/taskManager.md@@ -1,193 +1,55 @@# Task Manager (`taskManager`)-| Field | Value |-|------|-------|-| **Category** | ai_tools (dedicated AI tool, group `("tool", "ai")`) |-| **Backend handler** | [`server/nodes/tool/task_manager/__init__.py`](../../../server/nodes/tool/task_manager/__init__.py) — `TaskManagerNode`, dispatched via `BaseNode.execute()` + the `@Operation("manage")` method, which calls the inlined `_execute_task_manager` in the same file |-| **Tests** | [`server/tests/nodes/test_ai_tools.py`](../../../server/tests/nodes/test_ai_tools.py) |-| **Skill (if any)** | [`server/skills/assistant/task-manager/SKILL.md`](../../../server/skills/assistant/task-manager/SKILL.md) |-| **Dual-purpose tool** | tool-only — `ToolNode` exposed to the LLM as `task_manager` (`tool_name` class attr) |--## Purpose--Inspects the in-process registry of delegated agent tasks. The-`_execute_task_manager` body lives in the plugin file but reads **through** to-the delegation registry owned by `services/handlers/tools.py` (the-`_delegated_tasks` + `_delegation_results` dicts + `get_delegated_task_status`-3-layer lookup) — that lifecycle state stays in `tools.py` intentionally. Lets a-parent agent list currently-running / completed delegations, fetch details for a-specific `task_id`, or clear a finished task from tracking. Does **not** spawn-work itself; it only reads/mutates the delegation state populated by-`_execute_delegated_agent`.--## Inputs (handles)--| Handle | Connection type | Required | Purpose |-|--------|-----------------|----------|---------|-| `input-main` | main | no | Passive node - connect `output-tool` to an AI Agent's `input-tools` |--## Parameters--The declared `TaskManagerParams` model fields are below. The model carries-`model_config = ConfigDict(extra="allow")`, so the LLM-driven `operation` /-`status_filter` args (which `_execute_task_manager` reads) pass through even-though they are not declared fields.--| Name | Type | Default | Required | displayOptions.show | Description |-|------|------|---------|----------|---------------------|-------------|-| `action` | enum | `create` | no | - | Declared field: one of `create`, `list`, `complete`, `delete`, `update` (not the dispatch discriminator — see below) |-| `task_id` | string? | `None` | no | - | Target task id |-| `title` | string? | `None` | no | - | Declared but unused by the inlined op |-| `description` | string? | `None` | no | - | Declared but unused by the inlined op |-| `status` | string? | `None` | no | - | Declared but unused by the inlined op |--### LLM-provided tool args (the operations the op actually dispatches on)--The `manage` op passes `params.model_dump()` (with extras) into-`_execute_task_manager`, which reads `operation` / `task_id` / `status_filter`:--| Arg | Type | Description |-|-----|------|-------------|-| `operation` | string | One of `list_tasks`, `get_task`, `mark_done`; defaults to `'list_tasks'` |-| `task_id` | string | Required for `get_task` / `mark_done`; otherwise ignored |-| `status_filter` | string | Optional filter applied to `list_tasks` |--## Outputs (handles)--| Handle | Shape | Description |-|--------|-------|-------------|-| `output-tool` | object | Raw dict returned to the LLM (the `TaskManagerOutput` model has `extra="allow"`, so the full operation dict passes through) |--### Output payload (TypeScript shape)--`list_tasks`:-```ts-{- success: true;- operation: 'list_tasks';- tasks: Array<{- task_id: string;- status: 'running' | 'completed' | 'error' | 'cancelled';- active: boolean; // true = still in _delegated_tasks- agent_name?: string; // only present for entries from _delegation_results- result_summary?: string; // truncated to 200 chars- }>;- count: number;- running: number;- completed: number;- errors: number;-}-```--`get_task`:-```ts-{- success: boolean;- operation: 'get_task';- task_id: string;- status?: string;- agent_name?: string;- result?: unknown;- error?: string;-}-```--`mark_done`:-```ts-{- success: true;- operation: 'mark_done';- task_id: string;- removed: boolean;- message: string;-}-```--Unknown operation: `{success: false, error: "Unknown operation: <op>"}`.--## Logic Flow--```mermaid-flowchart TD- A[BaseNode.execute -> manage ctx params] --> A2[_execute_task_manager params.model_dump config]- A2 --> B[Read operation / task_id / status_filter<br/>tool_args wins, then params, then defaults]- B --> C{operation}- C -- list_tasks --> D[Iterate _delegated_tasks -> derive running/completed/cancelled/error]- D --> E[Merge _delegation_results entries not already in list]- E --> F{status_filter set?}- F -- yes --> G[Filter by status]- F -- no --> H[Skip]- G --> I[Return tasks + counts]- H --> I- C -- get_task --> J{task_id provided?}- J -- no --> Eno[Return success=false: task_id is required]- J -- yes --> K[await get_delegated_task_status task_ids=task_id]- K --> L{task found?}- L -- no --> M[Return success=false: Task not found]- L -- yes --> N[Return success + status + agent_name + result/error]- C -- mark_done --> O{task_id provided?}- O -- no --> Eno2[Return success=false: task_id is required]- O -- yes --> P[Pop task_id from _delegated_tasks AND _delegation_results]- P --> Q[Return removed flag + message]- C -- other --> Eop[Return success=false: Unknown operation]-```--## Decision Logic--- **Operation resolution**: `tool_args.operation OR node_params.operation OR 'list_tasks'`.-- **list_tasks status derivation**: for each entry in `_delegated_tasks`,- `task.done()` is checked; if done, `cancelled()` / `exception()` determine- `cancelled` vs `error` vs `completed`; otherwise `running`.-- **De-duplication**: `_delegation_results` entries whose `task_id` is- already in the `_delegated_tasks`-derived list are skipped.-- **status_filter**: an empty string means "all"; the check- `if status_filter:` treats `""` as falsy, so no filter is applied.-- **get_task missing id**: returns `{success: false, error: 'task_id is required ...'}`.-- **get_task not found**: `get_delegated_task_status` returns `{tasks: []}`,- handler returns `{success: false, error: 'Task <id> not found'}`.-- **mark_done missing id**: same `task_id is required` short-circuit.-- **mark_done when not tracked**: still returns `success=true` but with- `removed=false` and a "was not in active tracking" message.--## Side Effects--- **In-memory state writes**: `mark_done` deletes entries from the- module-level dicts `_delegated_tasks` and `_delegation_results`- (in `services/handlers/tools.py`).-- **Database writes**: none directly. `get_task` calls- `get_delegated_task_status`, which may read from `database` (if supplied),- but there is no write from `taskManager`.-- **Broadcasts**: none.-- **External API calls**: none.-- **File I/O**: none.-- **Subprocess**: none.--## External Dependencies--- **Credentials**: none.-- **Services**: `database` (optional) passed through from `context` for- `get_delegated_task_status`.-- **Python packages**: stdlib only.-- **Environment variables**: none.--## Edge cases & known limits--- State is **process-local** (module-level dicts). A restart wipes all- tracked tasks; a horizontally-scaled deployment never sees tasks spawned- on a different worker.-- `result_summary` is truncated to 200 characters via `str(...)[:200]`;- multi-line results may be cut mid-line.-- `list_tasks` counts only `running` / `completed` / `error` explicitly -- `cancelled` entries are included in `tasks` but not counted in any of the- three aggregate counters.-- Unknown `operation` returns a failed envelope rather than raising; the- agent might keep retrying with the same bad operation string.-- The dispatch discriminator is `operation` (read from the extra-allowed- tool args), NOT the declared `action` field — the `action` / `title` /- `description` / `status` model fields are vestigial and unused by the op.--## Related--- **Sibling tools**: [`calculatorTool`](./calculatorTool.md), [`currentTimeTool`](./currentTimeTool.md), [`duckduckgoSearch`](./duckduckgoSearch.md), [`writeTodos`](./writeTodos.md), [`agentBuilder`](./agentBuilder.md)-- **Skill using this tool**: [`task-manager/SKILL.md`](../../../server/skills/assistant/task-manager/SKILL.md)-- **Architecture docs**: [Agent Delegation](../../agent_delegation.md)+Task Manager is the durable control plane intrinsically bound to+`orchestrator_agent` and `ai_employee`. It is hidden from the palette and Agent+Builder, so users cannot remove the lead's task capability. Historical explicit+nodes remain readable and protected from deletion.++## Scope and authorization++The runtime injects workflow, execution, root execution, team, and lead IDs.+Model and browser payloads cannot select an arbitrary team. Assignment and+reassignment resolve against fresh canonical `input-teammates` descriptors and+the persisted execution membership snapshot.++## Operations++| Operation | Required fields | Valid source state |+|---|---|---|+| `assign_task` | `title`, `mission`, connected `assignee_node_id` or exact delegate name | new |+| `list_tasks` | optional `status_filter` | any |+| `get_task` | `task_id` | any |+| `modify_task` | `task_id`, `expected_revision`, changed fields | blocked/queued |+| `cancel_task` | `task_id`, `expected_revision`, optional `reason` | blocked/queued/running |+| `retry_task` | `task_id`, `expected_revision` | failed/submitted/cancelled |+| `reassign_task` | task/revision and connected assignee | failed/submitted/cancelled |+| `accept_task` | task/revision, normally | submitted |+| `finish_team` | none | every task accepted/cancelled |++`revision` is accepted as a compatibility alias for `expected_revision`. When+exactly one submitted task exists in the scoped execution, `accept_task` may+omit both fields and safely resolves that task. Zero or multiple submissions+produce an error instructing the lead to list/review tasks first.++`mark_done` is a deprecated alias for `accept_task`; it does not remove records.++## Assignment result++`assign_task` persists the task before returning a trusted+`delegation_request`. Temporal preflights same-turn assignments, starts children+under the root-wide permit coordinator, and returns the child result alongside+the task identity. Legacy execution passes the same precreated task ID into its+child bridge. Retries therefore cannot duplicate tasks.++## Status semantics++- `blocked`: dependencies unresolved+- `queued`: waiting for admission+- `running`: child owns the current attempt+- `submitted`: child returned; lead review required+- `accepted`: approved and counted as Done+- `failed`: unresolved terminal attempt+- `cancelled`: intentionally stopped/waived++See [Agent Teams](../../agent_teams.md) and+[Team Monitor](../chat_utility/teamMonitor.md).diff --git a/docs-internal/node-logic-flows/chat_utility/teamMonitor.md b/docs-internal/node-logic-flows/chat_utility/teamMonitor.mdindex e1f0b095..0273cbb8 100644--- a/docs-internal/node-logic-flows/chat_utility/teamMonitor.md+++ b/docs-internal/node-logic-flows/chat_utility/teamMonitor.md@@ -1,121 +1,46 @@# Team Monitor (`teamMonitor`)-| Field | Value |-|------|-------|-| **Category** | chat_utility |-| **Backend handler** | [`server/nodes/utility/team_monitor/__init__.py`](../../../server/nodes/utility/team_monitor/__init__.py) — dispatch via `BaseNode.execute()` + `@Operation("monitor")` |-| **Tests** | [`server/tests/nodes/test_chat_utility.py`](../../../server/tests/nodes/test_chat_utility.py) |-| **Skill (if any)** | - |-| **Dual-purpose tool** | no |+Team Monitor is the read-only view of one team lead execution. Connect an+`orchestrator_agent` or `ai_employee` output to its `input-main` handle.-## Purpose+## Panel behavior-Real-time monitoring window for Agent Team operations. Connects to the output-of an AI Employee or Orchestrator node and surfaces the team's members, task-counters, active tasks, and recent events for display. See-[`docs-internal/agent_teams.md`](../../agent_teams.md) for the overall teams-architecture.+The backend declares `isMonitorPanel`, `hideInputSection`,+`hideOutputSection`, and `hideRunButton`. The frontend consumes those hints and+renders only `TeamMonitorPanel` in the full-height middle section, matching the+Master Skill panel layout. Generic parameters and input/output columns are not+shown.-## Inputs (handles)+The panel:-| Handle | Connection type | Required | Purpose |-|--------|-----------------|----------|---------|-| `input-main` | main | yes (for non-empty output) | Upstream team-lead node whose output carries `team_id` |+- derives workflow and lead scope from the connection;+- shows agents on the lead's `input-teammates` handle before a run exists;+- merges persisted member status (`working`, `idle`) during execution;+- displays blocked, queued, running, submitted, accepted, failed, and cancelled+ counts;+- lists every current-execution task with assignee and queue position;+- refreshes on team lifecycle broadcasts and supports manual refresh.-## Parameters+Team Monitor never mutates tasks. Use the Task Manager panel bound to the lead+for accept, retry, modify, reassign, cancel, and finish actions.-| Name | Type | Default | Required | displayOptions.show | Description |-|------|------|---------|----------|---------------------|-------------|-| `team_id` | string | `""` | no | - | Explicit team id (usually resolved from upstream output instead) |-| `auto_refresh` | boolean | `true` | no | - | UI flag for periodic refresh of the monitor panel |-| `max_history_items` | number | `50` | no | - | Cap on `recent_events` slice length (`ge=1`) |+## Completion semantics-The node carries `ui_hints = {"isMonitorPanel": True, "hideInputSection": True,-"hideOutputSection": True}` — it renders as a dedicated monitor panel.+Worker completion changes a task to `submitted`. It is visible as awaiting+review and is not counted as Done. Only `accepted` tasks (and historical legacy+`completed` rows) contribute to the completed count. This distinction prevents+the monitor from reporting unreviewed work as finished.-## Outputs (handles)+## Backend operation-| Handle | Shape | Description |-|--------|-------|-------------|-| `output-main` | object | Team status snapshot (see shape) |+`server/nodes/utility/team_monitor/__init__.py` provides a read-only snapshot+for workflow execution and templating. It resolves connected teammates from the+canvas even without a `team_id`, then merges durable members, counts, active+tasks, and recent lifecycle events when a persisted team exists.-### Output payload (TypeScript shape)--```ts-{- team_id: string | null;- members: Array<unknown>;- tasks: {- total: number;- completed: number;- active: number;- pending: number;- failed: number;- };- active_tasks: Array<unknown>;- recent_events: Array<unknown>;- // When no team_id is resolved:- message?: "No team connected";-}-```--## Logic Flow--```mermaid-flowchart TD- A[Receive params + ctx.raw] --> B{ctx.raw.team_id set?}- B -- yes --> E[team_service.get_team_status]- B -- no --> C[Scan ctx.raw.outputs for dict with team_id]- C -- found --> E- C -- not found --> D[Return empty envelope with message=No team connected]- E --> F[Slice recent_events by max_history_items]- F --> G[Return envelope with counters + lists]-```--## Decision Logic--- **Validation**: none.-- **Branches**:- - `team_id` resolved via `ctx.raw["team_id"]` first, else the first value in- `ctx.raw["outputs"]` that is a dict containing a truthy `team_id`.- - When no `team_id` is found, returns an intentional success envelope with- zero counters - the node does not error.-- **Fallbacks**: counters default to 0 for any missing key; `members`,- `active_tasks`, `recent_events` default to empty lists.-- **Error paths**: no in-op try/except; any exception from- `get_team_status` is wrapped by `BaseNode.execute()` into the error envelope.--## Side Effects--- **Database writes**: none (the service reads `agent_teams`, `team_members`,- `team_tasks`, `agent_messages` tables behind `get_team_status`, but this- handler only reads the returned status dict).-- **Broadcasts**: none from this handler.-- **External API calls**: none.-- **File I/O**: none.-- **Subprocess**: none.--## External Dependencies--- **Credentials**: none.-- **Services**: `AgentTeamService` via- `services.agent_team.get_agent_team_service()`.-- **Python packages**: stdlib only.-- **Environment variables**: none.--## Edge cases & known limits--- `max_history_items` is used as a negative slice (`[-max:]`) on `recent_events`.-- The "find team_id in outputs" loop stops at the first dict it sees containing- a truthy `team_id`; if two upstream outputs carry different team ids, behaviour- is order-dependent.-- When the team disappears mid-run (`get_team_status` raises `TeamNotFound` or- similar) the envelope is `success=false` - the monitor does not gracefully- degrade.+The operation performs no writes, external calls, or subprocess work.## Related-- **Skills using this as a tool**: none.-- **Other nodes that consume this output**: downstream nodes can template on- `{{teamMonitor.tasks.total}}`, `{{teamMonitor.active_tasks}}` etc.-- **Architecture docs**: [`docs-internal/agent_teams.md`](../../agent_teams.md).+- [Durable Agent Teams](../../agent_teams.md)+- [Task Manager](../ai_tools/taskManager.md)diff --git a/docs-internal/node-logic-flows/specialized_agents/_pattern.md b/docs-internal/node-logic-flows/specialized_agents/_pattern.mdindex 7a9757f4..656acb02 100644--- a/docs-internal/node-logic-flows/specialized_agents/_pattern.md+++ b/docs-internal/node-logic-flows/specialized_agents/_pattern.md@@ -55,7 +55,7 @@ All 13 agents share these input handles.| `input-memory` | input/memory | no | `simpleMemory` node for conversation history || `input-tools` | input/tools | no | Tool nodes exposed to the LLM via `chat_model.bind_tools` || `input-task` | input/task | no | `taskTrigger` events from delegated child agents |-| `input-teammates` | input/teammates | no | **Only on `orchestrator_agent` and `ai_employee`** (via `team_lead_agent_handles()`) -- connected agents become `delegate_to_*` tools |+| `input-teammates` | input/teammates | no | **Only on `orchestrator_agent` and `ai_employee`** (via `team_lead_agent_handles()`) -- connected agents become Task Manager-authorized assignees |Handle topology comes from `std_agent_handles()` (or `team_lead_agent_handles()`for the two team leads) in@@ -122,7 +122,7 @@ flowchart TDE -- yes --> F[prompt = input_data.message/text/content/str]E -- no --> G{team lead?<br/>orchestrator / ai_employee}F --> G- G -- yes --> H[collect_teammate_connections<br/>append as delegate_to_* tools]+ G -- yes --> H[collect_teammate_connections<br/>bind Task Manager assignees]G -- no --> I[ai_service.execute_chat_agent]H --> II --> J[Return result payload<br/>or raise RuntimeError]diff --git a/docs-internal/node-logic-flows/specialized_agents/aiEmployee.md b/docs-internal/node-logic-flows/specialized_agents/aiEmployee.mdindex c131c587..cce00933 100644--- a/docs-internal/node-logic-flows/specialized_agents/aiEmployee.md+++ b/docs-internal/node-logic-flows/specialized_agents/aiEmployee.md@@ -13,8 +13,8 @@ Team-lead agent identical in behaviour to `orchestrator_agent`. Distinctonly in frontend presentation (display name "AI Employee", subtitle"Team Orchestration"). Backend routing is the same:`SpecializedAgentBase.execute_op` -> `prepare_agent_call`-(`collect_teammate_connections`) -> teammates appended to `tool_data` as-`delegate_to_*` tools -> `execute_chat_agent`.+(`collect_teammate_connections`) -> internal teammate descriptors plus the+intrinsic Task Manager -> `execute_chat_agent`.## What is unique to this node@@ -33,9 +33,8 @@ for the shared contract.## Edge cases-- Same as `orchestrator_agent`: non-agent teammates are silently skipped;- concurrency of `delegate_to_*` calls is owned by the downstream tool /- Temporal child-workflow dispatch, not by any node parameter.+- Same as `orchestrator_agent`: non-agent teammates are rejected by topology+ validation; durable assignments use the root-wide concurrency coordinator.## Relateddiff --git a/docs-internal/node-logic-flows/specialized_agents/orchestratorAgent.md b/docs-internal/node-logic-flows/specialized_agents/orchestratorAgent.mdindex f3ab3810..08fe4181 100644--- a/docs-internal/node-logic-flows/specialized_agents/orchestratorAgent.md+++ b/docs-internal/node-logic-flows/specialized_agents/orchestratorAgent.md@@ -9,9 +9,10 @@## Purpose-Team-lead agent that coordinates multiple specialized agents. Teammates-are wired via the extra `input-teammates` handle and become-`delegate_to_<agent_type>` tools the orchestrator can call.+Team-lead agent that coordinates agents wired through `input-teammates`.+Task Manager is intrinsically bound and is the only model-facing delegation+interface. Internal delegate descriptors resolve authorized assignees after a+durable `assign_task` record exists.## What is unique to this node@@ -24,7 +25,9 @@ are wired via the extra `input-teammates` handle and becomenode gets a meaningful tool string ("ONE-SHOT delegation ...").- **Team lead detection**: `prepare_agent_call` (in `_inline.py`) checks`node_type in TEAM_LEAD_TYPES = {'orchestrator_agent', 'ai_employee'}` and- calls `collect_teammate_connections` to expand teammates into tools.+ calls `collect_teammate_connections` to build internal teammate descriptors.+- **Task control panel**: selecting the node opens its non-removable Task+ Manager middle panel.## Teammate collection@@ -38,11 +41,9 @@ are wired via the extra `input-teammates` handle and become4. Loads `database.get_node_parameters(source_id)` for each teammate.5. Returns a list of `{node_id, node_type, label, parameters}` dicts.-`prepare_agent_call` then walks each teammate's own `input-tools` edges to-populate `child_tools` (so the delegation tool description lists what each-teammate can do) and appends the teammates to `tool_data` before-`execute_chat_agent` is called, so the LLM sees them as ordinary-`delegate_to_*` tools.+`prepare_agent_call` walks each teammate's own `input-tools` edges to populate+capability descriptions. The LLM receives connected node IDs and calls+`task_manager(operation="assign_task", ...)`; direct delegate tools are hidden.## Behaviour@@ -54,10 +55,8 @@ expansion above.- Non-`AI_AGENT_TYPES` nodes wired to `input-teammates` are silentlyskipped.-- Concurrency of `delegate_to_*` calls is not controlled by any node- parameter (no `teamMode`); it depends on how the downstream- `delegate_to_*` tool implementation / Temporal child-workflow dispatch- handles concurrent invocations.+- Concurrency is root-scoped and defaults to three active descendants.+ Additional durable assignments remain queued.- When zero teammates are connected, the node behaves identically to anyother specialized agent.diff --git a/docs-internal/node-logic-flows/workflow_triggers/taskTrigger.md b/docs-internal/node-logic-flows/workflow_triggers/taskTrigger.mdindex a7ff2dd7..195e7bed 100644--- a/docs-internal/node-logic-flows/workflow_triggers/taskTrigger.md+++ b/docs-internal/node-logic-flows/workflow_triggers/taskTrigger.md@@ -10,7 +10,7 @@## Purpose-Fires when a child agent delegated via `delegate_to_*` tools completes or+Fires when a child agent dispatched from a durable Task Manager assignment completes orerrors. The delegation code path in`server/services/handlers/tools.py::_execute_delegated_agent` calls`nodes.agent._events.broadcast_agent_task_completed` for both the success and@@ -20,7 +20,8 @@ discriminator carried in `data.status`) via `dispatch.emit`. `taskTrigger` iscanary-registered, so `DeploymentManager` starts a `TriggerListenerWorkflow`that receives the event via Temporal Signal and spawns a child workflow permatch. Used to let a parent workflow react to child completion without blocking-the parent on the child's result (fire-and-forget delegation).+external downstream automation. Temporal separately returns/signals the owning+lead for review; `taskTrigger` is not the lead-resume mechanism.## Inputs (handles)diff --git a/docs-internal/node_allowlist.md b/docs-internal/node_allowlist.mdindex 0dbeffad..82f27cfc 100644--- a/docs-internal/node_allowlist.md+++ b/docs-internal/node_allowlist.md@@ -69,7 +69,9 @@ Android service nodes are enabled and connect directly to an agent'sbundled Android skills are also visible. The former `androidTool` aggregatoris obsolete; legacy workflows are normalized to direct service-to-agent edges.-Task Manager is enabled for inspecting and cleaning up delegated agent tasks.+Task Manager is an intrinsic, non-removable capability of Orchestrator and AI+Employee nodes. It is intentionally absent from the normal palette and Agent+Builder catalogue; historical explicit nodes remain compatible.## agentBuilder integrationdiff --git a/docs-internal/tool_building_pipeline.md b/docs-internal/tool_building_pipeline.mdindex 7da6a056..91f00389 100644--- a/docs-internal/tool_building_pipeline.md+++ b/docs-internal/tool_building_pipeline.md@@ -42,7 +42,10 @@ Canonical home for how AI Agents discover connected tool nodes, build LangChain- **`tool_data`** is a list of dicts. Each entry: `{node_id, node_type, parameters, label, connected_services?}`. The `connected_services` field is only populated for `androidTool` (the gateway-tool pattern — see §6).- **MasterSkill expansion** runs at discovery time: a single `masterSkill` connection with `skillsConfig` expands into N individual skill entries, one per enabled skill key.-- **Team-lead expansion** (`orchestrator_agent` / `ai_employee`): agents connected to `input-teammates` become `delegate_to_*` entries automatically.+- **Team-lead expansion** (`orchestrator_agent` / `ai_employee`): agents connected+ to `input-teammates` become authorized descriptors. Internal `delegate_to_*`+ identities remain available to the coordinator, while the LLM delegates via+ Task Manager.## 3. Stage 2 — Build (services/ai.py:_build_tool_from_node)@@ -167,7 +170,12 @@ The LLM sees one tool with `{service_id, action, parameters}` arguments. `_execuDirect Android service tools (16 individual entries in `DEFAULT_TOOL_NAMES`) are an alternative path — connect a service node directly to `input-tools` without using the toolkit aggregator. Both paths exist; the toolkit is preferred when you want one cohesive `android_device` tool.-## 8. Delegation tools (`delegate_to_*`)+## 8. Internal delegation identities (`delegate_to_*`)++For team leads these identities are hidden from the model. Task Manager first+persists and authorizes an assignment, then the Temporal or legacy coordinator+uses the matching identity to dispatch the child. Direct calls described below+apply only to compatibility/non-team-lead paths.Specialized agents connected to an agent's `input-tools` handle become delegation tools. Schema is fixed:diff --git a/server/config/node_allowlist.json b/server/config/node_allowlist.jsonindex fbf170f2..d8f4f2cc 100644--- a/server/config/node_allowlist.json+++ b/server/config/node_allowlist.json@@ -3,6 +3,7 @@"enabled_nodes": ["start","chatTrigger",+ "taskTrigger","console","aiAgent",@@ -22,7 +23,6 @@"calculatorTool","currentTimeTool","writeTodos",- "taskManager","httpRequest","timer",diff --git a/server/core/database.py b/server/core/database.pyindex e65e47a1..6780d76e 100644--- a/server/core/database.py+++ b/server/core/database.py@@ -9,7 +9,7 @@ from pydantic_core import to_jsonable_pythonfrom sqlmodel import SQLModel, selectfrom sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmakerfrom sqlalchemy.exc import IntegrityError-from sqlalchemy import case, text, func, update+from sqlalchemy import case, text, func, update, or_from contextlib import asynccontextmanagerfrom core.config import Settings@@ -33,6 +33,7 @@ from models.database import (AgentTeam,TeamMember,TeamTask,+ TeamTaskAttempt,AgentMessage,SubagentConcurrencyCounter,SubagentConcurrencyPermit,@@ -252,6 +253,29 @@ class Database:if message_columns and "event_id" not in message_columns:await conn.execute(text("ALTER TABLE agent_messages ADD COLUMN event_id VARCHAR(255)"))await conn.execute(text("CREATE UNIQUE INDEX IF NOT EXISTS ix_agent_messages_event_id ON agent_messages(event_id) WHERE event_id IS NOT NULL"))++ result = await conn.execute(text("PRAGMA table_info(team_tasks)"))+ task_columns = {row[1] for row in result.fetchall()}+ additions = {+ "workflow_id": "VARCHAR(255)", "execution_id": "VARCHAR(255)",+ "root_execution_id": "VARCHAR(255)", "parent_agent_id": "VARCHAR(255)",+ "mission": "VARCHAR(10000)", "context": "JSON",+ "acceptance_criteria": "JSON", "queue_sequence": "INTEGER DEFAULT 0",+ "revision": "INTEGER DEFAULT 0", "current_attempt": "INTEGER DEFAULT 0",+ "child_workflow_id": "VARCHAR(500)", "child_run_id": "VARCHAR(255)",+ "trace_id": "VARCHAR(255)", "cancellation_requested": "BOOLEAN DEFAULT 0",+ "cancellation_reason": "VARCHAR(2000)", "usage": "JSON",+ }+ for column, definition in additions.items():+ if task_columns and column not in task_columns:+ await conn.execute(text(f"ALTER TABLE team_tasks ADD COLUMN {column} {definition}"))+ if task_columns:+ await conn.execute(text("UPDATE team_tasks SET status='queued' WHERE status='pending'"))+ await conn.execute(text("UPDATE team_tasks SET status='running' WHERE status='in_progress'"))+ await conn.execute(text("UPDATE team_tasks SET status='submitted' WHERE status='completed'"))+ await conn.execute(text("UPDATE team_tasks SET status='cancelled' WHERE status='skipped'"))+ await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_team_tasks_execution_id ON team_tasks(execution_id)"))+ await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_team_tasks_root_execution_id ON team_tasks(root_execution_id)"))except Exception as e:logger.warning(f"Agent-team migration check failed: {e}")@@ -2523,15 +2547,117 @@ class Database:priority=priority,created_by=created_by,depends_on={"task_ids": depends_on} if depends_on else None,+ status="queued",created_at=datetime.now(timezone.utc),)session.add(task)await session.commit()- return {"id": task.id, "title": title, "status": "pending"}+ return {"id": task.id, "title": title, "status": "queued"}except Exception as e:logger.error(f"Failed to add team task: {e}")return None+ @staticmethod+ def _team_task_dict(task: TeamTask, attempts: Optional[List[TeamTaskAttempt]] = None) -> Dict[str, Any]:+ allowed_actions = {+ "blocked": ["modify", "cancel"], "queued": ["modify", "cancel"],+ "running": ["cancel"], "submitted": ["accept", "retry", "reassign"],+ "failed": ["retry", "reassign"], "cancelled": ["retry", "reassign"],+ "accepted": [],+ }.get(task.status, [])+ return {+ "id": task.id, "team_id": task.team_id, "workflow_id": task.workflow_id,+ "execution_id": task.execution_id, "root_execution_id": task.root_execution_id,+ "parent_agent_id": task.parent_agent_id, "title": task.title,+ "description": task.description, "mission": task.mission,+ "context": task.context, "acceptance_criteria": task.acceptance_criteria,+ "status": task.status, "priority": task.priority, "queue_sequence": task.queue_sequence,+ "created_by": task.created_by, "assigned_to": task.assigned_to,+ "depends_on": task.depends_on.get("task_ids", []) if task.depends_on else [],+ "result": task.result, "error": task.error, "progress": task.progress,+ "revision": task.revision, "current_attempt": task.current_attempt,+ "retry_count": task.retry_count, "max_retries": task.max_retries,+ "child_workflow_id": task.child_workflow_id, "child_run_id": task.child_run_id,+ "trace_id": task.trace_id, "cancellation_requested": task.cancellation_requested,+ "cancellation_reason": task.cancellation_reason, "usage": task.usage,+ "created_at": task.created_at.isoformat() if task.created_at else None,+ "started_at": task.started_at.isoformat() if task.started_at else None,+ "completed_at": task.completed_at.isoformat() if task.completed_at else None,+ "attempts": [+ {"id": a.id, "attempt_number": a.attempt_number, "assignee_node_id": a.assignee_node_id,+ "status": a.status, "child_workflow_id": a.child_workflow_id,+ "child_run_id": a.child_run_id, "result": a.result, "error": a.error,+ "usage": a.usage, "created_at": a.created_at.isoformat() if a.created_at else None,+ "started_at": a.started_at.isoformat() if a.started_at else None,+ "completed_at": a.completed_at.isoformat() if a.completed_at else None}+ for a in (attempts or [])+ ],+ "allowed_actions": allowed_actions,+ }++ async def create_durable_team_task(self, **values: Any) -> Optional[Dict[str, Any]]:+ """Persist one scoped queue item, idempotently by task id."""+ try:+ async with self.get_session() as session:+ existing = (await session.execute(select(TeamTask).where(TeamTask.id == values["id"]))).scalar_one_or_none()+ if existing:+ return self._team_task_dict(existing) if existing.team_id == values["team_id"] else None+ maximum = (await session.execute(+ select(func.max(TeamTask.queue_sequence)).where(TeamTask.team_id == values["team_id"])+ )).scalar_one_or_none() or 0+ values.setdefault("queue_sequence", maximum + 1)+ values.setdefault("status", "blocked" if values.get("depends_on") else "queued")+ if isinstance(values.get("depends_on"), list):+ values["depends_on"] = {"task_ids": values["depends_on"]}+ task = TeamTask(**values)+ session.add(task)+ await session.commit()+ await session.refresh(task)+ return self._team_task_dict(task)+ except Exception as e:+ logger.error(f"Failed to create durable team task: {e}")+ return None++ async def get_durable_team_task(self, team_id: str, task_id: str) -> Optional[Dict[str, Any]]:+ async with self.get_session() as session:+ task = (await session.execute(select(TeamTask).where(TeamTask.id == task_id, TeamTask.team_id == team_id))).scalar_one_or_none()+ if not task:+ return None+ attempts = (await session.execute(+ select(TeamTaskAttempt).where(TeamTaskAttempt.task_id == task_id).order_by(TeamTaskAttempt.attempt_number)+ )).scalars().all()+ return self._team_task_dict(task, list(attempts))++ async def transition_team_task(+ self, team_id: str, task_id: str, expected_revision: int,+ allowed_statuses: List[str], values: Dict[str, Any], *, create_attempt: bool = False,+ ) -> Optional[Dict[str, Any]]:+ """Revision-and-state guarded task transition (compare-and-swap)."""+ async with self.get_session() as session:+ values = dict(values)+ values["revision"] = expected_revision + 1+ changed = await session.execute(+ update(TeamTask).where(+ TeamTask.id == task_id, TeamTask.team_id == team_id,+ TeamTask.revision == expected_revision, TeamTask.status.in_(allowed_statuses),+ ).values(**values)+ )+ if changed.rowcount != 1:+ await session.rollback()+ return None+ task = (await session.execute(select(TeamTask).where(TeamTask.id == task_id))).scalar_one()+ if create_attempt:+ attempt_number = task.current_attempt+ session.add(TeamTaskAttempt(+ id=f"{task.id}:attempt:{attempt_number}", task_id=task.id, team_id=team_id,+ attempt_number=attempt_number, assignee_node_id=task.assigned_to,+ status=task.status, child_workflow_id=task.child_workflow_id,+ child_run_id=task.child_run_id, created_at=datetime.now(timezone.utc),+ ))+ await session.commit()+ await session.refresh(task)+ return self._team_task_dict(task)+async def get_team_tasks(self, team_id: str, status: Optional[str] = None) -> List[Dict[str, Any]]:"""Get team tasks, optionally filtered by status."""try:@@ -2539,21 +2665,17 @@ class Database:query = select(TeamTask).where(TeamTask.team_id == team_id)if status:query = query.where(TeamTask.status == status)- query = query.order_by(TeamTask.priority.asc(), TeamTask.created_at.asc())+ query = query.order_by(TeamTask.queue_sequence.asc(), TeamTask.created_at.asc(), TeamTask.id.asc())result = await session.execute(query)- return [- {- "id": t.id,- "title": t.title,- "description": t.description,- "status": t.status,- "priority": t.priority,- "assigned_to": t.assigned_to,- "progress": t.progress,- "depends_on": t.depends_on.get("task_ids", []) if t.depends_on else [],- }- for t in result.scalars().all()- ]+ tasks = [self._team_task_dict(t) for t in result.scalars().all()]+ queue_position = 0+ for task in tasks:+ if task["status"] in {"blocked", "queued", "pending"}:+ queue_position += 1+ task["queue_position"] = queue_position+ else:+ task["queue_position"] = None+ return tasksexcept Exception as e:logger.error(f"Failed to get team tasks: {e}")return []@@ -2566,12 +2688,12 @@ class Database:update(TeamTask).where(TeamTask.id == task_id,- TeamTask.status == "pending",- TeamTask.assigned_to.is_(None),+ TeamTask.status == "queued",+ or_(TeamTask.assigned_to.is_(None), TeamTask.assigned_to == agent_node_id),).values(assigned_to=agent_node_id,- status="in_progress",+ status="running",started_at=datetime.now(timezone.utc),))@@ -2588,7 +2710,7 @@ class Database:won = bool(claimed.rowcount == 1)same_agent_retry = (- task.status == "in_progress"+ task.status == "running"and task.assigned_to == agent_node_id)if not won and not same_agent_retry:@@ -2606,17 +2728,17 @@ class Database:return Noneasync def complete_task(self, task_id: str, result_data: Optional[Dict[str, Any]] = None) -> bool:- """Atomically transition an in-progress task to completed."""+ """Atomically submit a running task for lead review."""try:async def _complete(session: AsyncSession) -> Dict[str, Any]:completed = await session.execute(update(TeamTask).where(TeamTask.id == task_id,- TeamTask.status == "in_progress",+ TeamTask.status == "running",).values(- status="completed",+ status="submitted",result=result_data,progress=100,completed_at=datetime.now(timezone.utc),@@ -2631,7 +2753,7 @@ class Database:task = selected.scalar_one_or_none()return {"success": bool(- task is not None and task.status == "completed"+ task is not None and task.status == "submitted")}@@ -2656,13 +2778,13 @@ class Database:update(TeamTask).where(TeamTask.id == task_id,- TeamTask.status == "in_progress",+ TeamTask.status == "running",).values(error=error,retry_count=next_retry,status=case(- (retryable, "pending"),+ (retryable, "queued"),else_="failed",),assigned_to=case(@@ -2687,7 +2809,7 @@ class Database:return {"success": bool(task is not None- and task.status in {"pending", "failed"}+ and task.status in {"queued", "failed"}and task.error == error)}@@ -2709,10 +2831,10 @@ class Database:async with self.get_session() as session:result = await session.execute(select(TeamTask).where(TeamTask.team_id == team_id))tasks = result.scalars().all()- completed_ids = {t.id for t in tasks if t.status == "completed"}+ completed_ids = {t.id for t in tasks if t.status == "accepted"}claimable = []for t in tasks:- if t.status != "pending" or t.assigned_to:+ if t.status != "queued":continuedeps = t.depends_on.get("task_ids", []) if t.depends_on else []if all(d in completed_ids for d in deps):@@ -2822,6 +2944,19 @@ class Database:tasks_result = await session.execute(select(TeamTask).where(TeamTask.team_id == team_id))tasks = tasks_result.scalars().all()+ counts = {+ state: sum(t.status == state for t in tasks)+ for state in ("blocked", "queued", "running", "submitted", "accepted", "failed", "cancelled")+ }+ # Compatibility with rows created by older runtimes during a rolling upgrade.+ pending_count = counts["blocked"] + counts["queued"] + sum(t.status == "pending" for t in tasks)+ active_count = counts["running"] + sum(t.status == "in_progress" for t in tasks)+ # A worker result is only submitted for review. "Done" means+ # the lead explicitly accepted it (plus historical completed+ # rows retained for compatibility).+ completed_count = counts["accepted"] + sum(t.status == "completed" for t in tasks)+ failed_count = counts["failed"]+return {"team_id": team_id,"status": team.status,@@ -2843,18 +2978,24 @@ class Database:"active_count": active_count,"completed_count": completed_count,"failed_count": failed_count,+ "blocked_count": counts["blocked"],+ "submitted_count": counts["submitted"],+ "accepted_count": counts["accepted"],+ "cancelled_count": counts["cancelled"],+ "status_counts": counts,"members": [{"id": m.agent_node_id, "agent_node_id": m.agent_node_id,"type": m.agent_type, "agent_type": m.agent_type, "label": m.agent_label,"role": m.role, "status": m.status, "capabilities": m.capabilities} for m in members],"queued_tasks": [{"id": t.id, "title": t.title, "assigned_to": t.assigned_to}- for t in tasks if t.status == "pending"+ for t in tasks if t.status in {"pending", "blocked", "queued"}],"active_tasks": [{"id": t.id, "title": t.title, "assigned_to": t.assigned_to, "progress": t.progress}for t in tasks- if t.status == "in_progress"+ if t.status in {"in_progress", "running"}],+ "tasks": [self._team_task_dict(t) for t in sorted(tasks, key=lambda item: (item.queue_sequence, item.created_at))],}except Exception as e:logger.error(f"Failed to get team stats: {e}")diff --git a/server/models/database.py b/server/models/database.pyindex a62f23d7..be99fc2e 100644--- a/server/models/database.py+++ b/server/models/database.py@@ -486,10 +486,26 @@ class TeamTask(SQLModel, table=True):team_id: str = Field(index=True, max_length=255)title: str = Field(max_length=500)description: Optional[str] = Field(default=None, max_length=5000)- status: str = Field(default="pending", max_length=20) # pending, in_progress, completed, failed, skipped+ status: str = Field(default="queued", index=True, max_length=20)priority: int = Field(default=3) # 1-5, lower = higher prioritycreated_by: str = Field(max_length=255) # agent_node_idassigned_to: Optional[str] = Field(default=None, max_length=255)+ workflow_id: Optional[str] = Field(default=None, index=True, max_length=255)+ execution_id: Optional[str] = Field(default=None, index=True, max_length=255)+ root_execution_id: Optional[str] = Field(default=None, index=True, max_length=255)+ parent_agent_id: Optional[str] = Field(default=None, max_length=255)+ mission: Optional[str] = Field(default=None, max_length=10000)+ context: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))+ acceptance_criteria: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))+ queue_sequence: int = Field(default=0, index=True)+ revision: int = Field(default=0)+ current_attempt: int = Field(default=0)+ child_workflow_id: Optional[str] = Field(default=None, max_length=500)+ child_run_id: Optional[str] = Field(default=None, max_length=255)+ trace_id: Optional[str] = Field(default=None, index=True, max_length=255)+ cancellation_requested: bool = Field(default=False)+ cancellation_reason: Optional[str] = Field(default=None, max_length=2000)+ usage: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))depends_on: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # List of task_idsresult: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))error: Optional[str] = Field(default=None, max_length=2000)@@ -503,6 +519,27 @@ class TeamTask(SQLModel, table=True):completed_at: Optional[datetime] = Field(default=None)+class TeamTaskAttempt(SQLModel, table=True):+ """Immutable execution history for a durable team task."""++ __tablename__ = "team_task_attempts"++ id: str = Field(primary_key=True, max_length=255)+ task_id: str = Field(index=True, max_length=255)+ team_id: str = Field(index=True, max_length=255)+ attempt_number: int+ assignee_node_id: Optional[str] = Field(default=None, max_length=255)+ status: str = Field(default="queued", max_length=20)+ child_workflow_id: Optional[str] = Field(default=None, max_length=500)+ child_run_id: Optional[str] = Field(default=None, max_length=255)+ result: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))+ error: Optional[str] = Field(default=None, max_length=5000)+ usage: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))+ created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))+ started_at: Optional[datetime] = None+ completed_at: Optional[datetime] = None++class AgentMessage(SQLModel, table=True):"""Inter-agent messages within a team.diff --git a/server/nodes/agent/_events.py b/server/nodes/agent/_events.pyindex 7663c681..ec0bc149 100644--- a/server/nodes/agent/_events.py+++ b/server/nodes/agent/_events.py@@ -38,6 +38,8 @@ async def broadcast_agent_task_completed(parent_node_id: str,workflow_id: Optional[str] = None,result: Optional[str] = None,+ event_id: Optional[str] = None,+ lifecycle_data: Optional[dict[str, Any]] = None,) -> None:"""Broadcast a delegated agent task completing successfully."""await _broadcast_task_event(@@ -48,6 +50,8 @@ async def broadcast_agent_task_completed(parent_node_id=parent_node_id,workflow_id=workflow_id,result=result,+ event_id=event_id,+ lifecycle_data=lifecycle_data,)@@ -59,6 +63,8 @@ async def broadcast_agent_task_failed(parent_node_id: str,workflow_id: Optional[str] = None,error: str,+ event_id: Optional[str] = None,+ lifecycle_data: Optional[dict[str, Any]] = None,) -> None:"""Broadcast a delegated agent task failing."""await _broadcast_task_event(@@ -69,6 +75,8 @@ async def broadcast_agent_task_failed(parent_node_id=parent_node_id,workflow_id=workflow_id,error=error,+ event_id=event_id,+ lifecycle_data=lifecycle_data,)@@ -82,6 +90,8 @@ async def _broadcast_task_event(workflow_id: Optional[str] = None,result: Optional[str] = None,error: Optional[str] = None,+ event_id: Optional[str] = None,+ lifecycle_data: Optional[dict[str, Any]] = None,) -> None:"""Single delivery path: build the envelope, route through:func:`services.events.dispatch.emit`.@@ -103,6 +113,7 @@ async def _broadcast_task_event("agent_node_id": agent_node_id,"parent_node_id": parent_node_id,"workflow_id": workflow_id,+ **(lifecycle_data or {}),}if status == "completed" and result is not None:payload["result"] = result@@ -115,6 +126,11 @@ async def _broadcast_task_event(agent=agent_name,data=payload,)+ # Temporal activity retries must reproduce the same event identity. The+ # listener workflow can therefore deduplicate a completion that was+ # delivered immediately before a worker failure/retry.+ if event_id:+ envelope.id = event_idawait emit(envelope, wire_routing_key=_WIRE_ROUTING_KEY)diff --git a/server/nodes/agent/ai_employee/__init__.py b/server/nodes/agent/ai_employee/__init__.pyindex 14be1785..180146a5 100644--- a/server/nodes/agent/ai_employee/__init__.py+++ b/server/nodes/agent/ai_employee/__init__.py@@ -1,4 +1,5 @@from .._handles import team_lead_agent_handles+from .._handles import STD_AGENT_HINTSfrom .._specialized import SpecializedAgentBase@@ -9,6 +10,7 @@ class AIEmployeeNode(SpecializedAgentBase):group = ("agent",)description = "Team lead for multi-agent coordination"handles = team_lead_agent_handles()+ ui_hints = {**STD_AGENT_HINTS, "isTaskManagerPanel": True}tool_description = ("ONE-SHOT delegation to AI Employee. Call ONCE per task, returns task_id. Coordinates multiple agents - do NOT re-call.")diff --git a/server/nodes/agent/orchestrator_agent/__init__.py b/server/nodes/agent/orchestrator_agent/__init__.pyindex a1811aa8..36519d3e 100644--- a/server/nodes/agent/orchestrator_agent/__init__.py+++ b/server/nodes/agent/orchestrator_agent/__init__.py@@ -1,4 +1,5 @@from .._handles import team_lead_agent_handles+from .._handles import STD_AGENT_HINTSfrom .._specialized import SpecializedAgentBase@@ -9,6 +10,7 @@ class OrchestratorAgentNode(SpecializedAgentBase):group = ("agent",)description = "Team lead that delegates to connected specialized agents"handles = team_lead_agent_handles()+ ui_hints = {**STD_AGENT_HINTS, "isTaskManagerPanel": True}tool_description = ("ONE-SHOT delegation to Orchestrator Agent. Call ONCE per task, returns task_id. Coordinates multiple agents - do NOT re-call.")diff --git a/server/nodes/tool/agent_builder/__init__.py b/server/nodes/tool/agent_builder/__init__.pyindex d2896739..106bd06d 100644--- a/server/nodes/tool/agent_builder/__init__.py+++ b/server/nodes/tool/agent_builder/__init__.py@@ -62,8 +62,9 @@ _TOOL_OUTPUT_HANDLE = "output-main"_MASTER_SKILL_TYPE = "masterSkill"_MASTER_SKILL_LABEL = "Master Skill"_AGENT_BUILDER_TYPE = "agentBuilder"+_TASK_MANAGER_TYPE = "taskManager"_TEAM_LEAD_TYPES = frozenset({"orchestrator_agent", "ai_employee"})-_DENIED_TOOL_TYPES = frozenset({_AGENT_BUILDER_TYPE, _MASTER_SKILL_TYPE})+_DENIED_TOOL_TYPES = frozenset({_AGENT_BUILDER_TYPE, _MASTER_SKILL_TYPE, _TASK_MANAGER_TYPE})_KEY_PARAM_FIELDS = ("provider", "model", "operation", "url", "query")_SKILLS_DIR = Path(__file__).resolve().parents[2] / "skills"diff --git a/server/nodes/tool/task_manager/__init__.py b/server/nodes/tool/task_manager/__init__.pyindex 0c37257e..a1d3827f 100644--- a/server/nodes/tool/task_manager/__init__.py+++ b/server/nodes/tool/task_manager/__init__.py@@ -1,203 +1,184 @@-"""Task Manager Tool — Wave 11.C migration; body inlined Wave 11.I (M.O).--Inspects the in-memory delegation registry that lives on-``services.handlers.tools`` (``_delegated_tasks`` for in-flight asyncio-tasks, ``_delegation_results`` for completed-but-still-cached results,-plus ``get_delegated_task_status`` which adds a DB-fallback layer for-older runs). The plugin doesn't own that state — the delegation-lifecycle in ``tools.py`` does — so we read through to it rather than-duplicating registry plumbing here.-"""+"""Durable, execution-scoped task control for agent team leads."""from __future__ import annotations-from typing import Any, Dict, Literal, Optional+from typing import Any, Dict, List, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Field-from core.logging import get_loggerfrom services.plugin import NodeContext, Operation, TaskQueue, ToolNode-logger = get_logger(__name__)+TaskOperation = Literal[+ "assign_task", "list_tasks", "get_task", "modify_task", "cancel_task",+ "retry_task", "reassign_task", "accept_task", "finish_team", "mark_done",+]class TaskManagerParams(BaseModel):- operation: Literal["list_tasks", "get_task", "mark_done"] = Field(- default="list_tasks",- description="List delegated tasks, retrieve one task, or remove a completed task from tracking.",- )- task_id: Optional[str] = Field(- default=None,- description="Delegated task ID. Required for get_task and mark_done.",- )- status_filter: Optional[Literal["running", "completed", "error", "cancelled"]] = Field(- default=None,- description="Optional status filter for list_tasks.",- )-+ operation: TaskOperation = "list_tasks"+ task_id: Optional[str] = None+ title: Optional[str] = Field(default=None, max_length=500)+ mission: Optional[str] = Field(default=None, max_length=10000)+ context: Optional[Dict[str, Any]] = None+ acceptance_criteria: Optional[Dict[str, Any]] = None+ depends_on: Optional[List[str]] = None+ assignee_node_id: Optional[str] = None+ delegate_name: Optional[str] = None+ expected_revision: Optional[int] = Field(default=None, ge=0)+ reason: Optional[str] = Field(default=None, max_length=2000)+ status_filter: Optional[str] = Nonemodel_config = ConfigDict(extra="allow")class TaskManagerOutput(BaseModel):- task_id: Optional[str] = None+ success: bool = True+ operation: Optional[str] = None+ task: Optional[dict] = Nonetasks: Optional[list] = None- success: Optional[bool] = None-+ team: Optional[dict] = Nonemodel_config = ConfigDict(extra="allow")class TaskManagerNode(ToolNode):type = "taskManager"display_name = "Task Manager"- subtitle = "AI Task Tracking"+ subtitle = "Durable Team Tasks"group = ("tool", "ai")- description = "Task management tool for AI agents to create, track, and manage tasks"+ description = "Assign, review, retry, reassign, cancel, and accept durable teammate tasks"component_kind = "tool"tool_name = "task_manager"- tool_description = "Track delegated sub-agent tasks. Operations: list_tasks (see all tasks), get_task (check specific task status/result), mark_done (cleanup completed tasks)."+ tool_description = (+ "Manage the current lead execution's durable team tasks. Assign only connected "+ "teammates, inspect submitted work, then accept, retry, reassign, or cancel it."+ )handles = ({"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},{"name": "output-tool", "kind": "output", "position": "top", "label": "Tool", "role": "tools"},)- ui_hints = {"isToolPanel": True, "hideRunButton": True}+ ui_hints = {"isToolPanel": True, "isTaskManagerPanel": True, "hideRunButton": True}annotations = {"destructive": True, "readonly": False, "open_world": False}task_queue = TaskQueue.DEFAULT-+ needs_canvas = TrueParams = TaskManagerParamsOutput = TaskManagerOutput@Operation("manage")async def manage(self, ctx: NodeContext, params: TaskManagerParams) -> Any:- return await _execute_task_manager(- params.model_dump(),- {"node_id": ctx.node_id, "workspace_dir": ctx.workspace_dir or ""},- )---async def _execute_task_manager(- tool_args: Dict[str, Any],- config: Dict[str, Any],-) -> Dict[str, Any]:- """Execute task manager operations.-- Dual-purpose: works as AI tool (LLM fills args) or workflow node- (uses params).-- Operations:- - ``list_tasks``: list all active and completed delegated tasks- - ``get_task``: detailed status for one task- - ``mark_done``: drop a task from active tracking- """- # Read-through to the delegation registry owned by tools.py. Keeping- # the singletons there is intentional -- the entire delegation- # lifecycle (spawn / cleanup / refcount / DB persistence) lives in- # tools.py and is genuine cross-cutting framework state.- from services.handlers.tools import (- _delegated_tasks,- _delegation_results,- get_delegated_task_status,- )+ config = {+ **ctx.raw,+ "node_id": ctx.node_id,+ "workflow_id": ctx.workflow_id or ctx.raw.get("workflow_id"),+ "execution_id": ctx.execution_id or ctx.raw.get("execution_id"),+ "nodes": ctx.nodes,+ "edges": ctx.edges,+ }+ return await _execute_task_manager(params.model_dump(exclude_none=True), config)- params = config.get("parameters", {})- operation = tool_args.get("operation") or params.get("operation", "list_tasks")- task_id = tool_args.get("task_id") or params.get("task_id")- status_filter = tool_args.get("status_filter") or params.get("status_filter")- database = config.get("database")- logger.debug(f"[TaskManager] Operation: {operation}, task_id: {task_id}, filter: {status_filter}")+def _scope(config: Dict[str, Any]) -> Dict[str, Any]:+ workflow_id = str(config.get("workflow_id") or "")+ lead_id = str(config.get("parent_node_id") or config.get("team_lead_node_id") or "")+ if not workflow_id or not lead_id:+ raise ValueError("Task Manager requires trusted workflow and team-lead execution context")+ return {"workflow_id": workflow_id, "team_lead_node_id": lead_id, "execution_id": config.get("execution_id")}- if operation == "list_tasks":- tasks = []-- # Active tasks from asyncio.Task tracking.- for tid, task in _delegated_tasks.items():- if task.done():- try:- if task.cancelled():- status = "cancelled"- elif task.exception():- status = "error"- else:- status = "completed"- except Exception:- status = "completed"- else:- status = "running"-- tasks.append({"task_id": tid, "status": status, "active": True})-- # Completed tasks from in-memory cache.- for tid, result in _delegation_results.items():- if tid not in [t["task_id"] for t in tasks]:- tasks.append(- {- "task_id": tid,- "status": result.get("status", "completed"),- "agent_name": result.get("agent_name"),- "result_summary": str(result.get("result", ""))[:200],- "active": False,- }- )-- if status_filter:- tasks = [t for t in tasks if t.get("status") == status_filter]- return {- "success": True,- "operation": "list_tasks",- "tasks": tasks,- "count": len(tasks),- "running": sum(1 for t in tasks if t.get("status") == "running"),- "completed": sum(1 for t in tasks if t.get("status") == "completed"),- "errors": sum(1 for t in tasks if t.get("status") == "error"),- }+def _resolve_teammate(config: Dict[str, Any], args: Dict[str, Any]) -> Dict[str, Any]:+ from services.plugin.edge_walker import build_teammate_descriptors- if operation == "get_task":- if not task_id:- return {"success": False, "error": "task_id is required for get_task operation"}-- # 3-layer lookup (live tasks -> memory cache -> DB).- result = await get_delegated_task_status(task_ids=[task_id], database=database)- tasks = result.get("tasks", [])-- if not tasks:- return {- "success": False,- "error": f"Task {task_id} not found",- "task_id": task_id,- }+ lead_id = str(config.get("parent_node_id") or config.get("team_lead_node_id") or "")+ descriptors = build_teammate_descriptors(lead_id, config)+ node_id, delegate_name = args.get("assignee_node_id"), args.get("delegate_name")+ matches = [d for d in descriptors if (node_id and d["node_id"] == node_id) or (delegate_name and d["delegate_tool_name"] == delegate_name)]+ if len(matches) != 1:+ available = [{"node_id": d["node_id"], "delegate_name": d["delegate_tool_name"], "label": d["label"]} for d in descriptors]+ raise ValueError(f"Assignee must resolve to exactly one connected teammate; available={available}")+ return matches[0]- task_info = tasks[0]- return {- "success": True,- "operation": "get_task",- "task_id": task_id,- "status": task_info.get("status"),- "agent_name": task_info.get("agent_name"),- "result": task_info.get("result"),- "error": task_info.get("error"),- }- if operation == "mark_done":- if not task_id:- return {"success": False, "error": "task_id is required for mark_done operation"}+async def _execute_task_manager(args: Dict[str, Any], config: Dict[str, Any]) -> Dict[str, Any]:+ from services.agent_team import get_agent_team_service- removed = False- if task_id in _delegated_tasks:- del _delegated_tasks[task_id]- removed = True- if task_id in _delegation_results:- del _delegation_results[task_id]- removed = True+ service = get_agent_team_service()+ operation = str(args.get("operation") or "list_tasks")+ scope = _scope(config)+ if operation == "list_tasks":+ tasks = await service.list_durable_tasks(**scope, status=args.get("status_filter"))+ return {"success": True, "operation": operation, "tasks": tasks, "count": len(tasks)}+ if operation == "get_task":+ task = await service.get_durable_task(**scope, task_id=str(args.get("task_id") or ""))+ return {"success": True, "operation": operation, "task": task}+ if operation == "assign_task":+ if not args.get("title") or not args.get("mission"):+ raise ValueError("assign_task requires title and mission")+ teammate = _resolve_teammate(config, args)+ task = await service.assign_durable_task(+ **scope, assignee_node_id=teammate["node_id"], title=args["title"],+ mission=args["mission"], context=args.get("context"),+ acceptance_criteria=args.get("acceptance_criteria"), depends_on=args.get("depends_on"),+ trace_id=config.get("tool_call_id"),+ )+ delegation = None+ if config.get("ai_service") and config.get("database"):+ from services.handlers.tools import _execute_delegated_agent++ child_config = {+ **config,+ "node_id": teammate["node_id"],+ "node_type": teammate["node_type"],+ "team_id": task["team_id"],+ }+ delegation = await _execute_delegated_agent(+ {"task": args["mission"], "context": args.get("context") or {}},+ child_config,+ precreated_task_id=task["id"],+ )+ # Temporal AgentWorkflow consumes this trusted scheduling envelope and+ # starts the matching child through its existing bounded child-workflow+ # machinery. Legacy execution may consume it through the shared+ # delegation coordinator without creating a second TeamTask.return {- "success": True,- "operation": "mark_done",- "task_id": task_id,- "removed": removed,- "message": (- f"Task {task_id} marked as done and removed from tracking" if removed else f"Task {task_id} was not in active tracking"- ),+ "success": True, "operation": operation, "task": task,+ "delegation": delegation,+ "delegation_request": {+ "team_task_id": task["id"], "assignee_node_id": teammate["node_id"],+ "delegate_name": teammate["delegate_tool_name"], "task": args["mission"],+ "context": args.get("context") or {},+ },}-- return {"success": False, "error": f"Unknown operation: {operation}"}+ if operation == "finish_team":+ team = await service.finish_durable_team(**scope)+ return {"success": True, "operation": operation, "team": team}++ task_id = str(args.get("task_id") or "")+ revision = args.get("expected_revision", args.get("revision"))+ # Completion review commonly follows immediately after one child result.+ # Resolve that unambiguous submitted task inside the trusted execution+ # scope instead of leaving it permanently submitted because the model+ # omitted identifiers. Never guess when multiple reviews are pending.+ if not task_id and operation in {"accept_task", "mark_done"}:+ submitted = await service.list_durable_tasks(**scope, status="submitted")+ if len(submitted) == 1:+ task_id = submitted[0]["id"]+ revision = submitted[0]["revision"]+ else:+ raise ValueError(+ "accept_task requires task_id when there is not exactly one submitted task; "+ "call list_tasks or get_task first"+ )+ if not task_id:+ raise ValueError(f"{operation} requires task_id")+ if revision is None:+ current = await service.get_durable_task(**scope, task_id=task_id)+ revision = current.get("revision")+ if revision is None:+ raise ValueError(f"{operation} requires expected_revision")+ mapped = "accept" if operation in {"accept_task", "mark_done"} else operation.removesuffix("_task")+ payload = {k: args[k] for k in ("title", "mission", "context", "acceptance_criteria", "reason") if k in args}+ if operation == "reassign_task":+ payload["assignee_node_id"] = _resolve_teammate(config, args)["node_id"]+ task = await service.mutate_durable_task(+ **scope, task_id=task_id, revision=int(revision), operation=mapped, **payload,+ )+ return {"success": True, "operation": operation, "task": task}diff --git a/server/nodes/utility/team_monitor/__init__.py b/server/nodes/utility/team_monitor/__init__.pyindex ad916cd7..88b21ffb 100644--- a/server/nodes/utility/team_monitor/__init__.py+++ b/server/nodes/utility/team_monitor/__init__.py@@ -48,6 +48,32 @@ class TeamMonitorNode(ActionNode):@Operation("monitor")async def monitor(self, ctx: NodeContext, params: TeamMonitorParams) -> Any:from services.agent_team import get_agent_team_service+ from services.plugin.edge_walker import build_teammate_descriptors++ lead_id = next(+ (+ edge.get("source")+ for edge in (ctx.edges or [])+ if edge.get("target") == ctx.node_id+ and any(+ node.get("id") == edge.get("source")+ and node.get("type") in {"orchestrator_agent", "ai_employee"}+ for node in (ctx.nodes or [])+ )+ ),+ None,+ )+ connected_members = [+ {+ "agent_node_id": teammate["node_id"],+ "agent_type": teammate["node_type"],+ "label": teammate["label"],+ "status": "connected",+ }+ for teammate in build_teammate_descriptors(+ lead_id, {**ctx.raw, "nodes": ctx.nodes, "edges": ctx.edges}+ )+ ] if lead_id else []team_id = ctx.raw.get("team_id")if not team_id:@@ -60,7 +86,7 @@ class TeamMonitorNode(ActionNode):return {"message": "No team connected","team_id": None,- "members": [],+ "members": connected_members,"tasks": {"total": 0, "completed": 0, "active": 0, "pending": 0, "failed": 0},"active_tasks": [],"recent_events": [],@@ -68,9 +94,17 @@ class TeamMonitorNode(ActionNode):status = await get_agent_team_service().get_team_status(team_id)max_history = params.max_history_items+ persisted_members = status.get("members", [])+ merged_members = {member.get("agent_node_id"): member for member in connected_members}+ for index, member in enumerate(persisted_members):+ member_id = member.get("agent_node_id") or member.get("id") or f"member-{index}"+ merged_members[member_id] = {+ **merged_members.get(member_id, {}),+ **member,+ }return {"team_id": team_id,- "members": status.get("members", []),+ "members": list(merged_members.values()),"tasks": {"total": status.get("task_count", 0),"completed": status.get("completed_count", 0),diff --git a/server/services/agent_team.py b/server/services/agent_team.pyindex d8a56741..54a9c04b 100644--- a/server/services/agent_team.py+++ b/server/services/agent_team.py@@ -6,6 +6,7 @@ Teams are scoped to specific workflow executions.import uuidimport hashlib+from datetime import datetime, timezonefrom typing import Dict, Any, List, Optionalfrom core.database import Databasefrom core.logging import get_logger@@ -134,6 +135,112 @@ class AgentTeamService:return {"error": "Team not found"}return await self.database.get_team_stats(team_id)+ async def resolve_lead_scope(+ self, *, workflow_id: str, team_lead_node_id: str,+ execution_id: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Resolve authority from the owning lead; callers cannot choose a team."""+ team = await self.database.find_team(workflow_id, team_lead_node_id, execution_id)+ if not team:+ raise ValueError("No team exists for this lead execution")+ return team++ async def _authorized_assignee(self, team_id: str, agent_node_id: str) -> Dict[str, Any]:+ stats = await self.database.get_team_stats(team_id)+ member = next((m for m in stats.get("members", []) if m["agent_node_id"] == agent_node_id), None)+ if not member or member.get("role") != "teammate":+ raise ValueError("Assignee is not a teammate of this lead")+ if member.get("status") == "offline":+ raise ValueError("Assignee is no longer available")+ return member++ async def assign_durable_task(+ self, *, workflow_id: str, team_lead_node_id: str, execution_id: Optional[str],+ assignee_node_id: str, title: str, mission: str,+ context: Optional[Dict[str, Any]] = None,+ acceptance_criteria: Optional[Dict[str, Any]] = None,+ depends_on: Optional[List[str]] = None, task_id: Optional[str] = None,+ trace_id: Optional[str] = None,+ ) -> Dict[str, Any]:+ team = await self.resolve_lead_scope(workflow_id=workflow_id, team_lead_node_id=team_lead_node_id, execution_id=execution_id)+ team_id = team["id"]+ await self._authorized_assignee(team_id, assignee_node_id)+ dependencies_resolved = True+ for dependency in depends_on or []:+ dependency_task = await self.database.get_durable_team_task(team_id, dependency)+ if not dependency_task:+ raise ValueError(f"Dependency is outside this team: {dependency}")+ dependencies_resolved = dependencies_resolved and dependency_task.get("status") == "accepted"+ task = await self.database.create_durable_team_task(+ id=task_id or f"task_{uuid.uuid4().hex[:12]}", team_id=team_id,+ workflow_id=team["workflow_id"], execution_id=team.get("execution_id"),+ root_execution_id=team.get("root_execution_id"), parent_agent_id=team_lead_node_id,+ title=title, mission=mission, description=mission, context=context,+ acceptance_criteria=acceptance_criteria, created_by=team_lead_node_id,+ assigned_to=assignee_node_id, depends_on=depends_on, trace_id=trace_id,+ status="queued" if dependencies_resolved else "blocked",+ )+ if not task:+ raise RuntimeError("Failed to persist task")+ await self.database.update_team_status(team_id, "active")+ if self.broadcaster:+ await self.broadcaster.broadcast_team_event(team_id, "team.task.queued", task)+ return task++ async def list_durable_tasks(self, *, workflow_id: str, team_lead_node_id: str, execution_id: Optional[str], status: Optional[str] = None) -> List[Dict[str, Any]]:+ team = await self.resolve_lead_scope(workflow_id=workflow_id, team_lead_node_id=team_lead_node_id, execution_id=execution_id)+ return await self.database.get_team_tasks(team["id"], status)++ async def get_durable_task(self, *, workflow_id: str, team_lead_node_id: str, execution_id: Optional[str], task_id: str) -> Dict[str, Any]:+ team = await self.resolve_lead_scope(workflow_id=workflow_id, team_lead_node_id=team_lead_node_id, execution_id=execution_id)+ task = await self.database.get_durable_team_task(team["id"], task_id)+ if not task:+ raise ValueError("Task not found in this lead execution")+ return task++ async def mutate_durable_task(+ self, *, workflow_id: str, team_lead_node_id: str, execution_id: Optional[str],+ task_id: str, revision: int, operation: str, **payload: Any,+ ) -> Dict[str, Any]:+ team = await self.resolve_lead_scope(workflow_id=workflow_id, team_lead_node_id=team_lead_node_id, execution_id=execution_id)+ team_id = team["id"]+ task = await self.database.get_durable_team_task(team_id, task_id)+ if not task:+ raise ValueError("Task not found in this lead execution")+ now = datetime.now(timezone.utc)+ transitions: Dict[str, tuple[List[str], Dict[str, Any], bool]] = {+ "modify": (["blocked", "queued"], {k: payload[k] for k in ("title", "mission", "context", "acceptance_criteria") if payload.get(k) is not None}, False),+ "cancel": (["blocked", "queued", "running"], {"status": "cancelled", "cancellation_requested": True, "cancellation_reason": payload.get("reason"), "completed_at": now}, False),+ "accept": (["submitted"], {"status": "accepted", "completed_at": now, "progress": 100}, False),+ "retry": (["failed", "submitted", "cancelled"], {"status": "queued", "current_attempt": task["current_attempt"] + 1, "retry_count": task["retry_count"] + 1, "result": None, "error": None, "completed_at": None, "cancellation_requested": False, "cancellation_reason": None}, True),+ }+ if operation == "reassign":+ assignee = payload.get("assignee_node_id")+ await self._authorized_assignee(team_id, assignee)+ allowed, values, create_attempt = transitions["retry"]+ values = {**values, "assigned_to": assignee}+ elif operation in transitions:+ allowed, values, create_attempt = transitions[operation]+ else:+ raise ValueError(f"Unsupported task operation: {operation}")+ if operation == "modify" and not values:+ raise ValueError("No mutable task fields supplied")+ changed = await self.database.transition_team_task(team_id, task_id, revision, allowed, values, create_attempt=create_attempt)+ if not changed:+ raise ValueError("Task changed or is not in a valid state; refresh and retry")+ if self.broadcaster:+ await self.broadcaster.broadcast_team_event(team_id, f"team.task.{changed['status']}", changed)+ return changed++ async def finish_durable_team(self, *, workflow_id: str, team_lead_node_id: str, execution_id: Optional[str]) -> Dict[str, Any]:+ team = await self.resolve_lead_scope(workflow_id=workflow_id, team_lead_node_id=team_lead_node_id, execution_id=execution_id)+ tasks = await self.database.get_team_tasks(team["id"])+ unresolved = [t for t in tasks if t["status"] not in {"accepted", "cancelled"}]+ if unresolved:+ raise ValueError("Team has unresolved tasks")+ await self.database.update_team_status(team["id"], "completed")+ return await self.database.get_team_stats(team["id"])+# -------------------------------------------------------------------------# Task Management# -------------------------------------------------------------------------@@ -188,7 +295,7 @@ class AgentTeamService:return taskasync def complete_task(self, team_id: str, task_id: str, result: Optional[Dict[str, Any]] = None) -> bool:- """Mark a task as completed."""+ """Submit a worker result for lead review."""# Get task to find assigned agenttasks = await self.database.get_team_tasks(team_id)task = next((t for t in tasks if t["id"] == task_id), None)@@ -201,7 +308,7 @@ class AgentTeamService:await self.database.update_member_status(team_id, task["assigned_to"], "idle")if self.broadcaster:- await self.broadcaster.broadcast_team_event(team_id, "task_completed", {"task_id": task_id, "result": result})+ await self.broadcaster.broadcast_team_event(team_id, "team.task.submitted", {"task_id": task_id, "result": result})return success@@ -226,11 +333,11 @@ class AgentTeamService:return await self.database.get_claimable_tasks(team_id)async def is_team_done(self, team_id: str) -> bool:- """Check if all tasks are completed/failed."""+ """Check whether all tasks have been explicitly resolved."""tasks = await self.database.get_team_tasks(team_id)if not tasks:return True- return all(t["status"] in ("completed", "failed", "skipped") for t in tasks)+ return all(t["status"] in ("accepted", "failed", "cancelled", "skipped") for t in tasks)async def acquire_subagent_permit(self, root_execution_id: str, permit_id: str, limit: int = 3) -> bool:"""Acquire one cross-process descendant slot for a delegation."""diff --git a/server/services/agent_teams/handlers.py b/server/services/agent_teams/handlers.pyindex e18de468..f70bf629 100644--- a/server/services/agent_teams/handlers.py+++ b/server/services/agent_teams/handlers.py@@ -132,16 +132,72 @@ async def handle_complete_team_task(data: Dict[str, Any], websocket: WebSocket)return {"success": success}-@ws_handler("team_id")+@ws_handler()async def handle_get_team_tasks(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:"""Get team tasks."""- from core.container import container-- database = container.database()- tasks = await database.get_team_tasks(data["team_id"], data.get("status"))+ from services.agent_team import get_agent_team_service+ if data.get("workflow_id") and data.get("team_lead_node_id"):+ tasks = await get_agent_team_service().list_durable_tasks(+ workflow_id=data["workflow_id"], team_lead_node_id=data["team_lead_node_id"],+ execution_id=data.get("execution_id"), status=data.get("status"),+ )+ elif data.get("team_id"):+ # Compatibility read only; mutations never accept caller-selected team IDs.+ tasks = await get_agent_team_service().database.get_team_tasks(data["team_id"], data.get("status"))+ else:+ return {"success": False, "error": "workflow_id and team_lead_node_id required"}return {"tasks": tasks}+@ws_handler("workflow_id", "team_lead_node_id", "assignee_node_id", "title", "mission")+async def handle_assign_team_task(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ from services.agent_team import get_agent_team_service+ task = await get_agent_team_service().assign_durable_task(+ workflow_id=data["workflow_id"], team_lead_node_id=data["team_lead_node_id"],+ execution_id=data.get("execution_id"), assignee_node_id=data["assignee_node_id"],+ title=data["title"], mission=data["mission"], context=data.get("context"),+ acceptance_criteria=data.get("acceptance_criteria"), depends_on=data.get("depends_on"),+ task_id=data.get("task_id"), trace_id=data.get("trace_id"),+ )+ return {"task": task}+++@ws_handler("workflow_id", "team_lead_node_id", "task_id")+async def handle_get_team_task(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ from services.agent_team import get_agent_team_service+ task = await get_agent_team_service().get_durable_task(+ workflow_id=data["workflow_id"], team_lead_node_id=data["team_lead_node_id"],+ execution_id=data.get("execution_id"), task_id=data["task_id"],+ )+ return {"task": task}+++@ws_handler("workflow_id", "team_lead_node_id", "task_id", "operation")+async def handle_manage_team_task(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ from services.agent_team import get_agent_team_service+ if "revision" not in data:+ return {"success": False, "error": "revision required"}+ task = await get_agent_team_service().mutate_durable_task(+ workflow_id=data["workflow_id"], team_lead_node_id=data["team_lead_node_id"],+ execution_id=data.get("execution_id"), task_id=data["task_id"],+ revision=int(data["revision"]), operation=data["operation"],+ title=data.get("title"), mission=data.get("mission"), context=data.get("context"),+ acceptance_criteria=data.get("acceptance_criteria"), reason=data.get("reason"),+ assignee_node_id=data.get("assignee_node_id"),+ )+ return {"task": task}+++@ws_handler("workflow_id", "team_lead_node_id")+async def handle_finish_team(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ from services.agent_team import get_agent_team_service+ status = await get_agent_team_service().finish_durable_team(+ workflow_id=data["workflow_id"], team_lead_node_id=data["team_lead_node_id"],+ execution_id=data.get("execution_id"),+ )+ return {"status": status}++@ws_handler("team_id", "from_agent", "content")async def handle_send_team_message(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:"""Send message in team."""@@ -181,6 +237,10 @@ WS_HANDLERS: Dict[str, Any] = {"claim_team_task": handle_claim_team_task,"complete_team_task": handle_complete_team_task,"get_team_tasks": handle_get_team_tasks,+ "assign_team_task": handle_assign_team_task,+ "get_team_task": handle_get_team_task,+ "manage_team_task": handle_manage_team_task,+ "finish_team": handle_finish_team,"send_team_message": handle_send_team_message,"get_team_messages": handle_get_team_messages,}diff --git a/server/services/ai.py b/server/services/ai.pyindex 6e46cf3a..fb906325 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -2236,7 +2236,28 @@ class AIService:if tool_data:await broadcast_status("building_tools", {"message": f"Building {len(tool_data)} tool(s)...", "tool_count": len(tool_data)})+ task_manager_bound = any(info.get("node_type") == "taskManager" for info in tool_data)+ durable_delegates = [info for info in tool_data if info.get("delegate_tool_name")]+ if task_manager_bound and durable_delegates:+ teammate_lines = "\n".join(+ f"- {info.get('node_id')}: {info.get('label') or info.get('node_type')} ({info.get('node_type')})"+ for info in durable_delegates+ )+ system_message += (+ "\n\n## Durable Team Delegation\n"+ "All teammate assignments MUST use task_manager with operation='assign_task'. "+ "Supply title, bounded mission, relevant context, acceptance criteria, and one "+ "assignee_node_id from the connected list below. Multiple assign_task calls may "+ "be issued together for parallel queued execution. Never call delegate_to_* "+ "directly. Review submitted tasks using list_tasks/get_task and accept, retry, "+ "modify, reassign, or cancel them before the final report. For mutations, copy "+ "task.id to task_id and task.revision to expected_revision.\n"+ f"Connected teammates:\n{teammate_lines}"+ )+for tool_info in tool_data:+ if task_manager_bound and tool_info.get("delegate_tool_name"):+ continue# Use AI Agent's _build_tool_from_node for all tool typestool, config = await self._build_tool_from_node(tool_info)if tool:diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex e716431f..cf447c76 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -300,7 +300,9 @@ async def _execute_generic(args: Dict[str, Any], config: Dict[str, Any]) -> Dict}-async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any]) -> Dict[str, Any]:+async def _execute_delegated_agent(+ args: Dict[str, Any], config: Dict[str, Any], *, precreated_task_id: Optional[str] = None,+) -> Dict[str, Any]:"""Delegate a task to a child AI Agent (fire-and-forget pattern).This spawns the child agent as an asyncio background task and returns@@ -346,7 +348,7 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])wait_seconds = float(config.get("delegation_wait_seconds") or 0)# Generate hash of task to detect duplicate delegation attempts- task_hash = hashlib.md5(f"{task_description}:{task_context}".encode()).hexdigest()[:16]+ task_hash = precreated_task_id or hashlib.md5(f"{task_description}:{task_context}".encode()).hexdigest()[:16]delegation_key = (parent_node_id, node_id, task_hash)# Check for duplicate delegation (prevents LLM from calling same delegation twice)@@ -371,7 +373,7 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])}# Generate unique task ID- task_id = f"delegated_{node_id}_{uuid.uuid4().hex[:8]}"+ task_id = precreated_task_id or f"delegated_{node_id}_{uuid.uuid4().hex[:8]}"root_execution_id = str(config.get("root_execution_id") or config.get("execution_id") or workflow_id or parent_node_id)delegation_depth = int(config.get("delegation_depth") or 0)@@ -437,15 +439,20 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])team_id = (team or {}).get("team_id") or (team or {}).get("id")if not team_id:return {"success": False, "status": "error", "error": "Failed to persist agent execution team"}- persisted = await team_service.add_task(- team_id,- title=task_description[:500] or f"Delegation to {node_type}",- description=task_context or task_description,- created_by=parent_node_id,- task_id=task_id,- )- if not persisted:- return {"success": False, "status": "error", "error": "Failed to persist delegated team task"}+ if precreated_task_id:+ persisted = await team_service.database.get_durable_team_task(team_id, task_id)+ if not persisted or persisted.get("assigned_to") != node_id:+ return {"success": False, "status": "error", "error": "Precreated task is not assigned to this teammate"}+ else:+ persisted = await team_service.add_task(+ team_id,+ title=task_description[:500] or f"Delegation to {node_type}",+ description=task_context or task_description,+ created_by=parent_node_id,+ task_id=task_id,+ )+ if not persisted:+ return {"success": False, "status": "error", "error": "Failed to persist delegated team task"}# Register this delegation to prevent duplicates_active_delegations[delegation_key] = task_id@@ -498,6 +505,13 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])"outputs": {},"parent_task_id": task_id,"execution_id": config.get("execution_id"),+ "root_execution_id": config.get("root_execution_id"),+ "delegation_depth": config.get("delegation_depth", 0),+ "team_id": config.get("team_id"),+ "max_concurrent_subagents": config.get("max_concurrent_subagents", 3),+ "max_delegation_depth": config.get("max_delegation_depth", 2),+ "ai_service": config.get("ai_service"),+ "database": config.get("database"),"root_execution_id": root_execution_id,"parent_node_id": parent_node_id,"delegation_depth": delegation_depth + 1,@@ -514,15 +528,15 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])f"[Delegated Agent] Context: {len(nodes)} nodes, {len(edges)} edges, " f"edge_targets={set(e.get('target') for e in edges)}")- async def finalize_team_task(*, result_data: Optional[Dict[str, Any]] = None, error: Optional[str] = None) -> None:+ async def finalize_team_task(*, result_data: Optional[Dict[str, Any]] = None, error: Optional[str] = None) -> str:if not team_service or not team_id:- return+ return "completed" if error is None else "failed"if error is not None:await team_service.fail_task(team_id, task_id, error)event_type, message_type, content = "failed", "task_failed", errorelse:await team_service.complete_task(team_id, task_id, result_data)- event_type, message_type, content = "completed", "task_complete", str((result_data or {}).get("result", ""))+ event_type, message_type, content = "submitted", "task_submitted", str((result_data or {}).get("result", ""))await team_service.send_message(team_id,from_agent=node_id,@@ -532,10 +546,9 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])event_id=f"{task_id}:{event_type}",extra_data={"task_id": task_id, "root_execution_id": root_execution_id, **(result_data or {})},)- if await team_service.is_team_done(team_id):- tasks = await team_service.database.get_team_tasks(team_id)- final_status = "failed" if any(item.get("status") == "failed" for item in tasks) else "completed"- await team_service.database.update_team_status(team_id, final_status)+ tasks = await team_service.database.get_team_tasks(team_id)+ persisted = next((item for item in tasks if item.get("id") == task_id), None)+ return str((persisted or {}).get("status") or event_type)# Define the background coroutineasync def run_child_agent():@@ -624,19 +637,22 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])},)- # Dispatch error event for trigger nodes — Wave 12 B8.- from nodes.agent._events import broadcast_agent_task_failed-- await broadcast_agent_task_failed(- task_id=task_id,- agent_name=agent_label,- agent_node_id=node_id,- parent_node_id=config.get("parent_node_id", ""),- workflow_id=workflow_id,- error=error_msg,- )-- await finalize_team_task(error=error_msg)+ persisted_status = await finalize_team_task(error=error_msg)+ # A retryable failure is queued again and must not wake a+ # taskTrigger as though it were terminal.+ if persisted_status not in {"pending", "queued", "blocked", "requeued"}:+ from nodes.agent._events import broadcast_agent_task_failed++ await broadcast_agent_task_failed(+ task_id=task_id,+ agent_name=agent_label,+ agent_node_id=node_id,+ parent_node_id=config.get("parent_node_id", ""),+ workflow_id=workflow_id,+ error=error_msg,+ event_id=f"{task_id}:{persisted_status}",+ lifecycle_data={"team_id": team_id, "root_execution_id": root_execution_id},+ )return result@@ -680,7 +696,10 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])},)- # Dispatch task_completed event for trigger nodes — Wave 12 B8.+ # Persist first, then dispatch taskTrigger. This ordering makes a+ # completion observable only after the authoritative task state is+ # available to the lead and human monitor.+ persisted_status = await finalize_team_task(result_data={"result": response_text})from nodes.agent._events import broadcast_agent_task_completedawait broadcast_agent_task_completed(@@ -690,10 +709,10 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])parent_node_id=config.get("parent_node_id", ""),workflow_id=workflow_id,result=response_text,+ event_id=f"{task_id}:{persisted_status}",+ lifecycle_data={"team_id": team_id, "root_execution_id": root_execution_id},)- await finalize_team_task(result_data={"result": response_text})-return resultexcept Exception as e:@@ -727,19 +746,20 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])},)- # Dispatch task_completed event for trigger nodes (error case) — Wave 12 B8.- from nodes.agent._events import broadcast_agent_task_failed-- await broadcast_agent_task_failed(- task_id=task_id,- agent_name=agent_label,- agent_node_id=node_id,- parent_node_id=config.get("parent_node_id", ""),- workflow_id=workflow_id,- error=str(e),- )+ persisted_status = await finalize_team_task(error=str(e))+ if persisted_status not in {"pending", "queued", "blocked", "requeued"}:+ from nodes.agent._events import broadcast_agent_task_failed- await finalize_team_task(error=str(e))+ await broadcast_agent_task_failed(+ task_id=task_id,+ agent_name=agent_label,+ agent_node_id=node_id,+ parent_node_id=config.get("parent_node_id", ""),+ workflow_id=workflow_id,+ error=str(e),+ event_id=f"{task_id}:{persisted_status}",+ lifecycle_data={"team_id": team_id, "root_execution_id": root_execution_id},+ )return {"success": False, "error": str(e)}diff --git a/server/services/plugin/base.py b/server/services/plugin/base.pyindex 3ac50fda..44ba89ae 100644--- a/server/services/plugin/base.py+++ b/server/services/plugin/base.py@@ -771,6 +771,9 @@ class BaseNode:"agent_iteration","tool_call_index","tool_call_id",+ "parent_node_id",+ "team_lead_node_id",+ "root_execution_id",):if key in context:extras[key] = context[key]diff --git a/server/services/plugin/edge_walker.py b/server/services/plugin/edge_walker.pyindex 42378c8e..d3b13075 100644--- a/server/services/plugin/edge_walker.py+++ b/server/services/plugin/edge_walker.py@@ -242,6 +242,28 @@ async def collect_agent_connections(log_prefix,)+ # A team lead must always be able to manage the durable work it delegates.+ # This is an intrinsic, non-removable team-lead capability. It is present+ # before the first teammate is connected so the lead and its human panel+ # have one stable control surface for the whole execution lifecycle.+ current_node = next(+ (node for node in (context.get("nodes") or []) if node.get("id") == node_id),+ None,+ )+ if (current_node or {}).get("type") in TEAM_LEAD_TYPES and not any(+ entry.get("node_type") == "taskManager" for entry in tool_data+ ):+ tool_data.append(+ {+ "node_id": f"builtin_task_manager_{node_id}",+ "node_type": "taskManager",+ "parameters": {},+ "label": "Task Manager",+ "builtin": True,+ }+ )+ logger.info("%s Auto-bound durable Task Manager for team lead %s", log_prefix, node_id)+logger.info(f"{log_prefix} Collected: {len(skill_data)} skills, {len(tool_data)} tools, "f"memory={'yes' if memory_data else 'no'}, "@@ -472,8 +494,8 @@ async def collect_teammate_connections(def format_task_context(task_data: Dict[str, Any]) -> str:"""Render a ``taskTrigger`` payload as a prompt-prepend block.- Tells the agent the delegated task is already done so it doesn't- re-delegate. Three branches: completed / error / other.+ Tells the lead to review the delegated result and choose the next+ lifecycle action. Three branches: completed / error / other."""status = task_data.get("status", "unknown")agent_name = task_data.get("agent_name", "Unknown Agent")@@ -487,8 +509,9 @@ def format_task_context(task_data: Dict[str, Any]) -> str:f"- Task ID: {task_id}\n""- Status: Completed Successfully\n"f"- Result: {result}\n\n"- "IMPORTANT: This task is COMPLETE. Do NOT delegate or call any agent tools.\n"- "Simply report this result to the user in a natural, conversational way."+ "REVIEW REQUIRED: Inspect this result against the original mission and "+ "acceptance criteria. Accept it if sufficient; otherwise revise, retry, "+ "or reassign it to a connected teammate before reporting completion.")if status == "error":@@ -499,8 +522,9 @@ def format_task_context(task_data: Dict[str, Any]) -> str:f"- Task ID: {task_id}\n""- Status: Error\n"f"- Error: {error}\n\n"- "IMPORTANT: This task has FAILED. Do NOT retry or delegate again.\n"- "Report this error to the user and suggest next steps if appropriate."+ "REVIEW REQUIRED: Inspect the failure and either retry, revise, reassign "+ "to a connected teammate, cancel/waive with a reason, or report an "+ "unrecoverable failure.")return f"Task update received:\n" f"- Agent: {agent_name}\n" f"- Task ID: {task_id}\n" f"- Status: {status}\n" f"- Data: {task_data}"diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.pyindex b9747040..2cb0f52e 100644--- a/server/services/temporal/agent_activities.py+++ b/server/services/temporal/agent_activities.py@@ -740,22 +740,38 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:# through the workflow verbatim so ``execute_llm_step`` can# rebuild the real StructuredTool inside the activity."tool_info": tool_info,+ # Team leads create and dispatch durable work through Task+ # Manager. Delegate descriptors stay in workflow state for+ # trusted assignee resolution, but are not callable directly+ # by the model.+ "llm_hidden": (+ node_type in {"orchestrator_agent", "ai_employee"}+ and tool.name.startswith("delegate_to_")+ ),})if any(tool["name"].startswith("delegate_to_") for tool in tools_payload):delegates = "\n".join(- f"- {tool['name']}: {(tool.get('tool_info') or {}).get('label', tool['node_type'])}"+ f"- {(tool.get('tool_info') or {}).get('node_id')}: "+ f"{(tool.get('tool_info') or {}).get('label', tool['node_type'])} "+ f"({tool['node_type']})"for tool in tools_payloadif tool["name"].startswith("delegate_to_"))system_message = (f"{system_message}\n\n"- "You lead a team of independent agents. Delegate a bounded mission "- "when a connected agent's capabilities fit the work. Delegations in "- "the same response may run in parallel. Do not delegate the same "- "mission twice. After results return, synthesize them into one answer.\n"- f"Available delegates:\n{delegates}"+ "You lead a team of independent agents. All delegation MUST use the "+ "task_manager tool with operation='assign_task'. Provide title, a bounded "+ "mission, relevant context, acceptance criteria, and exactly one connected "+ "assignee_node_id. Never call delegate_to_* directly. You may issue multiple "+ "assign_task tool calls in one response; they are durably queued and run in "+ "parallel subject to the team limit. Review submitted tasks with list_tasks "+ "and get_task, then accept, retry, modify, reassign, or cancel before finishing.\n"+ "For mutations, copy task.id into task_id and task.revision into expected_revision. "+ "After a single child submits work, accept_task may omit them only when that submitted "+ "task is unambiguous.\n"+ f"Connected teammates (assignee_node_id: label/type):\n{delegates}")# ---- Compaction threshold ------------------------------------------@@ -898,6 +914,7 @@ async def refresh_agent_tools(payload: Dict[str, Any]) -> Dict[str, Any]:ai_service = container.ai_service()operations: List[Dict[str, Any]] = payload.get("operations") or []+ team_lead_refresh = payload.get("agent_node_type") in {"orchestrator_agent", "ai_employee"}new_tools_payload: List[Dict[str, Any]] = []for op in operations:@@ -946,6 +963,7 @@ async def refresh_agent_tools(payload: Dict[str, Any]) -> Dict[str, Any]:"tool_node_id": tool_info["node_id"],"parameters": tool_info["parameters"],"tool_info": tool_info,+ "llm_hidden": bool(team_lead_refresh and is_agent_delegate),})@@ -1037,7 +1055,7 @@ async def queue_agent_delegation(payload: Dict[str, Any]) -> Dict[str, Any]:)if not message:raise RuntimeError("Failed to persist delegation queue event")- return {"team_id": team_id, "team_task_id": task_id, "status": "pending"}+ return {"team_id": team_id, "team_task_id": task_id, "status": "queued"}@activity.defn(name="agent.acquire_subagent_permit.v1")@@ -1091,8 +1109,8 @@ async def finish_agent_delegation(payload: Dict[str, Any]) -> Dict[str, Any]:raise RuntimeError("Delegated team task does not exist")succeeded = bool(payload.get("success"))- target_status = "completed" if succeeded else "failed"- if task.get("status") not in {"completed", "failed", "skipped"}:+ target_status = "submitted" if succeeded else "failed"+ if task.get("status") not in {"submitted", "accepted", "failed", "cancelled", "skipped"}:if succeeded:ok = await service.complete_task(team_id, task_id, payload.get("result") or {})else:@@ -1102,6 +1120,14 @@ async def finish_agent_delegation(payload: Dict[str, Any]) -> Dict[str, Any]:if not ok:raise RuntimeError(f"Failed to mark delegated task {target_status}")+ # Re-read the authoritative state. ``fail_task`` may queue another+ # attempt, so the requested failure is not necessarily terminal.+ tasks = await service.database.get_team_tasks(team_id)+ task = next((item for item in tasks if item.get("id") == task_id), task)+ persisted_status = str(task.get("status") or target_status)+ is_requeued = (not succeeded) and persisted_status in {"pending", "queued", "blocked"}+ target_status = "requeued" if is_requeued else persisted_status+error = str(payload.get("error") or "Delegated agent failed")content = f"Task {task_id} completed" if succeeded else f"Task {task_id} failed: {error}"message = await service.send_message(@@ -1116,6 +1142,47 @@ async def finish_agent_delegation(payload: Dict[str, Any]) -> Dict[str, Any]:)if not message:raise RuntimeError("Failed to persist delegation terminal event")++ # taskTrigger is an external automation consumer. Publish only after the+ # durable transition/message succeed, and never publish a terminal failure+ # for an attempt that the database actually requeued.+ if succeeded or not is_requeued:+ from nodes.agent._events import (+ broadcast_agent_task_completed,+ broadcast_agent_task_failed,+ )++ lifecycle_data = {+ "team_id": team_id,+ "root_execution_id": payload.get("root_execution_id"),+ "trace_id": payload.get("trace_id"),+ "parent_agent_workflow_id": payload.get("parent_agent_workflow_id"),+ }+ event_id = str(payload.get("terminal_event_id") or f"{task_id}:{target_status}")+ if succeeded:+ result = payload.get("result") or {}+ result_text = str(result.get("result", result) if isinstance(result, dict) else result)+ await broadcast_agent_task_completed(+ task_id=task_id,+ agent_name=str(payload.get("child_agent_name") or child_id),+ agent_node_id=child_id,+ parent_node_id=parent_id,+ workflow_id=payload.get("workflow_id"),+ result=result_text,+ event_id=event_id,+ lifecycle_data=lifecycle_data,+ )+ else:+ await broadcast_agent_task_failed(+ task_id=task_id,+ agent_name=str(payload.get("child_agent_name") or child_id),+ agent_node_id=child_id,+ parent_node_id=parent_id,+ workflow_id=payload.get("workflow_id"),+ error=error,+ event_id=event_id,+ lifecycle_data=lifecycle_data,+ )return {"team_id": team_id, "team_task_id": task_id, "status": target_status}@@ -1129,7 +1196,10 @@ async def finalize_agent_team(payload: Dict[str, Any]) -> Dict[str, Any]:raise ValueError("team_id is required")service = get_agent_team_service()tasks = await service.database.get_team_tasks(team_id)- if any(task.get("status") not in {"completed", "failed", "skipped"} for task in tasks):+ # Child completion is only a submission. The lead (or a human operator)+ # must explicitly accept every required task before the execution team can+ # be finalized.+ if any(task.get("status") not in {"accepted", "failed", "cancelled", "skipped"} for task in tasks):return {"team_id": team_id, "status": "active"}status = "failed" if any(task.get("status") == "failed" for task in tasks) else "completed"if not await service.database.update_team_status(team_id, status):diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.pyindex 0c03ab64..1c1153df 100644--- a/server/services/temporal/agent_workflow.py+++ b/server/services/temporal/agent_workflow.py@@ -46,6 +46,7 @@ References:from __future__ import annotations+import asynciofrom datetime import timedeltafrom typing import Any, Dict, List, Optional@@ -104,6 +105,7 @@ AGENT_ACTIVITY_RETRY: RetryPolicy = DEFAULT_ACTIVITY_RETRY# validation. Existing histories must retain their recorded activity/child# ids and last-wins tool index; new histories take the isolated path.TOOL_CALL_IDENTITY_V2_PATCH = "agent-tool-call-identity-v2"+TASK_MANAGER_DELEGATION_PATCH = "agent-task-manager-delegation-v1"DUPLICATE_TOOL_NAME_ERROR_TYPE = "DuplicateToolNameError"@@ -275,6 +277,7 @@ class AgentWorkflow:# runs record this marker and receive per-call command identity plus# deterministic duplicate-name validation.use_tool_call_identity_v2 = workflow.patched(TOOL_CALL_IDENTITY_V2_PATCH)+ use_task_manager_delegation = workflow.patched(TASK_MANAGER_DELEGATION_PATCH)# ---- Step 0: Resolve payload via the prep activity --------------# DB lookups + edge walking + tool schema build happen here, NOT@@ -419,7 +422,7 @@ class AgentWorkflow:"model": payload["model"],"api_key": payload["api_key"],"messages": messages,- "tool_data": [t["tool_info"] for t in tools],+ "tool_data": [t["tool_info"] for t in tools if not t.get("llm_hidden")],"system_message": system,"temperature": payload.get("temperature", 0.7),"max_tokens": payload.get("max_tokens", 4096),@@ -477,16 +480,26 @@ class AgentWorkflow:if kind == "final":final_content = step_result.get("content", "")- await self._persist_turn(payload, human_text=user_prompt, assistant_text=final_content)team_id = str(payload.get("team_id") or "")if team_id and payload.get("owns_execution_team"):- await workflow.execute_activity(+ finalization = await workflow.execute_activity("agent.finalize_team.v1",args=[{"team_id": team_id}],activity_id="finalize-agent-team",start_to_close_timeout=PERSIST_TURN_TIMEOUT,retry_policy=AGENT_ACTIVITY_RETRY,)+ if finalization.get("status") == "active":+ messages.append({+ "type": "human",+ "data": {"content": (+ "Team finalization is blocked: delegated work is still queued, running, "+ "failed, or awaiting review. Use Task Manager to inspect every task and "+ "accept, retry, reassign, or cancel it before producing the final report."+ )},+ })+ continue+ await self._persist_turn(payload, human_text=user_prompt, assistant_text=final_content)breakif kind != "tool_calls":@@ -598,6 +611,13 @@ class AgentWorkflow:"team_task_id": child_context["team_task_id"],"parent_agent_node_id": agent_node_id,"child_agent_node_id": candidate_tool["tool_node_id"],+ "child_agent_name": str(+ (candidate_tool.get("tool_info") or {}).get("label")+ or candidate_tool.get("node_type")+ or "agent"+ ),+ "workflow_id": payload.get("workflow_id"),+ "parent_agent_workflow_id": workflow.info().workflow_id,"task": task,"root_execution_id": root_execution_id,"delegation_depth": delegation_depth + 1,@@ -696,6 +716,286 @@ class AgentWorkflow:)raise+ async def _run_task_manager_delegation(+ request: Dict[str, Any], call_index: int, call: Dict[str, Any]+ ) -> Any:+ """Execute a trusted Task Manager scheduling envelope.++ ``assign_task`` has already authorized the teammate and+ persisted the TeamTask. This bridge resolves that teammate+ against the workflow's bound delegate surface and reuses the+ exact durable permit/claim/child/finalize lifecycle used by a+ direct ``delegate_to_*`` call.+ """+ nonlocal yielded_own_permit++ delegate_name = str(request.get("delegate_name") or "")+ assignee_id = str(request.get("assignee_node_id") or "")+ task_id = str(request.get("team_task_id") or "")+ mission = str(request.get("task") or "")+ request_context = request.get("context") or ""+ if not all((delegate_name, assignee_id, task_id, mission)):+ raise ValueError("Task Manager returned an incomplete delegation_request")++ delegate = tool_index.get(delegate_name)+ if (+ delegate is None+ or str(delegate.get("tool_node_id") or "") != assignee_id+ or delegate.get("node_type") not in AGENT_WORKFLOW_TYPES+ ):+ raise ValueError(+ "Task Manager assignee is not a connected Temporal delegate"+ )+ if delegation_depth >= max_delegation_depth:+ raise ValueError(+ f"Maximum delegation depth {max_delegation_depth} exceeded"+ )++ # A lead child cannot retain its own descendant permit while+ # waiting for another one; doing so can deadlock when every+ # root-wide slot is occupied by leads assigning descendants.+ if own_permit_id and not yielded_own_permit:+ await workflow.execute_activity(+ "agent.release_subagent_permit.v1",+ args=[{"root_execution_id": root_execution_id, "permit_id": own_permit_id}],+ activity_id=f"yield-own-permit-task-manager-{iteration + 1}",+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=AGENT_ACTIVITY_RETRY,+ )+ yielded_own_permit = True++ team_id = str(payload.get("team_id") or context.get("team_id") or "")+ if not team_id:+ raise ValueError("Task Manager delegation requires an execution team")+ trace_id = str(call.get("id", "") or "")+ lifecycle = {+ "team_id": team_id,+ "team_task_id": task_id,+ "parent_agent_node_id": agent_node_id,+ "child_agent_node_id": assignee_id,+ "child_agent_name": str(+ (delegate.get("tool_info") or {}).get("label")+ or delegate.get("node_type")+ or "agent"+ ),+ "workflow_id": payload.get("workflow_id"),+ "parent_agent_workflow_id": workflow.info().workflow_id,+ "task": mission,+ "root_execution_id": root_execution_id,+ "delegation_depth": delegation_depth + 1,+ "trace_id": trace_id,+ "assignment_event_id": f"{task_id}:assigned",+ }+ # queue_delegation is intentionally retained: it is+ # idempotent for the pre-created task and records the same+ # lifecycle event as direct delegation without duplicating it.+ await workflow.execute_activity(+ "agent.queue_delegation.v1",+ args=[{**lifecycle, "queued_event_id": f"{task_id}:queued"}],+ activity_id=f"queue-task-manager-{iteration + 1}-{call_index + 1}",+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=AGENT_ACTIVITY_RETRY,+ )+ await workflow.execute_activity(+ "agent.acquire_subagent_permit.v1",+ args=[{+ "root_execution_id": root_execution_id,+ "permit_id": task_id,+ "limit": max_concurrent_subagents,+ }],+ activity_id=f"acquire-task-manager-{iteration + 1}-{call_index + 1}",+ start_to_close_timeout=timedelta(hours=1),+ heartbeat_timeout=timedelta(seconds=10),+ retry_policy=AGENT_ACTIVITY_RETRY,+ )+ claimed = False+ finalization_started = False+ try:+ await workflow.execute_activity(+ "agent.begin_delegation.v1",+ args=[lifecycle],+ activity_id=f"begin-task-manager-{iteration + 1}-{call_index + 1}",+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=AGENT_ACTIVITY_RETRY,+ )+ claimed = True+ context_text = (+ request_context+ if isinstance(request_context, str)+ else _serialise_tool_result(request_context)+ )+ child_context = {+ "node_id": assignee_id,+ "node_type": delegate["node_type"],+ "node_data": {+ **(delegate.get("parameters") or {}),+ "system_message": mission,+ "prompt": context_text or mission,+ },+ "inputs": {},+ "workflow_id": payload.get("workflow_id"),+ "session_id": payload.get("session_id", "default"),+ "execution_id": execution_id,+ "root_execution_id": root_execution_id,+ "parent_node_id": agent_node_id,+ "delegation_depth": delegation_depth + 1,+ "team_id": team_id,+ "team_task_id": task_id,+ "trace_id": trace_id,+ "nodes": context.get("nodes") or [],+ "edges": context.get("edges") or [],+ "invocation": {"task": mission, "context": context_text},+ }+ child_id = _delegation_child_id_v2(+ workflow.info().workflow_id, assignee_id, iteration, call_index+ ) + f"-{task_id}"+ result = await workflow.execute_child_workflow(+ "AgentWorkflow",+ args=[child_context],+ id=child_id,+ execution_timeout=timedelta(hours=1),+ run_timeout=timedelta(hours=1),+ )+ succeeded = bool(result.get("success", True)) if isinstance(result, dict) else True+ finalization_started = True+ finalization = await workflow.execute_activity(+ "agent.finish_delegation.v1",+ args=[{+ **lifecycle,+ "success": succeeded,+ "result": result if isinstance(result, dict) else {"result": result},+ "error": result.get("error") if isinstance(result, dict) else None,+ "terminal_event_id": f"{task_id}:terminal",+ }],+ activity_id=f"finish-task-manager-{iteration + 1}-{call_index + 1}",+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=AGENT_ACTIVITY_RETRY,+ )+ return {+ "result": result,+ "status": finalization.get("status", "submitted"),+ }+ except Exception as exc:+ if claimed and not finalization_started:+ await workflow.execute_activity(+ "agent.finish_delegation.v1",+ args=[{+ **lifecycle,+ "success": False,+ "error": f"{type(exc).__name__}: {exc}",+ "terminal_event_id": f"{task_id}:terminal",+ }],+ activity_id=f"finish-task-manager-{iteration + 1}-{call_index + 1}",+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=AGENT_ACTIVITY_RETRY,+ )+ raise+ finally:+ await workflow.execute_activity(+ "agent.release_subagent_permit.v1",+ args=[{"root_execution_id": root_execution_id, "permit_id": task_id}],+ activity_id=f"release-task-manager-{iteration + 1}-{call_index + 1}",+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=AGENT_ACTIVITY_RETRY,+ )++ # Preflight every Task Manager assignment activity in this LLM+ # turn concurrently. Each activity performs authorization and+ # creates its durable queue row; only trusted scheduling envelopes+ # are allowed to reach the child-workflow bridge below.+ task_manager_preflight_indices: List[int] = []+ task_manager_preflight_handles: List[Any] = []+ if use_task_manager_delegation:+ for preflight_index, preflight_call in enumerate(calls):+ preflight_tool = tool_index.get(preflight_call.get("name", ""))+ preflight_args = preflight_call.get("args") or {}+ if (+ preflight_tool+ and preflight_tool.get("node_type") == "taskManager"+ and preflight_args.get("operation") == "assign_task"+ ):+ preflight_metadata = (+ _tool_call_metadata(+ agent_node_id=agent_node_id,+ iteration=iteration,+ call_index=preflight_index,+ call=preflight_call,+ )+ if use_tool_call_identity_v2+ else {}+ )+ preflight_payload = {+ "node_id": preflight_tool["tool_node_id"],+ "node_type": "taskManager",+ "node_data": {+ **(preflight_tool.get("parameters") or {}),+ **preflight_args,+ },+ "inputs": {},+ "workflow_id": payload.get("workflow_id"),+ "session_id": payload.get("session_id", "default"),+ "execution_id": execution_id,+ "root_execution_id": root_execution_id,+ "parent_node_id": agent_node_id,+ "team_lead_node_id": agent_node_id,+ "nodes": context.get("nodes") or [],+ "edges": context.get("edges") or [],+ **preflight_metadata,+ }+ task_manager_preflight_indices.append(preflight_index)+ task_manager_preflight_handles.append(+ workflow.start_activity(+ f"node.taskManager.v{preflight_tool['version']}",+ args=[preflight_payload],+ activity_id=(+ f"task-manager-preflight-{iteration + 1}-"+ f"{preflight_index + 1}"+ ),+ start_to_close_timeout=TOOL_STEP_TIMEOUT,+ heartbeat_timeout=TOOL_HEARTBEAT_TIMEOUT,+ )+ )++ task_manager_preflight_results: Dict[int, Any] = {}+ task_manager_delegation_tasks: Dict[int, asyncio.Task[Any]] = {}+ if task_manager_preflight_handles:+ preflight_results = await asyncio.gather(+ *task_manager_preflight_handles, return_exceptions=True+ )+ for preflight_index, preflight_result in zip(+ task_manager_preflight_indices, preflight_results+ ):+ task_manager_preflight_results[preflight_index] = preflight_result++ # Yield a child lead's slot exactly once before descendant+ # assignment coroutines contend for root-wide permits.+ if own_permit_id and not yielded_own_permit:+ await workflow.execute_activity(+ "agent.release_subagent_permit.v1",+ args=[{+ "root_execution_id": root_execution_id,+ "permit_id": own_permit_id,+ }],+ activity_id=f"yield-own-permit-task-manager-{iteration + 1}",+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=AGENT_ACTIVITY_RETRY,+ )+ yielded_own_permit = True++ for preflight_index in task_manager_preflight_indices:+ preflight_result = task_manager_preflight_results[preflight_index]+ if isinstance(preflight_result, BaseException):+ continue+ delegation_request = preflight_result.get("delegation_request")+ if isinstance(delegation_request, dict):+ task_manager_delegation_tasks[preflight_index] = asyncio.create_task(+ _run_task_manager_delegation(+ delegation_request,+ preflight_index,+ calls[preflight_index],+ )+ )+next_delegation_to_start = 0for delegation_index in delegation_call_indices[:max_concurrent_subagents]:await _start_delegation(delegation_index)@@ -828,6 +1128,11 @@ class AgentWorkflow:"workflow_id": payload.get("workflow_id"),"session_id": payload.get("session_id", "default"),"execution_id": execution_id,+ "parent_node_id": agent_node_id,+ "team_lead_node_id": agent_node_id,+ "team_id": payload.get("team_id") or context.get("team_id"),+ "root_execution_id": root_execution_id,+ "delegation_depth": delegation_depth,"nodes": child_nodes,"edges": child_edges,# Surface the auto-rebind toggle into the tool's ctx@@ -881,6 +1186,13 @@ class AgentWorkflow:"team_task_id": task_id,"parent_agent_node_id": agent_node_id,"child_agent_node_id": tool_info["tool_node_id"],+ "child_agent_name": str(+ (tool_info.get("tool_info") or {}).get("label")+ or tool_info.get("node_type")+ or "agent"+ ),+ "workflow_id": payload.get("workflow_id"),+ "parent_agent_workflow_id": workflow.info().workflow_id,"root_execution_id": root_execution_id,"trace_id": str(call.get("id", "") or ""),"success": bool(tool_result.get("success", True))@@ -911,13 +1223,38 @@ class AgentWorkflow:if use_tool_call_identity_v2else f"tool-{tool_info['tool_node_id']}-{iteration + 1}")- tool_result = await workflow.execute_activity(- tool_activity_name,- args=[tool_payload],- activity_id=tool_activity_id,- start_to_close_timeout=TOOL_STEP_TIMEOUT,- heartbeat_timeout=TOOL_HEARTBEAT_TIMEOUT,- )+ if call_index in task_manager_preflight_results:+ tool_result = task_manager_preflight_results[call_index]+ if isinstance(tool_result, BaseException):+ raise tool_result+ else:+ tool_result = await workflow.execute_activity(+ tool_activity_name,+ args=[tool_payload],+ activity_id=tool_activity_id,+ start_to_close_timeout=TOOL_STEP_TIMEOUT,+ heartbeat_timeout=TOOL_HEARTBEAT_TIMEOUT,+ )+ if (+ use_task_manager_delegation+ and tool_info["node_type"] == "taskManager"+ and isinstance(tool_result, dict)+ and isinstance(tool_result.get("delegation_request"), dict)+ ):+ if call_index in task_manager_delegation_tasks:+ # Await in original tool-call order; every+ # child was already started above, so slow+ # earlier siblings do not prevent later work.+ delegated = await task_manager_delegation_tasks[call_index]+ else:+ delegated = await _run_task_manager_delegation(+ tool_result["delegation_request"], call_index, call+ )+ tool_result = {+ **tool_result,+ "delegation_status": delegated["status"],+ "delegation_result": delegated["result"],+ }tool_content = _serialise_tool_result(tool_result)await self._emit_phase(agent_node_id,@@ -955,6 +1292,7 @@ class AgentWorkflow:)refresh_payload = {"operations": ops_from_tool,+ "agent_node_type": payload.get("node_type") or context.get("node_type"),**call_metadata,}refresh_result = await workflow.execute_activity(@@ -1028,6 +1366,13 @@ class AgentWorkflow:"team_task_id": task_id,"parent_agent_node_id": agent_node_id,"child_agent_node_id": tool_info["tool_node_id"],+ "child_agent_name": str(+ (tool_info.get("tool_info") or {}).get("label")+ or tool_info.get("node_type")+ or "agent"+ ),+ "workflow_id": payload.get("workflow_id"),+ "parent_agent_workflow_id": workflow.info().workflow_id,"root_execution_id": root_execution_id,"trace_id": str(call.get("id", "") or ""),"success": False,diff --git a/server/skills/assistant/agent-builder-skill/SKILL.md b/server/skills/assistant/agent-builder-skill/SKILL.mdindex 773685d4..9cf554b7 100644--- a/server/skills/assistant/agent-builder-skill/SKILL.md+++ b/server/skills/assistant/agent-builder-skill/SKILL.md@@ -113,8 +113,10 @@ Required field: `agent_type` (string).**Team-leads only** (`orchestrator_agent`, `ai_employee`). Pick`agent_type` from `inspect_canvas.available_agents`. Spawns aspecialized agent (`coding_agent`, `web_agent`, `task_agent`, etc.)-and wires it to your `input-teammates` handle. The new agent appears-as a `delegate_to_<name>` tool on your next turn.+and wires it to your `input-teammates` handle. The new agent appears in the+Task Manager connected-teammate list on your next turn. Assign work with+`task_manager(operation="assign_task", assignee_node_id=...)`; do not call a+`delegate_to_*` tool directly.**Idempotency**: if a teammate of this exact type is already wiredto you, `add_subagent` returns *"Teammate 'X' is already wireddiff --git a/server/skills/assistant/subagent-skill/SKILL.md b/server/skills/assistant/subagent-skill/SKILL.mdindex 01fde192..238c8345 100644--- a/server/skills/assistant/subagent-skill/SKILL.md+++ b/server/skills/assistant/subagent-skill/SKILL.md@@ -1,206 +1,80 @@----name: subagent-skill-description: Manage sub-agent delegation, handle task completion events, and coordinate multi-agent workflows.+name: subagent-orchestration+description: Coordinate connected subagents through durable Task Manager assignments, bounded parallel execution, review, retry, reassignment, and acceptance.+allowed-tools: task_managermetadata:author: opencompany- version: "2.0"+ version: "3.0"category: assistanticon: "🤖"color: "#8B5CF6"-----# Sub-Agent Management Skill--You are a parent agent that can delegate tasks to specialized sub-agents. This skill helps you understand, delegate to, and handle results from sub-agents effectively.--## CRITICAL: Always Check Sub-Agents First--**NEVER say "I don't have that tool" or "I can't do that" without first checking your connected sub-agents.**--When a user requests something you don't have a direct tool for:--1. **Check your connected sub-agents** - Look at what agents are available in your tools-2. **Delegate to the appropriate sub-agent** - They have their own tools and capabilities-3. **Only say you can't** if NO sub-agent can handle it--**Wrong approach:**-```-User: "Check my phone battery"-You: "I don't have access to Android tools, so I can't check your battery."-```+# Durable Subagent Orchestration-**Correct approach:**-```-User: "Check my phone battery"-You: [Check if Android Control Agent is connected]-You: [Delegate to Android Control Agent: "Get battery status"]-You: "Let me check that for you..." [waits for result]-```+Connected teammates extend the team lead's capabilities. Before declining a+request, inspect the connected teammate list and match the work to an agent's+label, type, and capability description.-## Available Sub-Agent Types+## Mandatory delegation path-You can delegate tasks to these specialized agents (when connected to your tools):+All teammate work must be created with `task_manager` using+`operation="assign_task"`. Never call `delegate_to_*` directly. The runtime+keeps those delegate identities private and uses them only after Task Manager+has authorized and persisted the assignment.-### Domain-Specific Agents+For every assignment provide:-| Agent | Icon | Specialty | Best For |-|-------|------|-----------|----------|-| **Android Control Agent** | 📱 | Android device automation | Battery checks, WiFi control, app launching, location tracking, sensor data |-| **Coding Agent** | 💻 | Code execution | Python/JavaScript execution, calculations, data processing |-| **Web Control Agent** | 🌐 | Browser automation | Web scraping, HTTP requests, form filling |-| **Social Media Agent** | 📱 | Social messaging | WhatsApp, Telegram, multi-platform messaging |-| **Travel Agent** | ✈️ | Travel planning | Itineraries, location lookups, travel recommendations |+- `title`: short human-readable task name;+- `mission`: one bounded outcome;+- `assignee_node_id`: an exact connected teammate ID;+- `context`: only relevant inputs and constraints;+- `acceptance_criteria`: observable conditions for approval;+- `depends_on`: task IDs when sequencing is required.-### Task & Workflow Agents+Independent `assign_task` calls may be emitted together. All tasks persist+before execution and enter a deterministic queue. At most three descendants,+including grandchildren, run concurrently; excess work remains `queued`.-| Agent | Icon | Specialty | Best For |-|-------|------|-----------|----------|-| **Task Management Agent** | 📋 | Task automation | Scheduling, reminders, to-do management |-| **Tool Agent** | 🔧 | Tool orchestration | Multi-tool workflows, complex task execution |-| **Productivity Agent** | ⏰ | Productivity | Time management, note-taking, workflow automation |+## Capability matching-### Business Agents+- Android agents: connected Android device services.+- Coding agents: implementation, code analysis, tests, and computation.+- Web agents: browsing, HTTP, extraction, and web interaction.+- Social agents: messaging and social-platform operations.+- Travel agents: location and itinerary work.+- Task agents: scheduling and task-domain operations.+- Custom `aiAgent` teammates: use their visible label and description.-| Agent | Icon | Specialty | Best For |-|-------|------|-----------|----------|-| **Payments Agent** | 💳 | Payment processing | Payment workflows, invoices, financial operations |-| **Consumer Agent** | 🛒 | Consumer support | Customer service, product recommendations, order management |+Only assign agents connected to this lead's `input-teammates` handle. Never+invent an agent ID, use an ordinary tool-edge agent, or target another team's+member.-## How to Check Sub-Agent Capabilities+## Review lifecycle-Before responding "I can't do that":+Task states are `blocked`, `queued`, `running`, `submitted`, `accepted`,+`failed`, and `cancelled`.-1. **List your available tools** - Sub-agents appear as delegation tools-2. **Match the request to an agent specialty** - Use the table above-3. **Delegate if a match exists** - The sub-agent has its own tools-4. **Only decline if truly impossible** - No matching agent connected+A worker completion produces `submitted`, not Done. When signalled:-### Capability Matching Examples+1. Inspect the result and acceptance criteria with `get_task` or `list_tasks`.+2. Copy `task.id` into `task_id` and `task.revision` into+ `expected_revision`.+3. Choose one outcome:+ - `accept_task` when the work satisfies the criteria;+ - `retry_task` for another attempt with the same assignee;+ - `reassign_task` to a different connected teammate;+ - `modify_task` only while blocked or queued;+ - `cancel_task` when work should stop or be waived.-| User Request | Check For | Delegate To |-|--------------|-----------|-------------|-| "Check my battery" | Android Control Agent | `delegate_to_android_agent` |-| "Send a WhatsApp" | Social Media Agent | `delegate_to_social_agent` |-| "Calculate this" | Coding Agent | `delegate_to_coding_agent` |-| "Find restaurants nearby" | Travel Agent | `delegate_to_travel_agent` |-| "Make an HTTP request" | Web Control Agent | `delegate_to_web_agent` |-| "Set a reminder" | Task Management Agent | `delegate_to_task_agent` |+When exactly one submitted task exists, `accept_task` may omit identifiers and+the runtime resolves it safely. With multiple submissions, always identify the+task explicitly. Revision conflicts mean the task changed: refresh it and make+a new decision instead of overwriting newer state.-## How Delegation Works+## Completion gate-### Fire-and-Forget Pattern-When you delegate a task:-1. The sub-agent receives the task and starts working immediately-2. You continue your conversation - delegation is non-blocking-3. The sub-agent works independently with its own tools and memory-4. When complete, a `task_completed` event is fired--### What You Receive Back-- **Task ID**: Unique identifier (e.g., `delegated_abc123_xyz`)-- **Status**: `completed` or `error`-- **Agent Name**: Which sub-agent completed the work-- **Result/Error**: The outcome or error message--## Delegation Best Practices--### When to Delegate-- User requests something outside your direct tools-- Task requires specialized capabilities (Android, WhatsApp, code execution, etc.)-- Task is time-consuming and can run in background-- Task matches a sub-agent's specialty area--### When NOT to Delegate-- Simple questions you can answer directly from knowledge-- Tasks that need immediate response AND you have the direct tool-- When the same task is already running (avoid duplicates)--### Delegation Format-When delegating, provide clear instructions:-```-Task: [Clear description of what needs to be done]-Context: [Any relevant background information]-Expected Output: [What format/information you need back]-```--## Handling Task Completion--### Successful Completion-When a delegated task completes successfully:--1. **DO NOT delegate again** - The task is finished-2. **Extract key information** from the result-3. **Report to the user** naturally and conversationally-4. **Suggest next steps** if appropriate--**Example Response:**-"The Android agent has checked your battery status. Your device is at 78% with approximately 5 hours of usage remaining. Would you like me to enable power-saving mode?"--### Failed Tasks-When a delegated task fails:--1. **DO NOT retry automatically** - Let the user decide-2. **Explain what went wrong** clearly-3. **Suggest alternatives** or troubleshooting steps--**Example Response:**-"I wasn't able to send the WhatsApp message because the contact wasn't found. Could you verify the phone number? Alternatively, I can try searching for the contact by name."--## Multi-Agent Coordination--### Sequential Delegation-For tasks requiring multiple steps:-1. Delegate first task to appropriate agent-2. Wait for completion via task trigger-3. Use result to delegate next task-4. Continue until workflow complete--### Parallel Delegation-For independent tasks:-- Delegate multiple tasks to different agents-- Each runs independently-- Collect results as they complete--## Critical Rules--1. **ALWAYS check sub-agents before saying "I can't"** - They extend your capabilities-2. **NEVER re-delegate after receiving a result** - Report it instead-3. **NEVER retry failed tasks automatically** - Ask user first-4. **ALWAYS acknowledge task completion** to the user-5. **ALWAYS match task to agent specialty** for best results--## Error Handling--| Error Type | Action |-|------------|--------|-| Agent not connected | Inform user which agent is needed and how to connect it |-| Task timeout | Report to user, suggest retry |-| Invalid parameters | Clarify requirements with user |-| Agent error | Report error details, suggest alternatives |--## Example Workflows--### Battery Check Workflow-```-User: "Check my phone battery"-You: [See Android Control Agent in tools]-You: Delegate to Android Control Agent with task "Get battery status"-Agent: Returns {status: 'completed', result: 'Battery at 78%, charging'}-You: "Your phone battery is at 78% and currently charging."-```--### Message Sending Workflow-```-User: "Send a WhatsApp to John saying I'll be late"-You: [See Social Media Agent in tools]-You: Delegate to Social Media Agent with message details-Agent: Returns {status: 'completed', result: 'Message sent to John'}-You: "Done! I've sent the message to John letting him know you'll be late."-```--### No Agent Available-```-User: "Check my phone battery"-You: [No Android Control Agent in tools]-You: "I don't have an Android Control Agent connected right now. To check your battery, please connect an Android Control Agent to my tools input, then ask again."-```+Call `finish_team` only when every required task is `accepted` or intentionally+`cancelled`. Synthesize accepted results in the final answer. Team Monitor is a+read-only view: it shows connected agents and lifecycle state, while all+mutations belong to Task Manager.diff --git a/server/skills/assistant/task-manager/SKILL.md b/server/skills/assistant/task-manager/SKILL.mdindex 0528736b..d6ec560e 100644--- a/server/skills/assistant/task-manager/SKILL.md+++ b/server/skills/assistant/task-manager/SKILL.md@@ -1,250 +1,82 @@---name: task-manager-description: Manage delegated tasks. List active tasks, check task status, get results from completed delegations, and mark tasks as done.+description: Coordinate durable team tasks by assigning connected teammates, reviewing results, and accepting, retrying, reassigning, or cancelling work.allowed-tools: task_managermetadata:author: opencompany- version: "1.0"+ version: "2.1"category: automation----# Task Manager-Manage and track delegated agent tasks.--## How It Works--This skill teaches the AI Assistant how to use the **Task Manager** tool. Connect the **Task Manager** node to the assistant's `input-tools` handle to enable delegated-task tracking.--## task_manager Tool--List, check, and manage delegated tasks.--### Schema Fields--| Field | Type | Required | Description |-|-------|------|----------|-------------|-| operation | string | Yes | `"list_tasks"`, `"get_task"`, or `"mark_done"` |-| task_id | string | For get_task, mark_done | Specific task ID to query |-| status_filter | string | No | Filter by status: `"running"`, `"completed"`, `"error"` |--### Operations--| Operation | Description | Required Fields |-|-----------|-------------|-----------------|-| `list_tasks` | List all tracked tasks | status_filter (optional) |-| `get_task` | Get details for specific task | task_id |-| `mark_done` | Remove task from tracking | task_id |--### Task States--| Status | Description |-|--------|-------------|-| `running` | Task is currently executing |-| `completed` | Task finished successfully |-| `error` | Task failed with error |-| `cancelled` | Task was cancelled |--### Examples--**List all tasks:**-```json-{- "operation": "list_tasks"-}-```--**List only running tasks:**-```json-{- "operation": "list_tasks",- "status_filter": "running"-}-```--**List completed tasks:**-```json-{- "operation": "list_tasks",- "status_filter": "completed"-}-```--**Get specific task details:**-```json-{- "operation": "get_task",- "task_id": "delegated_agent_abc12345"-}-```--**Mark task as done:**-```json-{- "operation": "mark_done",- "task_id": "delegated_agent_abc12345"-}-```--### Response Formats--**list_tasks response:**-```json-{- "success": true,- "operation": "list_tasks",- "tasks": [- {- "task_id": "delegated_coding_agent_abc12345",- "status": "completed",- "agent_name": "Coding Agent",- "result_summary": "Generated Python function for data processing...",- "active": false- },- {- "task_id": "delegated_web_agent_def67890",- "status": "running",- "active": true- }- ],- "count": 2,- "running": 1,- "completed": 1,- "errors": 0-}-```--**get_task response (completed):**-```json-{- "success": true,- "operation": "get_task",- "task_id": "delegated_coding_agent_abc12345",- "status": "completed",- "agent_name": "Coding Agent",- "result": "Here is the Python function you requested:\n\ndef process_data(items):\n return [x * 2 for x in items]"-}-```--**get_task response (running):**-```json-{- "success": true,- "operation": "get_task",- "task_id": "delegated_web_agent_def67890",- "status": "running",- "agent_name": "Web Agent"-}-```--**get_task response (error):**-```json-{- "success": true,- "operation": "get_task",- "task_id": "delegated_agent_xyz99999",- "status": "error",- "agent_name": "Social Agent",- "error": "Failed to connect to WhatsApp service"-}-```--**mark_done response:**-```json-{- "success": true,- "operation": "mark_done",- "task_id": "delegated_coding_agent_abc12345",- "removed": true,- "message": "Task delegated_coding_agent_abc12345 marked as done and removed from tracking"-}-```--### Error Response--```json-{- "success": false,- "error": "task_id is required for get_task operation"-}-```--```json-{- "success": false,- "error": "Task delegated_agent_notfound not found",- "task_id": "delegated_agent_notfound"-}-```--## Use Cases--| Use Case | Operation | Description |-|----------|-----------|-------------|-| Monitor progress | list_tasks | See all active delegations |-| Check result | get_task | Get completed task output |-| Verify completion | get_task | Confirm task finished |-| Clean up | mark_done | Remove processed tasks |-| Error handling | list_tasks + filter | Find failed tasks |--## Common Workflows--### Check on delegated work--1. Delegate task to sub-agent-2. Wait or continue with other work-3. Use `list_tasks` to see status-4. Use `get_task` to retrieve result--### Process all completed tasks--1. Use `list_tasks` with `status_filter: "completed"`-2. For each task, use `get_task` to get full result-3. Process the results-4. Use `mark_done` to clean up--### Handle errors--1. Use `list_tasks` with `status_filter: "error"`-2. Review failed tasks-3. Decide to retry or mark_done-4. Optionally re-delegate failed work--## Integration with Agent Delegation--When a parent agent delegates work:--1. `delegate_to_<agent>` tool returns `task_id`-2. Child agent runs in background-3. Parent can check status with `task_manager`-4. Results persist until `mark_done`--### Task ID Format--Task IDs follow the pattern:-```-delegated_<node_id>_<random_hex>-```--Example: `delegated_coding_agent_1_abc12345`--## Best Practices--1. **Track task IDs**: Store returned task_ids for later reference-2. **Poll appropriately**: Don't check too frequently-3. **Handle all states**: Account for running, completed, and error-4. **Clean up**: Use mark_done after processing results-5. **Check errors**: Review failed tasks before marking done--## Limitations--- Tasks not persistent across server restarts (in-memory)-- Results may be truncated if very large (4000 char limit in responses)-- Cannot cancel running tasks (only track status)--## Setup Requirements--1. Connect the **Task Manager** node to Zeenie's `input-tools` handle-2. Works with any agent that uses delegation-3. Task IDs are returned when delegating to sub-agents+Use `task_manager` as the team lead's durable control plane. It is scoped to+the current workflow execution and only permits assignment to agents connected+to this lead's `input-teammates` handle.++## Required workflow++1. Call `list_tasks` before assigning work so you do not duplicate an existing+ mission.+2. Split independent work into bounded tasks with explicit acceptance criteria.+3. Call `assign_task` once per mission. Use the connected teammate node ID or+ the exact delegate name reported by the lead's available teammate list.+ Do not call `delegate_to_*` directly; delegate descriptors are internal+ dispatch identities, not the lead's task-creation interface.+4. Independent tasks may be assigned together. The durable queue starts at most+ three descendants across the whole agent tree; excess tasks remain queued.+5. When a teammate submits work, inspect the complete result, error, attempt+ history, and acceptance criteria. Copy `task.id` to `task_id` and+ `task.revision` to `expected_revision` for the review mutation.+6. Choose exactly one review outcome:+ - `accept_task` when the result satisfies the task;+ - `modify_task` for blocked or queued work;+ - `retry_task` when the mission is still valid;+ - `reassign_task` to another connected teammate with revision context;+ - `cancel_task` when the work is no longer needed.+7. Call `finish_team` only after every required task is accepted or intentionally+ cancelled. Synthesize accepted results in the final report and disclose any+ unresolved failure.++## Operations++| Operation | Purpose | Important arguments |+|---|---|---|+| `assign_task` | Persist and queue a bounded mission | `title`, `mission`, `assignee_node_id` or `delegate_name`, optional `context`, `acceptance_criteria`, `depends_on` |+| `list_tasks` | Inspect the execution task list | optional `status_filter` |+| `get_task` | Review one task and all attempts | `task_id` |+| `modify_task` | Change queued/blocked work | `task_id`, `expected_revision`, changed task fields |+| `cancel_task` | Cancel queued or running work | `task_id`, `expected_revision`, `reason` |+| `retry_task` | Queue a new attempt | `task_id`, `expected_revision`, optional revision context |+| `reassign_task` | Queue a new attempt for another teammate | `task_id`, `expected_revision`, new connected assignee |+| `accept_task` | Record lead approval of submitted work | `task_id`, `expected_revision` |+| `finish_team` | Finalize after the review barrier clears | optional summary |++If exactly one task is `submitted` in the current execution, `accept_task` may+omit `task_id` and `expected_revision`; the runtime safely resolves that single+task and its current revision. If zero or multiple submissions await review,+you must call `list_tasks` or `get_task` and pass both fields. Never guess.++`mark_done` is a deprecated compatibility alias for `accept_task`. Never use it+to discard history.++## State model++- `blocked`: waiting for dependencies.+- `queued`: durable and waiting for a concurrency permit.+- `running`: owned by a teammate.+- `submitted`: teammate finished; lead review is required.+- `accepted`: lead approved the work.+- `failed`: no automatic attempt remains.+- `cancelled`: intentionally stopped; may be revised and reassigned.++Do not treat `submitted` as finished team work. Do not repeatedly poll a running+task; completion signals wake the lead. Do not invent teammate IDs, team IDs, or+execution IDs—the runtime supplies authority and rejects cross-team access.++## Team Monitor interpretation++Team Monitor is read-only. It shows graph-connected teammates immediately and+merges their persisted `working`/`idle` status during execution. Its Done count+means `accepted`, not merely `submitted`. Use Task Manager—not Team Monitor—to+accept, retry, modify, reassign, cancel, or finish work.diff --git a/server/tests/nodes/test_agent_builder.py b/server/tests/nodes/test_agent_builder.pyindex b3801c08..196673c7 100644--- a/server/tests/nodes/test_agent_builder.py+++ b/server/tests/nodes/test_agent_builder.py@@ -745,14 +745,14 @@ class TestCatalogueVisibility:)_ = original_get_config # silence unused-var lint- def test_task_manager_enabled_in_allowlist_json(self):- """The Task Manager is visible to both the palette and Agent Builder."""+ def test_task_manager_is_intrinsic_not_palette_addable(self):+ """Task Manager is bound to team leads, not offered as a deletable node."""from services.node_allowlist import get_node_allowlist_serviceconfig = get_node_allowlist_service().get_config()- assert "taskManager" in config["enabled_nodes"]+ assert "taskManager" not in config["enabled_nodes"]assert "taskManager" not in config["disabled_nodes"]- assert "taskManager" in ab._allowed_tool_types()+ assert "taskManager" not in ab._allowed_tool_types()def test_android_nodes_enabled_in_allowlist_json(self):"""Android services bind directly to agents as ordinary tools."""diff --git a/server/tests/nodes/test_ai_agents.py b/server/tests/nodes/test_ai_agents.pyindex 9514e888..07e31d98 100644--- a/server/tests/nodes/test_ai_agents.py+++ b/server/tests/nodes/test_ai_agents.py@@ -377,11 +377,12 @@ class TestChatAgent:_, kwargs = harness.ai_service.execute_chat_agent.call_argstool_data = kwargs["tool_data"]- assert tool_data is not None and len(tool_data) == 1- assert tool_data[0]["node_type"] == "coding_agent"- assert tool_data[0]["label"] == "CoderBot"+ assert tool_data is not None and len(tool_data) == 2+ teammate_tool = next(tool for tool in tool_data if tool["node_type"] == "coding_agent")+ assert teammate_tool["label"] == "CoderBot"+ assert any(tool["node_type"] == "taskManager" and tool.get("builtin") for tool in tool_data)# Teammate params come along so delegation knows provider/model- assert tool_data[0]["parameters"]["model"] == "gpt"+ assert teammate_tool["parameters"]["model"] == "gpt"async def test_chat_agent_task_error_strips_tools(self, harness):"""Same tool-strip behaviour as aiAgent on task failure."""diff --git a/server/tests/nodes/test_task_manager_delegation_bridge.py b/server/tests/nodes/test_task_manager_delegation_bridge.pynew file mode 100644index 00000000..96f8d0fc--- /dev/null+++ b/server/tests/nodes/test_task_manager_delegation_bridge.py@@ -0,0 +1,86 @@+from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest++from nodes.tool.task_manager import _execute_task_manager+++def _config():+ return {+ "workflow_id": "wf-1", "execution_id": "exec-1", "parent_node_id": "lead-1",+ "ai_service": object(), "database": object(),+ "nodes": [+ {"id": "lead-1", "type": "orchestrator_agent", "data": {}},+ {"id": "child-1", "type": "aiAgent", "data": {"label": "Researcher"}},+ ],+ "edges": [{"source": "child-1", "target": "lead-1", "targetHandle": "input-teammates"}],+ }+++async def test_assign_starts_legacy_child_with_precreated_task_id():+ service = SimpleNamespace(assign_durable_task=AsyncMock(return_value={+ "id": "task-1", "team_id": "team-1", "status": "queued",+ }))+ execute_child = AsyncMock(return_value={"success": True, "status": "delegated", "task_id": "task-1"})++ with patch("services.agent_team.get_agent_team_service", return_value=service), patch(+ "services.handlers.tools._execute_delegated_agent", execute_child+ ):+ result = await _execute_task_manager({+ "operation": "assign_task", "title": "Research", "mission": "Find evidence",+ "assignee_node_id": "child-1", "context": {"topic": "queues"},+ }, _config())++ service.assign_durable_task.assert_awaited_once()+ execute_child.assert_awaited_once()+ assert execute_child.await_args.kwargs["precreated_task_id"] == "task-1"+ assert execute_child.await_args.args[0]["task"] == "Find evidence"+ assert result["delegation"]["task_id"] == "task-1"+++async def test_assign_without_legacy_services_returns_temporal_envelope_only():+ service = SimpleNamespace(assign_durable_task=AsyncMock(return_value={+ "id": "task-2", "team_id": "team-1", "status": "queued",+ }))+ config = _config()+ config.pop("ai_service")+ config.pop("database")++ with patch("services.agent_team.get_agent_team_service", return_value=service):+ result = await _execute_task_manager({+ "operation": "assign_task", "title": "Research", "mission": "Find evidence",+ "assignee_node_id": "child-1",+ }, config)++ assert result["delegation"] is None+ assert result["delegation_request"]["team_task_id"] == "task-2"+++async def test_accept_infers_the_only_submitted_task_and_revision():+ submitted = {"id": "task-submitted", "revision": 4, "status": "submitted"}+ service = SimpleNamespace(+ list_durable_tasks=AsyncMock(return_value=[submitted]),+ mutate_durable_task=AsyncMock(return_value={**submitted, "revision": 5, "status": "accepted"}),+ )+ with patch("services.agent_team.get_agent_team_service", return_value=service):+ result = await _execute_task_manager({"operation": "accept_task"}, _config())++ assert result["task"]["status"] == "accepted"+ service.mutate_durable_task.assert_awaited_once_with(+ workflow_id="wf-1", team_lead_node_id="lead-1", execution_id="exec-1",+ task_id="task-submitted", revision=4, operation="accept",+ )+++async def test_accept_never_guesses_when_multiple_tasks_are_submitted():+ service = SimpleNamespace(list_durable_tasks=AsyncMock(return_value=[+ {"id": "one", "revision": 1}, {"id": "two", "revision": 2},+ ]))+ with patch("services.agent_team.get_agent_team_service", return_value=service):+ with pytest.raises(ValueError, match="call list_tasks or get_task first"):+ await _execute_task_manager({"operation": "accept_task"}, _config())diff --git a/server/tests/services/test_durable_team_tasks.py b/server/tests/services/test_durable_team_tasks.pynew file mode 100644index 00000000..034ad939--- /dev/null+++ b/server/tests/services/test_durable_team_tasks.py@@ -0,0 +1,80 @@+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest++from services.agent_team import AgentTeamService+++def _database(*, member_role="teammate"):+ return SimpleNamespace(+ find_team=AsyncMock(return_value={+ "id": "team-1", "workflow_id": "wf-1", "execution_id": "exec-1",+ "root_execution_id": "root-1", "team_lead_node_id": "lead-1",+ }),+ get_team_stats=AsyncMock(return_value={"members": [+ {"agent_node_id": "agent-1", "role": member_role, "status": "idle"},+ ]}),+ get_durable_team_task=AsyncMock(return_value=None),+ create_durable_team_task=AsyncMock(side_effect=lambda **values: {**values, "revision": 0}),+ update_team_status=AsyncMock(return_value=True),+ transition_team_task=AsyncMock(),+ get_team_tasks=AsyncMock(return_value=[]),+ )+++async def test_assignment_is_scoped_to_persisted_teammates():+ database = _database(member_role="team_lead")+ service = AgentTeamService(database)++ with pytest.raises(ValueError, match="not a teammate"):+ await service.assign_durable_task(+ workflow_id="wf-1", team_lead_node_id="lead-1", execution_id="exec-1",+ assignee_node_id="agent-1", title="Research", mission="Find evidence",+ )+ database.create_durable_team_task.assert_not_awaited()+++async def test_assignment_injects_execution_authority_server_side():+ database = _database()+ service = AgentTeamService(database)++ task = await service.assign_durable_task(+ workflow_id="wf-1", team_lead_node_id="lead-1", execution_id="exec-1",+ assignee_node_id="agent-1", title="Research", mission="Find evidence",+ )++ assert task["team_id"] == "team-1"+ assert task["root_execution_id"] == "root-1"+ assert task["parent_agent_id"] == "lead-1"+++async def test_stale_revision_is_rejected():+ database = _database()+ database.get_durable_team_task.return_value = {+ "id": "task-1", "status": "queued", "revision": 2,+ "current_attempt": 0, "retry_count": 0,+ }+ database.transition_team_task.return_value = None+ service = AgentTeamService(database)++ with pytest.raises(ValueError, match="refresh and retry"):+ await service.mutate_durable_task(+ workflow_id="wf-1", team_lead_node_id="lead-1", execution_id="exec-1",+ task_id="task-1", revision=1, operation="cancel", reason="Changed plan",+ )+++async def test_finish_requires_every_task_to_be_reviewed():+ database = _database()+ database.get_team_tasks.return_value = [{"id": "task-1", "status": "submitted"}]+ service = AgentTeamService(database)++ with pytest.raises(ValueError, match="unresolved"):+ await service.finish_durable_team(+ workflow_id="wf-1", team_lead_node_id="lead-1", execution_id="exec-1"+ )diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.pyindex 2e8e075a..ffc489b8 100644--- a/server/tests/temporal/test_agent_workflow.py+++ b/server/tests/temporal/test_agent_workflow.py@@ -97,6 +97,64 @@ class TestDurableTeamDelegationContract:assert "assignment_event_id" in sourceassert "terminal_event_id" in source+ def test_task_manager_assignment_uses_existing_delegation_lifecycle(self):+ """A persisted assign_task envelope must start real child work."""+ import inspect++ from services.temporal.agent_workflow import AgentWorkflow++ source = inspect.getsource(AgentWorkflow.run)+ assert 'tool_info["node_type"] == "taskManager"' in source+ assert 'tool_result.get("delegation_request")' in source+ assert "_run_task_manager_delegation" in source+ assert 'task_id = str(request.get("team_task_id")' in source+ assert 'delegate_name = str(request.get("delegate_name")' in source+ assert 'str(delegate.get("tool_node_id") or "") != assignee_id' in source++ def test_task_manager_bridge_is_bounded_and_retry_safe(self):+ import inspect++ from services.temporal.agent_workflow import AgentWorkflow++ source = inspect.getsource(AgentWorkflow.run)+ queue = source.index('activity_id=f"queue-task-manager-')+ permit = source.index('activity_id=f"acquire-task-manager-')+ claim = source.index('activity_id=f"begin-task-manager-')+ child = source.index("workflow.execute_child_workflow", claim)+ finish = source.index('activity_id=f"finish-task-manager-', child)+ release = source.index('activity_id=f"release-task-manager-', finish)+ assert queue < permit < claim < child < finish < release+ assert '"permit_id": task_id' in source+ assert '"team_task_id": task_id' in source+ assert "TASK_MANAGER_DELEGATION_PATCH" in source++ def test_task_manager_child_lead_yields_own_permit(self):+ import inspect++ from services.temporal.agent_workflow import AgentWorkflow++ source = inspect.getsource(AgentWorkflow.run)+ assert "yield-own-permit-task-manager" in source+ assert "if own_permit_id and not yielded_own_permit" in source++ def test_same_turn_task_manager_assignments_preflight_and_run_concurrently(self):+ import inspect++ from services.temporal.agent_workflow import AgentWorkflow++ source = inspect.getsource(AgentWorkflow.run)+ start_activity = source.index("workflow.start_activity(")+ gather = source.index("await asyncio.gather(")+ create_children = source.index("asyncio.create_task(", gather)+ ordered_loop = source.index("for call_index, call in enumerate(calls):", create_children)+ ordered_await = source.index(+ "await task_manager_delegation_tasks[call_index]", ordered_loop+ )+ assert start_activity < gather < create_children < ordered_loop < ordered_await+ assert "task_manager_preflight_results[call_index]" in source+ assert "task-manager-preflight-" in source+ assert "return_exceptions=True" in source+class TestAgentActivities:"""The three agent activities must register under stable names sodiff --git a/server/tests/test_node_spec.py b/server/tests/test_node_spec.pyindex f0eb31b3..3e0fd94d 100644--- a/server/tests/test_node_spec.py+++ b/server/tests/test_node_spec.py@@ -903,6 +903,7 @@ class TestNodeSpecContractInvariants:# middle section (in addition to isToolPanel)."isTodoEditor","isMonitorPanel",+ "isTaskManagerPanel","showLocationPanel","isAndroidToolkit","isChatTrigger",diff --git a/server/tests/test_task_trigger_canary_producer.py b/server/tests/test_task_trigger_canary_producer.pyindex e6246412..68531c70 100644--- a/server/tests/test_task_trigger_canary_producer.py+++ b/server/tests/test_task_trigger_canary_producer.py@@ -129,3 +129,58 @@ class TestTaskTriggerProducerCanaryEmit:assert envelope.subject == "task-2"assert envelope.data["status"] == "error"assert envelope.data["error"] == "timeout"++ @pytest.mark.asyncio+ async def test_lifecycle_identity_and_trace_fields_are_preserved(self, monkeypatch):+ """Activity retries reuse one event id and retain delegation tracing."""+ from nodes.agent import _events+ from services.events import dispatch as dispatch_mod++ emitted: List[Any] = []++ async def fake_emit(event, **kwargs):+ emitted.append(event)+ return event++ monkeypatch.setattr(dispatch_mod, "emit", fake_emit)+ await _events.broadcast_agent_task_completed(+ task_id="task-3",+ agent_name="coding agent",+ agent_node_id="agent-3",+ parent_node_id="lead-1",+ workflow_id="canvas-1",+ result="review me",+ event_id="task-3:submitted",+ lifecycle_data={+ "team_id": "team-1",+ "root_execution_id": "root-1",+ "trace_id": "call-1",+ },+ )++ envelope = emitted[0]+ assert envelope.id == "task-3:submitted"+ assert envelope.data["team_id"] == "team-1"+ assert envelope.data["root_execution_id"] == "root-1"+ assert envelope.data["trace_id"] == "call-1"++ def test_temporal_completion_emits_after_authoritative_state_read(self):+ """Temporal parity: retries/requeues are decided before taskTrigger."""+ from services.temporal import agent_activities++ source = inspect.getsource(agent_activities.finish_agent_delegation)+ reread = source.index("# Re-read the authoritative state")+ broadcast = source.index("broadcast_agent_task_completed")+ assert reread < broadcast+ assert 'target_status = "requeued" if is_requeued' in source+ assert "if succeeded or not is_requeued" in source++ def test_task_trigger_context_requires_lead_review(self):+ from services.plugin.edge_walker import format_task_context++ completed = format_task_context({"status": "completed", "result": "ok"})+ failed = format_task_context({"status": "error", "error": "boom"})+ assert "REVIEW REQUIRED" in completed+ assert "acceptance criteria" in completed+ assert "retry" in failed+ assert "connected teammate" in failed