Metadata-Version: 2.4
Name: strands-stash-plugin
Version: 0.1.1
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

[Strands Stash](https://github.com/strands-agents/stash) is a stateful
workspace for agents. It mounts your context sources as one directory of
files: Amazon Bedrock AgentCore Memory, knowledge bases, web search, AWS
Context, MCP servers, and any store that a plugin serves. Your agent reads
that directory with tools it already knows, such as `ls`, `cat`, `grep`, and
`jq`. Source files stay outside the context window until the agent reads
them. Stash sends steering, digests, and compact result views through the
integration.

A source is one store that a mount shows as a folder of files. A plugin is a
program that serves a store as a source. Its `list`, `get`, and `search`
methods give records, and Stash makes a file of each one. `plan` says what the mount loads
when it starts. `ingest` writes the turns of the agent back.

This SDK speaks the
[plugin protocol](https://github.com/strands-agents/stash/blob/main/docs/user/plugins.md)
for you: you write one Python function for each method that your store
serves.

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.
- `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`.
- With no `@plugin.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.

## 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"] } }
```

Stash sends `ingest` only when the source sets `write.trajectory = {}`. The
plugin gets only `env` and a few variables of the daemon, such as `PATH` and
`HOME`.

## 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 with `@plugin.list`, `@plugin.get`,
and `@plugin.ingest`. 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`.
