Metadata-Version: 2.4
Name: anydeck-sdk
Version: 0.0.1
Summary: Build your own action sources for Anydeck.
Author: crljn.labs
License-Expression: LicenseRef-PolyForm-Strict-1.0.0-with-Extension-Permission
Project-URL: Homepage, https://crljnlabs.com/en/anydeck/
Keywords: anydeck,macropad,stream deck,automation,sdk,extension
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Home Automation
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.14
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.28
Dynamic: license-file

# anydeck-sdk

Build your own action source for [Anydeck](https://github.com/crljnlabs/anydeck):
a new set of actions for its keys and flows, a connection to a service, values
and elements for its displays.

Anydeck's own sources (Home Assistant, OBS, webhooks, the keyboard, ...) are
built on exactly this package. There is no second, private API: what they use,
you can use.

> **Status:** 0.1.0, not on PyPI yet. Needs Python 3.14, the Python Anydeck
> runs on. An extension is installed by double clicking its file or dropping
> it under Settings → Extensions.

## Licence

PolyForm Strict 1.0.0 with an Extension Permission ([LICENSE](LICENSE)):
anyone may use the SDK to build extensions and pass them on, commercially
too, under the licence they choose; the SDK's own code may not be copied,
changed or passed on as an SDK of one's own.

## What you write

An action source is a class that lists its **features** - the areas it covers.
Each feature is a class you extend:

| Feature | What it is for |
|---|---|
| `features.Action` | what the source can be told to do: its actions and `run()` |
| `features.Connector` | what it takes to reach one instance: fields, stored safely |
| `features.CredentialsConnector` | a connector set up by typing credentials in, tried before they are kept |
| `features.Api` | talking to the instance over HTTP |
| `features.Settings` | what the person sets, for the whole source or one connection |
| `features.Display` | elements the source puts on displays |

A source needs only the features it uses. A dice needs no connection:

```python
import random

from anydeck_sdk import ActionDefinition, ActionField, ActionSource, Choice, Return, features


class DiceActions(features.Action):
    definitions = (
        ActionDefinition(
            name="roll",
            fields=(ActionField("sides", Choice(options=("6", "20")), default="6"),),
            returns=(Return("number", "number"),),
        ),
    )

    def run(self, action, params, variables, context):
        return {"number": random.randint(1, int(params["sides"]))}


class DiceSource(ActionSource):
    action_source = "dice"   # its id
    tag = "os"               # where it is listed: "os", "application" or "service"
    instantiable = False     # there is exactly one; nothing to connect
    provides = (DiceActions,)
```

## A source with a connection

```python
from anydeck_sdk import (
    HTTP_BASE_URL, ActionDefinition, ActionError, ActionField, ActionSource,
    ClientParams, ConnectorField, Text, features,
)


class HueConnector(features.CredentialsConnector):
    fields = (
        ConnectorField("address", Text(pattern=HTTP_BASE_URL), secret=False),
        ConnectorField("token"),             # secret unless it says otherwise
    )


class HueApi(features.Api):
    def client_params(self, configuration):
        return ClientParams(
            base_url=configuration["address"],
            headers={"Authorization": f"Bearer {configuration['token']}"},
        )

    def test_connection(self, configuration):
        # Called by "Connect" before anything is kept. Raise to refuse.
        with self.client("test", configuration) as api:
            self.call(lambda: api.get("lights"))


class HueActions(features.Action):
    definitions = (
        ActionDefinition(name="on", fields=(ActionField("light", Text()),)),
    )

    def run(self, action, params, variables, context):
        hue = self.features.api
        with hue.client("switch-on") as api:
            answer = hue.call(lambda: api.put(f"lights/{params['light']}", json={"on": True})).json()
        if not answer.get("success"):
            raise ActionError(self.tracking, f"{params['light']} did not switch on: {answer}",
                              user_message="The light did not switch on.")
        return {}


class HueSource(ActionSource):
    action_source = "hue"
    tag = "service"
    provides = (HueConnector, HueApi, HueActions)
```

Every feature reaches the others of its source through `self.features`:
`self.features.connector`, `self.features.api`, or `self.features.of(HueApi)`
for your own class with its own methods.

`self.features.connector.load_configuration()` gives the stored fields of this
instance - secrets included - as one dict. Anydeck stores them: secret fields
encrypted, with the key in the system's credential store.

## Fields

What a form asks for. A field is the slot (`ActionField` in an action,
`ConnectorField` in a connection or a setting); its kind is what goes in it:

| Kind | The control |
|---|---|
| `Text` | a line of text - `pattern=`, `multiline=` |
| `Number` | a number - `minimum=`, `maximum=` |
| `Choice` | pick from `options` |
| `Checkbox` | on or off |
| `PathInput` | a file or folder on this computer |
| `Media` | files from Anydeck's media folder |
| `KeyCombo` | a key combination, recorded by pressing it |
| `JsonArea`, `Items`, `Markdown`, `Button`, `ApiList`, `VariableRef`, ... | see `anydeck_sdk.fields` |

`Container(fields, when=When(...))` shows a group of fields only for some
values of another. Anydeck checks every value against its field before
`run()` is called, so `run()` only ever gets values that fit.

`ActionField("operation", Choice(options=("up", "down")), by_turn=("down", "up"))`
names the option for a knob turned left and turned right: a person who puts
the action on a turn to the left finds "down" already chosen.

### What Anydeck does for you

You get these for every field, without writing anything:

- **`{{ }}`** - a person can type `{{ room }}` into a field. Anydeck puts the
  variable's value in before `run()`; you get `"Kitchen"`. Turn it off for a
  field with `allow_reference=False`.
- **Rules** - a person can choose a field's value by conditions ("above 100:
  bright, otherwise normal"). Anydeck works them out before `run()`.
- **Checking** - required fields filled in, numbers in range, choices on the
  list. A value that does not fit stops the run with a clear message.
- **Secrets in returns** - `Return("token", secret=True)` is masked in every
  log.

## Returns and variables

`returns` says what `run()` answers with, so the next nodes of a flow can use
it: `Return("state")`, `Return("brightness", "number")`, and objects and lists
with `fields=` and `items=`. Types are `text`, `number`, `bool`, `list`,
`object`.

`variables.get("room")` reads a variable of the flow; `creates=` declares the
ones `run()` adds with `variables.add(...)`.

## When it goes wrong

Raise `ActionError(self.tracking, "what happened, for the log",
user_message="what to tell the person")`. It is recorded where it happened
and shown to the person - nothing else to do.

## The log of a run

`self.tracking` is the log of what is being done now. Your editor lists its
methods: `note()` for a line, `step("name")` to label what follows,
`conceal(value)` to mask a value from then on. Calls made through
`features.Api` are recorded by themselves, with their answers.

## What it did, in a sentence

The history of runs shows a sentence for each action - "Rolled: [4, 2]." -
and folds the raw answer away under it. Your action says it through the
log, when it has done it:

```python
numbers = [random.randint(1, sides) for _ in range(count)]
self.tracking.say("zufall.summary.roll", {"numbers": shown(numbers)})
```

- `say(key, values)` is one sentence: a translation key of yours and the
  values that go into it. Say more than one where it helps - "3 files
  copied", then "2 skipped". What was said before an error stays in the
  history beside the error.
- `show(value, key)` puts a value under the sentences - the whole list after
  adding to it - with a heading by translation key.
- `shown(value)` puts a value into a sentence: short, and text in quotes, so
  "3" and 3 can be told apart. Anydeck masks a secret in it before cutting
  it short.

An action that says nothing shows its raw answer, as before.

## Values for {{ }}

`features.Values` keeps values a person can use anywhere a `{{ }}` goes - a
field, a flow's condition, a display: `{{ dice.last }}`.

```python
from anydeck_sdk import BackgroundValue, features


class DiceValues(features.Values):
    def read(self, name):
        return {"last": LAST_ROLL}          # everything under "dice", at once

    def describe(self):                     # what is offered while typing
        return [
            {"path": "dice", "type": "object", "i18n": {"key": "references.system.dice"}},
            {"path": "dice.last", "type": "number", "i18n": {"key": "references.system.dice_last"}},
        ]
```

- `owns(name)` - whether its values are read under this name, the part
  before the first dot in `{{ claude.usage.week }}`. By default only the
  source's own short name; a source with connections owns one more per
  connection (`claude`, `claude1`, `claude2`, where "claude" is the first).
- `read(name)` - everything under one name as one object, at once: a
  display reads ten times a second.
- `describe()` - the values worth offering while typing.
- `has_path(path)` - whether a reference like `claude1.usage.week` can lead
  somewhere, asked when it is saved. By default from `owns()` and
  `describe()`; override it where `describe()` does not list every path.

A value that takes long to find out is a `BackgroundValue`:

```python
usage = BackgroundValue(read_usage, every=300)
usage.get()     # the last value, at once - None before the first read
```

`get()` never waits. A thread reads the value again every `every` seconds
while something read it in the last two minutes, then stops until it is
read again. A read that fails keeps the value from before.

## Where it runs

```python
from anydeck_sdk import Desktop, System

self.environment.system     # System.MAC, System.WINDOWS or System.LINUX
self.environment.desktop    # under Linux: Desktop.KDE, Desktop.X11, Desktop.WAYLAND, ... - else None
self.environment.language   # "de" or "en", what the person chose in Anydeck
```

Two values, not one: on a Linux machine with KDE, `system == System.LINUX`
and `desktop == Desktop.KDE` are both true. One value that equals both would
need `==` to mean "belongs to", and Python then quietly drops items from sets
and dicts that hold both - so it does not.

An action that cannot run everywhere says where it can, with both kinds in one
list. Anywhere else it is not offered:

```python
ActionDefinition(name="front", platforms=(System.MAC, Desktop.KDE))   # any Mac, Linux under KDE
```

What the system has to allow first (the microphone, screen recording, ...)
goes in `needs=`; Anydeck asks for it before the first run.

## On a display

Everything for displays is in `anydeck_sdk.display`, and it has two kinds of
"element":

- **`DisplayElement`** - what your source offers: a thing a person drags from
  the editor's list onto a display and sets with its options ("usage as
  rings"). List them in your `features.Display`.
- **`Element`** - a drawable block: `Text`, `Bar`, `Ring`, `Icon`, `Row`,
  `Column`, `Layers`, `Repeat`, ... A DisplayElement's `build()` answers with
  these - how it looks.

```python
from anydeck_sdk import Choice, ConnectorField, features
from anydeck_sdk.display import Bar, BuildContext, Column, DisplayElement, Element, Options, Text, ref


class WeekElement(DisplayElement):
    id = "week"
    options = (ConnectorField("style", Choice(options=("bar", "text")), secret=False, default="bar"),)
    words = {"en": {"name": "Week", "week": "Week"}, "de": {"name": "Woche", "week": "Woche"}}

    def build(self, options: Options, context: BuildContext) -> Element:
        value = ref("claude1.usage.week")        # a {{ }} reference, read when it is drawn
        if options.style == "text":
            return Text(value)
        return Column(Text(context.t("week")), Bar(value))


class MyDisplay(features.Display):
    elements = (WeekElement,)
```

`context.size` is the element's own size on the display, `context.t(key)`
its word in the person's language, `context.connections` the source's
connections.

`anydeck_sdk.display` has its own `Text` - the text on a display, not the
`Text` field. Write elements in a file of their own and import from
`anydeck_sdk.display` there.

## An extension, whole: Zufall

[`examples/zufall`](examples/zufall) is a complete extension - roll dice, or
pick one entry of a list - with every part an extension can have, one class
per file. It is the one Anydeck's own tests install:

    zufall/
      manifest.json                 what it is
      source/
        __init__.py                 brings ZufallSource, the entry
        zufall_source.py            ZufallSource: its short name, its parts,
                                    and migrate - what 1.1.0 renamed
        zufall_connector.py         a connection: where the chance comes from -
                                    this computer, or random.org with a key
        zufall_api.py               the numbers, from here or from random.org
        zufall_settings.py          how many sides a die has
        zufall_actions.py           roll, pick - each says what it did
        zufall_values.py            {{ zufall.last }}, {{ zufall.numbers }},
                                    {{ zufall.sum }}
        zufall_display.py           what it offers for displays
        last_roll_element.py        the last roll, large, on a display
      translations/de.json          its texts, by translation key
      translations/en.json
      icon.svg                      or icon.png
      requirements.txt              optional: libraries it needs (it needs none)

`manifest.json`:

```json
{
  "manifest": 1,
  "id": "com.crljnlabs.zufall",
  "name": "Zufall",
  "version": "1.1.0",
  "author": "crljn.labs",
  "sdk": ">=0.1,<1",
  "source": "zufall",
  "entry": "ZufallSource",
  "systems": ["macos", "windows", "linux"],
  "icon": "icon.svg"
}
```

- `id` is yours for good: a newer version with the same id replaces the older.
- `source` is the short name of its action source - `{{ zufall.… }}`, the
  connections `zufall1`, `zufall2` - and the same as its class's
  `action_source`. It has to be free on the computer it is installed on: not
  one of Anydeck's own sources, not another extension's.
- `entry` is the ActionSource class `source/__init__.py` brings. Inside
  `source/` import your own modules relatively: `from .zufall_api import
  ZufallApi`.
- `sdk` says which SDK versions it was built for. On another one it still
  runs, and Anydeck says it was built for another version.

A connection says where the chance comes from. "This computer" needs
nothing; random.org needs a free API key, which shows only for it and is kept
encrypted. "Verbinden" tries the key first (`ZufallApi.test_connection`):

```python
class ZufallConnector(features.CredentialsConnector):
    fields = (
        ConnectorField("origin", Choice(options=(COMPUTER, RANDOM_ORG)), secret=False, default=COMPUTER),
        Container(fields=(ConnectorField("api_key"),), when=When((Condition("origin", "eq", RANDOM_ORG),))),
    )
```

random.org says no with status 200 and an `error` in the body, so
`ZufallApi.accept_response` looks into the body - one line in the log either
way, with what was sent and what came back.

It has one setting for all its connections - how many sides a die has when a
roll leaves `sides` empty:

```python
class ZufallSettings(features.Settings):
    source_fields = (ConnectorField("sides", Number(minimum=2, maximum=1000), secret=False, default=6),)

# in ZufallActions.run
sides = int(params.get("sides") or self.features.settings.get("sides"))
```

Each roll is remembered for `{{ zufall.last }}` (`ZufallValues`), and the
display element "Letzter Wurf" shows it large - offered once there is a
connection (`LastRollElement.available`).

Version 1.1.0 calls the number of dice `dice` - 1.0.0 called it `count` -
and adds their `sum`. Its `migrate` takes every saved roll along:

```python
@staticmethod
def migrate(place, old, from_version):
    if older_than(from_version, "1.1.0") and place.kind == "action" and place.name == "roll":
        if "count" in place.values:
            values = dict(place.values)
            values["dice"] = values.pop("count")
            return values
    return NO_CHANGE
```

Its texts are the translation keys the interface looks up, each naming the
source: `actions.source.zufall`, `actions.field.zufall.origin` (the
connection), `actions.field.zufall.sides` (the setting), `references.zufall.last`,
`picker.action.zufall.roll`, `picker.field.zufall.roll.sides`,
`flows.output.zufall.number`, and your own like `zufall.summary.roll`. A key that does not name the source is ignored -
an extension cannot change Anydeck's own words.

## The command: check, test, pack, merge

The SDK brings a command, `anydeck-sdk`, run in the extension's folder (or
`python -m anydeck_sdk` where it is not on the path). The first steps, from an
empty folder to an installed file, are in
[docs/first-action-source.md](docs/first-action-source.md).

```bash
anydeck-sdk check                        # what Anydeck's window will say about it -
                                         # and what changed since the last pack
anydeck-sdk test                         # load it without Anydeck: what it offers,
                                         # which texts it lacks
anydeck-sdk test --run roll sides=20 dice=2
                                         # run one action for real
anydeck-sdk test --connect address=http://hue.local token=abc --run on light=1
                                         # one that has to connect first
anydeck-sdk pack                         # the .anydeck-actionsource file, in build/
anydeck-sdk pack -o dist/                # in another folder
anydeck-sdk pack --for all               # with wheels for macOS, Windows and Linux
anydeck-sdk merge mac.anydeck-actionsource win.anydeck-actionsource linux.anydeck-actionsource -o hue.anydeck-actionsource
```

`pack` names the file after the source and its version -
`build/zufall-1.0.0.anydeck-actionsource`: packed again, the same version
replaces its file, a new version is a new file beside it. `-o` takes a folder
(one that is there, or ending in `/`) or the file itself.

`test` plays Anydeck's part itself: a connection and settings live as long as
the command. The libraries the code imports come from the Python it runs in -
install what requirements.txt names there.

**Libraries.** What your code imports and neither Python, the SDK nor the
libraries below bring goes into `requirements.txt` beside `manifest.json`.
`pack` makes wheels of it for the Python Anydeck runs on (3.14): with `pip
wheel` for this system - building what has no ready wheel - and with `pip
download` for others, which only finds ready wheels on PyPI. A library that is
Python only lands once under `wheels/any/`, one with compiled parts under
`wheels/<system>/` - `macos-arm64`, `windows-x64`, `linux-x64`. Where a
library has no ready wheel for a system, pack on that system and `merge` the
files; [examples/github-actions/pack.yml](examples/github-actions/pack.yml)
does that on GitHub's machines. The libraries Anydeck brings are never
packed: Anydeck's copy is the one that is imported.

**Installing.** Double click the file, or drop it under Settings →
Extensions. Anydeck checks it and shows what it is and what may not work
before anything is installed - built for another SDK version, not for this
system, libraries it imports but does not bring (read from your `import`
lines; one inside `try: ... except ImportError` is left out). `anydeck-sdk
check` says the same before you hand the file on.

In a checkout of Anydeck, a script installs without the window - only for
what you built yourself:

```bash
backend/.venv/bin/python -m anydeck_sdk pack sdk/examples/zufall
backend/.venv/bin/python scripts/extensions.py install sdk/examples/zufall/build/zufall-1.1.0.anydeck-actionsource
```

With `ANYDECK_DATA_DIR=/tmp/anydeck-test-instance` in front it works on the
folder `scripts/dev.py --test-instance` runs on, not on your own data.

## Libraries Anydeck brings

An extension may use these without packing them, at least in this version
(`anydeck_sdk.provided`): httpx 0.28, websockets 17.3, Pillow 12.3, psutil 7.2,
cryptography 50.0 - and all of Python's own standard library. Anything else it
brings itself, as wheels.

## Versions

The SDK counts by semantic versioning: the last number for a fix, the middle
one for something new that breaks nothing, the first for a change that can
break an extension written against the one before. Something that is to go
away is marked deprecated first and removed only with the next major version.

## A new version of your extension: migrate

What a person set up with your extension is saved in Anydeck: its settings,
its connections, every node in a flow and every key that runs one of its
actions, its display elements, every `{{ zufall.… }}` in a text. When a new
version renames or rebuilds one of these, it says how in `migrate` - and
when the person replaces the old version, Anydeck hands every one of these
places to it and saves what comes back.

```python
from anydeck_sdk import NO_CHANGE, ActionSource, older_than


class ZufallSource(ActionSource):
    ...

    @staticmethod
    def migrate(place, old, from_version):
        # Version 2 calls the sides "seiten".
        if older_than(from_version, "2.0.0"):
            if place.kind == "settings" and place.connection is None:
                return {"seiten": place.values.get("sides", 6)}
            if place.kind == "action" and place.name == "roll":
                values = dict(place.values)
                values["seiten"] = values.pop("sides", None)
                return values
            if place.kind == "value" and place.name == "last":
                return "letzter"          # {{ zufall.last }} becomes {{ zufall.letzter }}
        return NO_CHANGE
```

- **`place`** is the place it is called for. `place.kind` is `"settings"`
  (the extension's, or with `place.connection` one connection's),
  `"connection"` (a connection's fields), `"action"`, `"element"` or
  `"value"`; `place.name` the action, the element or the value; and
  `place.values` what is saved there.
- **`old`** has everything as it was before any place changed:
  `old.settings`, `old.connections`, `old.connection_settings`,
  `old.actions`, `old.elements`, `old.values`. So a value can move either
  way - the sides taken out of every roll into one setting:

  ```python
  if place.kind == "action" and place.name == "roll":
      return {key: value for key, value in place.values.items() if key != "sides"}
  if place.kind == "settings" and place.connection is None:
      used = [one.values.get("sides") for one in old.actions if one.name == "roll"]
      return {"sides": max([one for one in used if one], default=6)}
  ```

- **`from_version`** is the version the person comes from. Who skips one
  comes in once, from the oldest: check each step in turn,
  `older_than(from_version, "2.0.0")`, then `"3.0.0"`. For an action it is
  the version its values were saved with - Anydeck keeps it beside them - so
  a flow node saved with 1.0.0 comes from 1.0.0 even when the extension was
  removed in between and 1.1.0 is installed now.
- **What comes back** is saved as it is: a field left out is gone.
  `NO_CHANGE` leaves the place alone.

Before anything is saved, Anydeck shows the person every change, before and
after. When `migrate` raises for any place, nothing is changed and the old
version stays installed. A file shared with an older version is brought
along the same way when it is imported.

A field that is new and has to be filled in with nothing to start from, a
value a choice no longer offers, an action that is gone: keys and flow nodes
with them stop until someone adjusts them by hand, unless `migrate` brings
them along. `anydeck-sdk check` on the folder compares with the version
packed last in build/ and warns where a field changed like that and
`migrate` does nothing for values saved with that version. A new field with
a default needs nothing: a value that is not there takes the default.

Try it on values saved with the old version - Zufall's own:

```bash
anydeck-sdk test --from 1.0.0 --run roll count=3
```

    migrate from 1.0.0:
      before: {"count": 3}
      after:  {"dice": 3}
