Metadata-Version: 2.4
Name: pynteract-agent
Version: 0.1.0
Summary: An AI agent inhabiting a shared interactive Python session
License-Expression: MIT
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: b4pt0r-the-framework<0.4,>=0.3.3
Requires-Dist: modict>=0.5
Requires-Dist: pynteract>=1.4.1
Dynamic: license-file

# Py — an agent in Pynteract

Py adds model/tool turns to an ordinary, persistent `pynteract.Shell`. The user
and agent work with the same Python objects, execution engine and stream hooks.
There is no second interpreter, background agent loop or hidden input session.

Distribution: `pynteract-agent`. Import: `pynteract_agent`. Terminal: `py-agent`.
Requires Python 3.12+, Pynteract 1.4.1+, and The Framework 0.3.3+ (below 0.4).
Install from PyPI with `python -m pip install pynteract-agent`.

Licensed under [MIT](LICENSE).

## Start where you already work

Inside an existing Pynteract cell:

```python
from pynteract_agent import install
py = install(__shell__)
```

This installs `py` and the `%py` / `%%py` magic in that Shell. It does not create
an API client, authenticate, request a model, or start a REPL. Repeating
`install(__shell__)` returns the same agent; changing configuration is explicit
through `py.config`. Occupied names/magics are rejected, never overwritten.

**Local Python does not mean local model context.** Objects live in the Shell,
but, by default, Py records ordinary cell code and observed output (including
errors), and sends that context with later model requests. Attachment also
imports eligible cells already in the Shell's history. Opt out independently:

```python
py = install(__shell__, include_shell_history=False, observe_shell_cells=False)
```

`include_shell_history` is read on attachment; `py.config.observe_shell_cells`
can be changed for future cells. Neither removes existing model history,
filters explicit prompts or tool outputs, nor restricts what Python can access.

Use `%py explain our current data` for conversation. It works with both
`shell.run(...)` and `await shell.arun(...)`, using their native execution mode.
The magic emits text events without redisplaying a return value.

## One API that follows the execution context

The same method names work in scripts and async code. Nested calls follow the
active turn's mode; otherwise calls from a Pynteract cell follow that cell's
`run()` or `arun()` mode. Only outside a turn and cell does an asyncio loop
determine whether the call is synchronous or must be awaited.

| Purpose | Blocking | Asynchronous |
| --- | --- | --- |
| Conversational text | `py.ask(prompt)` | `await py.ask(prompt)` |
| Native Python result | `py(prompt, **params)` or `py.call(...)` | `await py(prompt, **params)` |
| Continue from history | `py.generate()` | `await py.generate()` |
| Compact context | `py.compact()` | `await py.compact()` |
| Terminal interaction | `py.interact()` | `await py.interact()` |
| Detach / close | `py.close()` | `await py.close()` |

For example, in synchronous Python:

```python
summary = py.ask("Explain the records already in our namespace")
result = py("Build an index of these records", records=records)
```

Or in an asynchronous cell:

```python
summary = await py.ask("Explain the records already in our namespace")
result = await py("Build an index of these records", records=records)
```

A programmatic call exposes its **original objects** in `py.call_params`.
The model executes Python and returns from the turn with `py.end_turn(value)`.
The rest of the cell is skipped, but `finally` blocks run. An error in cleanup
replaces the return. `py.end_turn()` explicitly returns `None`.
The caller receives that actual object; no JSON copy or string conversion is
involved. Missing results and backend failures
raise exceptions. Python tool failures are recorded as tool observations.

Both execution modes drive one turn implementation, with native SDK calls and native
`Cell.run` / `Cell.arun` on the shared Shell. There is no `asyncio.run` bridge or helper thread.
The async Python tool supports top-level `await`; the sync tool does not.
The `aask`, `acall`, `agenerate`, `acompact`, `ainteract`, `arun_python_code`,
and `aclose` methods remain available for compatibility and explicitly select
async execution. No prefix is required for ordinary usage. Python still requires
`await` to suspend asynchronous work; context adaptation cannot make it implicit.

### Explore once, then replay a cell without the model

A turn can return a Pynteract cell with `py.end_turn(cell)`, just like
any other Python object. To reuse a self-contained cell from that turn, give it
explicit inputs rather than retaining the turn's working namespace:

```python
# `view` is a Cell returned by Py; it only needs `samples` and `threshold`.
response = await view.arun(inputs={"samples": samples, "threshold": 2},
                           cause="slider moved to 2")
```

The same cell keeps its creation parent, and the new pass has a distinct run ID.
Py is only called again if the cell's own code explicitly calls it. See
`tests/general/test_gather.py::test_native_delegation_produces_a_cell_that_replays_without_the_model`
for the offline example from the initial Python call to the replay.

### Reentry and concurrency

Direct, sequential self-calls are supported in the same thread/task and mode:
`py(...)` inside a sync Python tool, `await py(...)` inside an async one.
Each nested turn forks the parent's replayable history, excluding unfinished
ancestor tool calls. Its transcript stays out of the parent history.
A nested programmatic turn can return its native object and add a short,
optional handoff to the parent's model context:

```python
py.end_turn(findings, summary="Two regressions confirmed; offline tests passed.")
```

The parent receives a developer message with the child ID, depth, status, and
the summary on success. Summaries are trimmed to 1,200 characters; without one
the message is just a completion or failure marker. The result is not
serialized into the message. Conversational subturns return their text to
Python without automatically forwarding it to the parent's model context.
Delegated tool stdout/stderr is captured by the child's tool, not repeated
in the parent's model observation. It still follows Shell hooks and silence
settings. Hosts can observe activity via events and Shell runs; Py does not
archive complete nested model transcripts automatically.
 Programmatic and nested turns resolve names through their caller's
globals, with a separate scope for new bindings. Their Python objects are still
shared by reference. A root conversational turn writes to the console as usual.

Nesting is bounded by `py.config.max_turn_depth` (default 8). Independent
concurrent turns, manual compaction and closure are rejected rather than
queued. Hosts needing a queue should own that queue. Switching modes during
a nested turn is rejected.

From an active async turn, `py.gather` provides structured concurrency:

```python
quality, trends = await py.gather(
    py.request("Check data quality and return a list of issues", table=df),
    py.request("Find the main trends and return a summary", table=df),
)
```

`py.request` describes a programmatic call without starting it. Each branch
starts from the same replayable parent context with its own child scope. Model I/O runs concurrently,
but tool calls execute one at a time on the joining task, in the same Shell.
Results and outcome messages join in request order, regardless of completion
order. Live events can interleave and carry their branch session IDs.

If a branch fails, the batch cancels its siblings and waits for cleanup before
raising (`ExceptionGroup` for ordinary branch errors). A failed or cancelled
batch does not publish any branch outcomes. This is not a transaction: branch inputs
are shared Python references, and mutations already made are not undone.
Prefer read-only analyses or prepare independent inputs when results must not
depend on tool execution order. Use `py.gather`, not `asyncio.gather` or
`create_task` around `py(...)`; only the former coordinates tools and joins.

A Python cell holds the Shell even across an `await`: it must not wait for a
sibling's queued tool. When results depend on one another, use sequential
`await py(...)` calls instead. `py.gather(..., timeout=30)` optionally bounds
cooperative async waits in the batch (seconds); it raises `TimeoutError` after
cancelling and joining the branches. It cannot preempt blocking Python code.

## History, events and Python streams

Py adds stable Shell instructions to the Framework agent. A Framework provider
supplies the current execution mode, task, depth, and argument names as ephemeral
context. The canonical history remains a stable prefix across tool rounds; the
provider is refreshed each time and never persisted or sent for compaction.

Ordinary cells, including output and failures, become observations in the
Framework `Session`. Tool cells use its native tool call/output pairs instead.
Framework decides when to compact from the projected input, including newly
observed cells. Compaction changes model history, never the live namespace.
`py.session.context_usage` is Framework's last API-reported usage, not its local
compaction estimate. Inspect Framework lifecycle events via `py.agent.on(...)`.

```python
py.events.on("text.delta", lambda event: host.append_text(event.text))
py.events.on("tool.started", lambda event: host.show_activity(event.name))
```

Agent events never implicitly write to Python stdout/stderr. They carry
`session_id`, `parent_session_id` and `depth` for nested-turn correlation.
Python output stays on Pynteract's capture, display and stream hooks, including
the calling cell's silence policy. Printing a returned text is an explicit
Python action and is captured normally.

Async event handlers are awaited by the async agent API. Sync calls require
sync handlers. **`shell.cell.completed` always requires sync handlers**, even
under `shell.arun`.

Handlers run inline: their exceptions propagate to the caller. For rendering
outside the turn, the host can use `with py.events.buffer(max_events=256) as pending:`
and drain `pending` on the owning thread while it drives the session. The deque
drops the oldest events on overflow and is not an audit log.

Py subscribes via `Shell.observe_cells` without wrapping the host's
`post_run_hook`. A host can subscribe independently to see both ordinary and
tool cells. Py labels tool executions `py.tool` in the Shell's history and does
not re-import them as user context after reattaching. Its `shell.cell.completed`
event is only for cells recorded as live user observations; it includes
`cell_name` and `origin`.

For terminal presentation, `py-agent` binds `TerminalRenderer` around the native
async REPL. Embedded callers choose their own presentation; they may explicitly
attach `TerminalRenderer(output=..., errors=...)` to `py.events`.

## Drive a session from an async host

`LocalHost` is an opt-in, in-process adapter for a notebook, UI or service
loop that wants to submit work and handle cancellation separately. It borrows
the installed Py and its Shell:

```python
import asyncio
from pynteract import Shell
from pynteract_agent import LocalHost, install

async def main():
    with Shell() as shell:
        async with install(shell) as py:
            host = LocalHost(py)
            cell = host.submit_cell("values = [2, 4, 6]\\nsum(values)", filename="total")
            response = await cell.wait()
            assert response.result == 12

            turn = host.submit_ask("Summarize values")
            # A UI callback on this loop can call turn.cancel() while wait() runs.
            try:
                print(await turn.wait())
            except asyncio.CancelledError:
                if turn.status != "cancelled":
                    raise

asyncio.run(main())
```

Use `host.submit_call(prompt, **params)` for a native Python result. Each handle
has a host-local `id`, `status`, `done`, `cancel()` and `wait()`; `host.active`
is available to cell hooks and Py event handlers for correlation. Keep using
`Shell.observe_cells` and `py.events` for detailed activity. The adapter does
not queue work or route events: send all external operations for this session
through one host, on one event loop.

`cancel()` requests task cancellation, even when no Shell cell is executing.
It is cooperative: blocking Python may prevent timely cancellation and prior
mutations survive. Wait for the operation to finish before submitting another
or closing the borrowed resources. Cancelling just `wait()` (for example
through a timeout) does not cancel the underlying operation. A failed Python
cell still returns its `ShellResponse` (inspect `.exception`); a backend
failure raises. No transport, server or serialization is involved.

## Ownership and embedding

With Pynteract's namespace reset API, `reset_namespace()`, `restart_session()`
and `arestart_session()` restore the same `py` and `%py` / `%%py` bindings
before any startup script runs. Py keeps its configuration, clients and
subscribers, but starts a new model context and session ID. Past cells are
still in the Shell's bounded history; Py only imports cells from the current
namespace generation, even after reattaching. A cell that performs the reset
belongs to the generation in which it started. Reset is rejected before
mutation while an agent turn is active, even if no cell is running.

`set_namespace(new_dict)` also starts a fresh Py context when it installs a
different dictionary; it keeps the same Py instance and magic. The supplied
dictionary is still used by reference. A `py` key belonging to the host is
rejected before mutation; Py does not silently overwrite it. This behavior
requires Pynteract's namespace replacement guards.

`Py(shell=existing_shell)` borrows a Shell; `Py()` creates and owns one.
Both are context managers (`with` / `async with`). Closing detaches only Py's
own bindings and subscription (or legacy hook), leaving host replacements and borrowed resources intact.
A borrowed Shell can detach Py from its own cell and remains usable afterward.

Py uses one Framework Agent and backend per conversation. The Framework lazily
creates and authenticates the blocking and async SDK clients independently;
`py.client` and `py.async_client` expose them. Inject `client=` and/or
`async_client=` to borrow configured clients or offline doubles. Py delegates
cleanup to the Framework, which never closes injected clients. Once the async
client has been used, `await py.close()` on the same event loop. `with py`
selects blocking cleanup and `async with py` selects async cleanup.
A failed resource close may be retried on the already detached agent.

`py.agent` is the same Framework `Agent` between turns and during delegation.
`py.session` selects the current Framework `Session`; nested calls and `gather`
branches use isolated sessions via `Agent.subturn()`. `Py(session=...)` accepts
a root session directly. A Shell reset starts a fresh in-memory conversation
without modifying the previous session file.

Customize the agent and its shared tools with an `AgentSpec`:

```python
from pynteract_agent import install
from the_framework.agent import AgentSpec, CustomTool

def add_tools(agent):
    agent.add_tool(CustomTool.from_function(str.upper, name="uppercase"))

spec = AgentSpec(name="lab", configuration={"compaction": {"context_token_limit": 128_000}},
                 initializers=(add_tools,))
py = install(shell, spec=spec)
```

`py.config` covers Shell observation and Py call limits only. Model settings go
in the recipe; tools registered directly on `py.agent` affect that instance
only. Supply native backend clients at attachment time (`client=` /
`async_client=`); use `py.ask` / `py(...)` to run with Shell ownership and scope.

Py is not a sandbox, permissions layer, persistence service or transport.
In the Harness worker it must preserve the existing `agent` proxy. Remote event
transport, runtime deployment and a Pynteract package extra remain separate work.

## Development

Use the workspace root `.venv`; from this repository run
`../.venv/bin/python -m pytest`. Default tests block SDK authentication and HTTP
requests. The marked live scenario requires explicit `PY_AGENT_LIVE_TESTS=1`
and is excluded from ordinary offline verification.

Context adaptation restores the prototype's `await py.ask(...)` and
`await py(...)` spellings while retaining native synchronous script execution.
Failures are exceptions, not successful-looking error strings.

### Runtime boundary

`the_framework` runs model turns, decodes Responses events, records the tool
protocol, and compacts model context. Py binds those turns to Pynteract cells.
A child runs with its own Framework session, seeded from the parent's replayable
history. `py.gather` starts one model turn per branch and sends Python tool work
back to the task that owns the enclosing cell. Native parameters and results
stay in Python; children share object references, not mutable model history.
