Metadata-Version: 2.4
Name: visus-sdk-runpilot
Version: 0.3.0
Summary: In-process Python SDK for the RunPilot RPA orchestrator (the client bots use to talk back to the server).
Author-email: Matheus Pereira <matheuszwilkdev@gmail.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/botvisus/visus-sdk-runpilot
Project-URL: Repository, https://github.com/botvisus/visus-sdk-runpilot.git
Project-URL: Documentation, https://github.com/botvisus/visus-sdk-runpilot#readme
Project-URL: Bug Tracker, https://github.com/botvisus/visus-sdk-runpilot/issues
Keywords: rpa,orchestrator,automation,runpilot,sdk,bot,workflow
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Office/Business
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: requests>=2.32.3
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Dynamic: license-file

# runpilot — Python SDK

In-process Python SDK ([source](https://github.com/botvisus/visus-sdk-runpilot)) for the
RunPilot RPA orchestrator of [BotVisus](https://botvisus.com). This is the library your bot imports to talk back to the RunPilot
server from *inside* a run: report progress, stream logs, fetch credentials,
upload artifacts, poll interrupt/kill signals, pull DataPool items and call the
integrations released to the task (Google Sheets, Gmail, Drive, Jira, WhatsApp, ...).

Think of it as the runtime bridge between an RPA script and the orchestrator that
scheduled it. The runner injects the connection details as environment variables;
the SDK reads them and gives you a single `Orchestrator` object.

## Installation

```sh
pip install visus-sdk-runpilot
```

The package is published as `visus-sdk-runpilot`; you import it as `runpilot`.

Requires Python 3.9+. The only runtime dependency is `requests` (2.32.3+).

## Quick start

Inside a run, build the client from the environment the runner injected:

```python
from runpilot import Orchestrator

bot = Orchestrator.from_env()          # reads RUNPILOT_SERVER + run token / api key

ctx = bot.get_run()                    # the run + task context
bot.report_progress(10, "starting")

api_key = bot.get_credential("stripe", "SECRET_KEY")

pool = bot.datapool("invoices")        # claim-and-report DataPool items
while (item := pool.next_item()) is not None:
    process(item.data)
    item.report_done()                 # or item.report_error(business=True, message=...)

art = bot.upload_artifact("out/report.pdf")

signals = bot.get_signals()            # cooperative interrupt / kill
if signals.kill_requested or signals.interrupt_requested:
    bot.finish("failure", "interrupted")
    raise SystemExit(0)

bot.finish("success", "processed 42 rows")   # canonical: success | failure
```

### Environment variables

`Orchestrator.from_env()` reads:

| Variable | Purpose |
|----------|---------|
| `RUNPILOT_SERVER` | Base URL of the orchestrator (no path). Required with a run token; with only an API key it defaults to `https://botvisus.com` (with a one-time warning) |
| `RUNPILOT_RUN_TOKEN` | Per-run token (RUN_TOKEN mode — the in-run path) |
| `RUNPILOT_RUN_ID` | Run ID that accompanies the run token |
| `RUNPILOT_API_KEY` | Organization API key (management mode) |

RUN_TOKEN mode is what you get inside a run; the in-run methods
(`report_progress`, `get_credential`, `datapool`, `upload_artifact`, `finish`, …)
require it.

`RUNPILOT_SERVER` has no default in RUN_TOKEN mode: `from_env()` raises
`ConfigurationError` and `try_from_env()` returns `None` without it, so a run token from a
self-hosted orchestrator is never sent to the SaaS by mistake. With only `RUNPILOT_API_KEY`,
a missing `RUNPILOT_SERVER` means the BotVisus SaaS (`https://botvisus.com`), and the SDK
logs `RUNPILOT_SERVER not set; using https://botvisus.com` once.

> **Self-hosted orchestrator: always set `RUNPILOT_SERVER`.** In API-key mode a missing
> `RUNPILOT_SERVER` sends your API key to `botvisus.com`, not to your own server.

## Integrations

An integration is a connection (Google Sheets, Gmail, Outlook, SMTP, Google Drive,
SharePoint/OneDrive, Jira, Slack, Teams, WhatsApp, webhooks, ...) set up in the orchestrator
and released to the task. The orchestrator runs the action with the connection's
credential, which never reaches the bot: the SDK only sends the input and gets the result
back. Integrations need the run token (inside a run); `integration()` raises
`AuthModeError` with only an API key.

```python
sheets = bot.integration("sales-sheet")     # the connection's reference
sheets.call("append_rows", spreadsheetId="1AbC", range="A1", values=[["x", 1]])

rows = sheets.call("read_range", spreadsheetId="1AbC", range="A1:C10")
```

- **Parameter names go exactly as the action defines them** (camelCase, the same names the
  Studio shows): `spreadsheetId`, `artifactIds`, `fileId`. Nothing is converted, so a typo
  fails with `IntegrationInvalidInputError` instead of being sent under another name.
- For a key that is not a Python identifier, pass a dict instead of keyword arguments
  (not both): `bot.integration("mail").call("send", {"from": "ops@example.com", ...})`.
- The dict goes **positionally**: `call("send", {...})`. `call("send", input={...})` does not
  pass the dict; it sends one parameter named `input`.
- `describe()` returns the connection's provider and, per action, whether it is read-only
  and how long the SDK waits for it. It is read once per reference; a failed read is
  remembered for about 60 s (calls in that window do not read again).

### Errors

Every SDK error derives from `RunPilotError`. An integration failure raises a subclass of
`IntegrationError` (itself an `ApiError`), with two exceptions that are `ApiError` but not
`IntegrationError`: `RunTerminalError` (the run is already finished) and
`AuthenticationError` (the run token was rejected). So `except ApiError` catches every failure
of `call()`, `describe()` and `upload_file()`. `download_file()` can also raise
`FileNotFoundError` / `NotADirectoryError` (the destination folder) and `OSError` (writing
the file). Each `IntegrationError` has `ref`, `action`, `code`, `status_code`, `hint` (the
server's message, cleaned and with secrets masked; informative only) and `outcome_unknown`.

| Exception | Code (HTTP) | When |
|-----------|-------------|------|
| `IntegrationNotFoundError` | `not_found` (404) | No such connection here, or not released to this task |
| `IntegrationNotAllowedError` | `not_allowed` (403) | The connection was not released to this task |
| `IntegrationForbiddenError` | `forbidden` (403) | The connection may not do this operation |
| `IntegrationDisabledError` | `disabled` (403) | The connection is turned off |
| `IntegrationInvalidInputError` | `invalid_input` (400) | The input does not match the action (or was refused before sending) |
| `IntegrationUnknownActionError` | `unknown_action` (400) | The provider has no such action |
| `IntegrationRateLimitedError` | `rate_limited` (429) | The service throttled the calls (never retried automatically) |
| `IntegrationTimeoutError` | `timeout` (504), `client_timeout` | The service, or the wait for the answer, took too long |
| `IntegrationAuthError` | `auth` (502) | The *service* rejected the connection's credential |
| `IntegrationUpstreamError` | `upstream` (502), `bad_response` | The service failed, or the answer was not what was expected |
| `IntegrationAbortedError` | `aborted` (499) | The call was cancelled before it finished |
| `IntegrationResponseTooLargeError` | `response_too_large` | The answer is larger than 16 MiB |
| `IntegrationConnectionError` | `connection_error` | The orchestrator could not be reached, or the connection dropped |
| `RunTerminalError` | `run_finished` (409) | The run is already finished |
| `AuthenticationError` | (401) | The run token was rejected |

`IntegrationNotAllowedError`, `IntegrationForbiddenError` and `IntegrationDisabledError` share
the base `IntegrationPermissionError`.

**`outcome_unknown = True` means the action may have run on the other side** (a timeout, a
dropped connection after the request went out, a failure of the service halfway, any 5xx
answer without an integration code). For an
action that changes data (sends an email, appends rows, uploads a file), **check the target
before calling it again**: calling blindly may send it twice. It is always `False` for a
read-only action and when the request surely never left.

### Partial sends: `PartialResult`

A send to several recipients that stopped partway (a failure or the deadline in the middle)
does not raise: the orchestrator answers with what went out, and the SDK returns a
`PartialResult` instead of the plain result. **Never resend a partial send**: the items that
went out would go out twice. Check `not_sent` and `unconfirmed`, then decide.

```python
from runpilot import PartialResult

out = bot.integration("mail").call("send_email", to=["a@example.com", "b@example.com"], subject="Hi", text="...")
if isinstance(out, PartialResult):
    bot.log("warning", f"{out.not_sent} not sent ({out.unconfirmed} may have gone out), code {out.error_code}")
```

`PartialResult` has `not_sent`, `unconfirmed`, `error_code`, `sent` and `ids` (when present),
`complete` (always `False`) and `raw` (the result as the orchestrator sent it). The result
shapes are:

| Provider | Complete result | Partial result (`raw`) |
|----------|-----------------|------------------------|
| Gmail | `{id}`, or `{ids}` when each recipient gets their own email | `{ids, notSent, unconfirmed, errorCode}` |
| Outlook | `{sent}` | `{sent, notSent, unconfirmed, errorCode}` |
| SMTP | `{sent, refused}` | `{sent, notSent, unconfirmed, errorCode}` |
| WhatsApp | `{sent, ids}`; the ids are opaque references (`wa_...`), never the phone number | `{sent, ids, notSent, unconfirmed, errorCode}` (no `errorCode` when WhatsApp only held messages) |
| Jira | `{key}` (new issue), `{id}` (comment) | (not a multi-send) |

A result is partial when it is a dict whose `notSent` is a number greater than 0.

### Retries, deadlines and limits

- **An action that changes data is sent once and never retried**, whatever happens (the
  same holds when the SDK could not read whether the action is read-only).
- **A read-only action** is retried (3 attempts, waiting 0.5 s and 1.5 s) only when the
  connection never opened, dropped without an answer, or a proxy answered 502/503/504
  without an integration error code. Never after a timeout, never on a 429 and never on an
  answer that carries a code.
- **Deadline per action.** The SDK reads, once per reference, how long each action may take
  on the orchestrator and waits that long plus 15 s (for example 105 s for an email send).
  That total deadline runs from the moment the request starts: sending it, waiting for the
  headers and reading the body all count, so a server that answers one byte at a time cannot
  hold the bot beyond it. Opening the connection (DNS, the TCP connect to each address and
  the TLS handshake) is limited by the 10 s connect timeout of each step, not by the total
  deadline. When the connection cannot be read (an older orchestrator, a network failure),
  the SDK waits up to 135 s and does not retry.
- **Through a SOCKS proxy** (`socks5://`, which needs PySocks), only the body is under the
  total deadline; the earlier phases are limited by the connect timeout and by the wait for
  each read. This is a known limit: a slow proxy can make a call last longer, but nothing
  leaks and nothing is resent.
- **Request body up to 5 MiB**, checked before any network; for files, use the shortcuts
  below (the file goes as a run artifact, never inline).
- **Answer up to 16 MiB**, read in pieces (a 10 MiB download is about 14 MB in base64).
  Above it: `IntegrationResponseTooLargeError`.
- **A credential revealed by `get_credential()` never goes back in an input.** For an action
  that changes data (or whose read-only flag is unknown), an input that contains one (in a
  value or a key) raises `IntegrationInvalidInputError` before the action is sent: "The input
  contains a value revealed by get_credential; it would be sent masked. Remove it or pass it
  explicitly via a non-revealed source." Sending it with `***` in place of the value would
  send the wrong email, row or file. For a read-only action the value is replaced by `***`
  and one warning is logged.
- The run token never shows in an error, a `repr` or a log.

### File shortcuts (Google Drive, SharePoint/OneDrive)

The `google-drive` and `microsoft-files` connections have two shortcuts:

```python
drive = bot.integration("team-drive")

# download: writes the file into the folder and returns a DownloadedFile
f = drive.download_file("downloads", fileId="1XyZ")           # SharePoint: path="Reports/sales.pdf"
print(f.path, f.size, f.mime_type)

# upload: sends the local file as a run artifact, then the action with its artifactId
drive.upload_file("out/report.csv", folderId="1FoLdEr")        # SharePoint: path="Reports/report.csv"
```

- **The file name the service sends is untrusted** (whoever uploaded the file chose it, and
  it may contain `/`, `..`, a Windows device name or invisible characters).
  `download_file` sanitizes it and writes the file **directly inside** the destination
  folder (which must exist). It never overwrites an existing file (it uses `name (1).ext`
  instead, unless `overwrite=True`) and never follows a link already there.
- `DownloadedFile` has `path`, `name` (the sanitized name), `original_name` (the name as
  sent: for information only, never use it as a path), `mime_type` and `size`.
- `upload_file` sets `artifactId` itself: do not pass it. The upload is an action that
  changes data, so it is never retried.
- The providers take files of at most 20 MiB. `upload_file` reads the whole file into
  memory to upload it, and the run artifact stays on the run even when the action then
  fails (for example a full folder or a refused path).
- For anything else on these connections (`list_files`, ...), use `call()`.

### AI agent integrations (Composio, Parallel, your own MCP server)

These connections use the same generic `call()`; there are no extra methods.

**Composio and MCP server.** An admin discovers the service's tools in the orchestrator and
chooses which ones the connection allows (each has a short name and is either read-only or a
change). The bot runs one with `call_tool`, naming the tool by its remote name:

```python
github = bot.integration("github-tools")
issue = github.call(
    "call_tool",
    tool="GITHUB_CREATE_AN_ISSUE",
    arguments={"owner": "acme", "repo": "app", "title": "Bug"},
)

allowed = github.call("list_tools")          # the allowed tools; no call to the service
```

- `call_tool` counts as a change: it is **never retried**. `read_tool` runs only a tool the
  admin marked read-only, and is retried like any read.
- A tool that is not on the allowed list fails with `IntegrationInvalidInputError` before
  anything is sent. The result is the service's answer as data (for an MCP server:
  `{"isError", "text", "structured", "omitted"}`; for Composio: `{"successful", "data", "error"}`).
  A tool that reports its own failure still returns normally, so check those fields.

**Parallel** searches the public web and runs research tasks, within the processors and daily
limits the admin set on the connection:

```python
from runpilot.exceptions import IntegrationNotFoundError

research = bot.integration("research")
found = research.call("search", queries=["botvisus rpa"], objective="Who makes BotVisus?")

run = research.call("create_task", input="Summarize what BotVisus does.", processor="lite")
try:
    while True:
        task = research.call("get_task", runId=run["runId"], waitSeconds=30)
        if task["status"] == "completed":
            print(task["output"]["content"])
            break
except IntegrationNotFoundError:
    # Parallel answers "not found" for a task that failed (or a run id it does not know)
    print("The research task failed.")
```

- `create_task` costs money and is **never retried**. `get_task` waits up to `waitSeconds`
  (at most 60) and answers `"running"` while the task is still going: call it again.
- A task that **failed** makes `get_task` raise `IntegrationNotFoundError` (Parallel answers
  "not found" for a failed run and for an unknown run id), so the polling loop above catches it
  instead of polling forever.
- A daily limit that is used up fails with `IntegrationRateLimitedError`; a processor the
  connection does not allow fails with `IntegrationInvalidInputError`, with nothing sent.

## Security and reliability

- **https only.** The token goes in the `Authorization` header, so `RUNPILOT_SERVER`
  must be `https://…`. Plain `http` is accepted only for this computer (`localhost`,
  `127.0.0.1`, `::1`) — or `host.docker.internal` with `RUNPILOT_DEV=1`, which is how a
  runner machine reaches a local orchestrator in development.
- **Downloaded files carry no Mark-of-the-Web.** A file saved from an integration (for
  example a Google Drive or SharePoint download) is written as plain bytes: Windows will not
  flag it as "from the internet", so SmartScreen and Office's Protected View do not kick in.
  Its name is sanitized, but its content is whatever the uploader put there — treat
  executables, scripts and macro-enabled documents with care and never run them blindly.
- **Credentials never come back.** Every value revealed by `get_credential()` is replaced
  by `***` in everything the SDK sends — logs, errors and tracebacks, steps, alerts and
  progress. (Values shorter than 4 characters are not masked.)
- **Network blips don't kill the bot.** Reads (GET) are retried on connection errors,
  timeouts and 502/503/504 (3 attempts, waiting 0.5 s and 1.5 s). Writes (POST) are retried
  only when the request surely never reached the server (the connection never opened, or
  503) — so a slow answer never duplicates a step, log, alert or DataPool report. Real errors
  (4xx) are not retried, and neither is claiming a DataPool item.
- **Plain http on a trusted local network** needs an explicit `RUNPILOT_ALLOW_HTTP=1`.
- **`best_effort=True`** makes `log()`, `report_progress()`, `alert()` and `step()` only
  warn on a failure (and, after a network failure, skip reporting for 30 s instead of waiting
  on every call), so a reporting problem never stops the automation — `finish()` included:
  `Orchestrator(server, run_token=..., best_effort=True)`.
- **Light screenshots.** With Pillow installed, step screenshots wider than 1920 px are
  scaled down and sent as JPEG; one over 20 MB is dropped (the step is still reported).
- **Threads.** Each thread gets its own HTTP connection.
- **Your `session=`.** The SDK's own calls use the session you pass. Integration calls use a
  session the SDK owns (it never resends an action): from yours, only `verify`, `cert`,
  `proxies` and `trust_env` are copied. Adapters mounted on your session (custom retries,
  certificate pinning, an mTLS `SSLContext`) are not used for integrations.
- **`.netrc` never replaces the token.** The `Authorization: Bearer` header is set as the
  request's auth, so a `.netrc` entry for the orchestrator's host is not used.

## Testing your bot — fully offline

`Orchestrator.mock()` returns a client that never performs a network request.
Every in-run call is recorded on `.calls` and returns a sensible canned value, so
you can unit-test a bot without a live server:

```python
from runpilot import Orchestrator

bot = Orchestrator.mock(
    run={"run": {"id": "run_1"}, "task": {"name": "demo"}},
    credentials={("stripe", "SECRET_KEY"): "sk_test_123"},
    datapool={"invoices": [{"id": "inv_1", "data": {"amount": 10}}]},
)

bot.report_progress(50, "halfway")
assert bot.get_credential("stripe", "SECRET_KEY") == "sk_test_123"
assert bot.calls[-1]["method"] == "get_credential"
```

Integration calls are mocked with `integrations={(ref, action): answer}`. The answer is the
result to return, an exception (instance or class) to raise, or a function that receives the
input dict. A call with no entry returns `{}`, and each call is recorded on `.calls` as
`{"method": "integration_call", "ref", "action", "input"}`:

```python
from runpilot import IntegrationRateLimitedError, Orchestrator

bot = Orchestrator.mock(
    integrations={
        ("sales-sheet", "append_rows"): {"updatedRows": 1},
        ("mail", "send_email"): IntegrationRateLimitedError,
        ("crm", "lookup"): lambda data: {"found": data["email"].endswith("@example.com")},
    }
)

assert bot.integration("sales-sheet").call("append_rows", values=[[1]]) == {"updatedRows": 1}
assert bot.calls[-1]["action"] == "append_rows"
```

## API surface

`from runpilot import ...`

| Export | What it is |
|--------|-----------|
| `Orchestrator` | The client. `from_env()`, `mock()`, `get_run()`, `report_progress()`, `log()`, `get_credential()`, `upload_artifact()`, `get_signals()`, `datapool()`, `integration()`, `finish()` |
| `Integration` | One connection: `call()`, `describe()`, `download_file()`, `upload_file()` |
| `IntegrationInfo`, `PartialResult`, `DownloadedFile` | What `describe()`, a partial send and `download_file()` return |
| `DataPool`, `DataPoolItem` | Claim-and-report work queue; `pool.next_item()`, then `item.report_done()` / `item.report_error()` |
| `Run`, `RunContext`, `Task`, `Artifact`, `Signals` | Typed models returned by the client |
| `RunPilotError` and subclasses | `ConfigurationError`, `AuthModeError`, `AuthenticationError`, `NotFoundError`, `ApiError`, `RunAlreadyFinishedError`, `RunTerminalError`, `IntegrationError` and its subclasses (see [Errors](#errors)) |

## License

Apache-2.0 (see `LICENSE` and `NOTICE`).
