Self-improving AI Employees for everyone
AI Agent (aiAgent)
| Field | Value |
|---|---|
| Category | ai_agents / agent |
| Backend execution | Temporal graph runs normally use AgentWorkflow, with preparation in agent_activities.py. The node/Activity path uses AIAgentNode.execute_op, prepare_agent_call, and AIService.execute_agent. |
| Tests | server/tests/nodes/test_ai_agents.py |
| Skill (if any) | n/a (the agent consumes skills via input-skill) |
| Dual-purpose tool | no |
Purpose
aiAgent is the general-purpose tool-calling agent node. It reads a prompt
and system message, continues its stored conversation when a Context node is
connected on input-context (RFC-0002), loads instructions from connected
skill nodes, binds tool nodes as provider-neutral AgentToolSpec values, and
runs until the LLM produces a final answer. The node/Activity path gathers
connected payloads through edge_walker.collect_agent_connections (context,
skill, tool, input, task) and calls AIService.execute_agent with
run_native_agent_loop. The default Temporal graph path uses the same native
provider boundary through durable AgentWorkflow scheduling: preparation,
each LLM step, and each ordinary tool call are regular Activities.
Temporal execution and Stop/Resume
Routing is frozen in the graph run's input. aiAgent takes the child-Workflow
path when TEMPORAL_AGENT_WORKFLOW_ENABLED was captured as true; otherwise it
runs inside the ordinary node Activity. For new controlled generations with
execution_control_version=1, the child Workflow closes admission before each
model request, tool, refresh, compaction, and child start. Stop lets admitted
work and its result bookkeeping finish, including parallel admitted work.
Pending calls from a recorded model response remain in the live continuation.
Resume starts the next pending action with the same execution scope rather
than repeating the response or completed tools.
Attached agents are discovered through their parent's native child tree;
detached Task Manager runners enroll independently with the generation
controller. Version 1 continuation carries prepared configuration, resolved
tools and plugin Activity policies, transcript, thinking, usage, iteration,
execution identity, and control state. It restores this state at a clean turn
boundary and reports AgentContinuationTooLarge if the complete encoded input
cannot fit. It never falls back to the opening prompt. Existing generations
retain legacy paths and do not acquire this stronger acknowledgement contract.
Unlimited LLM retries can keep Stop in pausing during an outage. Tool effects
before recorded completion remain subject to retry/idempotency rules; a
heartbeat status string cannot checkpoint an opaque request. If child-Workflow
routing is disabled, the entire node Activity is the cooperative boundary.
See Temporal workflow control and
Agent continuation.
Inputs (handles)
| Handle | Connection type | Required | Purpose |
|---|---|---|---|
input-main |
main | no | Upstream data. Used as auto-prompt when prompt is empty. |
input-skill |
main | no | Skill nodes (masterSkill is expanded into individual skills). |
input-context |
main | no | A Context node. The agent loads its stored conversation at run start and saves it after every turn, only in a started workflow. Legacy simpleMemory -> input-memory edges are rewritten on load into a Context node plus a Memory tool edge. |
input-tools |
main | no | Tool nodes (search, calculator, HTTP, Android service nodes, the Memory tool, child agents, etc.). |
input-task |
main | no | taskTrigger output - completed delegated-task payload. |
Parameters
Source: AIAgentParams in ai_agent/__init__.py.
| Name | Type | Default | Required | Group | Description |
|---|---|---|---|---|---|
prompt |
string (textarea, rows 4) | "" |
no | - | User prompt; may reference upstream node outputs via templates. Empty -> auto-prompt fallback from input-main. |
provider |
string (ProviderRef) |
openai |
no | - | A provider reference: any registered provider id, or a saved named endpoint openai_compatible:<slug>. Options come from the aiProviders loader, so a new endpoint appears without a schema change; nodes/agent/_provider.py validates the value. |
model |
string | "" |
no | - | Model id; loaded dynamically from the provider. |
system_message |
string (rows 3) | You are a helpful assistant |
no | - | System prompt prepended to the conversation. |
temperature |
number (optional) | None |
no | options | 0-2, step 0.1. Unset falls through to agent.default_temperature in llm_defaults.json. |
max_tokens |
int (optional) | None |
no | options | 1-200000. Unset falls through to the per-model default; clamped in AIService._resolve_max_tokens. |
Note:
api_keyis not a declared field — credentials are auto-injected at execution time bynode_executor._inject_api_keys. The thinking/reasoning controls are resolved by the LLM service layer from provider/model metadata, not exposed asAIAgentParamsfields.
Outputs (handles)
| Handle | Shape | Description |
|---|---|---|
output-main |
object | Envelope from AIService.execute_agent. |
Output payload (shape returned by execute_agent)
{
response: string;
thinking?: string; // when thinkingEnabled=true and provider supports it
model: string;
provider: string;
finish_reason?: string;
timestamp: string;
}
Wrapped in the standard envelope: { success: true, result: <payload>, execution_time: number }.
Logic Flow
This diagram describes the node/Activity entry point. The default Temporal child-Workflow loop is documented in Temporal architecture.
flowchart TD
A[execute_op -> prepare_agent_call] --> B[edge_walker.collect_agent_connections]
B --> C{task_data?}
C -- yes --> D[Format task_context<br/>prepend to prompt]
D --> E{task status in<br/>completed/error AND<br/>tool_data?}
E -- yes --> F[Strip ALL tools<br/>tool_data = empty]
E -- no --> G
F --> G
C -- no --> G{prompt empty AND<br/>input_data present?}
G -- yes --> H[Extract message/text/content<br/>from input_data<br/>-> parameters.prompt]
G -- no --> I
H --> I[Get status broadcaster]
I --> J[await ai_service.execute_agent<br/>with context/skill/tool/broadcaster]
J --> K[Return envelope]
Decision Logic
edge_walker.collect_agent_connectionsscanscontext.edgesfor edges whose target is this node, then routes each bytargetHandle:input-context-> the agent-context builder registered by the Context plugin returns the conversation descriptor (context_data). Legacyinput-memory+simpleMemoryedges in old graphs still yield their recorded Memory descriptor.input-skill-> append toskill_data.masterSkillis expanded into one entry per enabled skill inskillsConfig; instructions come from the DB-storedinstructionsfirst, with a skill-folder fallback.input-tools-> append totool_data. Two special expansions:- Android service nodes are exposed directly as individual tools
and attaches them under
connected_services. - Any
AI_AGENT_TYPESsource (child agents) -> attacheschild_toolsdescribing the child's owninput-toolsneighbours.
- Android service nodes are exposed directly as individual tools
and attaches them under
input-main(orinput-chat, orNone) -> readscontext.outputsfor the source node and stores asinput_data.input-task-> readscontext.outputsfirst, falling back tocontext.get_output_fn(session_id, source_id, 'output_0'). Unwraps{ result: {...} }when nested.
- Task completion short-circuit: if
task_dataexists,_format_task_contextproduces a plain-English wrapper which is prepended to the prompt. If the task status iscompletedorerrorand any tools are present, all tools are stripped to prevent the LLM from delegating again. (Seeprepare_agent_callin_inline.py.) - Auto-prompt fallback: if
parameters.promptis empty after the task block,prepare_agent_callextractsinput_data.message,input_data.text, orinput_data.content(first truthy wins) and assigns it toprompt. If the input is not a dict the whole value is stringified. - Team-lead delegation: for
orchestrator_agent/ai_employee, teammates connected viainput-teammatesbecome Task Manager assignees (not applicable toaiAgentitself unless it is used as a teammate). - Delegation to AIService:
execute_opreturnsresponse.get("result")on success; asuccess=Falseenvelope raisesRuntimeError. Typed openai SDK failures surface asNodeUserErrorfrom insideexecute_agent.
Side Effects
- Database writes: none directly in
execute_op. A memory-connected in-processAIService.execute_agentwritestoken_usage_metricsviaCompactionService.track; Temporal aggregates usage in its result. With a Context node connected, the conversation is saved toagent_conversationsafter every turn of a started workflow; a manual node Run saves nothing. - Broadcasts:
prepare_agent_callresolvesStatusBroadcasterand passes it intoexecute_agent. The service then emitsupdate_node_status(thinking,executing_tool,success, ...) plustoken_usage_updateand potentiallycompaction_starting/compaction_completedevents.BaseNode.execute()additionally wraps the body in anode.aiAgent.executeOpenTelemetry span +log_context(node_id, node_type, workflow_id). - External API calls: every registered provider runs through
ChatUnifierand the native provider layer: Anthropic usesanthropic, Gemini usesgoogle-genai, and OpenAI plus the OpenAI-compatible providers (OpenRouter, Groq, Cerebras, xAI, DeepSeek, Kimi, Mistral, Sarvam, Ollama, LM Studio and named endpoints) useopenaiwith the configured or saved endpoint. Tool nodes may spawn their own HTTP or subprocess calls viaexecute_tool. - File I/O: none in
execute_op. Filesystem tool nodes may read/write the per-workflow workspace (context.workspace_dir). - Subprocess: none directly. Tool executors (shell, process manager, browser, code executors) spawn subprocesses.
External Dependencies
- Credentials: provider API keys via
auth_service.get_api_key(<provider>), resolved insideAIService. Can be overridden by a provider proxy URL (<provider>_proxyAPI key) for Ollama-style local routing. - Services:
AIService,ChatUnifier,run_native_agent_loop,Database,StatusBroadcaster,CompactionService,PricingService,SkillLoader(formasterSkillexpansion). - Python packages: native provider SDKs (
anthropic,openai,google-genai). - Environment variables: none read directly by
execute_op.
Edge cases & known limits
- One conversation per agent: the stored conversation is keyed by
(workflow_id, generation, agent_node_id), so every caller of a started workflow continues the same conversation. Reset admits a new generation and clears the stored conversations. masterSkillexpansion swallows missing skills: if a skill key has noinstructionsin DB and the skill loader raises, the skill entry is still appended with an empty instruction body (logged as a warning, not an error).- Task-completion tool strip is unconditional: even unrelated tools (e.g.
writeTodos) are removed when any task completes. This was introduced as a "CRITICAL FIX" because binding tools while instructing the LLM not to use them confused Gemini into returning empty tool call arrays. - No pre-flight token budget check:
collect_agent_connectionscan produce an arbitrarily long prompt (task context + memory + skills).prepare_agent_calldoes not trim before callingexecute_agent; the provider may reject withprompt_too_long. See../../memory_compaction.md. - Input fallback is field-ordered:
message > text > content > str(dict). An upstream node that outputs bothmessageandtextwill never reachtext. - Child-agent tool discovery is one level deep: grandchildren are not traversed.
Related
- Shared collection helper:
edge_walker.collect_agent_connections+_inline.prepare_agent_callare used by every specialized-agent type (android_agent, coding_agent, web_agent, ...). SeechatAgent.mdfor the same contract with a different system prompt. - Context node:
context.md; Memory tool:simpleMemory.md - Architecture docs: Agent Architecture, Agent Delegation, Native LLM SDK, Memory Compaction