Metadata-Version: 2.4
Name: rpa-bot-sdk-core
Version: 1.11.0
Summary: Orchestrator bot-side core: server client, pause/stop, logging, config loading. Shared by rpa-bot-sdk-performer and rpa-bot-sdk-dispatcher.
Author: Kasun Perera
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: pandas
Requires-Dist: openpyxl
Provides-Extra: sqlcipher
Requires-Dist: sqlcipher3; extra == "sqlcipher"
Requires-Dist: keyring; extra == "sqlcipher"
Provides-Extra: secure
Requires-Dist: cryptography; extra == "secure"
Provides-Extra: screenshot
Requires-Dist: pyautogui; extra == "screenshot"
Provides-Extra: brain
Requires-Dist: boto3; extra == "brain"
Requires-Dist: cryptography; extra == "brain"

# rpa-bot-sdk-core

The Orchestrator bot-side code shared by every role: `DbClient` (server auth,
queue, assets, storage, human-in-the-loop over HTTP, or a local SQLite queue
in StandaloneMode), `PauseController`/`checkpoint`, `start_command_listener`,
structured logging, `init_all_settings()` (Config.xlsx loader),
`take_screenshot()`, and the `safe_*` UI-action wrappers.

## Server-issued PAUSE/STOP actually reaching the bot

`PauseController`/`checkpoint()` are purely local — they only read/write an
in-process flag. Something still has to notice the server recorded a
PAUSE/RESUME/STOP and set/clear that flag; that something is
`start_command_listener()`, a daemon thread polling once a second. Call it
once, early in `main.py`, right after `db_client.register_run_token(...)`:

```python
from rpa_bot_sdk_core import start_command_listener

start_command_listener(db_client, pause_controller, run_label=run_id,
                       on_stop=lambda: setattr(ctx, "stop_requested", True))
```

Skip this and a bot that reaches a "PAUSE received, waiting for RESUME" wait
(see `rpa-bot-sdk-dispatcher`'s `DispatchState` / `rpa-bot-sdk-performer`'s
`GetTransactionState`) has nothing to wake it back up — it sits until
`MaxPauseDuration` elapses and auto-converts to STOP, even if the server's
own record was resumed within seconds. This is a straight port of the
"ASYNC PAUSE"/"ASYNC RESUME" listener thread pattern already proven in
production bots generated by `enterprise_patch.py`; a bot built directly
from `rpa-bot-sdk-dispatcher`/`-performer` needs this one explicit call to
get the same behaviour.

Neither a Performer nor a Dispatcher project installs this directly — it's
the shared dependency of [`rpa-bot-sdk-performer`](../performer/README.md)
and [`rpa-bot-sdk-dispatcher`](../dispatcher/README.md), pulled in
automatically by whichever of those two a project actually needs.

## Secure Cloud: `SecureDbClient` (1.4.0)

A `DbClient` that encrypts PHI with the project's Fernet key before it
leaves the machine, and decrypts it on the way back in. The server stores
only the ciphertext (`queue.json_data_secure`, `actions.form_data_secure`).

```python
from rpa_bot_sdk_core import SecureDbClient, PhiKeyError

try:
    client = SecureDbClient(base_url=url, api_key=key,
                            phi_key_path="data/phi.key",   # Config.xlsx PhiKeyPath
                            secure_fields="*")             # Config.xlsx SecureFields
except PhiKeyError as e:   # missing or not a Fernet key: do not start
    ...
logger.info(f"phi.key fingerprint {client.key_fingerprint}")
```

- `secure_fields="*"` encrypts the whole `json_data`; `"First Name,Email"`
  encrypts those keys only and keeps the rest plaintext, so the server can
  chart them.
- A fetched item whose ciphertext does not decrypt with this key is not
  dropped: its data carries `_phi_error`, and the Performer fails it.
- `key_fingerprint` names the key without revealing it. Every machine of
  one project must log the same one.

## A PAUSE that nobody resumes: `PauseController(max_pause_seconds=)` (1.6.0)

```python
pause_controller = PauseController(max_pause_seconds=int_setting(config, "MaxPauseDuration", 3600))
```

A checkpoint that has waited longer than `max_pause_seconds` stops the run
as a STOP would, and `pause_controller.stop_reason` says why. Without it a
paused checkpoint waits for RESUME however long it takes -- and the command
listener pauses the controller first, so `MaxPauseDuration` was never applied.
A PAUSE that arrives after a STOP no longer blocks.

## Whole-number settings: `int_setting()` (1.6.0)

`int_setting(config, "MaxRetries", 3)` -- a blank cell is the default, a 0
stays 0, and text raises `ValueError` naming the setting.
`config.get("MaxRetries") or 3` turned MaxRetries 0 into 3, and
`int(config.get(...))` crashed on a blank cell.

## The run token and its close (1.6.0)

The run token is 32 hex characters (it was 8, which collide). `close_run_token()`
returns whether the Orchestrator recorded the close and logs a refusal; a
close that never arrived (connection refused, no healthy node) is sent again.
A timeout is not resent: the Orchestrator may have closed the run and sent
its alert already.

## Keeping a log line on the machine: `LOCAL_ONLY`

`attach_proxy_handler()` forwards every log line at INFO and above to the
Orchestrator; DEBUG lines never leave the machine, since libraries log whole
request URLs at DEBUG (1.6.0). A line logged with `extra=LOCAL_ONLY` is
written to the local log and the console only -- for detail that can quote a
cell value, such as an exception message.

## Which exception text reaches the Orchestrator: `ReportableError` (1.4.0)

The SDK states store a failed item's exception text on the server and
forward their log lines. An exception raised in a bot's steps can quote what
it was working on, so `report_exception()` keeps the message only of a
`ReportableError` -- an error the bot wrote for the server, naming IDs,
settings or files, never a field value. Any other exception reaches the
server as its type name. Derive a bot's own exceptions from `ReportableError`.

## Logging an exception safely: `describe_error()` (1.7.0)

A log file outlives the run and is read on a shared bot machine, so a bot
should not write an exception's message even to its own log. `describe_error(error)`
gives its type, a `ReportableError`'s message, and the line of the bot's own
code it came from -- `ValueError at activities/process.py:225 in process` --
taken from the innermost traceback frame in a file under the bot's folder,
outside any installed package. `report_exception()` writes that line locally
instead of the message and traceback it wrote before 1.7.0.

## Checking a queue identifier: `identifier_problem()` (1.7.0)

`identifier_problem("Unique ID", value, 128)` says what is wrong with a Unique
ID or Reference -- empty, too long, a control character -- without repeating
the value, or returns `""` when it is usable.

## No exception text in the client's own log; the local queue's lock wait (1.8.0)

- The catch-all handlers of `DbClient.send_command` and of the StandaloneMode
  queue log the error's type only (`DbClient error on add_queue_item:
  TypeError`), never its message, which can quote a value. The reply still
  carries the message for the caller to decide on.
- `standalone_queue_args()` also returns `queue_db_timeout`, read from
  Config.xlsx `SQLiteTimeoutSeconds` (30 when blank or not 1 or more), and
  `DbClient`/`SecureDbClient` pass it to the local queue: each connection
  waits that long for the file's lock instead of a fixed 30 seconds.

## Bot Brain: `from rpa_bot_sdk_core import brain` (since 1.9.0)

Ask an AI model in Amazon Bedrock for a decision, for help with a System
exception, or for a web element that moved. Needs the extra:
`pip install "rpa-bot-sdk-core[brain]==1.11.0"` (boto3, cryptography) and
Orchestrator v22.0.0. Without the extra every call answers "unavailable".

```python
from rpa_bot_sdk_core import brain

brain.configure(client, config)          # the Performer does this for you
step = brain.decide("denial_next_step", facts={"carc": "CO-16"},
                    include_item=True, include_trail=True)
if step.answer is None:                  # off, unsure, unavailable, over_cap ...
    ...                                  # your own fallback

result = brain.decide_batch("era_line_action", rows=lines, key="line_id",
                            facts={"check_total": 12450.00}, include_trail=True)
for r in result.rows:                    # r.key, r.answer, r.confidence, r.decided_by
    ...

with brain.row("L001"):                  # steps and log lines inside go to that row's trail
    brain.step("Claim found, already posted 12 Oct")   # memory only, sent to Bedrock
brain.step("Opened claim in Charge Entry")

help = brain.exception_help(error)       # non-Performer bots; .remedy, .postpone_minutes
save = brain.locate(page, "#btnSave", describe="Save button on Charge Entry")
```

- **Never raises.** `decide`, `decide_batch` and `exception_help` return
  `answer`/`remedy` None with a `decided_by` (`off`, `unsure`, `too_large`,
  `unavailable`, `over_cap`, `limit`). `locate` raises only the original
  not-found error.
- **Patient data goes to Bedrock only**, from this machine. The Orchestrator
  gets names and numbers: the decision or exception type name, the answer,
  the confidence, who decided, tokens. The trail lives in memory and is
  cleared when the item ends. Healed locators stay in
  `data/brain/healed_locators.json`; the `LOCAL_ONLY` log line names only
  the element.
- **Config.xlsx:** `BotBrainPhiKeyPath` (blank = no person step; the phi.key
  that encrypts Bot Brain's Actions cards) and, Performer only,
  `BotBrainExceptionHelp` (`false` by default).
- **Item details in the trail:** A plain log line is forwarded to the Orchestrator and stored readable: put item details in `brain.step(...)`, or log them with `extra=LOCAL_ONLY`. The trail captures both.
- **Outside a Performer** (a Dispatcher, a hand-written bot), `brain.step`,
  `brain.row`, log capture and `include_trail` need an item: call
  `brain.begin_item(...)` when one transaction starts and `brain.end_item()`
  when it is done. The Performer does this for you.

```python
for txn in transactions:                 # outside a Performer: scope each item yourself
    brain.begin_item(txn["id"], txn["Unique ID"], data=txn)
    try:
        with brain.row(txn["line_id"]):
            brain.step("Claim found, already posted 12 Oct")
        result = brain.decide_batch("era_line_action", rows=lines, key="line_id",
                                    include_trail=True)
    finally:
        brain.end_item()                 # clears the trail
```

- **StandaloneMode:** Bot Brain is off. Print `brain.STANDALONE_WARNING`.

### A person answers without holding the machine (1.10.0)

When the AI is below the threshold and the bot has a phi.key, a person answers
on the Orchestrator's Actions page. By default (`BotBrainPersonWait` = `block`)
the call waits for that answer, up to 30 minutes, and the machine does nothing
else. With `BotBrainPersonWait` = `postpone`:

```python
step = brain.decide("denial_next_step", facts={"carc": "CO-16"}, include_trail=True)
if step.decided_by == "waiting":         # the card is open; step.action_id names it
    raise brain.WaitingForPerson(step, minutes=15)   # the Performer puts the item back
if step.answer is None:
    ...                                  # your own fallback
```

- The card is raised and the call returns at once with `decided_by` `"waiting"`.
  A Performer (1.8.0) puts the item back in the queue when a step raises
  `brain.WaitingForPerson`: not Successful, not Failed, no retry counted.
- When the item comes round again, the same call reads the card instead of
  asking the model again: the person's answer (`person`), still `waiting`, or
  `unsure` once the card is cancelled or expires (after 24 hours).
- `decide_batch` works the same way; its rows on the card are `waiting`.
- The card travels with the queue item, not the machine: the Performer keeps
  the item's answers in its json_data (`brain.CARDS_FIELD`) when it puts the
  item back, and passes them to `brain.begin_item(cards=...)` when any robot
  takes it again. They are names and numbers only -- the card's id, the AI's
  answer, confidences, row keys, tokens -- never an item value. A deleted item
  takes its cards with it.
- Once settled, an answer (the person's, or the AI's) stays with the item for
  its later passes, so a retry or a second wait gets the same answer without
  asking again. Call each decision name once per item.
- The usage record is sent once, when the card is settled. A card the
  Orchestrator cannot find for more than 25 hours is given up as `unsure`. A
  card made for an older decision version is withdrawn and asked again.
- Postpone needs a phi.key and an item whose host carries its cards (the
  Performer 1.8.0; `brain.begin_item(..., cards={})` elsewhere). Without a
  phi.key there is no person step. A call with no item to put back -- a
  Dispatcher, or a call outside an item -- asks nobody (1.10.1): its unsure
  answer is `unsure` and your own rule decides, so postpone never holds the
  machine (Bot Brain decisions; `brain.ask_person` ignores it), even with a
  Config.xlsx shared by both roles. Exception help's "Ask a person" still
  waits.

### Ask a person, and a second locator (1.11.0)

- `brain.ask_person(name, title, question, choices, ...)` puts a card in
  Actions. Inside an item whose host keeps its cards (the Performer, or
  `begin_item(cards=...)`) the item waits in the queue (`WaitingForPerson`);
  anywhere else the call waits on the machine for up to `wait_minutes`,
  whatever `BotBrainPersonWait` says. Row values go only in `secure_context`
  (encrypted with phi.key); the other fields are readable, so use the Unique
  ID only.
- In a Performer, the item's steps run again from the start on each pass
  until the card is answered. Set `BotBrainPersonWait` = `postpone` (with
  `BotBrainPhiKeyPath` set) so a Bot Brain decision made earlier in the item
  is kept (with `block`, it is asked again on each pass), and keep the steps
  before this call free of side effects.
- `brain.locate(page, locator, describe, fallback=None)` tries the locator, the
  stored heal, `fallback`, then the AI. With Playwright, once the fallback or
  a heal has found a moved element, later calls in the run wait for it
  together with the locator, so the 30-second wait is paid once; when nothing
  finds the element, every call still waits. `fallback` is never sent
  readable: it travels only inside the phi.key-encrypted heal record, which a
  bot with a phi.key sends to the Activity tab.

## Request timeout

`DbClient(timeout=15)` -- seconds to wait for one Orchestrator reply.
`QueueManager` reads it from Config.xlsx `OrchestratorTimeoutSeconds`.

Bump this package's version specifically when the server contract itself
changes (a `db_client.py` field/action). A change confined to one role's own
orchestration (e.g. `QueueManager`) belongs in that role's package instead.
