Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat: make team task delegation durable and asynchronous
trohitg6e92943fff1c
diff --git a/CLAUDE.md b/CLAUDE.mdindex bbcb85e1..f00765cf 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1452,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 | `TaskManagerParams` | `_execute_task_manager()` | Intrinsic durable team assignment, review, retry/reassignment, cancellation, and acceptance |+| taskManager | `TaskManagerParams` | `_execute_task_manager()` | Intrinsic durable team assignment; returns queued through detached Temporal runner, preserves cross-run history, review, retry/reassignment, cancellation, acceptance, timestamps, elapsed time, and token usage || 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 2acbbfaa..d2075ecd 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`. 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.+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. `task_manager(assign_task)` persists and returns `queued`; Temporal hands work to a detached `DelegatedTaskWorkflow`, while legacy execution reuses the same durable task record. Completion emits `taskTrigger` with owning execution context for a separate lead review. 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/client/src/components/parameterPanel/TaskManagerPanel.tsx b/client/src/components/parameterPanel/TaskManagerPanel.tsxindex 897bf42d..fa098877 100644--- a/client/src/components/parameterPanel/TaskManagerPanel.tsx+++ b/client/src/components/parameterPanel/TaskManagerPanel.tsx@@ -98,18 +98,42 @@ const jsonText = (value: unknown): string => {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));+const timestampMs = (value?: string): number | null => {+ if (!value) return null;+ // SQLite commonly returns UTC timestamps without a trailing zone. Browsers+ // otherwise interpret those as local time and skew elapsed durations.+ const normalized = /(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value.replace(' ', 'T')}Z`;+ const parsed = new Date(normalized).getTime();+ return Number.isFinite(parsed) ? parsed : null;+};++const formatTimestamp = (value?: string): string => {+ const parsed = timestampMs(value);+ return parsed == null ? '—' : new Intl.DateTimeFormat(undefined, {+ dateStyle: 'medium', timeStyle: 'medium',+ }).format(new Date(parsed));+};++const elapsed = (task: TeamTaskView, nowMs: number): string => {+ const startMs = timestampMs(task.started_at);+ if (startMs == null) return '—';+ const completedMs = timestampMs(task.completed_at);+ const end = completedMs ?? nowMs;+ const seconds = Math.max(0, Math.floor((end - startMs) / 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));+const taskUsage = (task: TeamTaskView) => {+ const nested = task.result && typeof task.result === 'object'+ ? (task.result as { usage?: TeamTaskView['usage'] }).usage : undefined;+ const usage = task.usage || nested || {};+ const input = Number(usage.input_tokens || 0);+ const output = Number(usage.output_tokens || 0);+ const total = Number(usage.total_tokens ?? (input + output));+ return { input, output, total, cost: Number(usage.cost || 0) };+};interface Props { nodeId: string; workflowId?: string; nodes: Node[]; edges: Edge[] }@@ -126,6 +150,7 @@ const TaskManagerPanel: React.FC<Props> = ({ nodeId, workflowId, nodes, edges })const [assignee, setAssignee] = useState('');const [busy, setBusy] = useState(false);const [page, setPage] = useState(0);+ const [nowMs, setNowMs] = useState(() => Date.now());const pageSize = 25;const connectedLead = useMemo(() => {@@ -152,10 +177,14 @@ const TaskManagerPanel: React.FC<Props> = ({ nodeId, workflowId, nodes, edges })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),- ]);+ const response = await sendRequest<{ status?: TeamStatusView }>('get_team_status', scope);+ const resolvedExecutionId = response?.status?.execution_id;+ const taskResponse = await sendRequest<{ tasks?: TeamTaskView[] }>('get_team_tasks', {+ ...scope,+ ...(executionId === 'active'+ ? { include_history: true }+ : resolvedExecutionId ? { execution_id: resolvedExecutionId } : {}),+ });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');@@ -197,6 +226,10 @@ const TaskManagerPanel: React.FC<Props> = ({ nodeId, workflowId, nodes, edges })const visible = tasks.slice(page * pageSize, (page + 1) * pageSize);useEffect(() => setPage(0), [filter, search, executionId]);+ useEffect(() => {+ const timer = window.setInterval(() => setNowMs(Date.now()), 1_000);+ return () => window.clearInterval(timer);+ }, []);const runAction = async () => {if (!pending || !workflowId || !connectedLead) return;@@ -242,7 +275,7 @@ const TaskManagerPanel: React.FC<Props> = ({ nodeId, workflowId, nodes, edges })<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>}+ {(status?.archived_executions?.length || 0) > 0 && <Select value={executionId} onValueChange={setExecutionId}><SelectTrigger className="w-48" aria-label="Execution"><SelectValue /></SelectTrigger><SelectContent><SelectItem value="active">Latest 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>@@ -255,16 +288,18 @@ const TaskManagerPanel: React.FC<Props> = ({ nodeId, workflowId, nodes, edges })<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>}+ <table className="w-full min-w-[1200px] 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','Created','Started','Completed','Elapsed','Attempt','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) => { const usage = taskUsage(task); return <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="whitespace-nowrap px-3 py-3 text-xs">{formatTimestamp(task.created_at)}</td><td className="whitespace-nowrap px-3 py-3 text-xs">{formatTimestamp(task.started_at)}</td><td className="whitespace-nowrap px-3 py-3 text-xs">{formatTimestamp(task.completed_at)}</td><td className="px-3 py-3 tabular-nums">{elapsed(task, nowMs)}</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"><span className="block font-medium">{usage.total.toLocaleString()}</span><span className="whitespace-nowrap text-[11px] text-fg-muted">{usage.input.toLocaleString()} in · {usage.output.toLocaleString()} out</span></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={10} 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>+ <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, nowMs)}</span></div>+ <section className="grid gap-2 rounded border border-border-default p-3 text-xs text-fg-muted sm:grid-cols-3"><span>Created<br/><strong className="font-medium text-fg-default">{formatTimestamp(selected.created_at)}</strong></span><span>Started<br/><strong className="font-medium text-fg-default">{formatTimestamp(selected.started_at)}</strong></span><span>Completed<br/><strong className="font-medium text-fg-default">{formatTimestamp(selected.completed_at)}</strong></span></section>+ <section><h3 className="mb-2 font-medium">Token usage</h3><div className="grid grid-cols-3 gap-2 rounded border border-border-default p-3 text-center"><div><div className="text-xs text-fg-muted">Input</div><div className="font-semibold tabular-nums">{taskUsage(selected).input.toLocaleString()}</div></div><div><div className="text-xs text-fg-muted">Output</div><div className="font-semibold tabular-nums">{taskUsage(selected).output.toLocaleString()}</div></div><div><div className="text-xs text-fg-muted">Total</div><div className="font-semibold tabular-nums">{taskUsage(selected).total.toLocaleString()}</div></div></div></section><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>diff --git a/client/src/components/parameterPanel/TeamMonitorPanel.tsx b/client/src/components/parameterPanel/TeamMonitorPanel.tsxindex d10c3fdf..6ab1684b 100644--- a/client/src/components/parameterPanel/TeamMonitorPanel.tsx+++ b/client/src/components/parameterPanel/TeamMonitorPanel.tsx@@ -5,6 +5,7 @@ import type { Edge, Node } from 'reactflow';import { useWebSocket } from '@/contexts/WebSocketContext';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';import { cn } from '@/lib/utils';const LEAD_TYPES = new Set(['orchestrator_agent', 'ai_employee']);@@ -23,6 +24,7 @@ const TeamMonitorPanel: React.FC<Props> = ({ nodeId, workflowId, nodes, edges })const [status, setStatus] = useState<Record<string, any> | null>(null);const [tasks, setTasks] = useState<Task[]>([]);const [loading, setLoading] = useState(false);+ const [executionId, setExecutionId] = useState('active');const lead = useMemo(() => {const incoming = edges.filter((edge) => edge.target === nodeId);@@ -54,15 +56,21 @@ const TeamMonitorPanel: React.FC<Props> = ({ nodeId, workflowId, nodes, edges })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),- ]);+ const scope = {+ workflow_id: workflowId,+ team_lead_node_id: lead.id,+ ...(executionId !== 'active' ? { execution_id: executionId } : {}),+ };+ const teamResponse = await sendRequest<{ status?: Record<string, any> }>('get_team_status', scope);+ const resolvedExecutionId = teamResponse?.status?.execution_id;+ const taskResponse = await sendRequest<{ tasks?: Task[] }>('get_team_tasks', {+ ...scope,+ ...(resolvedExecutionId ? { execution_id: resolvedExecutionId } : {}),+ });setStatus(teamResponse.status || null);setTasks(taskResponse.tasks || []);} finally { if (!quiet) setLoading(false); }- }, [lead, sendRequest, workflowId]);+ }, [executionId, lead, sendRequest, workflowId]);useEffect(() => { void refresh(); }, [refresh]);useEffect(() => {@@ -81,7 +89,10 @@ const TeamMonitorPanel: React.FC<Props> = ({ nodeId, workflowId, nodes, edges })<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 className="flex items-center gap-2">+ {(status?.archived_executions?.length || 0) > 0 && <Select value={executionId} onValueChange={setExecutionId}><SelectTrigger className="w-48" aria-label="Execution history"><SelectValue /></SelectTrigger><SelectContent><SelectItem value="active">Latest execution</SelectItem>{status!.archived_executions.map((run: any) => <SelectItem key={run.execution_id || run.team_id} value={run.execution_id}>{run.label || String(run.execution_id).slice(0, 12)}</SelectItem>)}</SelectContent></Select>}+ <Button variant="outline" size="sm" onClick={() => void refresh()} disabled={loading}><RefreshCw className={cn('h-4 w-4', loading && 'animate-spin')} /> Refresh</Button>+ </div></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>)}diff --git a/client/src/components/parameterPanel/__tests__/TaskManagerPanel.test.tsx b/client/src/components/parameterPanel/__tests__/TaskManagerPanel.test.tsxindex 28f4185d..44cb59a9 100644--- a/client/src/components/parameterPanel/__tests__/TaskManagerPanel.test.tsx+++ b/client/src/components/parameterPanel/__tests__/TaskManagerPanel.test.tsx@@ -30,7 +30,9 @@ const edges: any[] = [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 },+ result: { summary: 'done' }, usage: { input_tokens: 70, output_tokens: 50, total_tokens: 120 },+ created_at: '2026-07-18 10:00:00', started_at: '2026-07-18 10:00:05',+ completed_at: '2026-07-18 10:01:10',};describe('TaskManagerPanel', () => {@@ -48,8 +50,13 @@ describe('TaskManagerPanel', () => {expect(await screen.findByText('Implement feature')).toBeInTheDocument();expect(screen.getByText('2 / 3')).toBeInTheDocument();expect(screen.getByText('Coder')).toBeInTheDocument();+ expect(screen.getByText('Created')).toBeInTheDocument();+ expect(screen.getByText('Started')).toBeInTheDocument();+ expect(screen.getByText('Completed')).toBeInTheDocument();+ expect(screen.getByText('1m 5s')).toBeInTheDocument();+ expect(screen.getByText('70 in · 50 out')).toBeInTheDocument();expect(wsMock.sendRequest).toHaveBeenCalledWith('get_team_tasks', {- workflow_id: 'workflow-1', team_lead_node_id: 'lead',+ workflow_id: 'workflow-1', team_lead_node_id: 'lead', include_history: true,});});@@ -57,7 +64,7 @@ describe('TaskManagerPanel', () => {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',+ workflow_id: 'workflow-1', team_lead_node_id: 'lead', include_history: true,});});diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex 0ccd041d..c1802a10 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -401,7 +401,7 @@ AgentWorkflow.run(context):`emit_phase(phase, status?)` is a thin helper that schedules `agent.broadcast_progress.v1`. The activity emits `WorkflowEvent.agent_progress` (CloudEvents v1.0, `type="com.opencompany.agent.progress"`) for FE consumers; when `status` is supplied it also drives a raw-dict `update_node_status` for the canvas-glow color (executing / success / error). Same dual-channel pattern F4.A's `_node_activity` uses. When this workflow is itself a delegated child (`context["parent_node_id"]` set), every `emit_phase` call ALSO schedules a second broadcast against the parent's `node_id` with `phase="delegating"` — the parent's canvas badge then advances in real time while the child loops, instead of freezing at "executing" glow until the child completes.-Each LLM step is one activity, each tool call is one per-type activity (the same activities F4.A registered). **Delegation tool calls** (`delegate_to_<x>`) where the child type is in `AGENT_WORKFLOW_TYPES` are the exception: they spawn a child `AgentWorkflow` via `workflow.execute_child_workflow` instead of a per-type activity, with `parent_node_id` injected into `child_context` to enable the parent-mirror broadcast above. Deterministic child workflow id is `f"{parent_workflow_id}-delegate-{child_node_id}-{iteration}"` so Temporal retries don't spawn duplicates. Non-agent tools and excluded types (`rlm_agent`, `claude_code_agent`) still go through `execute_activity` as before. Failures of tool activities surface as error messages back to the LLM (matching the in-process agent loop behaviour); the agent loop continues.+Each LLM step is one activity and each ordinary tool call is one per-type activity. Team-lead Task Manager assignments are different: persistence happens first, then the lead starts a deterministic detached `DelegatedTaskWorkflow` with `ParentClosePolicy.ABANDON` and receives `queued` immediately. The runner owns the root-wide permit, claim, child `AgentWorkflow`, terminal result/usage persistence, `taskTrigger`, and permit release, so the assigning lead can return without polling. Direct non-team delegation retains the child-workflow path. Non-agent tools and excluded types (`rlm_agent`, `claude_code_agent`) still go through `execute_activity`. Failures surface as durable task failures and trigger review rather than being lost when the lead invocation closes.**Delegation input contract (input-vs-config separation).** The LLM's `{task, context}` args are per-invocation *input*, not node configuration, and travel as the child workflow input's `invocation` field. `prepare_agent_payload` applies it AFTER its config resolution (`{**node_data, **db_params}` — DB wins for config liveness): `task` → system_message, `context`-or-`task` → prompt — the same semantics as the legacy `handlers.tools._execute_delegated_agent`. Stored node parameters (including the empty default `prompt` the frontend persists on drop) therefore never override the delegated task. A call with both fields empty is rejected at the parent's call boundary (tool-error message to the LLM, no child spawn). Bypass agents dispatched as plain activities (`rlm_agent` / `claude_code_agent`) instead receive the remap directly in `node_data` — their per-type activity consumes `node_data` verbatim with no DB re-merge.@@ -475,7 +475,7 @@ server/services/temporal/│ ├── execute_node_activity() # Main activity method│ └── _execute_via_websocket() # WebSocket execution├── plugin_activities.py # collect_plugin_activities() -> per-type node.{type}.v{ver} activities (F4.A)-├── agent_workflow.py # AgentWorkflow child workflow (F4.B agent loop)+├── agent_workflow.py # AgentWorkflow loop + detached DelegatedTaskWorkflow├── agent_activities.py # collect_agent_activities() -> the 7 agent.*.v1 activities (F4.B)├── workflow.py # MachinaWorkflow class│ ├── run() # Main orchestratordiff --git a/docs-internal/agent_delegation.md b/docs-internal/agent_delegation.mdindex e6f3c3a3..1672c1b0 100644--- a/docs-internal/agent_delegation.md+++ b/docs-internal/agent_delegation.md@@ -16,7 +16,7 @@ AI Agents can delegate tasks to other agents connected to their `input-tools` ha**Two execution paths** depending on whether the parent is running under Temporal F4.B:-- **F4.B (default, `TEMPORAL_AGENT_WORKFLOW_ENABLED=true`):** the delegation tool dispatch inside `AgentWorkflow` spawns the child as a **child `AgentWorkflow`** via `workflow.execute_child_workflow`. The LLM's `{task, context}` args travel as `child_context["invocation"]` — the per-invocation input contract: `prepare_agent_payload` applies it AFTER its config resolution (`task` → system_message, `context`-or-`task` → prompt), so the child's stored parameters (including the empty default `prompt` saved on drop) never override the delegated task. Calls with both fields empty are rejected at the parent's call boundary (tool-error to the LLM, no spawn). Parent's `node_id` is passed in `child_context["parent_node_id"]` so the child's `_emit_phase` mirrors progress onto the parent canvas badge. Parent awaits the child's result synchronously through the Temporal child-workflow handle — see [TEMPORAL_ARCHITECTURE.md §F4.B](./TEMPORAL_ARCHITECTURE.md#agent-as-child-workflow-f4b).+- **F4.B (default, `TEMPORAL_AGENT_WORKFLOW_ENABLED=true`):** Task Manager assignment persists first, then `AgentWorkflow` starts a detached **`DelegatedTaskWorkflow`** with `ParentClosePolicy.ABANDON` and immediately returns `queued` to the lead. The runner owns the root-wide permit, task claim, child `AgentWorkflow`, compact result/usage persistence, `taskTrigger`, and permit release. The LLM's `{task, context}` args travel as `child_context["invocation"]`; `prepare_agent_payload` applies them after stored config resolution, so saved defaults cannot override the mission. Parent identity still travels in `parent_node_id` for status mirroring. Completion starts a separately scoped lead review instead of blocking the assigning invocation — see [TEMPORAL_ARCHITECTURE.md §F4.B](./TEMPORAL_ARCHITECTURE.md#agent-as-child-workflow-f4b).- **Legacy / F4.A-only:** the rest of this doc. `_execute_delegated_agent` spawns the child as an independent `asyncio.Task` and the parent continues working immediately — the **fire-and-forget** pattern. Applies the same task/context semantics by overwriting `child_params` AFTER loading them from the DB. Still the path for `rlm_agent` / `claude_code_agent` (excluded from `AGENT_WORKFLOW_TYPES`) and any deployment with F4.B disabled.In both paths the parent passes only a `task` string and optional `context` string — per-invocation input that always wins over stored configuration. Everything else -- the child's provider, model, memory, skills, and tools -- comes from the child's own configuration and workflow connections.diff --git a/docs-internal/agent_teams.md b/docs-internal/agent_teams.mdindex cf37a65f..046f5c00 100644--- a/docs-internal/agent_teams.md+++ b/docs-internal/agent_teams.md@@ -60,8 +60,10 @@ The default root-wide limit is three active descendants, includinggrandchildren and excluding the root lead. Assignments persist before childrenstart. Eligible tasks enter a deterministic FIFO queue, dependencies remainblocked, 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.+`assign_task` calls in one Temporal turn are preflighted together. Each returns+`queued` after starting a detached `DelegatedTaskWorkflow`; the lead reports+the assignment and returns without polling. The runner owns admission, claim,+child execution, terminal persistence, event emission, and permit release.Each child receives an isolated AgentWorkflow context containing only itsbounded mission, relevant context, and its own connected tools, skills, and@@ -72,18 +74,20 @@ inspectable through task attempts and execution traces.After durable persistence, lifecycle transitions emit deterministic events suchas `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.+`team.task.cancelled`. A canonical task completion CloudEvent feeds+`taskTrigger` with owning team/execution/root, task, trace, result/error, and+usage context. A connected lead starts a separate review invocation scoped to+the original execution, reads Task Manager, and reports without duplicating work.## Human interfaces### Task ManagerSelecting 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.+durable tasks across workflow restarts by default. Archived executions remain+individually selectable. Rows show local created/started/completed timestamps,+live or frozen elapsed duration, input/output/total tokens, attempts, results,+errors, and authorized accept/retry/reassign/modify/cancel/finish controls.### Team Monitordiff --git a/docs-internal/node-logic-flows/ai_tools/taskManager.md b/docs-internal/node-logic-flows/ai_tools/taskManager.mdindex 7b82b03d..3a79edb3 100644--- a/docs-internal/node-logic-flows/ai_tools/taskManager.md+++ b/docs-internal/node-logic-flows/ai_tools/taskManager.md@@ -17,7 +17,7 @@ the persisted execution membership snapshot.| 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 |+| `list_tasks` | optional `status_filter`, `include_history` | 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 |@@ -36,10 +36,18 @@ produce an error instructing the lead to list/review tasks first.## 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.+`delegation_request`. Temporal starts a detached `DelegatedTaskWorkflow` and+returns `queued` immediately. The runner owns admission, child execution,+compact result/usage persistence, `taskTrigger`, and permit release. Legacy+execution passes the same precreated task ID into its background child bridge.+Retries therefore cannot duplicate tasks.++The human panel includes durable history by default, so workflow restarts do+not clear the visible list. Specific execution selections remain scoped for+safe mutations. Created/started/completed timestamps are normalized as UTC and+shown locally. Elapsed time starts at `started_at`, ticks while running, and+freezes at `completed_at`. Usage shows input, output, and total tokens, with a+fallback to usage embedded in historical result envelopes.## Status semanticsdiff --git a/docs-internal/node-logic-flows/chat_utility/teamMonitor.md b/docs-internal/node-logic-flows/chat_utility/teamMonitor.mdindex 0273cbb8..b1008532 100644--- a/docs-internal/node-logic-flows/chat_utility/teamMonitor.md+++ b/docs-internal/node-logic-flows/chat_utility/teamMonitor.md@@ -18,7 +18,9 @@ The panel:- merges persisted member status (`working`, `idle`) during execution;- displays blocked, queued, running, submitted, accepted, failed, and cancelledcounts;-- lists every current-execution task with assignee and queue position;+- resolves the newest lead execution instead of trusting stale `active` flags;+- lists all tasks from that execution, including submitted and accepted work;+- exposes an execution selector for historical runs;- refreshes on team lifecycle broadcasts and supports manual refresh.Team Monitor never mutates tasks. Use the Task Manager panel bound to the lead@@ -35,8 +37,9 @@ the monitor from reporting unreviewed work as finished.`server/nodes/utility/team_monitor/__init__.py` provides a read-only snapshotfor 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.+canvas even without a `team_id`, then follows the connected lead output's+`team_id`, `execution_id`, and `root_execution_id`. It merges durable members,+all tasks, active tasks, counts, and recent lifecycle events.The operation performs no writes, external calls, or subprocess work.diff --git a/docs-internal/node-logic-flows/workflow_triggers/taskTrigger.md b/docs-internal/node-logic-flows/workflow_triggers/taskTrigger.mdindex 195e7bed..90e30599 100644--- a/docs-internal/node-logic-flows/workflow_triggers/taskTrigger.md+++ b/docs-internal/node-logic-flows/workflow_triggers/taskTrigger.md@@ -19,9 +19,10 @@ error paths, which emits a CloudEvents `WorkflowEvent`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 per-match. Used to let a parent workflow react to child completion without blocking-external downstream automation. Temporal separately returns/signals the owning-lead for review; `taskTrigger` is not the lead-resume mechanism.+match. The assigning lead has already returned after receiving `queued`. When+the detached runner submits or fails the task, this trigger starts the connected+lead's separate review invocation. The event preserves the owning execution,+so Task Manager reads the original durable task rather than the trigger run.## Inputs (handles)@@ -56,6 +57,10 @@ Declared `TaskTriggerOutput` fields:result?: string; // Present when status='completed'error?: string; // Present when status='error'workflow_id?: string;+ team_id?: string;+ execution_id?: string;+ root_execution_id?: string;+ trace_id?: string;}```@@ -121,8 +126,8 @@ If any filter rejects, the event is skipped and the waiter stays blocked.- Waiter has no timeout; if the child agent never dispatches a`task_completed` event (e.g. it is still running or died silently) thetrigger blocks until cancelled.-- Fire-and-forget delegation means the parent workflow does not know the- child failed unless this trigger is present and matches.+- Lead review requires a connected matching trigger path. External consumers+ may use the event without receiving authority to mutate another team.## Relateddiff --git a/server/core/database.py b/server/core/database.pyindex 6780d76e..95e213ef 100644--- a/server/core/database.py+++ b/server/core/database.py@@ -2421,9 +2421,13 @@ class Database:)if execution_id:query = query.where(AgentTeam.execution_id == execution_id)- elif active_first:- query = query.order_by(case((AgentTeam.status == "active", 0), else_=1), AgentTeam.created_at.desc())else:+ # Execution identity, not a mutable lifecycle flag, defines+ # the current run. A crashed/legacy team can remain marked+ # active forever; active-first ordering then hides every+ # newer submitted or accepted task. The newest execution is+ # the default, and callers select older runs explicitly by+ # execution_id.query = query.order_by(AgentTeam.created_at.desc())result = await session.execute(query.limit(1))team = result.scalar_one_or_none()@@ -2432,6 +2436,35 @@ class Database:logger.error(f"Failed to find team: {e}")return None+ async def list_team_executions(+ self, workflow_id: str, team_lead_node_id: str+ ) -> List[Dict[str, Any]]:+ """List every durable execution owned by a workflow lead, newest first."""+ try:+ async with self.get_session() as session:+ result = await session.execute(+ select(AgentTeam)+ .where(+ AgentTeam.workflow_id == workflow_id,+ AgentTeam.team_lead_node_id == team_lead_node_id,+ )+ .order_by(AgentTeam.created_at.desc(), AgentTeam.id.desc())+ )+ return [+ {+ "team_id": team.id,+ "execution_id": team.execution_id,+ "root_execution_id": team.root_execution_id,+ "status": team.status,+ "created_at": team.created_at.isoformat() if team.created_at else None,+ "completed_at": team.completed_at.isoformat() if team.completed_at else None,+ }+ for team in result.scalars().all()+ ]+ except Exception as e:+ logger.error(f"Failed to list team executions: {e}")+ return []+async def update_team_status(self, team_id: str, status: str) -> bool:"""Update team status."""try:@@ -2730,6 +2763,11 @@ class Database:async def complete_task(self, task_id: str, result_data: Optional[Dict[str, Any]] = None) -> bool:"""Atomically submit a running task for lead review."""try:+ usage = (+ result_data.get("usage")+ if isinstance(result_data, dict) and isinstance(result_data.get("usage"), dict)+ else None+ )async def _complete(session: AsyncSession) -> Dict[str, Any]:completed = await session.execute(update(TeamTask)@@ -2740,6 +2778,7 @@ class Database:.values(status="submitted",result=result_data,+ usage=usage,progress=100,completed_at=datetime.now(timezone.utc),)diff --git a/server/nodes/tool/task_manager/__init__.py b/server/nodes/tool/task_manager/__init__.pyindex a1d3827f..d385153a 100644--- a/server/nodes/tool/task_manager/__init__.py+++ b/server/nodes/tool/task_manager/__init__.py@@ -27,6 +27,7 @@ class TaskManagerParams(BaseModel):expected_revision: Optional[int] = Field(default=None, ge=0)reason: Optional[str] = Field(default=None, max_length=2000)status_filter: Optional[str] = None+ include_history: bool = Falsemodel_config = ConfigDict(extra="allow")@@ -49,13 +50,20 @@ class TaskManagerNode(ToolNode):tool_name = "task_manager"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."+ "teammates, inspect submitted work, then accept, retry, reassign, or cancel it. "+ "Use list_tasks with include_history=true to consult prior executions.")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, "isTaskManagerPanel": True, "hideRunButton": True}+ ui_hints = {+ "isToolPanel": True,+ "isTaskManagerPanel": True,+ "hideInputSection": True,+ "hideOutputSection": True,+ "hideRunButton": True,+ }annotations = {"destructive": True, "readonly": False, "open_world": False}task_queue = TaskQueue.DEFAULTneeds_canvas = True@@ -104,7 +112,14 @@ async def _execute_task_manager(args: Dict[str, Any], config: Dict[str, Any]) ->scope = _scope(config)if operation == "list_tasks":- tasks = await service.list_durable_tasks(**scope, status=args.get("status_filter"))+ if args.get("include_history"):+ tasks = await service.list_durable_task_history(+ workflow_id=scope["workflow_id"],+ team_lead_node_id=scope["team_lead_node_id"],+ status=args.get("status_filter"),+ )+ else:+ 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 ""))diff --git a/server/nodes/utility/team_monitor/__init__.py b/server/nodes/utility/team_monitor/__init__.pyindex 88b21ffb..4584b6a0 100644--- a/server/nodes/utility/team_monitor/__init__.py+++ b/server/nodes/utility/team_monitor/__init__.py@@ -78,8 +78,17 @@ class TeamMonitorNode(ActionNode):team_id = ctx.raw.get("team_id")if not team_id:for output in (ctx.raw.get("outputs", {}) or {}).values():- if isinstance(output, dict) and output.get("team_id"):- team_id = output["team_id"]+ current = output+ # AgentWorkflow output is commonly wrapped as+ # {success, result: {team_id, execution_id, ...}}.+ for _ in range(3):+ if not isinstance(current, dict):+ break+ if current.get("team_id"):+ team_id = current["team_id"]+ break+ current = current.get("result")+ if team_id:breakif not team_id:@@ -113,5 +122,8 @@ class TeamMonitorNode(ActionNode):"failed": status.get("failed_count", 0),},"active_tasks": status.get("active_tasks", []),+ "all_tasks": status.get("tasks", []),+ "execution_id": status.get("execution_id"),+ "root_execution_id": status.get("root_execution_id"),"recent_events": status.get("recent_events", [])[-max_history:],}diff --git a/server/services/agent_team.py b/server/services/agent_team.pyindex 54a9c04b..ab34c21f 100644--- a/server/services/agent_team.py+++ b/server/services/agent_team.py@@ -133,7 +133,38 @@ class AgentTeamService:team_id = team["id"] if team else Noneif not team_id:return {"error": "Team not found"}- return await self.database.get_team_stats(team_id)+ status = await self.database.get_team_stats(team_id)+ if workflow_id and team_lead_node_id and not status.get("error"):+ executions = await self.database.list_team_executions(+ workflow_id, team_lead_node_id+ )+ status["archived_executions"] = [+ {+ **item,+ "label": f"{item.get('status', 'unknown').title()} · "+ f"{(item.get('execution_id') or item['team_id'])[:12]}",+ }+ for item in executions+ if item.get("execution_id")+ and item.get("execution_id") != status.get("execution_id")+ ]+ return status++ async def list_durable_task_history(+ self, *, workflow_id: str, team_lead_node_id: str,+ status: Optional[str] = None,+ ) -> List[Dict[str, Any]]:+ """Return tasks across this lead's executions without crossing authority scope."""+ history: List[Dict[str, Any]] = []+ for execution in await self.database.list_team_executions(+ workflow_id, team_lead_node_id+ ):+ tasks = await self.database.get_team_tasks(execution["team_id"], status)+ history.extend(+ {**task, "team_execution_id": execution.get("execution_id")}+ for task in tasks+ )+ return historyasync def resolve_lead_scope(self, *, workflow_id: str, team_lead_node_id: str,diff --git a/server/services/agent_teams/handlers.py b/server/services/agent_teams/handlers.pyindex f70bf629..bfc5990a 100644--- a/server/services/agent_teams/handlers.py+++ b/server/services/agent_teams/handlers.py@@ -137,10 +137,17 @@ async def handle_get_team_tasks(data: Dict[str, Any], websocket: WebSocket) -> D"""Get team tasks."""from services.agent_team import get_agent_team_serviceif 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"),- )+ service = get_agent_team_service()+ if data.get("include_history"):+ tasks = await service.list_durable_task_history(+ workflow_id=data["workflow_id"],+ team_lead_node_id=data["team_lead_node_id"], status=data.get("status"),+ )+ else:+ tasks = await 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"))diff --git a/server/services/plugin/edge_walker.py b/server/services/plugin/edge_walker.pyindex d3b13075..529e1d09 100644--- a/server/services/plugin/edge_walker.py+++ b/server/services/plugin/edge_walker.py@@ -445,11 +445,7 @@ async def _resolve_task_payload(if not source_output:return None- if isinstance(source_output, dict) and "result" in source_output and isinstance(source_output.get("result"), dict):- task_data = source_output.get("result")- logger.info(f"{log_prefix} Extracted nested task_data from result key")- else:- task_data = source_output+ task_data = extract_task_event_payload(source_output) or source_outputif isinstance(task_data, dict):logger.info(f"{log_prefix} Task completion data: task_id={task_data.get('task_id')}, "@@ -458,6 +454,23 @@ async def _resolve_task_payload(return task_data+def extract_task_event_payload(value: Any) -> Optional[Dict[str, Any]]:+ """Unwrap task data from executor and CloudEvent envelopes."""+ current = value+ seen: set[int] = set()+ while isinstance(current, dict) and id(current) not in seen:+ seen.add(id(current))+ if current.get("task_id") and current.get("status"):+ return current+ nested = current.get("data")+ if not isinstance(nested, dict):+ nested = current.get("result")+ if not isinstance(nested, dict):+ return None+ current = nested+ return None++async def collect_teammate_connections(node_id: str,context: Dict[str, Any],@@ -509,9 +522,10 @@ 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"- "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."+ "This taskTrigger run is the lead's completion review. Use Task Manager "+ "list_tasks and get_task to read the durable task, verify the submitted "+ "result against its mission and acceptance criteria, then produce the "+ "requested user-facing output. Do not create a duplicate assignment.")if status == "error":@@ -522,9 +536,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"- "REVIEW REQUIRED: Inspect the failure and either retry, revise, reassign "- "to a connected teammate, cancel/waive with a reason, or report an "- "unrecoverable failure."+ "This taskTrigger run is the lead's failure review. Use Task Manager "+ "list_tasks and get_task to inspect the durable attempt before reporting, "+ "retrying, or reassigning it. Do not create a duplicate assignment.")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 2cb0f52e..e65cfa95 100644--- a/server/services/temporal/agent_activities.py+++ b/server/services/temporal/agent_activities.py@@ -70,8 +70,8 @@ def _ensure_llm_contents(messages: List[Any]) -> None:raise ApplicationError("Agent has no invokable content: message list contains no user, "- "assistant, or tool messages. Provide a non-empty 'task' in the "- "delegate_to_* call, set the agent's 'prompt' parameter, or "+ "assistant, or tool messages. Provide a non-empty Task Manager mission, "+ "set the agent's 'prompt' parameter, or ""connect an input trigger.",type="EmptyAgentPrompt",non_retryable=True,@@ -502,6 +502,8 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:from services.plugin.edge_walker import (collect_agent_connections,collect_teammate_connections,+ extract_task_event_payload,+ format_task_context,)node_id = context["node_id"]@@ -609,20 +611,43 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:"nodes": context.get("nodes") or [],"edges": context.get("edges") or [],"workflow_id": workflow_id,+ # MachinaWorkflow passes upstream results as ``inputs``. Edge walking+ # uses the legacy node-id keyed ``outputs`` name, so bridge the two+ # shapes for chat triggers and taskTrigger alike.+ "outputs": context.get("outputs") or context.get("inputs") or {},}- memory_data, skill_data, tool_data, input_data, _task_data = await collect_agent_connections(+ memory_data, skill_data, tool_data, input_data, task_data = await collect_agent_connections(node_id,walk_context,database,log_prefix=f"[AgentWorkflow:{node_type}]",)+ # taskTrigger may be wired to input-task (task_data) or input-main+ # (input_data). In both cases preserve the CloudEvent payload as invokable+ # content. This is an external automation run, separate from the owning+ # AgentWorkflow which already receives the child result for durable review.+ trigger_task_data = task_data+ if not trigger_task_data and isinstance(input_data, dict):+ trigger_task_data = extract_task_event_payload(input_data)+ if trigger_task_data:+ task_prompt = format_task_context(trigger_task_data)+ prompt = f"{task_prompt}\n\n{prompt}" if prompt else task_prompt+# Team-handle edges are configuration edges and are intentionally not# returned by collect_agent_connections. Expand them here before tools# are built, mirroring the legacy inline agent path. Without this step# Temporal removes teammates from graph scheduling but never exposes a# delegate_to_* function to the lead LLM.execution_team_id: Optional[str] = context.get("team_id")+ team_execution_id: Optional[str] = None+ if trigger_task_data:+ # Completion automation runs in a new Temporal execution but reviews+ # the durable task in the execution that originally assigned it.+ execution_team_id = str(trigger_task_data.get("team_id") or "") or None+ team_execution_id = (+ str(trigger_task_data.get("execution_id") or "") or None+ )owns_execution_team = Falseif node_type in {"orchestrator_agent", "ai_employee"}:teammates = await collect_teammate_connections(@@ -658,7 +683,11 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:"child_tools": child_tools,}tool_data = [*(tool_data or []), entry]- if teammates and workflow_id:+ # A taskTrigger completion is a separate downstream automation run.+ # It must not mint a second empty "active" team for the same lead;+ # doing so makes the owning execution's submitted/accepted tasks seem+ # to disappear from Task Manager and Team Monitor.+ if teammates and workflow_id and not trigger_task_data:from services.agent_team import get_agent_team_serviceexecution_id = str(context.get("execution_id") or "")@@ -768,6 +797,9 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:"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"+ "When assign_task returns status='queued', do not poll or wait in this run. "+ "Tell the user the task was delegated and return immediately. Completion starts "+ "a separate taskTrigger review with the owning task context.\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"@@ -802,6 +834,10 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:if field in out and out[field]:prompt = str(out[field])break+ if not prompt and isinstance(out, dict) and out:+ import json++ prompt = json.dumps(out, ensure_ascii=False, default=str)# Read user-overridable globals once at prep time.# - auto_rebind_tools: forwarded into every per-tool activity so@@ -871,6 +907,7 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:"max_concurrent_subagents": max_concurrent_subagents,"max_delegation_depth": max_delegation_depth,"team_id": execution_team_id,+ "team_execution_id": team_execution_id,"owns_execution_team": owns_execution_team,"root_execution_id": str(context.get("root_execution_id")@@ -1154,6 +1191,7 @@ async def finish_agent_delegation(payload: Dict[str, Any]) -> Dict[str, Any]:lifecycle_data = {"team_id": team_id,+ "execution_id": task.get("execution_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"),@@ -1161,7 +1199,11 @@ async def finish_agent_delegation(payload: Dict[str, Any]) -> Dict[str, Any]: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)+ if isinstance(result, dict):+ result_value = result.get("response", result.get("result", result))+ else:+ result_value = result+ result_text = str(result_value)await broadcast_agent_task_completed(task_id=task_id,agent_name=str(payload.get("child_agent_name") or child_id),diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.pyindex 1c1153df..b3acbf17 100644--- a/server/services/temporal/agent_workflow.py+++ b/server/services/temporal/agent_workflow.py@@ -52,6 +52,7 @@ from typing import Any, Dict, List, Optionalfrom temporalio import workflowfrom temporalio.common import RetryPolicy # kept for type hints+from temporalio.workflow import ParentClosePolicyfrom services.node_registry import get_node_class@@ -193,6 +194,69 @@ def _duplicate_visible_tool_name_error(tools: List[Dict[str, Any]]) -> Optional[)[email protected](sandboxed=False, name="DelegatedTaskWorkflow")+class DelegatedTaskWorkflow:+ """Own one queued delegation after the lead returns to its caller."""++ @workflow.run+ async def run(self, request: Dict[str, Any]) -> Dict[str, Any]:+ lifecycle = request["lifecycle"]+ task_id = lifecycle["team_task_id"]+ root_id = lifecycle["root_execution_id"]+ acquired = False+ began = False+ try:+ await workflow.execute_activity(+ "agent.acquire_subagent_permit.v1",+ args=[{"root_execution_id": root_id, "permit_id": task_id,+ "limit": request.get("limit", 3)}],+ start_to_close_timeout=timedelta(hours=1),+ heartbeat_timeout=timedelta(seconds=10),+ retry_policy=AGENT_ACTIVITY_RETRY,+ )+ acquired = True+ await workflow.execute_activity(+ "agent.begin_delegation.v1", args=[lifecycle],+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=AGENT_ACTIVITY_RETRY,+ )+ began = True+ result = await workflow.execute_child_workflow(+ "AgentWorkflow", args=[request["child_context"]],+ id=request["child_workflow_id"],+ execution_timeout=timedelta(hours=1), run_timeout=timedelta(hours=1),+ )+ succeeded = bool(result.get("success", True)) if isinstance(result, dict) else True+ _response, summary = _normalise_delegated_result(result)+ return await workflow.execute_activity(+ "agent.finish_delegation.v1",+ args=[{**lifecycle, "success": succeeded, "result": summary,+ "error": result.get("error") if isinstance(result, dict) else None,+ "terminal_event_id": f"{task_id}:terminal"}],+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=AGENT_ACTIVITY_RETRY,+ )+ except Exception as exc:+ if began:+ 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"}],+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=AGENT_ACTIVITY_RETRY,+ )+ raise+ finally:+ if acquired:+ await workflow.execute_activity(+ "agent.release_subagent_permit.v1",+ args=[{"root_execution_id": root_id, "permit_id": task_id}],+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=AGENT_ACTIVITY_RETRY,+ )++@workflow.defn(sandboxed=False, name="AgentWorkflow")class AgentWorkflow:"""Run an AI agent as a Temporal child workflow.@@ -296,6 +360,17 @@ class AgentWorkflow:# the ``child_context`` spread below. ``workflow.info().run_id``# is deterministic — safe inside workflow code.execution_id = str(context.get("execution_id") or "") or workflow.info().run_id[:8]+ task_scope_execution_id = str(+ payload.get("team_execution_id") or execution_id+ )+ # Needed by every terminal result, including agents that never make a+ # tool call (for example downstream taskTrigger automation). It was+ # previously initialized only inside the tool-call branch.+ root_execution_id = str(+ payload.get("root_execution_id")+ or context.get("root_execution_id")+ or execution_id+ )max_iterations = int(payload.get("max_iterations") or _default_max_iterations())agent_node_id = payload["node_id"]agent_workflow_id = payload.get("workflow_id")@@ -482,23 +557,17 @@ class AgentWorkflow:final_content = step_result.get("content", "")team_id = str(payload.get("team_id") or "")if team_id and payload.get("owns_execution_team"):- finalization = await workflow.execute_activity(+ # Finalization is opportunistic. Queued/running work keeps+ # the durable team active, but must not force this lead+ # invocation to wait. Completion will emit taskTrigger and+ # start the separately scoped review invocation.+ 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."- )},- })- continueawait self._persist_turn(payload, human_text=user_prompt, assistant_text=final_content)break@@ -522,11 +591,6 @@ class AgentWorkflow:max_concurrent_subagents = max(1, int(payload.get("max_concurrent_subagents") or 3))- root_execution_id = str(- payload.get("root_execution_id")- or context.get("root_execution_id")- or execution_id- )delegation_call_indices = [indexfor index, candidate in enumerate(calls)@@ -588,7 +652,7 @@ class AgentWorkflow:"inputs": {},"workflow_id": payload.get("workflow_id"),"session_id": payload.get("session_id", "default"),- "execution_id": execution_id,+ "execution_id": task_scope_execution_id,"root_execution_id": root_execution_id,"parent_node_id": agent_node_id,"delegation_depth": delegation_depth + 1,@@ -796,108 +860,32 @@ class AgentWorkflow: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,+ 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}"+ runner_id = f"{child_id}-runner"+ await workflow.start_child_workflow(+ "DelegatedTaskWorkflow",+ args=[{"lifecycle": lifecycle, "child_context": child_context,+ "child_workflow_id": child_id, "limit": max_concurrent_subagents}],+ id=runner_id,+ parent_close_policy=ParentClosePolicy.ABANDON,+ execution_timeout=timedelta(hours=2), run_timeout=timedelta(hours=2),)- 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,- )+ return {"status": "queued", "result": None, "runner_workflow_id": runner_id}# Preflight every Task Manager assignment activity in this LLM# turn concurrently. Each activity performs authorization and@@ -934,7 +922,7 @@ class AgentWorkflow:"inputs": {},"workflow_id": payload.get("workflow_id"),"session_id": payload.get("session_id", "default"),- "execution_id": execution_id,+ "execution_id": task_scope_execution_id,"root_execution_id": root_execution_id,"parent_node_id": agent_node_id,"team_lead_node_id": agent_node_id,@@ -1127,7 +1115,7 @@ class AgentWorkflow:"inputs": {},"workflow_id": payload.get("workflow_id"),"session_id": payload.get("session_id", "default"),- "execution_id": execution_id,+ "execution_id": task_scope_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"),@@ -1173,6 +1161,17 @@ class AgentWorkflow:start_to_close_timeout=PERSIST_TURN_TIMEOUT,retry_policy=AGENT_ACTIVITY_RETRY,)+ child_succeeded = (+ bool(tool_result.get("success", True))+ if isinstance(tool_result, dict) else True+ )+ child_error = (+ tool_result.get("error")+ if isinstance(tool_result, dict) else None+ )+ child_response, child_summary = _normalise_delegated_result(+ tool_result+ )team_id = str(payload.get("team_id") or context.get("team_id") or "")if team_id:task_id = (@@ -1195,11 +1194,9 @@ class AgentWorkflow:"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))- if isinstance(tool_result, dict) else True,- "result": tool_result if isinstance(tool_result, dict) else {"result": tool_result},- "error": tool_result.get("error")- if isinstance(tool_result, dict) else None,+ "success": child_succeeded,+ "result": child_summary,+ "error": child_error,"terminal_event_id": f"{task_id}:terminal",}],activity_id=(@@ -1208,6 +1205,13 @@ class AgentWorkflow:start_to_close_timeout=PERSIST_TURN_TIMEOUT,retry_policy=AGENT_ACTIVITY_RETRY,)+ tool_result = {+ "success": child_succeeded,+ "status": "submitted" if child_succeeded else "failed",+ "result": child_response,+ "usage": child_summary.get("usage"),+ **({"error": child_error} if child_error else {}),+ }if next_delegation_to_start < len(delegation_call_indices):await _start_delegation(delegation_call_indices[next_delegation_to_start]@@ -1254,6 +1258,7 @@ class AgentWorkflow:**tool_result,"delegation_status": delegated["status"],"delegation_result": delegated["result"],+ "delegation_usage": delegated.get("usage"),}tool_content = _serialise_tool_result(tool_result)await self._emit_phase(@@ -1478,6 +1483,9 @@ class AgentWorkflow:"model": payload.get("model"),"provider": payload.get("provider"),"usage": usage_total,+ "team_id": payload.get("team_id") or context.get("team_id"),+ "execution_id": context.get("execution_id"),+ "root_execution_id": root_execution_id,}# Persist the result to the OutputStore via the workflow_service@@ -1602,6 +1610,27 @@ class AgentWorkflow:)+def _normalise_delegated_result(result: Any) -> tuple[str, Dict[str, Any]]:+ """Expose the child's answer, not its internal AgentWorkflow envelope."""+ if isinstance(result, dict):+ payload = result.get("result") if isinstance(result.get("result"), dict) else result+ response = result.get("response")+ if response is None:+ response = payload.get("response")+ if response is None:+ response = result.get("result", result.get("error", ""))+ text = response if isinstance(response, str) else _serialise_tool_result(response)+ summary = {+ "response": text,+ "usage": payload.get("usage") or result.get("usage") or {},+ "model": payload.get("model") or result.get("model"),+ "provider": payload.get("provider") or result.get("provider"),+ }+ return text, {key: value for key, value in summary.items() if value not in (None, {})}+ text = str(result) if result is not None else ""+ return text, {"response": text}++def _serialise_tool_result(result: Any) -> str:"""Return a string body for a ``ToolMessage``.diff --git a/server/services/temporal/worker.py b/server/services/temporal/worker.pyindex 14900971..7606c6fe 100644--- a/server/services/temporal/worker.py+++ b/server/services/temporal/worker.py@@ -168,7 +168,7 @@ class TemporalWorkerManager:collect_polling_activities,)from services.temporal.agent_activities import collect_agent_activities- from services.temporal.agent_workflow import AgentWorkflow+ from services.temporal.agent_workflow import AgentWorkflow, DelegatedTaskWorkflowfrom services.temporal.activities import (broadcast_trigger_status_activity,store_node_output_activity,@@ -215,6 +215,7 @@ class TemporalWorkerManager:workflows=[MachinaWorkflow,AgentWorkflow,+ DelegatedTaskWorkflow,TriggerListenerWorkflow,PollingTriggerWorkflow,],diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.pyindex 352a4c08..0b25385d 100644--- a/server/services/temporal/workflow.py+++ b/server/services/temporal/workflow.py@@ -24,6 +24,21 @@ from services.workflow_naming import node_label_slug# Zeenie handles: input-skill, input-toolsCONFIG_HANDLES = {"input-tools", "input-memory", "input-model", "input-skill", "input-task", "input-teammates"}++def _is_config_edge(edge: Dict[str, Any], node_map: Dict[str, Dict[str, Any]]) -> bool:+ """Return whether an edge attaches configuration rather than runtime data.++ ``input-task`` is normally a configuration handle, but a taskTrigger emits+ runtime completion data through that handle. Treating that edge as config+ removes both the pre-executed trigger and its payload before dependency+ resolution, leaving the downstream agent with an empty prompt.+ """+ handle = edge.get("targetHandle", "")+ if handle not in CONFIG_HANDLES:+ return False+ source = node_map.get(edge.get("source"), {})+ return not (handle == "input-task" and source.get("type") == "taskTrigger")+# Trigger node types — event listeners that should never be scheduled# as blocking activities. Imported from constants to avoid drift (was# previously redefined here with a "keep in sync" comment — Wave 11.E.2).@@ -587,7 +602,7 @@ class MachinaWorkflow:source_id = edge.get("source")# Edges to config handles mean source is a config node- if handle in CONFIG_HANDLES:+ if _is_config_edge(edge, node_map):config_ids.add(source_id)# Android services connected as direct tools@@ -604,7 +619,9 @@ class MachinaWorkflow:exec_edges = [efor e in edges- if e.get("source") not in config_ids and e.get("target") not in config_ids and e.get("targetHandle", "") not in CONFIG_HANDLES+ if e.get("source") not in config_ids+ and e.get("target") not in config_ids+ and not _is_config_edge(e, node_map)]return exec_nodes, exec_edgesdiff --git a/server/skills/assistant/subagent-skill/SKILL.md b/server/skills/assistant/subagent-skill/SKILL.mdindex 238c8345..5fec3f49 100644--- a/server/skills/assistant/subagent-skill/SKILL.md+++ b/server/skills/assistant/subagent-skill/SKILL.md@@ -4,7 +4,7 @@ description: Coordinate connected subagents through durable Task Manager assignmallowed-tools: task_managermetadata:author: opencompany- version: "3.0"+ version: "3.1"category: assistanticon: "🤖"color: "#8B5CF6"@@ -35,6 +35,9 @@ For every assignment provide:Independent `assign_task` calls may be emitted together. All tasks persistbefore execution and enter a deterministic queue. At most three descendants,including grandchildren, run concurrently; excess work remains `queued`.+Once assignments return `queued`, tell the user work was delegated and return.+Never wait or poll for completion in the assigning invocation. A detached+durable runner continues the work and `taskTrigger` starts the later review.## Capability matching@@ -55,7 +58,8 @@ member.Task states are `blocked`, `queued`, `running`, `submitted`, `accepted`,`failed`, and `cancelled`.-A worker completion produces `submitted`, not Done. When signalled:+A worker completion produces `submitted`, not Done. In the task-trigger review+invocation, which is scoped to the original team execution:1. Inspect the result and acceptance criteria with `get_task` or `list_tasks`.2. Copy `task.id` into `task_id` and `task.revision` intodiff --git a/server/skills/assistant/task-manager/SKILL.md b/server/skills/assistant/task-manager/SKILL.mdindex d6ec560e..301ce24a 100644--- a/server/skills/assistant/task-manager/SKILL.md+++ b/server/skills/assistant/task-manager/SKILL.md@@ -4,7 +4,7 @@ description: Coordinate durable team tasks by assigning connected teammates, revallowed-tools: task_managermetadata:author: opencompany- version: "2.1"+ version: "2.2"category: automation---@@ -16,8 +16,8 @@ to this lead's `input-teammates` handle.## Required workflow-1. Call `list_tasks` before assigning work so you do not duplicate an existing- mission.+1. Call `list_tasks` with `include_history=true` before assigning work so you+ do not duplicate a mission from an earlier workflow execution.2. Split independent work into bounded tasks with explicit acceptance criteria.3. Call `assign_task` once per mission. Use the connected teammate node ID orthe exact delegate name reported by the lead's available teammate list.@@ -25,6 +25,8 @@ to this lead's `input-teammates` handle.dispatch identities, not the lead's task-creation interface.4. Independent tasks may be assigned together. The durable queue starts at mostthree descendants across the whole agent tree; excess tasks remain queued.+ After `assign_task` returns `queued`, report that delegation started and+ return immediately. Do not poll or wait in the assigning invocation.5. When a teammate submits work, inspect the complete result, error, attempthistory, and acceptance criteria. Copy `task.id` to `task_id` and`task.revision` to `expected_revision` for the review mutation.@@ -43,7 +45,7 @@ to this lead's `input-teammates` handle.| 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` |+| `list_tasks` | Inspect current or historical tasks | optional `status_filter`, `include_history` || `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` |@@ -70,8 +72,9 @@ to discard history.- `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+Do not treat `submitted` as finished team work. Do not poll a running task;+`taskTrigger` starts a separate review invocation carrying the owning execution.+Do not invent teammate IDs, team IDs, orexecution IDs—the runtime supplies authority and rejects cross-team access.## Team Monitor interpretationdiff --git a/server/tests/nodes/test_chat_utility.py b/server/tests/nodes/test_chat_utility.pyindex d39b4c92..f440e1d1 100644--- a/server/tests/nodes/test_chat_utility.py+++ b/server/tests/nodes/test_chat_utility.py@@ -308,6 +308,30 @@ class TestTeamMonitor:harness.assert_envelope(result, success=False)assert "boom" in result["error"]+ async def test_nested_agent_output_pins_monitor_to_execution_team(self, harness):+ fake_service = MagicMock()+ fake_service.get_team_status = AsyncMock(return_value={+ "execution_id": "exec-live",+ "root_execution_id": "root-live",+ "tasks": [{"id": "accepted-1", "status": "accepted"}],+ "active_tasks": [],+ })+ ctx = harness.build_context(extra={+ "outputs": {+ "lead-1": {+ "success": True,+ "result": {"team_id": "team-live", "execution_id": "exec-live"},+ }+ }+ })+ with patch("services.agent_team.get_agent_team_service", return_value=fake_service):+ result = await harness.execute("teamMonitor", {}, context=ctx)++ payload = result["result"]+ fake_service.get_team_status.assert_awaited_once_with("team-live")+ assert payload["execution_id"] == "exec-live"+ assert payload["all_tasks"] == [{"id": "accepted-1", "status": "accepted"}]+# ============================================================================# textGeneratordiff --git a/server/tests/nodes/test_task_manager_delegation_bridge.py b/server/tests/nodes/test_task_manager_delegation_bridge.pyindex 96f8d0fc..e4796627 100644--- a/server/tests/nodes/test_task_manager_delegation_bridge.py+++ b/server/tests/nodes/test_task_manager_delegation_bridge.py@@ -84,3 +84,19 @@ async def test_accept_never_guesses_when_multiple_tasks_are_submitted():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())+++async def test_list_tasks_can_include_prior_executions():+ service = SimpleNamespace(list_durable_task_history=AsyncMock(return_value=[+ {"id": "old-task", "status": "accepted", "team_execution_id": "exec-old"},+ ]))+ with patch("services.agent_team.get_agent_team_service", return_value=service):+ result = await _execute_task_manager(+ {"operation": "list_tasks", "include_history": True}, _config()+ )++ assert result["tasks"][0]["team_execution_id"] == "exec-old"+ service.list_durable_task_history.assert_awaited_once_with(+ workflow_id="wf-1", team_lead_node_id="lead-1", status=None+ )diff --git a/server/tests/services/test_durable_team_tasks.py b/server/tests/services/test_durable_team_tasks.pyindex 034ad939..328e46c3 100644--- a/server/tests/services/test_durable_team_tasks.py+++ b/server/tests/services/test_durable_team_tasks.py@@ -20,6 +20,7 @@ def _database(*, member_role="teammate"):update_team_status=AsyncMock(return_value=True),transition_team_task=AsyncMock(),get_team_tasks=AsyncMock(return_value=[]),+ list_team_executions=AsyncMock(return_value=[]),)@@ -78,3 +79,23 @@ async def test_finish_requires_every_task_to_be_reviewed():await service.finish_durable_team(workflow_id="wf-1", team_lead_node_id="lead-1", execution_id="exec-1")+++async def test_task_history_keeps_accepted_tasks_from_prior_executions():+ database = _database()+ database.list_team_executions.return_value = [+ {"team_id": "team-new", "execution_id": "exec-new"},+ {"team_id": "team-old", "execution_id": "exec-old"},+ ]+ database.get_team_tasks.side_effect = [+ [{"id": "current", "status": "running"}],+ [{"id": "historical", "status": "accepted", "result": {"response": "done"}}],+ ]++ tasks = await AgentTeamService(database).list_durable_task_history(+ workflow_id="wf-1", team_lead_node_id="lead-1"+ )++ assert [task["id"] for task in tasks] == ["current", "historical"]+ assert tasks[1]["team_execution_id"] == "exec-old"diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.pyindex ffc489b8..cef42b6c 100644--- a/server/tests/temporal/test_agent_workflow.py+++ b/server/tests/temporal/test_agent_workflow.py@@ -29,6 +29,13 @@ class TestAgentWorkflowDefinition:assert defn is not None, "AgentWorkflow missing @workflow.defn"assert defn.name == "AgentWorkflow"+ def test_detached_delegation_runner_is_workflow_defn(self):+ from services.temporal.agent_workflow import DelegatedTaskWorkflow++ defn = getattr(DelegatedTaskWorkflow, "__temporal_workflow_definition", None)+ assert defn is not None+ assert defn.name == "DelegatedTaskWorkflow"+def test_class_is_sandboxed_false(self):"""Workflow needs to import frozen registry dicts deterministically(for tool type → activity name resolution). Sandboxing must be off@@ -38,6 +45,23 @@ class TestAgentWorkflowDefinition:defn = getattr(AgentWorkflow, "__temporal_workflow_definition")assert defn.sandboxed is False, "AgentWorkflow must be sandboxed=False so it can read " "services.node_registry deterministically"+ def test_delegated_result_exposes_response_not_workflow_envelope(self):+ from services.temporal.agent_workflow import _normalise_delegated_result++ response, summary = _normalise_delegated_result({+ "success": True,+ "result": {"response": "child answer", "thinking": "private"},+ "usage": {"total_tokens": 12},+ "provider": "test",+ })++ assert response == "child answer"+ assert summary == {+ "response": "child answer",+ "usage": {"total_tokens": 12},+ "provider": "test",+ }+class TestDurableTeamDelegationContract:"""Regression coverage for team-handle Temporal delegation."""@@ -52,6 +76,30 @@ class TestDurableTeamDelegationContract:assert '"input-tools"' in sourceassert "get_or_create_execution_team" in sourceassert '"team_id": execution_team_id' in source+ assert '"outputs": context.get("outputs") or context.get("inputs")' in source+ assert "format_task_context(trigger_task_data)" in source+ assert "and not trigger_task_data" in source+ assert 'team_execution_id = (' in source++ def test_agent_result_carries_owning_team_identity(self):+ import inspect++ from services.temporal.agent_workflow import AgentWorkflow++ source = inspect.getsource(AgentWorkflow.run)+ assert '"team_id": payload.get("team_id") or context.get("team_id")' in source+ assert '"execution_id": context.get("execution_id")' in source++ def test_root_execution_identity_is_initialized_before_agent_loop(self):+ import inspect++ from services.temporal.agent_workflow import AgentWorkflow++ source = inspect.getsource(AgentWorkflow.run)+ initialization = source.index("root_execution_id = str(")+ tool_loop = source.index("for iteration in range(max_iterations)")+ result_payload = source.index('"root_execution_id": root_execution_id')+ assert initialization < tool_loop < result_payloaddef test_same_turn_delegations_start_before_ordered_await(self):import inspect@@ -64,6 +112,31 @@ class TestDurableTeamDelegationContract:assert "delegation_handles[call_index]" in sourceassert "tool_result = await handle" in source+ def test_task_manager_assignment_returns_after_detached_start(self):+ import inspect++ from services.temporal.agent_workflow import AgentWorkflow, DelegatedTaskWorkflow++ lead_source = inspect.getsource(AgentWorkflow.run)+ runner_source = inspect.getsource(DelegatedTaskWorkflow.run)+ assert '"DelegatedTaskWorkflow"' in lead_source+ assert "ParentClosePolicy.ABANDON" in lead_source+ assert 'return {"status": "queued"' in lead_source+ assert '"agent.finish_delegation.v1"' in runner_source+ assert '"agent.release_subagent_permit.v1"' in runner_source++ def test_queued_work_does_not_block_lead_final_response(self):+ import inspect++ from services.temporal.agent_activities import prepare_agent_payload+ from services.temporal.agent_workflow import AgentWorkflow++ workflow_source = inspect.getsource(AgentWorkflow.run)+ prepare_source = inspect.getsource(prepare_agent_payload)+ assert "Team finalization is blocked" not in workflow_source+ assert "must not force this lead" in workflow_source+ assert "do not poll or wait in this run" in prepare_source+def test_child_invocation_has_isolated_trace_envelope(self):import inspect@@ -114,17 +187,20 @@ class TestDurableTeamDelegationContract:def test_task_manager_bridge_is_bounded_and_retry_safe(self):import inspect- from services.temporal.agent_workflow import AgentWorkflow+ from services.temporal.agent_workflow import AgentWorkflow, DelegatedTaskWorkflowsource = 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+ detached = source.index('"DelegatedTaskWorkflow"', queue)+ assert queue < detached+ runner = inspect.getsource(DelegatedTaskWorkflow.run)+ permit = runner.index('"agent.acquire_subagent_permit.v1"')+ claim = runner.index('"agent.begin_delegation.v1"')+ child = runner.index('"AgentWorkflow"', claim)+ finish = runner.index('"agent.finish_delegation.v1"', child)+ release = runner.index('"agent.release_subagent_permit.v1"', finish)+ assert permit < claim < child < finish < release+ assert '"permit_id": task_id' in runnerassert '"team_task_id": task_id' in sourceassert "TASK_MANAGER_DELEGATION_PATCH" in sourcediff --git a/server/tests/temporal/test_task_trigger_graph.py b/server/tests/temporal/test_task_trigger_graph.pynew file mode 100644index 00000000..9f4dc87c--- /dev/null+++ b/server/tests/temporal/test_task_trigger_graph.py@@ -0,0 +1,37 @@+"""Regression tests for taskTrigger runtime data entering Temporal agents."""++from services.temporal.workflow import MachinaWorkflow+++def test_task_trigger_input_task_is_runtime_dependency() -> None:+ trigger = {"id": "task-trigger", "type": "taskTrigger", "_pre_executed": True}+ agent = {"id": "lead", "type": "orchestrator_agent"}+ edge = {+ "id": "task-to-lead",+ "source": "task-trigger",+ "target": "lead",+ "targetHandle": "input-task",+ }++ nodes, edges = MachinaWorkflow()._filter_executable_graph([trigger, agent], [edge])++ assert nodes == [trigger, agent]+ assert edges == [edge]+ dependencies, _ = MachinaWorkflow()._build_dependency_maps(nodes, edges)+ assert dependencies["lead"] == {"task-trigger"}+++def test_non_trigger_input_task_remains_configuration() -> None:+ task_config = {"id": "task-config", "type": "taskManager"}+ agent = {"id": "lead", "type": "orchestrator_agent"}+ edge = {+ "id": "config-to-lead",+ "source": "task-config",+ "target": "lead",+ "targetHandle": "input-task",+ }++ nodes, edges = MachinaWorkflow()._filter_executable_graph([task_config, agent], [edge])++ assert nodes == [agent]+ assert edges == []diff --git a/server/tests/test_node_spec.py b/server/tests/test_node_spec.pyindex 3e0fd94d..01a049c6 100644--- a/server/tests/test_node_spec.py+++ b/server/tests/test_node_spec.py@@ -767,6 +767,18 @@ class TestUIHintsInNodeSpec:assert hints.get("hideInputSection") is Trueassert hints.get("hideOutputSection") is True+ def test_task_manager_surfaces_span_the_full_parameter_panel(self):+ hints = get_node_spec("taskManager").get("uiHints", {})+ assert hints.get("isTaskManagerPanel") is True+ assert hints.get("hideInputSection") is True+ assert hints.get("hideOutputSection") is True++ for node_type in ("orchestrator_agent", "ai_employee"):+ lead_hints = get_node_spec(node_type).get("uiHints", {})+ assert lead_hints.get("isTaskManagerPanel") is True+ assert lead_hints.get("hideInputSection") is not True+ assert lead_hints.get("hideOutputSection") is not True+def test_master_skill_seeded(self):spec = get_node_spec("masterSkill")assert spec is not Nonediff --git a/server/tests/test_task_trigger_canary_producer.py b/server/tests/test_task_trigger_canary_producer.pyindex 68531c70..6d68dede 100644--- a/server/tests/test_task_trigger_canary_producer.py+++ b/server/tests/test_task_trigger_canary_producer.py@@ -174,13 +174,22 @@ class TestTaskTriggerProducerCanaryEmit:assert reread < broadcastassert 'target_status = "requeued" if is_requeued' in sourceassert "if succeeded or not is_requeued" in source+ assert 'result.get("response", result.get("result", result))' in source+ assert '"execution_id": task.get("execution_id")' in source- def test_task_trigger_context_requires_lead_review(self):- from services.plugin.edge_walker import format_task_context+ def test_task_trigger_context_requires_durable_lead_review(self):+ from services.plugin.edge_walker import extract_task_event_payload, format_task_contextcompleted = 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+ assert "lead's completion review" in completed+ assert "list_tasks and get_task" in completed+ assert "Do not create a duplicate assignment" in completed+ assert "lead's failure review" in failed+ assert "retrying, or reassigning" in failed+ nested = {"specversion": "1.0", "data": {"result": {+ "task_id": "task-1", "status": "completed", "result": "saved",+ }}}+ assert extract_task_event_payload(nested) == {+ "task_id": "task-1", "status": "completed", "result": "saved",+ }