strands-stash-plugin 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- stash_plugin/__init__.py +371 -0
- stash_plugin/py.typed +0 -0
- strands_stash_plugin-0.1.0.dist-info/METADATA +185 -0
- strands_stash_plugin-0.1.0.dist-info/RECORD +8 -0
- strands_stash_plugin-0.1.0.dist-info/WHEEL +5 -0
- strands_stash_plugin-0.1.0.dist-info/licenses/LICENSE +202 -0
- strands_stash_plugin-0.1.0.dist-info/licenses/NOTICE +4 -0
- strands_stash_plugin-0.1.0.dist-info/top_level.txt +1 -0
stash_plugin/__init__.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"""Write a Stash source plugin in Python.
|
|
2
|
+
|
|
3
|
+
A plugin is a program that Stash starts. Stash sends it JSON-RPC 2.0
|
|
4
|
+
requests on stdin, one on each line, and reads one response for each on
|
|
5
|
+
stdout. This module speaks that protocol: decorate a function for each method
|
|
6
|
+
that the plugin serves, and call ``Plugin.run``.
|
|
7
|
+
|
|
8
|
+
plugin = Plugin("notes")
|
|
9
|
+
|
|
10
|
+
@plugin.initialize
|
|
11
|
+
def start(settings, env):
|
|
12
|
+
return settings["root"]
|
|
13
|
+
|
|
14
|
+
@plugin.get
|
|
15
|
+
def get(root, id):
|
|
16
|
+
return Record(id=id, body=open(f"{root}/{id}").read())
|
|
17
|
+
|
|
18
|
+
main = plugin.run
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import inspect
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import sys
|
|
27
|
+
import threading
|
|
28
|
+
import traceback
|
|
29
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
30
|
+
from dataclasses import dataclass
|
|
31
|
+
from datetime import datetime, timezone
|
|
32
|
+
from typing import IO, Any, Callable, Dict, Iterable, Optional, Tuple, Union
|
|
33
|
+
|
|
34
|
+
__all__ = ["Failure", "Plugin", "Record", "PROTOCOL_VERSION"]
|
|
35
|
+
|
|
36
|
+
PROTOCOL_VERSION = 1
|
|
37
|
+
|
|
38
|
+
_METHODS = ("list", "get", "search", "ingest", "plan")
|
|
39
|
+
|
|
40
|
+
# The requests that run at the same time. Stash times each request from
|
|
41
|
+
# when it sends it, so a request must not wait behind a slow one.
|
|
42
|
+
_WORKERS = 8
|
|
43
|
+
|
|
44
|
+
Time = Union[datetime, str, None]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class Record:
|
|
49
|
+
"""One record of the store. Stash shows it as the file ``<dir>/<name>``.
|
|
50
|
+
|
|
51
|
+
``id`` must be the same for the same record in each call. ``name`` is the
|
|
52
|
+
whole file name, such as ``deploy.md`` or ``menu.csv``; with none, the file
|
|
53
|
+
is ``<date of created_at>__<words of the body>.md``. A ``.md`` file is the
|
|
54
|
+
body, then the time of the fetch; any other file is the body alone.
|
|
55
|
+
``preview`` is the line that a search shows; with none, the body. A time is
|
|
56
|
+
a ``datetime`` (a naive one is UTC) or RFC 3339 text.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
id: str
|
|
60
|
+
body: str
|
|
61
|
+
dir: str = ""
|
|
62
|
+
name: Optional[str] = None
|
|
63
|
+
preview: Optional[str] = None
|
|
64
|
+
created_at: Time = None
|
|
65
|
+
updated_at: Time = None
|
|
66
|
+
|
|
67
|
+
def to_json(self) -> Dict[str, Any]:
|
|
68
|
+
if not str(self.id).strip():
|
|
69
|
+
raise Failure.malformed("a record has a blank id")
|
|
70
|
+
record: Dict[str, Any] = {"id": str(self.id), "body": self.body}
|
|
71
|
+
if self.dir.strip("/"):
|
|
72
|
+
record["dir"] = self.dir.strip("/")
|
|
73
|
+
if self.name is not None:
|
|
74
|
+
record["name"] = self.name
|
|
75
|
+
if self.preview is not None:
|
|
76
|
+
record["preview"] = self.preview
|
|
77
|
+
for key in ("created_at", "updated_at"):
|
|
78
|
+
at = _time(getattr(self, key))
|
|
79
|
+
if at is not None:
|
|
80
|
+
record[key] = at
|
|
81
|
+
return record
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _time(at: Time) -> Optional[str]:
|
|
85
|
+
if isinstance(at, datetime):
|
|
86
|
+
if at.tzinfo is None:
|
|
87
|
+
at = at.replace(tzinfo=timezone.utc)
|
|
88
|
+
return at.isoformat()
|
|
89
|
+
return at
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Failure(Exception):
|
|
93
|
+
"""A failure that Stash acts on by its kind: it retries ``throttled``,
|
|
94
|
+
``unavailable``, and ``timeout``, and starts the plugin again, with its
|
|
95
|
+
secrets read again, after ``access_denied``."""
|
|
96
|
+
|
|
97
|
+
def __init__(self, kind: str, message: str):
|
|
98
|
+
super().__init__(message)
|
|
99
|
+
self.kind = kind
|
|
100
|
+
self.message = message
|
|
101
|
+
|
|
102
|
+
@classmethod
|
|
103
|
+
def not_found(cls, message: str) -> "Failure":
|
|
104
|
+
return cls("not_found", message)
|
|
105
|
+
|
|
106
|
+
@classmethod
|
|
107
|
+
def access_denied(cls, message: str) -> "Failure":
|
|
108
|
+
return cls("access_denied", message)
|
|
109
|
+
|
|
110
|
+
@classmethod
|
|
111
|
+
def throttled(cls, message: str) -> "Failure":
|
|
112
|
+
return cls("throttled", message)
|
|
113
|
+
|
|
114
|
+
@classmethod
|
|
115
|
+
def unavailable(cls, message: str) -> "Failure":
|
|
116
|
+
return cls("unavailable", message)
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def timeout(cls, message: str) -> "Failure":
|
|
120
|
+
return cls("timeout", message)
|
|
121
|
+
|
|
122
|
+
@classmethod
|
|
123
|
+
def validation(cls, message: str) -> "Failure":
|
|
124
|
+
return cls("validation", message)
|
|
125
|
+
|
|
126
|
+
@classmethod
|
|
127
|
+
def malformed(cls, message: str) -> "Failure":
|
|
128
|
+
return cls("malformed", message)
|
|
129
|
+
|
|
130
|
+
@classmethod
|
|
131
|
+
def unsupported(cls, message: str) -> "Failure":
|
|
132
|
+
return cls("unsupported", message)
|
|
133
|
+
|
|
134
|
+
@classmethod
|
|
135
|
+
def other(cls, message: str) -> "Failure":
|
|
136
|
+
return cls("other", message)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class _RpcError(Exception):
|
|
140
|
+
def __init__(self, code: int, message: str):
|
|
141
|
+
super().__init__(message)
|
|
142
|
+
self.code = code
|
|
143
|
+
self.message = message
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
Handler = Callable[..., Any]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class Plugin:
|
|
150
|
+
"""The methods of one plugin. Each decorator registers the function that
|
|
151
|
+
serves one method, and the plugin declares each method that it has.
|
|
152
|
+
|
|
153
|
+
A request to ``list`` or ``search`` can name a folder and filters. The
|
|
154
|
+
function gets them as the keyword arguments ``scope`` and ``filters`` only
|
|
155
|
+
when it has those parameters. Without them, the SDK refuses such a request
|
|
156
|
+
with ``unsupported``, so that the function never answers it wrongly.
|
|
157
|
+
|
|
158
|
+
After ``initialize``, the functions can run at the same time on different
|
|
159
|
+
threads. Keep the state safe to use from more than one thread: for
|
|
160
|
+
example, put a client that is not safe behind a ``threading.Lock``."""
|
|
161
|
+
|
|
162
|
+
def __init__(self, name: str, description: Optional[str] = None):
|
|
163
|
+
self.name = name
|
|
164
|
+
self.description = description
|
|
165
|
+
self._start: Optional[Handler] = None
|
|
166
|
+
self._handlers: Dict[str, Handler] = {}
|
|
167
|
+
self._state: Any = None
|
|
168
|
+
self._started = False
|
|
169
|
+
|
|
170
|
+
def initialize(self, function: Handler) -> Handler:
|
|
171
|
+
"""``function(settings, env) -> state``: called once, before any other
|
|
172
|
+
method. ``settings`` is the source's ``settings`` table, and ``env`` is
|
|
173
|
+
the plugin's environment. Each other method gets ``state`` first."""
|
|
174
|
+
self._start = function
|
|
175
|
+
return function
|
|
176
|
+
|
|
177
|
+
def list(self, function: Handler) -> Handler:
|
|
178
|
+
"""``function(state, cursor, limit, scope=None, filters=()) ->
|
|
179
|
+
(records, next_cursor)``, or ``records`` alone for the last page.
|
|
180
|
+
``cursor`` is ``None`` for the
|
|
181
|
+
first page, and a ``next_cursor`` of ``None`` ends the listing.
|
|
182
|
+
``limit`` can be ``None``."""
|
|
183
|
+
self._handlers["list"] = function
|
|
184
|
+
return function
|
|
185
|
+
|
|
186
|
+
def get(self, function: Handler) -> Handler:
|
|
187
|
+
"""``function(state, id) -> Record``. Raise ``Failure.not_found`` for
|
|
188
|
+
a record that does not exist."""
|
|
189
|
+
self._handlers["get"] = function
|
|
190
|
+
return function
|
|
191
|
+
|
|
192
|
+
def search(self, function: Handler) -> Handler:
|
|
193
|
+
"""``function(state, query, limit, scope=None, filters=()) ->
|
|
194
|
+
[(Record, score) or Record]``, best first. A score can be ``None``."""
|
|
195
|
+
self._handlers["search"] = function
|
|
196
|
+
return function
|
|
197
|
+
|
|
198
|
+
def plan(self, function: Handler) -> Handler:
|
|
199
|
+
"""``function(state, replays) -> {"directories": [...], "steps": [...]}``:
|
|
200
|
+
what the mount loads when it starts. Each step is ``{"list": {...}}`` or
|
|
201
|
+
``{"search": {...}}``, with the parameters of that method. Without a
|
|
202
|
+
plan, Stash lists 100 records of a plugin that lists."""
|
|
203
|
+
self._handlers["plan"] = function
|
|
204
|
+
return function
|
|
205
|
+
|
|
206
|
+
def ingest(self, function: Handler) -> Handler:
|
|
207
|
+
"""``function(state, token, session, turns) -> id``: write the turns of
|
|
208
|
+
an agent's session. Each turn has ``id``, ``role``, ``text``, and
|
|
209
|
+
``at``. Stash can send the same batch again, with the same
|
|
210
|
+
``token``: write it once. Return an id of the write, or ``None`` for
|
|
211
|
+
the token."""
|
|
212
|
+
self._handlers["ingest"] = function
|
|
213
|
+
return function
|
|
214
|
+
|
|
215
|
+
def run(self) -> None:
|
|
216
|
+
"""Serve requests on stdin until it closes. While a method runs,
|
|
217
|
+
``print`` goes to stderr, which Stash logs, so that it cannot break
|
|
218
|
+
the protocol on stdout."""
|
|
219
|
+
out = sys.stdout
|
|
220
|
+
sys.stdout = sys.stderr
|
|
221
|
+
try:
|
|
222
|
+
self.serve(sys.stdin, out)
|
|
223
|
+
except KeyboardInterrupt:
|
|
224
|
+
pass
|
|
225
|
+
finally:
|
|
226
|
+
sys.stdout = out
|
|
227
|
+
|
|
228
|
+
def serve(self, lines: Iterable[str], out: IO[str]) -> None:
|
|
229
|
+
"""Answer each request in ``lines`` on ``out``. ``initialize`` runs
|
|
230
|
+
before the next line is read. After it, the requests run at the same
|
|
231
|
+
time, and each answer goes out when it is ready."""
|
|
232
|
+
lock = threading.Lock()
|
|
233
|
+
|
|
234
|
+
def answer(line: str) -> None:
|
|
235
|
+
response = self.handle(line)
|
|
236
|
+
if response is None:
|
|
237
|
+
return
|
|
238
|
+
try:
|
|
239
|
+
text = json.dumps(response, ensure_ascii=False)
|
|
240
|
+
except (TypeError, ValueError) as error:
|
|
241
|
+
# On a worker thread, an answer that is lost costs a timeout
|
|
242
|
+
# and a restart of the plugin.
|
|
243
|
+
text = json.dumps(_error(response.get("id"), -32000,
|
|
244
|
+
f"the answer is not JSON: {error}", "malformed"))
|
|
245
|
+
with lock:
|
|
246
|
+
out.write(text + "\n")
|
|
247
|
+
out.flush()
|
|
248
|
+
|
|
249
|
+
with ThreadPoolExecutor(max_workers=_WORKERS) as pool:
|
|
250
|
+
for line in lines:
|
|
251
|
+
if not line.strip():
|
|
252
|
+
continue
|
|
253
|
+
if self._started:
|
|
254
|
+
pool.submit(answer, line)
|
|
255
|
+
else:
|
|
256
|
+
answer(line)
|
|
257
|
+
|
|
258
|
+
def handle(self, line: str) -> Optional[Dict[str, Any]]:
|
|
259
|
+
"""The response to one message, or ``None`` for a notification."""
|
|
260
|
+
try:
|
|
261
|
+
message = json.loads(line)
|
|
262
|
+
except ValueError as error:
|
|
263
|
+
return _error(None, -32700, f"the line is not JSON: {error}")
|
|
264
|
+
if not isinstance(message, dict) or not isinstance(message.get("method"), str):
|
|
265
|
+
return _error(message.get("id") if isinstance(message, dict) else None,
|
|
266
|
+
-32600, "the message is not a request")
|
|
267
|
+
if "id" not in message:
|
|
268
|
+
return None
|
|
269
|
+
id = message["id"]
|
|
270
|
+
params = message.get("params") or {}
|
|
271
|
+
try:
|
|
272
|
+
result = self._dispatch(message["method"], params)
|
|
273
|
+
except Failure as failure:
|
|
274
|
+
return _error(id, -32000, failure.message, failure.kind)
|
|
275
|
+
except _RpcError as error:
|
|
276
|
+
return _error(id, error.code, error.message)
|
|
277
|
+
except Exception as error: # noqa: BLE001 - each failure is an answer
|
|
278
|
+
traceback.print_exc(file=sys.stderr)
|
|
279
|
+
return _error(id, -32000, f"{type(error).__name__}: {error}", "other")
|
|
280
|
+
return {"jsonrpc": "2.0", "id": id, "result": result}
|
|
281
|
+
|
|
282
|
+
def _dispatch(self, method: str, params: Dict[str, Any]) -> Any:
|
|
283
|
+
if method == "initialize":
|
|
284
|
+
return self._initialize(params)
|
|
285
|
+
handler = self._handlers.get(method)
|
|
286
|
+
if handler is None:
|
|
287
|
+
raise _RpcError(-32601, f"{self.name} has no method {method}")
|
|
288
|
+
if not self._started:
|
|
289
|
+
raise Failure.validation("initialize must come first")
|
|
290
|
+
if method == "plan":
|
|
291
|
+
return handler(self._state, params.get("replays") or [])
|
|
292
|
+
if method == "list":
|
|
293
|
+
answer = handler(
|
|
294
|
+
self._state,
|
|
295
|
+
params.get("cursor"),
|
|
296
|
+
params.get("limit"),
|
|
297
|
+
**_narrowing(handler, method, params),
|
|
298
|
+
)
|
|
299
|
+
# A tuple of records is one page too. Only `(records, cursor)` has a cursor.
|
|
300
|
+
if isinstance(answer, tuple) and len(answer) == 2 and not isinstance(answer[0], Record):
|
|
301
|
+
records, next_cursor = answer
|
|
302
|
+
else:
|
|
303
|
+
records, next_cursor = answer, None
|
|
304
|
+
return {
|
|
305
|
+
"records": [_record(record) for record in records],
|
|
306
|
+
"next": None if next_cursor is None else str(next_cursor),
|
|
307
|
+
}
|
|
308
|
+
if method == "get":
|
|
309
|
+
record = handler(self._state, params["id"])
|
|
310
|
+
if record is None:
|
|
311
|
+
raise Failure.not_found(f"no record {params['id']}")
|
|
312
|
+
return {"record": _record(record)}
|
|
313
|
+
if method == "search":
|
|
314
|
+
hits = handler(
|
|
315
|
+
self._state,
|
|
316
|
+
params["query"],
|
|
317
|
+
params.get("limit"),
|
|
318
|
+
**_narrowing(handler, method, params),
|
|
319
|
+
)
|
|
320
|
+
return {"results": [_hit(hit) for hit in hits]}
|
|
321
|
+
token = params["token"]
|
|
322
|
+
written = handler(self._state, token, params["session"], params["turns"])
|
|
323
|
+
return {"id": token if written is None else str(written)}
|
|
324
|
+
|
|
325
|
+
def _initialize(self, params: Dict[str, Any]) -> Dict[str, Any]:
|
|
326
|
+
version = params.get("protocol_version")
|
|
327
|
+
if version != PROTOCOL_VERSION:
|
|
328
|
+
raise Failure.validation(
|
|
329
|
+
f"{self.name} speaks the plugin protocol {PROTOCOL_VERSION}, not {version}"
|
|
330
|
+
)
|
|
331
|
+
if self._start is not None:
|
|
332
|
+
self._state = self._start(params.get("settings") or {}, dict(os.environ))
|
|
333
|
+
self._started = True
|
|
334
|
+
hello: Dict[str, Any] = {
|
|
335
|
+
"protocol_version": PROTOCOL_VERSION,
|
|
336
|
+
"capabilities": [method for method in _METHODS if method in self._handlers],
|
|
337
|
+
}
|
|
338
|
+
if self.description:
|
|
339
|
+
hello["description"] = self.description
|
|
340
|
+
return hello
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _narrowing(handler: Handler, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
|
|
344
|
+
narrowing = {key: params[key] for key in ("scope", "filters") if params.get(key)}
|
|
345
|
+
accepted = inspect.signature(handler).parameters
|
|
346
|
+
takes_any = any(p.kind is inspect.Parameter.VAR_KEYWORD for p in accepted.values())
|
|
347
|
+
for key in narrowing:
|
|
348
|
+
if not takes_any and key not in accepted:
|
|
349
|
+
raise Failure.unsupported(f"{method} cannot take a {key}")
|
|
350
|
+
return narrowing
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _record(record: Any) -> Dict[str, Any]:
|
|
354
|
+
if not isinstance(record, Record):
|
|
355
|
+
raise TypeError(f"a method returned {type(record).__name__}, not a Record")
|
|
356
|
+
return record.to_json()
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _hit(hit: Union[Record, Tuple[Record, Optional[float]]]) -> Dict[str, Any]:
|
|
360
|
+
record, score = hit if isinstance(hit, tuple) else (hit, None)
|
|
361
|
+
found: Dict[str, Any] = {"record": _record(record)}
|
|
362
|
+
if score is not None:
|
|
363
|
+
found["score"] = float(score)
|
|
364
|
+
return found
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _error(id: Any, code: int, message: str, kind: Optional[str] = None) -> Dict[str, Any]:
|
|
368
|
+
error: Dict[str, Any] = {"code": code, "message": message}
|
|
369
|
+
if kind is not None:
|
|
370
|
+
error["data"] = {"kind": kind}
|
|
371
|
+
return {"jsonrpc": "2.0", "id": id, "error": error}
|
stash_plugin/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: strands-stash-plugin
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Write a Stash source plugin in Python
|
|
5
|
+
Author: Stash
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/strands-agents/stash/tree/main/integrations/plugin-sdk/python
|
|
8
|
+
Project-URL: Documentation, https://github.com/strands-agents/stash/blob/main/docs/user/sources/write-a-plugin.md
|
|
9
|
+
Project-URL: Repository, https://github.com/strands-agents/stash
|
|
10
|
+
Project-URL: Issues, https://github.com/strands-agents/stash/issues
|
|
11
|
+
Keywords: strands,stash,plugin
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
License-File: NOTICE
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# strands-stash-plugin
|
|
29
|
+
|
|
30
|
+
Write a Stash source plugin in Python. The SDK speaks the
|
|
31
|
+
[plugin protocol](https://github.com/strands-agents/stash/blob/main/docs/user/plugins.md)
|
|
32
|
+
for you: you write one function for each thing that your store can do.
|
|
33
|
+
|
|
34
|
+
It needs Python 3.9 or later, and nothing else.
|
|
35
|
+
|
|
36
|
+
## A plugin
|
|
37
|
+
|
|
38
|
+
This plugin searches the web:
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
import hashlib
|
|
42
|
+
import json
|
|
43
|
+
import socket
|
|
44
|
+
import urllib.error
|
|
45
|
+
import urllib.request
|
|
46
|
+
from datetime import datetime, timezone
|
|
47
|
+
|
|
48
|
+
from stash_plugin import Failure, Plugin, Record
|
|
49
|
+
|
|
50
|
+
plugin = Plugin("perplexity", description="The web, through the Perplexity Search API.")
|
|
51
|
+
|
|
52
|
+
@plugin.initialize
|
|
53
|
+
def start(settings, env):
|
|
54
|
+
key = env.get("PERPLEXITY_API_KEY", "").strip()
|
|
55
|
+
if not key:
|
|
56
|
+
raise Failure.validation("set env.PERPLEXITY_API_KEY")
|
|
57
|
+
return key
|
|
58
|
+
|
|
59
|
+
@plugin.search
|
|
60
|
+
def search(key, query, limit):
|
|
61
|
+
body = json.dumps({"query": query, "max_results": min(limit, 20)}).encode()
|
|
62
|
+
request = urllib.request.Request(
|
|
63
|
+
"https://api.perplexity.ai/search", data=body,
|
|
64
|
+
headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
|
|
65
|
+
try:
|
|
66
|
+
with urllib.request.urlopen(request, timeout=20) as answer:
|
|
67
|
+
results = json.load(answer)["results"]
|
|
68
|
+
except urllib.error.HTTPError as error:
|
|
69
|
+
if error.code in (408, 425):
|
|
70
|
+
raise Failure.timeout("Perplexity did not finish the search") from None
|
|
71
|
+
if error.code == 429:
|
|
72
|
+
raise Failure.throttled("Perplexity throttled the search") from None
|
|
73
|
+
if error.code >= 500:
|
|
74
|
+
raise Failure.unavailable("Perplexity is unavailable") from None
|
|
75
|
+
if error.code in (401, 403):
|
|
76
|
+
raise Failure.access_denied("Perplexity refused the API key") from None
|
|
77
|
+
raise Failure.other(f"Perplexity answered HTTP {error.code}") from None
|
|
78
|
+
except urllib.error.URLError as error:
|
|
79
|
+
if isinstance(error.reason, socket.timeout):
|
|
80
|
+
raise Failure.timeout("Perplexity did not answer") from None
|
|
81
|
+
raise Failure.unavailable("Perplexity is unavailable") from None
|
|
82
|
+
except socket.timeout:
|
|
83
|
+
raise Failure.timeout("Perplexity did not answer") from None
|
|
84
|
+
found = datetime.now(timezone.utc)
|
|
85
|
+
return [to_record(result, found) for result in results if result.get("url")]
|
|
86
|
+
|
|
87
|
+
def to_record(result, found):
|
|
88
|
+
url, snippet = result["url"], result.get("snippet") or ""
|
|
89
|
+
record_id = hashlib.sha256(f"{url}\0{snippet}".encode()).hexdigest()[:32]
|
|
90
|
+
return Record(
|
|
91
|
+
# The same passage of the same page keeps its file in each search.
|
|
92
|
+
id=record_id,
|
|
93
|
+
name=f"{record_id}.md",
|
|
94
|
+
body=f"{snippet}\n\nSource: {url}\n",
|
|
95
|
+
preview=snippet[:1000],
|
|
96
|
+
created_at=found,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
main = plugin.run
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
- `initialize` gets the `settings` table of the source and the environment of
|
|
103
|
+
the plugin. It returns the `state` that each other function gets first.
|
|
104
|
+
- The plugin declares each method that has a function. Leave out the others.
|
|
105
|
+
- `list` and `search` get a folder and filters only if the function has the
|
|
106
|
+
parameters `scope` and `filters`. Otherwise the SDK refuses such a request
|
|
107
|
+
with `unsupported`.
|
|
108
|
+
- `@plugin.plan` returns what Stash loads when the mount starts. With no plan,
|
|
109
|
+
the mount loads nothing until a search or get request.
|
|
110
|
+
- `list` returns a page and the cursor of the next page (`None` at the end),
|
|
111
|
+
or the records alone for the last page.
|
|
112
|
+
- `search` returns records, or `(record, score)` pairs, best first.
|
|
113
|
+
- `ingest` can get the same batch again, with the same `token`: write it once.
|
|
114
|
+
Return an id of the write, or `None` to use the token.
|
|
115
|
+
- Raise a `Failure` (`not_found`, `access_denied`, `throttled`, `unavailable`,
|
|
116
|
+
`timeout`, `validation`, `malformed`, or `unsupported`). Any other exception
|
|
117
|
+
is `other`, and its traceback goes to the daemon log, as `print` does.
|
|
118
|
+
- After `initialize`, functions run on up to 8 threads at the same time. Keep
|
|
119
|
+
the state thread-safe, for example a `sqlite3` connection behind a
|
|
120
|
+
`threading.Lock`.
|
|
121
|
+
- Do not sleep for a rate limit. Raise `Failure.throttled`, and Stash retries.
|
|
122
|
+
- [`examples/notes.py`](https://github.com/strands-agents/stash/blob/main/integrations/plugin-sdk/python/examples/notes.py)
|
|
123
|
+
uses `@plugin.list`, `@plugin.get`, and `@plugin.ingest`.
|
|
124
|
+
|
|
125
|
+
## A `Record`
|
|
126
|
+
|
|
127
|
+
| Field | Description |
|
|
128
|
+
|---|---|
|
|
129
|
+
| `id` | The same for the same record in each call. |
|
|
130
|
+
| `body` | The text of the file. |
|
|
131
|
+
| `dir` | The folder below the source, such as `team/runbooks`. The SDK removes a `/` at the start or the end. |
|
|
132
|
+
| `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`. |
|
|
133
|
+
| `preview` | The line that a search shows. With none, the body. |
|
|
134
|
+
| `created_at`, `updated_at` | A `datetime` (a naive one is UTC) or RFC 3339 text. |
|
|
135
|
+
|
|
136
|
+
The file is `<dir>/<name>`. A `.md` file is the body, then the time of the
|
|
137
|
+
fetch in a YAML block. Any other file is the body alone.
|
|
138
|
+
Follow the protocol's
|
|
139
|
+
[path rules](https://github.com/strands-agents/stash/blob/main/docs/user/plugins.md#paths)
|
|
140
|
+
when a store supplies `dir` or `name`.
|
|
141
|
+
|
|
142
|
+
## Publish it
|
|
143
|
+
|
|
144
|
+
Name the package and its program `stash-source-<plugin>`. For a source with
|
|
145
|
+
no `command`, Stash runs that program from the `PATH` of the daemon.
|
|
146
|
+
|
|
147
|
+
```toml
|
|
148
|
+
[project]
|
|
149
|
+
name = "stash-source-perplexity"
|
|
150
|
+
dependencies = ["strands-stash-plugin"]
|
|
151
|
+
|
|
152
|
+
[project.scripts]
|
|
153
|
+
stash-source-perplexity = "stash_source_perplexity:main"
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
A user installs it with `pipx install stash-source-perplexity`, and adds a
|
|
157
|
+
source with no `command`:
|
|
158
|
+
|
|
159
|
+
```toml
|
|
160
|
+
[sources.web]
|
|
161
|
+
kind = "plugin"
|
|
162
|
+
plugin = "perplexity"
|
|
163
|
+
env = { PERPLEXITY_API_KEY = { command = ["op", "read", "op://me/perplexity/api-key"] } }
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
A source that writes the trajectory of the agent back sets
|
|
167
|
+
`write.trajectory = {}`, and the plugin must serve `ingest`. The plugin gets
|
|
168
|
+
only a few variables of the daemon, such as `PATH` and `HOME`, and the
|
|
169
|
+
variables in `env`.
|
|
170
|
+
|
|
171
|
+
## Try it
|
|
172
|
+
|
|
173
|
+
[`examples/notes.py`](https://github.com/strands-agents/stash/blob/main/integrations/plugin-sdk/python/examples/notes.py)
|
|
174
|
+
serves the Markdown files of one folder. It needs no other package:
|
|
175
|
+
|
|
176
|
+
```toml
|
|
177
|
+
[sources.notes]
|
|
178
|
+
kind = "plugin"
|
|
179
|
+
plugin = "notes"
|
|
180
|
+
command = ["python3", "/path/to/examples/notes.py"]
|
|
181
|
+
settings = { root = "~/notes" }
|
|
182
|
+
env = { PYTHONPATH = "/path/to/integrations/plugin-sdk/python/src" }
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Run the tests with `python3 -m unittest discover -s tests`.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
stash_plugin/__init__.py,sha256=gm-pJHIHwIj98D6nCAnPBFpWBS7cNZLFaRQPaT1q7Og,14208
|
|
2
|
+
stash_plugin/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
strands_stash_plugin-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
4
|
+
strands_stash_plugin-0.1.0.dist-info/licenses/NOTICE,sha256=St1b9JUj0iUDNQOJKqBqr05bHrpXcwyyQYgB7FmtRtA,145
|
|
5
|
+
strands_stash_plugin-0.1.0.dist-info/METADATA,sha256=344IqiIHdZEmwe2vnzjEc_hgnkR_Nsyv9ASUuAfXiX4,7533
|
|
6
|
+
strands_stash_plugin-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
strands_stash_plugin-0.1.0.dist-info/top_level.txt,sha256=CBoG0IiulZ_uYscr6ZWtQ1ZqOnymfLl7Nv9lQJdZxfs,13
|
|
8
|
+
strands_stash_plugin-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
stash_plugin
|