# Agent and Context

| Entry | Does |
| --- | --- |
| `agent()` / `agent_async()` | Runs a model tool loop |
| `Agent` | Stores reusable configuration, scopes ordinary subclass methods |
| `Context` | Supplies named content and history selection |

```
from openprogram import Agent, agent, agent_async

answer = agent("Summarize this text", tools=[])

class Researcher(Agent):
    instructions = "Return a short, factual answer."
    tools = []

    def prepare(self, question):
        """Remove surrounding whitespace."""
        return question.strip()

    def research(self, question):
        """Answer the prepared question."""
        return self(self.prepare(question))

researcher = Researcher(model="configured-model")
answer = researcher.research("A question")
# In async code: answer = await researcher.arun("A question")
# Or: answer = await agent_async("A question", tools=[])
```

All entries use the existing Runtime and Session DAG. Ordinary calls need no manual Context.

## Direct calls and Agent classes

| Option | Effect |
| --- | --- |
| `prompt` | A string or content blocks |
| `model`, `effort`, `runtime` | Common options. Tool execution options: [Runtime](https://fzkuji.github.io/OpenProgram/docs/reference/api/runtime.html) |
| `tools` | `None` resolves available tools. `[]` requests none. |
| `choices` | The closing reply becomes a [next-step decision](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/choosing-the-next-step/next-step-decision.html); returns the resolved pick |

| Rule | Behaviour |
| --- | --- |
| `Agent(model=, instructions=, context=, tools=, runtime=, effort=, **options)` | Instance settings override class defaults; per-call options override instance settings. `**options` accepts the keyword options of `agent()`. |
| `Agent.from_spec(spec, **overrides)` | Uses an AgentSpec configuration without creating a saved Agent entry |
| Construction | No model request, no execution session |
| Invocation | Inherits an active execution, otherwise owns a separate one and releases its resources. Reusing an instance does not continue an earlier independent conversation. |
| Methods | Instance, static and class methods get automatic call scopes, including single-underscore helpers. Dunder methods and generators are excluded. Recording registers no model tool. |

The class-and-method interface takes inspiration from [NVIDIA-labs OO Agents](https://github.com/NVIDIA-NeMo/labs-OO-Agents). OpenProgram does not claim NOOA API compatibility.

## Context

```
from openprogram import Agent, Context

context = Context(
    {"notes": "Use the project terminology."},
    providers={"current_topic": lambda current: "Agent context"},
)
researcher = Agent(context=context, tools=[])
```

The framework derives and binds Context automatically; this is optional. Content is separate from system instructions and tool authority.

| Name | Effect |
| --- | --- |
| `Context(blocks=None, *, parent=None, providers=None, history=, call_id=, store=None, head_id=None)` | Mutable mapping of named content |
| `derive()` | Child with independent content |
| `Context.current()` | The task binding, or `None` |
| `merge(other)` | Overlays named content and explicit selection; keeps the scope call identity |
| `bind()` | For host integrations that need an explicit binding |
| `providers` | Synchronous callables taking the current Context, run for each model request. A failure aborts that request. Expression strings are never executed. |

| `history` | The request sees |
| --- | --- |
| `None` | Nothing |
| `"thread"` | Only earlier requests made with this same Context object |
| `"chat"` | The visible conversation (Context default) |
| callable | `(node, context)` filters conversation nodes after the visibility checks |
| unset in a Workflow role call | No history |

These settings cannot expand tool permissions. Model interactions stay in the execution session.

## Explicit session lifetime

To make several independent calls continue one session, pass an existing `SessionNodeWriter`.

```
from openprogram import Agent, Context
from openprogram.state.store import SessionStore, SessionNodeWriter

store = SessionStore(root_path="/var/lib/myapp/sessions")
store.create_session("research", agent_id="main")
writer = SessionNodeWriter(store, "research")
researcher = Agent(context=Context(store=writer), tools=[])
try:
    first = researcher("List the project requirements.")
    second = researcher("Review the requirements from the previous call.")
finally:
    store.close()
```

- `head_id` selects an existing branch tip; `None` continues the current head.
- The caller owns and closes the store. Execution scopes do not.
- This supplies the event lifetime for NOOA-style repeated instance calls. The Agent still stores configuration; its default calls stay independent.

## Method options

```
from openprogram import Agent
from openprogram.runtime.agent import llm

class ExampleAgent(Agent):
    method_options = {
        'f': {'tool': True},
    }

    def f(self, x: str) -> str:
        """One-line summary of what f does."""
        return llm([{"type": "text", "text": f"...{x}..."}])

_example_agent = ExampleAgent()
f = _example_agent.f
```

Signature and docstring supply names, types, defaults and summaries; `method_options` supplies the rest, with no decorator. Agent owns method execution and registration. Context resolves request content and visible history.

### Execution and Context

| Parameter | Type | Default | Meaning |
| --- | --- | --- | --- |
| `capture_io` | `bool` | method `False`, tool `True` | Record arguments and return values. Structural call identity stays available without them. |
| `resumable` | `bool` | `False` | Opt in to [durable steps](#durable-steps-and-code-selection) |
| `expose` | `str` | method `"full"`, tool `"io"` | What others see of this function in the DAG (table below). Any other value raises `ValueError`. |
| `render_range` | `dict` | `None` | How many history nodes this function's `llm()` reads: `{"callers": N, "subcalls": M}`, sliced by `seq` |
| `input` | `dict` | `None` | Per-parameter UI metadata for the WebUI form: `description`, `placeholder`, `multiline`, `options` (dropdown and JSON-schema `enum`), `hidden` (out of the form and tool schema) |
| `system` | `str` | `None` | System prompt for this function's LLM calls; restored afterwards |

| `expose` | Name and return value | LLM exchanges | Nested code calls |
| --- | --- | --- | --- |
| `"io"` | visible | hidden | hidden |
| `"llm"` | hidden | visible | hidden |
| `"full"` | visible, with docstring and parameters | visible | visible |
| `"hidden"` | no DAG nodes written | no DAG nodes written | no DAG nodes written |

| `render_range` key | Counts nodes | Default | Values |
| --- | --- | --- | --- |
| `callers` | written before this frame started; newest N | `None`, unlimited | `0` is a full wall |
| `subcalls` | written after this frame started; newest N | `-1`, unlimited, so the frame sees its own progress | `N>=0` truncates; `0` walls off the frame |

**Tool registration parameters**

With `tool=True` the method registers as an LLM-callable tool in `openprogram.programs`, beside `@function` tools. Names and semantics match `@function`.

| Parameter | Type | Default | Meaning |
| --- | --- | --- | --- |
| `tool` / `as_tool` | `bool` | `False` | Register as a tool. `False`: Python-direct only |
| `name` | `str` | `None` | Override; default `__name__` |
| `description` | `str` | `None` | Override; default docstring |
| `parameters` | `dict` | `None` | JSON-schema override; default from type hints and `input`, excluding runtime-injected and `hidden` parameters |
| `label` | `str` | `None` | Label in tool UIs |
| `toolset` | `tuple` | `()` | Toolset names, used by `exec(toolset=...)` |
| `unsafe_in` | `tuple` | `()` | Channel sources where the tool is filtered out |
| `check_fn` | `Callable` | `None` | Per-call gate before dispatch; falsy blocks |
| `requires_env` | `tuple` | `()` | Env variables that must be set for it to be offered |
| `can_use` | `Callable` | `None` | Availability predicate at tool resolution |
| `max_result_weight` | `int` | `None` | A smaller bound for this tool's result than the model's, in weight (a CJK character 1, anything else 0.25). The tool never cuts its text: the agent loop bounds it once and keeps the whole text in the conversation's `tool_results/` |
| `requires_approval` | — | `None` | Forwarded to the tool registry, same shape as `@function` |
| `cache` | `bool` | `False` | Memoize tool-dispatched calls on `(name, args)` |
| `cache_ttl` | `float` | `300.0` | Seconds, with `cache=True` |
| `timeout` | `float` | `None` | Hard wall-clock kill in seconds; the model receives an error result |
| `available_if` | `Callable` | `None` | Falsy or raising skips registration; method scopes stay active |
| `defer` | `bool` | `False` | Deferred tool: schema loaded on demand |
| `register_globally` | `bool` | `True` | `False` keeps it out of the global registry |

### Runtime for a method

A method runs on its Agent's Runtime, or the caller's when the Agent has none: `ExampleAgent(runtime=rt).f("x")` runs `f`, its model requests and the Agent methods it calls on `rt`. Configure Runtimes where the program starts, not through method arguments. For two models in one workflow, give the second role its own Agent instance.

**Older functions: runtime injection**

Parameters named `runtime`, `exec_runtime` or `review_runtime` are filled when the caller passes none: from the current call chain, or for an entry-point call from `create_runtime()`, closed when the function returns. Several such parameters get the same runtime. They never appear in the tool schema or WebUI form. New methods do not declare them.

**Introspection and safety**

- `fn.spec`: generated tool spec `{"name", "description", "parameters"}`. `fn.execute(**kwargs)` invokes with LLM-provided kwargs.
- Re-entering itself more than 5 levels deep raises `RecursionError`; an injected situational prompt also steers the model away.
- `add_pre_invocation_hook` / `remove_pre_invocation_hook`: hooks run at the top of every call and may raise `CancelledError` to abort it, as the WebUI stop button does.

**Recording to the DAG**

| Moment | Write |
| --- | --- |
| Enter the function | `code` node (`output=None`, `status="running"`); docstring in `metadata.doc`, prepended to `function_name(args)` when rendering |
| Each `llm()` in the body | One `llm` node |
| Exit | Backfill the same `code` node's `output` and `status` |

`expose="hidden"` writes nothing. With no DAG store installed, recording is a no-op.

## Durable steps and code selection

```
from openprogram import Agent
from openprogram.runtime.agent.durable_steps import step

class ExampleAgent(Agent):
    method_options = {
        'report': {'tool': True, 'resumable': True},
    }

    def report(self, topic: str):
        research = step("research", collect_research, topic)
        return step("write", write_report, research)

_example_agent = ExampleAgent()
report = _example_agent.report
```

Execution is restored at explicit steps, not arbitrary Python stack frames. `collect_research` and `write_report` are ordinary source-defined functions.

| Construct | Rule |
| --- | --- |
| `step(name, fn, *args, **kwargs)` | JSON-compatible inputs and results. A completed step returns its saved result without calling the action again. Repeated names are distinguished by occurrence; keep order and completed inputs stable. |
| `workflow(name, fn, *args, **kwargs)` | Nested orchestration |
| `parallel({"branch": (fn, args, kwargs)})` | Named workflows run concurrently, each with independent durable progress; waits for every branch before releasing ownership |

| `execution.code_change_policy` | After a restart |
| --- | --- |
| `keep_original` (default) | Retained source runs. After adopting B, a later restart keeps B even if the installed code is C. |
| `use_latest` | Completed results stay; the current function runs the remaining compatible steps |

The task's Continue control can override the policy.

| Outcome | Cases |
| --- | --- |
| Pauses | Deleted or reordered recorded steps, changed completed inputs, an unavailable or changed pinned dependency |
| Keeps the active version | A candidate that fails compatibility before adopting any remaining step |
| Still checked | Permission and tool parameter contract changes |
| Rejected before steps run | Imports inside retained helpers, dynamic import APIs, generated code, third-party and user package objects as opaque dependencies (only the pinned standard library is supported) |
| Unsupported | Calls and external mutations outside steps, asynchronous orchestration, generators, live handles, non-JSON results |
| Needs reconciliation | The process died after an external action started but before its result was committed; recovery cannot assume it failed |
| Never an automatic retry | Explicit pauses, cancellation, unanswered approvals, uncertain external results |

**Authoring notes**

- Pass persistent state through JSON step inputs and results. Do not share mutable globals, closures or defaults between steps.
- Import step dependencies at module scope. Source-defined Python helpers are retained recursively.
- If B needs a different local state shape, write the conversion as pure orchestration over saved JSON before its remaining steps.
- Manual calls resume the same execution and function record. Chat calls return their eventual result to the original pending tool call.
- Restart-owned interruptions follow `execution.auto_resume_window_seconds` (default `-1`, no limit; `0` disables automatic restart).
- The function run dialog distinguishes functions that declare this contract from ordinary ones, which need a new run after interruption.

## Managed Program sources

| Captured | Not captured |
| --- | --- |
| Source-defined functions, submodules and nested definitions inside authorized package roots: selected first-party sources, installed and catalogued Program packages, owner-recorded external harnesses, published Programs, retained source snapshots | Arbitrary host files, unrelated dependencies, lambdas, generated code, unavailable source |

A package lists public entries in `PROGRAM_ENTRIES`; a plain entry can carry an `__agent_options__` mapping. Captured helpers do not become tools. Explicit method metadata is preserved; generators are excluded.

## Session turns and continuation

| Name | Effect |
| --- | --- |
| `Agent.run_turn(request, *, context=None, on_event=None, cancel_event=None, execution_context=None)` | Returns `TurnResult`. Instance configuration applies before a fresh turn. Import `TurnRequest` and `TurnResult` from `openprogram`. |
| `arun_turn(request, **options)` | Same, asynchronous, with cooperative cancellation |
| `resume_turn(continuation, **options)`, `aresume_turn(...)` | Reuse the checkpoint's request without repeating admission |
| `Context.for_session(store, session_id, head_id=, blocks=, providers=)` | Binds a persistent store and branch. A request for another session is rejected. `Context.session_id` exposes the graph identity. |
| `ChatAgent` | Production conversation type; inherits this contract. Overriding turn entry methods does not wrap them as helper calls. |

Event callbacks receive the runtime event dictionaries and run on the execution thread. Durable pause and steering keep the existing execution-control owner and safe-point protocol.

[Runtime](https://fzkuji.github.io/OpenProgram/docs/reference/api/runtime.html)
