# Agent execution core

1. **Programs** Workflow roles, Agent methods `agent()`, `Agent`: current Runtime
2. **Sessions** Chat, CLI, sub-agent, Job `run_agent_turn()`: session, branch, Job, recovery, head, archive
3. **One Agent loop** `runtime/agent/loop` same retry, cancel, timeout, usage and Call events

Lifecycle before and after the loop is all that differs. No per-function decorator is needed: `Agent` scopes ordinary methods itself. `agent()`, `agent_async()` and `Agent.arun` share the core.

## Primitives

| Primitive | Means | Persistent session | DAG |
| --- | --- | --- | --- |
| `llm()` | One logical model request, with structured output and its repair budget | No, current Runtime | One LLM Call |
| `agent()` | Model and tool loop for one task; final text or a validated structured value | No, current Runtime | Agent Call holding LLM and Function Calls |
| Workflow role | `role(prompt, context=)` runs a tool loop; `role.choose` picks one option | No, current Runtime | Child of the entry node, exact request stored |
| `goal` Program, `create_goal` | Keeps an objective active across a conversation's turns until verification accepts it. Needs a conversation. | Yes, saved in its session | Turns, then a verification turn |
| `run_agent_turn()` | Internal session lifecycle; not a Program primitive | Yes | Independent Agent Call on a session branch |

Workflow code calls the model only through roles. The contract is in [Workflows](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/workflows/workflow.html); the Agent and Context owners are in [Agent and Context contract](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/agent/unified-agent.html).

**Signature of agent()**

```
def agent(
    prompt: str | list[dict],
    *,
    model=None, effort=None, tools=None, tools_deny=None,
    response_format=None, choices=None,
    max_iterations=None, stop_after_tool_round=False, timeout_s=None,
    tool_choice=None, parallel_tool_calls=None, execution_kind="agent",
    runtime=None, return_raw=False, toolset=None, tools_allow=None,
    instructions=None, context=None, tools_source=None,
    on_retry=None, web_search=None, stream_fn=None,
) -> Any: ...
```

No `session_id`, `branch_from`, `advance_head`, `archive_when_done` or `run_in_background`: persistence belongs to the execution environment. Saved Agent profiles go through `Agent.from_spec`, whose explicit overrides win.

## Boundaries

| Not added | Instead |
| --- | --- |
| A third Agent abstraction or a public wrapper over Jobs | `agent()` and `Agent` |
| Workflow DSL or graph engine | Python packages; static graphs from imports and entry identities |
| Second profile system or extra database | Existing Agents profiles and stores |
| Hidden chain-of-thought in the UI | Model-output summaries |

Programs do not import `runtime.conversation.peer_agents.sub_agent_run`, except the sub-agent tools (`programs/tools/agents/agent`, `send_message`), its product entry.

## Workflow lifecycle

| Stage | Who | Result | Where to see it |
| --- | --- | --- | --- |
| Write | Chat Agent with file tools | Package in `~/.openprogram/programs/<name>/` | Tool calls in the chat |
| Check | `openprogram programs check` | Import probe, sandboxed tests, Git commit on success | Report (`--json`) |
| Load | Worker watcher | Entries of the clean committed revision become tools | Programs page, `openprogram programs list` |
| Run | The Workflow's code | Entry result | Entry node with one child per role call |

## What the UI shows

| Level | Collapsed | Expanded |
| --- | --- | --- |
| Workflow | Name, state, duration, step count, full Conclusion | Role calls in order, each with its exact request and reply |
| Agent | Label, state, iterations | Model-output summaries, actual Program calls |
| Program Call | Name, argument summary, state | Input, output, errors, side-panel details |
| Sub-agent session | Navigable row | Switches to the child session; returning keeps the same row |

Plain functions are not recorded. Children expand progressively, not all at once.

## Failures

| Failure | Handling | User sees |
| --- | --- | --- |
| No native structured output | Falls back by capability to text JSON with local schema validation | An error stays on its LLM or Agent Call; Workflow failed |
| `programs check` fails | No commit; the chat Agent reads the report and edits | Check report in the chat |
| Worker restart | Session and Job paths recover. A `resumable` entry resumes through `step()`. Other in-Program Agents end with the parent. | No stale running state |
| User cancellation | One token reaches Runtime, provider and tools; children end before the parent | Cancelled or interrupted, never completed |
| Tool or child Workflow failure | Keeps error payload, caller and partial artifacts | Failed nodes and Conclusion agree |

## Invariants

- Only `PROGRAM_ENTRIES` register as tools; category directories do not.
- Each role call is a child of its entry node, and every Program a Workflow calls appears in the DAG.
- A direct Workflow does not attach to the prior assistant through `predecessor`.
- App, Web and TUI of one profile share one worker.

**Focused tests**

```
pytest -q tests/unit/programs/dag/test_runtime_exec_dag.py
pytest -q tests/component/agent/jobs/test_async_job_recovery.py
pytest -q tests/unit/agent/jobs/test_spawn_caller_invariant.py
pytest -q tests/component/webui/abilities/test_programs_explorer.py
```

**Compared with other frameworks**

| Reference | Adopted | Not adopted |
| --- | --- | --- |
| [OpenAI Agents SDK: running agents](https://openai.github.io/openai-agents-python/running_agents/) | A runner owns the loop of one logical turn; limits, sessions and hooks are separate | A second runtime |
| [OpenAI Agents SDK: tools](https://openai.github.io/openai-agents-python/tools/) | Function tools and agent-as-tool are explicit; parents observe child execution | Turning Workflows into handoffs |
| [OpenAI Agents SDK: orchestration](https://openai.github.io/openai-agents-python/multi_agent/) | Calling a child differs from handing over control | Implicit session branches from `agent()` |
| [LangGraph: workflows and agents](https://docs.langchain.com/oss/python/langgraph/workflows-agents) | Workflows are predefined paths; Agents choose tools locally | A graph DSL |
| [LangGraph: persistence](https://docs.langchain.com/oss/python/langgraph/persistence) | Persistence and interruption recovery are explicit lifecycle capabilities | A persistent thread for every in-Program Agent |

## Implementation status

| Status | Items |
| --- | --- |
| Implemented | `llm()`, `agent()` on the current Runtime; structured output; Workflow roles on the public core; `programs check` and loading; session adapter |
| Not yet verified | DAG and Conclusion display after reload in the installed App |
