Metadata-Version: 2.4
Name: strands-stash-plugin
Version: 0.1.0
Summary: Write a Stash source plugin in Python
Author: Stash
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/strands-agents/stash/tree/main/integrations/plugin-sdk/python
Project-URL: Documentation, https://github.com/strands-agents/stash/blob/main/docs/user/sources/write-a-plugin.md
Project-URL: Repository, https://github.com/strands-agents/stash
Project-URL: Issues, https://github.com/strands-agents/stash/issues
Keywords: strands,stash,plugin
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
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: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Dynamic: license-file

# strands-stash-plugin

Write a Stash source plugin in Python. The SDK speaks the
[plugin protocol](https://github.com/strands-agents/stash/blob/main/docs/user/plugins.md)
for you: you write one function for each thing that your store can do.

It needs Python 3.9 or later, and nothing else.

## A plugin

This plugin searches the web:

```python
import hashlib
import json
import socket
import urllib.error
import urllib.request
from datetime import datetime, timezone

from stash_plugin import Failure, Plugin, Record

plugin = Plugin("perplexity", description="The web, through the Perplexity Search API.")

@plugin.initialize
def start(settings, env):
    key = env.get("PERPLEXITY_API_KEY", "").strip()
    if not key:
        raise Failure.validation("set env.PERPLEXITY_API_KEY")
    return key

@plugin.search
def search(key, query, limit):
    body = json.dumps({"query": query, "max_results": min(limit, 20)}).encode()
    request = urllib.request.Request(
        "https://api.perplexity.ai/search", data=body,
        headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(request, timeout=20) as answer:
            results = json.load(answer)["results"]
    except urllib.error.HTTPError as error:
        if error.code in (408, 425):
            raise Failure.timeout("Perplexity did not finish the search") from None
        if error.code == 429:
            raise Failure.throttled("Perplexity throttled the search") from None
        if error.code >= 500:
            raise Failure.unavailable("Perplexity is unavailable") from None
        if error.code in (401, 403):
            raise Failure.access_denied("Perplexity refused the API key") from None
        raise Failure.other(f"Perplexity answered HTTP {error.code}") from None
    except urllib.error.URLError as error:
        if isinstance(error.reason, socket.timeout):
            raise Failure.timeout("Perplexity did not answer") from None
        raise Failure.unavailable("Perplexity is unavailable") from None
    except socket.timeout:
        raise Failure.timeout("Perplexity did not answer") from None
    found = datetime.now(timezone.utc)
    return [to_record(result, found) for result in results if result.get("url")]

def to_record(result, found):
    url, snippet = result["url"], result.get("snippet") or ""
    record_id = hashlib.sha256(f"{url}\0{snippet}".encode()).hexdigest()[:32]
    return Record(
        # The same passage of the same page keeps its file in each search.
        id=record_id,
        name=f"{record_id}.md",
        body=f"{snippet}\n\nSource: {url}\n",
        preview=snippet[:1000],
        created_at=found,
    )

main = plugin.run
```

- `initialize` gets the `settings` table of the source and the environment of
  the plugin. It returns the `state` that each other function gets first.
- The plugin declares each method that has a function. Leave out the others.
- `list` and `search` get a folder and filters only if the function has the
  parameters `scope` and `filters`. Otherwise the SDK refuses such a request
  with `unsupported`.
- `@plugin.plan` returns what Stash loads when the mount starts. With no plan,
  the mount loads nothing until a search or get request.
- `list` returns a page and the cursor of the next page (`None` at the end),
  or the records alone for the last page.
- `search` returns records, or `(record, score)` pairs, best first.
- `ingest` can get the same batch again, with the same `token`: write it once.
  Return an id of the write, or `None` to use the token.
- Raise a `Failure` (`not_found`, `access_denied`, `throttled`, `unavailable`,
  `timeout`, `validation`, `malformed`, or `unsupported`). Any other exception
  is `other`, and its traceback goes to the daemon log, as `print` does.
- After `initialize`, functions run on up to 8 threads at the same time. Keep
  the state thread-safe, for example a `sqlite3` connection behind a
  `threading.Lock`.
- Do not sleep for a rate limit. Raise `Failure.throttled`, and Stash retries.
- [`examples/notes.py`](https://github.com/strands-agents/stash/blob/main/integrations/plugin-sdk/python/examples/notes.py)
  uses `@plugin.list`, `@plugin.get`, and `@plugin.ingest`.

## A `Record`

| Field | Description |
|---|---|
| `id` | The same for the same record in each call. |
| `body` | The text of the file. |
| `dir` | The folder below the source, such as `team/runbooks`. The SDK removes a `/` at the start or the end. |
| `name` | The whole file name, such as `deploy.md` or `menu.csv`. With none, the file is `<date of created_at>__<words of the body>.md`. |
| `preview` | The line that a search shows. With none, the body. |
| `created_at`, `updated_at` | A `datetime` (a naive one is UTC) or RFC 3339 text. |

The file is `<dir>/<name>`. A `.md` file is the body, then the time of the
fetch in a YAML block. Any other file is the body alone.
Follow the protocol's
[path rules](https://github.com/strands-agents/stash/blob/main/docs/user/plugins.md#paths)
when a store supplies `dir` or `name`.

## Publish it

Name the package and its program `stash-source-<plugin>`. For a source with
no `command`, Stash runs that program from the `PATH` of the daemon.

```toml
[project]
name = "stash-source-perplexity"
dependencies = ["strands-stash-plugin"]

[project.scripts]
stash-source-perplexity = "stash_source_perplexity:main"
```

A user installs it with `pipx install stash-source-perplexity`, and adds a
source with no `command`:

```toml
[sources.web]
kind = "plugin"
plugin   = "perplexity"
env      = { PERPLEXITY_API_KEY = { command = ["op", "read", "op://me/perplexity/api-key"] } }
```

A source that writes the trajectory of the agent back sets
`write.trajectory = {}`, and the plugin must serve `ingest`. The plugin gets
only a few variables of the daemon, such as `PATH` and `HOME`, and the
variables in `env`.

## Try it

[`examples/notes.py`](https://github.com/strands-agents/stash/blob/main/integrations/plugin-sdk/python/examples/notes.py)
serves the Markdown files of one folder. It needs no other package:

```toml
[sources.notes]
kind = "plugin"
plugin   = "notes"
command  = ["python3", "/path/to/examples/notes.py"]
settings = { root = "~/notes" }
env      = { PYTHONPATH = "/path/to/integrations/plugin-sdk/python/src" }
```

Run the tests with `python3 -m unittest discover -s tests`.
