Metadata-Version: 2.4
Name: mru-sdk
Version: 0.1.0a2
Summary: Python job launch and hardware-independent robot sessions
License-Expression: Apache-2.0
Project-URL: Repository, https://github.com/Druzrka/mru-python-sdk
Project-URL: Changelog, https://github.com/Druzrka/mru-python-sdk/blob/main/CHANGELOG.md
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# MRU Python SDK

Write robot jobs using observations and named actuators. The job owns its policy,
models, and checkpoints; the robot agent owns physical execution and hardware
drivers. Python 3.11+; no runtime dependencies.

```text
Python job → MRU SDK → job session protocol → robot agent → drivers → robot
```

This repository implements a Python launch client, the runtime SDK, a Unix-socket transport, and an in-process
fake agent. It does **not** implement the platform scheduler, a production robot
agent, or hardware drivers. Observation and command traffic uses the job session
connection without going through a web backend.

## Install

The package is published on PyPI as `mru-sdk` and imported as `mru`. Current
releases are pre-releases, so allow them explicitly:

```sh
uv add mru-sdk --prerelease=allow
# or
pip install --pre mru-sdk
```

`mru-sdk` is separate from the `mru-cli` command-line tool; installing both is fine.

## Launch from Python

**The launch client targets a proposed API that still needs backend implementation.**
It is tested against a local HTTP fixture. It does not use the existing MRU
deployment API or CLI configuration, and it has no default production URL.
The concrete backend handoff is in [docs/launch-api.md](docs/launch-api.md).

```python
from mru import Client

client = Client.from_env()  # MRU_API_URL and MRU_API_TOKEN
job = client.launch(
    "job.py",
    robot_id="robot_123",
    dependencies=["numpy==2.1.0"],
    params={"target": 0.2},
)
print(job.id)
job.wait(timeout=300)
print(job.status)
```

Omit `robot_id` (or pass `None` or `""`) to let the backend select its default
robot. The SDK omits the field in those cases; the backend must support default
selection and still checks account access and robot capabilities.

`job.py` is uploaded and executed on MRU. It can use the `Job`/`run` interface
shown below. Only that file is included by default; add explicit supporting
files with `files=["policy.py", "assets/settings.json"]`. Paths are relative to
`source_dir`, which defaults to the entry point's parent. Model weights and large
datasets are separate from this source-only upload (8 MiB, 128 files maximum).

The launcher does not import your code or install dependencies locally. It returns
after the backend accepts the job; the remote job can continue after the submitting
process exits. `client.get_job(job_id)` reconnects, `job.refresh()` retrieves status,
`job.logs(after=cursor)` fetches a `LogPage`, and `job.cancel()` requests cancellation.
`job.status` is cached until refreshed; `job.details` holds the full job record from
the last response. `wait()` returns for completed, failed, or cancelled jobs; callers
inspect `status` and `details["error"]`. Timing out while waiting leaves the remote
job running.

```python
cursor = 0
while True:
    page = job.logs(after=cursor)
    for entry in page.entries:
        print(entry.stream, entry.message)
    cursor = page.cursor
    if not page.has_more:
        break
```

`Client(api_url=..., token=...)` accepts explicit account credentials. `client.me()`
checks them with the backend. Runtime credentials (`Auth` / `MRU_JOB_TOKEN`) are
separate and are supplied by the platform to the launched job. Nothing reads or
writes a saved CLI login.

Launch requests carry an idempotency key. Pass `request_id` to choose it; inspect
`job.request_id` after success or `LaunchError.request_id` if the outcome is unknown.
There is no automatic launch retry. Reuse the same key and unchanged files/options
after a lost response so the backend can return the original job.

See [examples/launch_job.py](examples/launch_job.py) for a submission script and
[examples/manage_job.py](examples/manage_job.py) to reconnect by job ID, follow
logs, and cancel.

## Run locally

```sh
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -e .
python examples/local_job.py
```

Alternatively, without installing: `PYTHONPATH=src python3 examples/local_job.py`.

```python
from mru import ActuatorRequirement, Job, Requirements, run
from mru.testing import FakeRobot

async def main(job: Job):
    async for observation in job.observations():
        # Your model can compute these positions. The SDK does not load models.
        await job.actuators["left_arm"].move(
            positions=(0.2, -0.2),
            duration_ms=100,
            observation_id=observation.id,
        )
        await job.complete()
        return

requirements = Requirements(
    sensors={"left_arm": "joint_state"},
    actuators={"left_arm": ActuatorRequirement(
        unit="rad", joints=("shoulder", "elbow"),
    )},
)

robot = FakeRobot(params={"task": "reach"})
run(main, session=robot.session(), requirements=requirements)
```

For a platform-managed job, use `run(main, requirements=requirements)`. The
platform supplies `MRU_SESSION_SOCKET`, a Unix socket connected to the assigned
agent or a runtime-side relay, and `MRU_JOB_TOKEN`, a job credential. Socket access control and the robot assignment
belong to the platform. A remote deployment needs a relay or an implementation
of `mru.transport.Transport` with authenticated, encrypted networking; no remote transport
is included. In an existing event loop, use
`await run_async(...)`.

## Runtime session authentication

Supply a platform-issued job token explicitly:

```python
from mru import Auth, run

auth = Auth.from_token(job_token)  # Obtained from the platform, not a password
run(main, auth=auth)
```

Or read the credential supplied to the runtime:

```python
run(main, auth=Auth.from_env())  # Reads MRU_JOB_TOKEN
```

When using the built-in platform connection, `run(main)` and `run_async(main)`
load `MRU_JOB_TOKEN` automatically and fail before connecting if it is missing or
malformed. An explicit `auth` argument takes precedence over the environment.
With a supplied session, credentials are passed explicitly; no environment token
is read. Lower-level callers use `await session.open(requirements, auth=auth)`.

The SDK sends the bearer credential only in the session handshake, separately
from job parameters and actuator commands. `Auth` hides the token in its ordinary
string representation; it is still sensitive data in memory and on the wire.
Never log or record handshake payloads. The SDK does not persist credentials.

`Auth.from_token()` constructs a credential; successful authentication occurs
when the agent accepts the handshake. The agent must validate the token, its
expiry/revocation, and its job/robot/action permissions before exposing data or
granting a lease. Missing or invalid credentials produce `AuthenticationError`;
insufficient permissions produce `AuthorizationError`. These are also subclasses
of `CommandRejected`.

**User registration, interactive login, token issuance/refresh, and production
agent verification are not implemented in this repository.** These require the
MRU platform service. Supplying a token does not by itself establish that a user
is registered or authorized. The SDK transports the credential; the agent must
enforce access even for callers that bypass the SDK.

For a local authentication test:

```python
robot = FakeRobot(required_token="local-test-token")
run(main, session=robot.session(), auth=Auth.from_token("local-test-token"))
```

The fake compares the supplied token before granting access; it does not implement
identity, scopes, expiration, or token issuance. `FakeRobot()` without
`required_token` remains available without login for local simulation.

## Author interface

| Piece | Interface |
| --- | --- |
| Launch client | `Client.from_env()`, `client.launch("job.py", robot_id=...)` |
| Remote job | `job.refresh()`, `job.wait()`, `job.logs()` → `LogPage`, `job.cancel()` |
| Job | `job.params`, `await job.complete()`, `await job.fail(reason)` |
| Observations | `async for observation in job.observations()` |
| Actuators | `job.actuators[name].spec`, `await handle.move(...)` |
| Session | `Session(transport, timeout=10, observation_buffer=16)` |
| Authentication | `Auth.from_token(token)`, `Auth.from_env()`, `run(main, auth=auth)` |
| Testing | `FakeRobot`, `load_recording`, `save_recording` |

Observations have a session-unique ID, an agent capture timestamp in Unix epoch
nanoseconds, named joint states, encoded images, and optional scalar readings.
Joint states declare joint order and units. Images contain encoded bytes and a
MIME encoding such as `image/jpeg`; the job handles decoding and preprocessing.
An observation timestamp describes the frame; this version does not represent
separate capture times for asynchronously sampled sensors. Agents must group
samples accordingly.

`move()` supports absolute joint positions only. Values follow `handle.spec.joints`
and use `handle.spec.unit` (for example, `rad` or `m`), without implicit unit
conversion. The message includes the command type and unit. The SDK validates
shape, finite values, and advertised limits; the agent must validate them again.
`duration_ms` is a positive integer. Every move needs an observation ID issued
in the same session. The agent decides whether that observation is fresh enough.

`move()` returns an `ExecutionAck` only when the agent reports execution finished,
not when the command is merely received or queued. Rejections raise
`CommandRejected` with a machine-readable `.code`. A timeout covers sending and
waiting for the acknowledgement, defaults to the session timeout, and can be
overridden per move. Allow enough time for execution and transport latency.
`DeadlineExceeded` means the outcome is uncertain: the SDK ends the session and
requests a stop. It never automatically retries physical commands.

There is one observation consumer per session. The bounded buffer drops the
oldest frames if the job falls behind, keeping recent data. This stream is not
a lossless recording facility. Finite recording exhaustion ends iteration;
returning from the job completes it.

## Lifecycle and cancellation

The session handshake checks requirements before the job callback runs. The
platform should also perform the same check before launching the runtime.
The agent grants at most one active job per robot and holds its lease until
connection teardown. Completion and failure stop execution. Returning normally
from `main` completes the job; an exception reports failure and propagates.

Platform cancellation interrupts SDK waits with `JobCancelled`, requests a stop,
and makes `run_async` cancel the job callback. Cancelling a command or observation
wait also ends the session and requests a stop. Teardown waits at most one second
(or the shorter session timeout) to send the best-effort stop. The SDK cannot
guarantee delivery over a broken connection or establish a physical safety state.
The agent must independently stop on connection loss, enforce its own watchdogs
and limits, and reject commands from revoked sessions. Cooperative asyncio
cancellation requires the job to yield; blocking inference should run outside
the event loop.

`job.logger` is Python's `mru.job` logger. Configure standard Python logging in
the job (for example, `logging.basicConfig(level=logging.INFO)`). The platform
collects process stdout/stderr and session lifecycle events. Logs need not travel
through the robot data connection.

## Keep configuration ownership separate

**Robot operator configuration** defines sensor names/types, actuator groups,
joint order, units, supported commands, limits, hardware mappings, and freshness
and watchdog policies. The handshake advertises capabilities, not driver details.
`RobotCapabilities` describes this advertised subset; it is not a hardware
configuration loader.

**Job author configuration** defines the Python entry point, dependencies,
`Requirements`, and task parameters. The platform installs dependencies and runs
the entry point, then supplies assigned parameters through the handshake as
`job.params`. Model settings and checkpoint locations are ordinary job-owned
parameters; the SDK neither interprets nor downloads them. This repository
uses the proposed launch manifest described in [the launch API contract](docs/launch-api.md).

## Fake robot and recordings

`FakeRobot()` emits joint feedback for a two-joint `left_arm`. It simulates
command duration, execution acknowledgements, capability checks, stale-data
rejection, exclusive access, and stop behavior. It is a protocol test double,
not a physics simulator or proof of hardware safety. Only one command per
actuator may execute at a time; concurrent commands to that actuator are rejected.

Use `FakeRobot(capabilities=..., observations=..., params=...)` for another setup.
Recorded frames are emitted every `interval` seconds (default 0.02), preserving
their IDs and timestamps. IDs must be unique. Replay freshness uses local emission
time, allowing old recordings to be used; it does not compare recorded wall-clock
timestamps to the current clock. The fake retains the latest 256 observation IDs
and defaults to a 0.5-second freshness window. Generated feedback updates after
execution; replayed observations remain as recorded.

```python
from mru.testing import FakeRobot, load_recording, save_recording

save_recording("observations.jsonl", observations)
robot = FakeRobot(observations=load_recording("observations.jsonl"))
```

`await robot.cancel(reason)` simulates platform cancellation, and
`await robot.disconnect()` simulates connection loss. Inspect `robot.commands`
for completed executions and `robot.status` for lifecycle state.

## Examples

| Example | Shows | Needs a backend |
| --- | --- | --- |
| [local_job.py](examples/local_job.py) | A minimal job against the fake robot | No |
| [replay_recording.py](examples/replay_recording.py) | Saving observations and replaying them through `FakeRobot` | No |
| [local_cancellation.py](examples/local_cancellation.py) | How a job sees platform cancellation (`JobCancelled`) | No |
| [launch_job.py](examples/launch_job.py) | Uploading source and launching a job | Yes |
| [manage_job.py](examples/manage_job.py) | Reconnecting by job ID, following logs, cancelling | Yes |

The test suite runs every example; the backend-dependent ones run against a
local HTTP fixture.

## Known V1 limits

- **One active job per robot.** The agent grants one lease at a time; a second
  job waits in the platform queue or is rejected with `robot_busy`.
- **Absolute joint positions only.** `move()` sends `joint_position` commands in
  the actuator's declared joint order and unit. No velocity, torque, Cartesian,
  gripper-specific, or trajectory commands; no unit conversion.
- **Joint states, encoded images, and scalar readings only.** Images arrive as
  encoded bytes (for example JPEG); the job decodes them. Each observation has one
  capture timestamp; there are no per-sensor timestamps.
- **One observation consumer per session**, with a bounded, lossy buffer that keeps
  the most recent frames. It is not a recording facility.
- **One command at a time per actuator.** Concurrent moves on the same actuator are
  rejected, not queued.
- **No automatic retries.** Neither launches nor physical commands are retried
  when the outcome is uncertain.
- **Unix-socket transport only.** Remote connections need a platform relay or a
  custom `Transport` with authenticated, encrypted networking.
- **Source-only uploads:** at most 128 files and 8 MiB. Model weights and datasets
  are fetched by the job itself.
- **The launch client needs a backend** implementing [mru.python-job/v1](docs/launch-api.md);
  none is deployed yet.
- **`FakeRobot` is a behavioral test double**, not a physics or safety simulator.

## Versioning

The package uses semantic versioning; the launch API and job session protocol
are versioned separately. See [compatibility and versioning](docs/compatibility.md)
and the [changelog](CHANGELOG.md). The package ships type information (`py.typed`).
Shared launch-contract fixtures for backend tests are in [contracts/launch-v1](contracts/launch-v1/README.md).
Maintainers: see [releasing](docs/releasing.md).

## Development

Use Python 3.11 or newer:

```sh
PYTHONPATH=src python3.12 -m unittest discover -s tests -v
uvx mypy   # or: pip install mypy && mypy; strict settings are in pyproject.toml
```

The suite includes a real local Unix-socket round trip and requires permission
to bind a temporary socket. See [the protocol contract](docs/protocol.md) to
implement an agent or a transport.

## License

Apache License 2.0. See [LICENSE](LICENSE).
