# Direct calls, Agent classes and automatic DAG context

| Name | Defines |
| --- | --- |
| `Agent` | Reusable model configuration. Owns no default conversation |
| `Context` | Parent, named content, dynamic providers, history visibility. Built by the framework; applications need not construct one |
| Reused unchanged | Runtime, AgentSpec, tool policy, execution control, Session DAG |

## Usage

```
from openprogram import agent
answer = agent("Analyze this paper", model="configured-model")
```

Uses the current execution session, or opens one independent execution.

```
from openprogram import Agent
bot = Agent(model="configured-model")
first = bot("Investigate this topic")
second = bot(first)
```

Reuses configuration, not history: execution scope decides continuity, and independent top-level calls share none.

```
class Researcher(Agent):
    model = "configured-model"
    def research(self, question):
        text = self.prepare(question)
        return self(text)
    def prepare(self, text):
        return text.strip()
result = Researcher().research("A topic")
```

No per-method decorators. `research` is an entry, `prepare` an unrecorded helper.

| Entry | Rule |
| --- | --- |
| `agent()`, `Agent.__call__` | Synchronous. Both delegate to one internal execution function |
| `await bot.arun(...)`, `await agent_async(...)` | For calls inside an active event loop |
| Construction | Resolves configuration only: no model request, no persistent session. The first execution resolves the session |
| Global state | No process-global default Bot stores history |

## Context lifecycle

| Trigger | Rule |
| --- | --- |
| Program or top-level entry | Establish a scope, bind its Context; inherit an ambient session and explicit branch |
| Function or method entry | Derive a scope with ancestry and visibility rules; history is not copied |
| Before each model request | Resolve DAG sources, instance content, dynamic content, call overrides; select, deduplicate, budget |
| Model return | Update execution state, visible to later construction by the rules |
| Return, error, cancellation | Restore the parent. Completed interactions follow `expose` and `render_range`; children are not merged unconditionally |
| Top-level exit | Unbind task-local state, close owned resources |

| Relation | Determines |
| --- | --- |
| Invocation ancestry | Inheritance and visibility |
| Predecessor | Conversation order |
| Each Agent execution | Owns its DAG. Records user messages, model requests, directly dispatched tools; ordinary helpers create no durable nodes |
| Calling another Agent | Independent DAG; the parent stores the result and a `child_session_id` |
| Permission, cancellation, file checkpoints | Stay with the originating execution, whatever owns the graph |

Context is a runtime construction object; complete intermediate values are neither copied nor persisted. Session persistence and Trace export stay separate.

## One Context model

| Part | Behavior |
| --- | --- |
| Parent | A child inherits the current Context; scope exit restores the parent |
| Content | Named instructions and business data. A child overrides a name without touching its parent. Instance binding is this, attached when the invocation derives its Context |
| Evaluation | Python providers receive the current Context and run during request construction. Expression strings are not evaluated |
| Visibility | Session DAG rules select interactions by branch, call scope, `expose`, `render_range` |

- History selection and content replacement are separate. Equal text does not identify the same interaction; selected DAG identities are recorded at the actual request.
- No second history database or provider runtime. Tool authorization is independent of history visibility.

| API | Behavior |
| --- | --- |
| `Context.current()` | Current binding |
| `Context.derive()` | Child Context |
| `bind()` | Publishes the task context and explicit writer, rejects a conflicting ambient writer, restores on exit |
| `Context(store=writer, head_id=None)` | Binds an existing `SessionNodeWriter` for repeated calls: NOOA-style instance event lifetime, made explicit. `head_id` picks a branch tip, default the session head. The caller owns the store |

## Ordinary function capture

```
def research(question):
    data = prepare(question)
    return analyze(data)
def prepare(question):
    return question.strip()
def analyze(data):
    return agent(data)
```

| Code | Treatment |
| --- | --- |
| Registered Program sources | The managed loader keeps Runtime injection and entry adaptation; helpers get lightweight scopes with no per-call persistence |
| Agent methods, including `_` helpers | Automatic scopes; neither append DAG nodes nor become tools. Instance, static and class methods follow Agent ownership |
| Host files, dependencies, lambdas, generated code, unavailable source | No capture. `agent()` still works; Python ancestry is not persisted |
| All | Signatures, returns, exceptions, imports keep Python semantics. Entry registration and tool exposure stay explicit. Generator creation records no completed call |

## Configuration and authority

| Setting | Ownership |
| --- | --- |
| model, effort, instructions, tools | Call override → instance → class default → ambient session → product default. Omission differs from an explicit empty value |
| `expose`, `render_range` | Existing defaults; `method_options` or explicit metadata sets them |
| Tool visibility, approval | Separate from DAG visibility. Inner configuration cannot expand outer authority |
| AgentSpec, session | Saved Bots reuse AgentSpec. A Python object creates no sidebar Bot or schedule |

Default construction needs model interactions and call relationships, not ordinary arguments or locals. Explicit content is bounded; `self` is represented by identity or type; method names are qualified by module and class. Call recording does not approve arbitrary Python effects; the sandbox still governs them.

## Concurrency and failure

- Current Context, call identity and effective configuration bind per task and restore on exit. Inheritance copies no history or mutable branch configuration. Nested reentry is allowed.
- Shared Agent configuration does not imply shared history. Mutable instance content and shared sessions need defined synchronization.
- Errors, timeouts and cancellation restore the parent and keep completed interactions. Recovery uses safe points and explicit steps, never arbitrary Python stacks. Standalone calls reuse permission context and non-interactive approval rules.
- Without an outer execution, the entry owns an environment and releases it on exit.
- Resumable functions keep one durable node ID across call and continuation; provider tool-call identity stays in node metadata.

## Implementation contract

| Part | Where and how |
| --- | --- |
| Public entries | `Agent`, `Context`, `agent`, `agent_async` |
| Context | `openprogram/runtime/context/model.py` |
| Agent | `openprogram/runtime/agent/agent_class.py` |
| `CallScope` | `openprogram/runtime/agent/call_scope.py`. Separates recorded operations from lightweight functions. Handles explicit metadata and automatic scopes |
| History selection | `openprogram/runtime/agent/runtime/history.py` |
| Managed loading | `openprogram/programs/_host/source_loader.py`, `_registry` in `programs/_host/runtime.py` |
| Internal call state | `openprogram/runtime/agent/call_state.py` |
| Requests | `Runtime.exec`, existing providers, authorization, budgets, compaction |
| English interface text | ASD-STE100 sentence structure, consistent terms |

### No function decorator

- The removed public decorator has no adapter or replacement. `Agent.method_options` keeps input metadata, Runtime injection, registration and schemas, availability, permissions, visibility, retry, execution controls and explicit-step recovery.
- Managed sources declare `PROGRAM_ENTRIES` and `__agent_options__`. Methods carry `_is_agent_method`. Stored node schemas and history stay readable.
- First-party workflows, generated programs, scanners and dispatchers use ordinary Agent classes.
- Harness packages migrate in their own repositories and keep their `agentics` paths; the runtime bundles none. Six locally published workflows migrated in isolation, which is no upstream release.

**Behavior-test host and cancellation display**

- The host initializes the standard SessionStore before the OS sandbox. The runner binds its `SessionNodeWriter` through Context and Agent calls reuse it. Candidate tests cannot spawn processes, write the source snapshot, read host secrets or use the network.
- Cancellation closes the canonical execution; unresolved external effects stay inspectable.
- The assistant projection retries through the durable DAG outbox when its node or storage is unavailable. A display failure does not reject an applied cancellation.
- Cancelling a paused continuation error replaces its error display with cancelled, clears error metadata and keeps content.
- Resource-release observer failures stay visible to the control caller. Normal Job completion keeps its result-bearing projection owner; cancellation notifications do not publish other terminal Job rows before it supplies result and error fields.

**Acceptance**

| Scenario | Observable result |
| --- | --- |
| Non-model parent | Correct research → prepare, analyze → agent scopes; attributable model inputs, outputs, failures |
| Inheritance and evaluation | Parent inheritance, instance blocks, per-request dynamic refresh, override order, deduplication that keeps distinct repeated interactions |
| Equivalence | Same history for old and new entries with the same DAG, branch, policy; provenance recorded at actual requests |
| Session lifetime | No constructor effects; same instance in unrelated tasks isolated; different Agents in one task share permitted context; existing sessions need explicit continuation |
| Budget and compaction | Existing compaction with provenance; summary usage metered; failures do not drop history |
| Concurrency and resources | Sibling isolation, explicit policy for shared instance state, reentry, parent restoration, owner-only cleanup |
| Loading and identity | Authorized sources only; recursion and import aliases keep records; same-name methods do not collide; metadata does not duplicate nodes |
| Policy and display | Recording exposes no tool; deny before effects; standalone entries enforce policy; the default App shows function, model and tool calls and terminal state |

Also covers conversation projections, Goal lifecycle, cancellation, recovery and shipped Programs. Recording keeps DAG relationships without changing content, ownership or authority. Checks are the smallest affected set.

## Relationship to NOOA

| Area | Choice |
| --- | --- |
| Classes and methods | Adopt class declarations, ordinary calls, framework-managed methods |
| Context modeling | Adopt class-based instance content, dynamic resolution, scoped overrides; add DAG sources. Effective context belongs to execution scope |
| History filtering | NOOA filters by `call_id` with nested policy inheritance. OpenProgram keeps DAG branch and frame rules |
| Trace and model context | NOOA separates events and traces. OpenProgram keeps one DAG with distinct display and input views |
| Not adopted | Per-function manual contexts, process-global history, whole-interpreter tracing, second provider or event database |

Public documentation credits NVIDIA-labs OO Agents and cites its repository and paper. Retain applicable licenses if source is reused.

## Implementation status

| Item | Status |
| --- | --- |
| Public entries, shared scopes, managed sources, decorator removal | Implemented |
| Installed App | Verified separately from source checks, on the default App (`default` profile, port 18100, `~/.openprogram`, `/Applications/OpenProgram.app`) |
| NOOA Predict, CodeAct, typed returns, persistent cells | Separate later work. No upstream API compatibility or benchmark parity is claimed |

**References**

- [NVIDIA-labs OO Agents: Native Python Object-Oriented Agents](https://arxiv.org/abs/2607.20709)
- [NOOA ContextManager](https://github.com/NVIDIA-NeMo/labs-OO-Agents/blob/main/src/nooa/runtime/context_manager.py)
- [NOOA context construction](https://github.com/NVIDIA-NeMo/labs-OO-Agents/blob/main/src/nooa/runtime/context_builder.py)
- [NOOA execution architecture](https://github.com/NVIDIA-NeMo/labs-OO-Agents/blob/main/docs/architecture.md)
- [NOOA context lifetime](https://github.com/NVIDIA-NeMo/labs-OO-Agents/blob/main/docs/concepts/prompts-and-context.md)
- [NOOA event selection](https://github.com/NVIDIA-NeMo/labs-OO-Agents/blob/main/src/nooa/runtime/event_query.py)
- [NOOA event tagging](https://github.com/NVIDIA-NeMo/labs-OO-Agents/blob/main/src/nooa/runtime/event_manager.py)
- [NOOA tracing](https://github.com/NVIDIA-NeMo/labs-OO-Agents/blob/main/docs/concepts/tracing.md)
- [NOOA CodeAct reference](https://github.com/NVIDIA-NeMo/labs-OO-Agents/blob/main/src/nooa/strategies/codeact_v2.py)
- [NOOA source license](https://github.com/NVIDIA-NeMo/labs-OO-Agents/blob/main/LICENSE)
- [ASD-STE100 skill](https://github.com/danyuchn/asd-ste100-skill)
- [OpenProgram execution contract](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/agent/llm-and-agent.html)
- [OpenProgram Agent configuration contract](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/agent-configuration/agent-configuration-ui.html)
