fromscratch-pystack 0.5.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.
Files changed (43) hide show
  1. fromscratch_pystack-0.5.0.dist-info/METADATA +510 -0
  2. fromscratch_pystack-0.5.0.dist-info/RECORD +43 -0
  3. fromscratch_pystack-0.5.0.dist-info/WHEEL +4 -0
  4. fromscratch_pystack-0.5.0.dist-info/entry_points.txt +3 -0
  5. fromscratch_pystack-0.5.0.dist-info/licenses/LICENSE +21 -0
  6. pystack/__init__.py +1 -0
  7. pystack/_version.py +24 -0
  8. pystack/adapters/__init__.py +1 -0
  9. pystack/adapters/db_storage.py +157 -0
  10. pystack/adapters/os_pebble.py +118 -0
  11. pystack/adapters/pebble_db.py +85 -0
  12. pystack/cli.py +127 -0
  13. pystack/environment.py +272 -0
  14. pystack/plugins/__init__.py +1 -0
  15. pystack/plugins/_dbcrash_child.py +56 -0
  16. pystack/plugins/_schedagents.py +37 -0
  17. pystack/plugins/_schedalerts.py +103 -0
  18. pystack/plugins/_schedweb.py +79 -0
  19. pystack/plugins/_shared.py +26 -0
  20. pystack/plugins/_webdemo.py +171 -0
  21. pystack/plugins/base.py +201 -0
  22. pystack/plugins/coldb_plugin.py +165 -0
  23. pystack/plugins/crypto_plugin.py +115 -0
  24. pystack/plugins/docdb_plugin.py +172 -0
  25. pystack/plugins/git_plugin.py +94 -0
  26. pystack/plugins/graphdb_plugin.py +206 -0
  27. pystack/plugins/kv_plugin.py +156 -0
  28. pystack/plugins/llm_plugin.py +102 -0
  29. pystack/plugins/mq_plugin.py +290 -0
  30. pystack/plugins/net_plugin.py +247 -0
  31. pystack/plugins/pydb_plugin.py +111 -0
  32. pystack/plugins/registry.py +150 -0
  33. pystack/plugins/sched_plugin.py +235 -0
  34. pystack/plugins/search_plugin.py +151 -0
  35. pystack/plugins/tsdb_plugin.py +175 -0
  36. pystack/plugins/vecdb_plugin.py +168 -0
  37. pystack/plugins/web_plugin.py +95 -0
  38. pystack/py.typed +0 -0
  39. pystack/web/__init__.py +1 -0
  40. pystack/web/app.py +138 -0
  41. pystack/web/static/app.js +105 -0
  42. pystack/web/static/style.css +158 -0
  43. pystack/web/templates/index.html +59 -0
@@ -0,0 +1,172 @@
1
+ """PyDocDB integration plugin for PyStack.
2
+
3
+ Bridge PyDocDB's document store into Pebble so kids can insert, find,
4
+ and count JSON-like documents from their Pebble programs.
5
+
6
+ A document database is like a filing cabinet where every index card
7
+ can have different fields -- no fixed schema required!
8
+
9
+ Pebble module name: ``docdb``
10
+
11
+ Example Pebble usage::
12
+
13
+ import "docdb"
14
+ doc_insert("students", {"name": "Alice", "age": 14})
15
+ let results = doc_find("students", {"name": "Alice"})
16
+ print(results)
17
+ """
18
+
19
+ import hashlib
20
+ import json
21
+ from pathlib import Path
22
+ from urllib.parse import quote
23
+
24
+ from pebble import StdlibModule
25
+ from pebble import Value as PebbleValue
26
+ from pydocdb.collection import Collection
27
+ from pydocdb.persistence import load_collection, save_collection
28
+
29
+ from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_method
30
+
31
+ # Long enough to be readable, short enough for any file system.
32
+ _MAX_READABLE_NAME = 60
33
+
34
+
35
+ def _collection_file(name: str) -> str:
36
+ """Return a safe, unique file name for collection *name*.
37
+
38
+ The name comes from a Pebble program, so it could be anything: ``../x``,
39
+ an empty string, or ``Pets`` next to ``pets`` (the same file on a Mac,
40
+ whose disk ignores case). An escaped, shortened copy of the name keeps
41
+ the file readable; a short fingerprint of the exact name keeps it unique.
42
+ The real name is stored inside the file and used when loading.
43
+ """
44
+ readable = quote(name, safe="")[:_MAX_READABLE_NAME]
45
+ fingerprint = hashlib.sha256(name.encode("utf-8")).hexdigest()[:12]
46
+ return f"{readable}-{fingerprint}.json"
47
+
48
+
49
+ class DocDBPlugin(Plugin):
50
+ """Integrate PyDocDB document store functions into PyStack.
51
+
52
+ Register insert/find/count functions in Pebble's ``docdb`` stdlib
53
+ module and shell commands for interactive use.
54
+ """
55
+
56
+ def __init__(self) -> None:
57
+ """Start with no data; it is created on first use or loaded at start-up."""
58
+ self._collections: dict[str, Collection] = {}
59
+
60
+ def _get_collection(self, name: str) -> Collection:
61
+ """Return a collection by name, creating it if needed."""
62
+ if name not in self._collections:
63
+ self._collections[name] = Collection(name)
64
+ return self._collections[name]
65
+
66
+ @pebble_method
67
+ def doc_insert(self, args: list[PebbleValue]) -> PebbleValue:
68
+ """Insert a document into a named collection."""
69
+ collection_name = str(args[0])
70
+ data = args[1]
71
+ col = self._get_collection(collection_name)
72
+ if isinstance(data, dict):
73
+ doc = col.insert_one(data)
74
+ return str(doc.id)
75
+ return "error: data must be a dictionary"
76
+
77
+ @pebble_method
78
+ def doc_find(self, args: list[PebbleValue]) -> PebbleValue:
79
+ """Find documents in a collection matching a query."""
80
+ collection_name = str(args[0])
81
+ query = args[1] if len(args) > 1 else {}
82
+ col = self._get_collection(collection_name)
83
+ if not isinstance(query, dict):
84
+ query = {}
85
+ results = col.find(query)
86
+ result_list: list[PebbleValue] = [str(r) for r in results]
87
+ return result_list
88
+
89
+ @pebble_method
90
+ def doc_count(self, args: list[PebbleValue]) -> PebbleValue:
91
+ """Count documents in a collection."""
92
+ collection_name = str(args[0])
93
+ col = self._get_collection(collection_name)
94
+ return col.count()
95
+
96
+ def load_state(self, folder: Path) -> None:
97
+ """Load every saved collection (one file each)."""
98
+ if not folder.is_dir():
99
+ return
100
+ for path in sorted(folder.glob("*.json")):
101
+ collection = load_collection(path)
102
+ self._collections[collection.name] = collection
103
+
104
+ def save_state(self, folder: Path) -> None:
105
+ """Save every collection, one file each (see :func:`_collection_file`)."""
106
+ if not self._collections:
107
+ return
108
+ folder.mkdir(parents=True, exist_ok=True)
109
+ for name, collection in self._collections.items():
110
+ save_collection(collection, folder / _collection_file(name))
111
+
112
+ def info(self) -> PluginInfo:
113
+ """Return plugin metadata."""
114
+ return PluginInfo(
115
+ name="PyDocDB",
116
+ description="Document store for Pebble programs",
117
+ version="0.1.0",
118
+ )
119
+
120
+ def pebble_module_name(self) -> str:
121
+ """Return the Pebble import name."""
122
+ return "docdb"
123
+
124
+ def pebble_stdlib(self) -> StdlibModule:
125
+ """Return the docdb stdlib module with insert/find/count functions."""
126
+ return StdlibModule(
127
+ functions={
128
+ "doc_insert": (2, self.doc_insert),
129
+ "doc_find": (2, self.doc_find),
130
+ "doc_count": (1, self.doc_count),
131
+ },
132
+ constants={},
133
+ )
134
+
135
+ def shell_commands(self) -> list[ShellCommand]:
136
+ """Return the doc shell commands."""
137
+
138
+ def _doc_insert_cmd(args: list[str]) -> str:
139
+ """Insert a document into a collection."""
140
+ if len(args) < 2: # noqa: PLR2004
141
+ return "Usage: doc-insert <collection> <json>"
142
+ try:
143
+ data = json.loads(" ".join(args[1:]))
144
+ except json.JSONDecodeError:
145
+ return "Error: invalid JSON"
146
+ doc = self._get_collection(args[0]).insert_one(data)
147
+ return f"Inserted document {doc.id}"
148
+
149
+ def _doc_find_cmd(args: list[str]) -> str:
150
+ """Find documents in a collection."""
151
+ if not args:
152
+ return "Usage: doc-find <collection> [query]"
153
+ query: dict[str, object] = {}
154
+ if len(args) >= 2: # noqa: PLR2004
155
+ try:
156
+ query = json.loads(" ".join(args[1:]))
157
+ except json.JSONDecodeError:
158
+ return "Error: invalid JSON query"
159
+ results = self._get_collection(args[0]).find(query)
160
+ return "\n".join(str(r) for r in results) if results else "(no documents found)"
161
+
162
+ def _doc_count_cmd(args: list[str]) -> str:
163
+ """Count documents in a collection."""
164
+ if not args:
165
+ return "Usage: doc-count <collection>"
166
+ return str(self._get_collection(args[0]).count())
167
+
168
+ return [
169
+ ShellCommand(name="doc-insert", handler=_doc_insert_cmd, help_text="Insert a document"),
170
+ ShellCommand(name="doc-find", handler=_doc_find_cmd, help_text="Find documents"),
171
+ ShellCommand(name="doc-count", handler=_doc_count_cmd, help_text="Count documents"),
172
+ ]
@@ -0,0 +1,94 @@
1
+ """PyGit integration plugin for PyStack.
2
+
3
+ Bridge PyGit's hashing and diff functionality into Pebble so kids can
4
+ compute Git-style SHA-1 hashes and diff two strings from their Pebble
5
+ programs.
6
+
7
+ Version control is like a photographer who fingerprints every snapshot
8
+ and circles exactly what changed between two photos.
9
+
10
+ Pebble module name: ``git``
11
+
12
+ Example Pebble usage::
13
+
14
+ import "git"
15
+ let h = git_hash("hello world")
16
+ print(h)
17
+
18
+ let d = git_diff("line1", "line2")
19
+ print(d)
20
+ """
21
+
22
+ from pebble import StdlibModule
23
+ from pebble import Value as PebbleValue
24
+ from pygit.diff import diff_lines, format_diff
25
+ from pygit.hashing import hash_object
26
+
27
+ from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_handler
28
+
29
+
30
+ @pebble_handler
31
+ def _git_hash(args: list[PebbleValue]) -> PebbleValue:
32
+ """Return the Git blob hash of a text string -- the same as ``git hash-object``."""
33
+ return hash_object("blob", str(args[0]).encode())
34
+
35
+
36
+ @pebble_handler
37
+ def _git_diff(args: list[PebbleValue]) -> PebbleValue:
38
+ """Return a unified diff between two text strings."""
39
+ old = str(args[0])
40
+ new = str(args[1])
41
+ lines = diff_lines(old, new)
42
+ return format_diff(lines)
43
+
44
+
45
+ class GitPlugin(Plugin):
46
+ """Integrate PyGit hashing and diff into PyStack.
47
+
48
+ Register git_hash and git_diff functions in Pebble's ``git``
49
+ stdlib module, and a ``git-hash`` shell command.
50
+ """
51
+
52
+ def info(self) -> PluginInfo:
53
+ """Return plugin metadata."""
54
+ return PluginInfo(
55
+ name="PyGit",
56
+ description="Git hashing and diff for Pebble programs",
57
+ version="0.1.0",
58
+ )
59
+
60
+ def pebble_module_name(self) -> str:
61
+ """Return the Pebble import name."""
62
+ return "git"
63
+
64
+ def pebble_stdlib(self) -> StdlibModule:
65
+ """Return the git stdlib module with git_hash and git_diff."""
66
+ return StdlibModule(
67
+ functions={
68
+ "git_hash": (1, _git_hash),
69
+ "git_diff": (2, _git_diff),
70
+ },
71
+ constants={},
72
+ )
73
+
74
+ def shell_commands(self) -> list[ShellCommand]:
75
+ """Return git-hash and git-diff shell commands."""
76
+
77
+ def _git_hash_cmd(args: list[str]) -> str:
78
+ """Print the SHA-1 hash of the given text."""
79
+ if not args:
80
+ return "Usage: git-hash <text>"
81
+ text = " ".join(args)
82
+ return hash_object("blob", text.encode())
83
+
84
+ def _git_diff_cmd(args: list[str]) -> str:
85
+ """Show a diff (requires two arguments)."""
86
+ if len(args) < 2: # noqa: PLR2004
87
+ return "Usage: git-diff <old> <new>"
88
+ lines = diff_lines(args[0], args[1])
89
+ return format_diff(lines)
90
+
91
+ return [
92
+ ShellCommand(name="git-hash", handler=_git_hash_cmd, help_text="Print SHA-1 hash"),
93
+ ShellCommand(name="git-diff", handler=_git_diff_cmd, help_text="Show diff"),
94
+ ]
@@ -0,0 +1,206 @@
1
+ """PyGraphDB integration plugin for PyStack.
2
+
3
+ Bridge PyGraphDB's graph database into Pebble so kids can create nodes,
4
+ add edges, find shortest paths, and traverse graphs from their programs.
5
+
6
+ A graph database stores data as nodes (dots) and edges (lines connecting
7
+ them) -- like a social network map showing who is friends with whom.
8
+
9
+ Pebble module name: ``graphdb``
10
+
11
+ Example Pebble usage::
12
+
13
+ import "graphdb"
14
+ graph_add_node("alice", "Person")
15
+ graph_add_node("bob", "Person")
16
+ graph_add_edge("alice", "bob", "KNOWS")
17
+ let path = graph_shortest_path("alice", "bob")
18
+ print(path)
19
+ """
20
+
21
+ import sys
22
+ from pathlib import Path
23
+ from typing import cast
24
+
25
+ from pebble import StdlibModule
26
+ from pebble import Value as PebbleValue
27
+ from pygraphdb.graph import Graph
28
+ from pygraphdb.pathfinding import shortest_path
29
+ from pygraphdb.persistence import load_graph, save_graph
30
+ from pygraphdb.traversal import bfs
31
+
32
+ from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_method
33
+
34
+ _GRAPH_FILE = "graph.json"
35
+
36
+
37
+ def _saved_edges(graph: Graph) -> list[dict[str, str]]:
38
+ """Return the edges of *graph* as plain dicts (each has an ``edge_id``)."""
39
+ edges = graph.to_dict()["edges"]
40
+ return cast("list[dict[str, str]]", edges)
41
+
42
+
43
+ def _counter_number(edge_id: str) -> int | None:
44
+ """Return the number in an id this plugin makes itself (``e7`` -> 7), else None."""
45
+ number = edge_id[1:]
46
+ # ``isdigit`` alone also says yes to "²", which ``int`` can't read,
47
+ # and this plugin only ever writes 0-9.
48
+ if not (edge_id.startswith("e") and number.isascii() and number.isdigit()):
49
+ return None
50
+ # Python reads and writes ints of at most 4,300 digits. An id that long
51
+ # (``e`` + 4,300 nines) has a next id nobody can write down, so it can't
52
+ # be one this plugin numbered: don't count from it.
53
+ limit = sys.get_int_max_str_digits()
54
+ if limit and len(number) >= limit:
55
+ return None
56
+ return int(number)
57
+
58
+
59
+ class GraphDBPlugin(Plugin):
60
+ """Integrate PyGraphDB graph database functions into PyStack.
61
+
62
+ Register node/edge/path/traversal functions in Pebble's ``graphdb``
63
+ stdlib module and shell commands for interactive use.
64
+ """
65
+
66
+ def __init__(self) -> None:
67
+ """Start with no data; it is created on first use or loaded at start-up."""
68
+ self._graph: Graph | None = None
69
+ self._edge_counter: int = 0
70
+
71
+ def _get_graph(self) -> Graph:
72
+ """Return this plugin's Graph, creating it on first use."""
73
+ if self._graph is None:
74
+ self._graph = Graph()
75
+ return self._graph
76
+
77
+ def _next_edge_id(self) -> str:
78
+ """Return the next ``e<n>`` id, skipping any the graph already has."""
79
+ graph = self._get_graph()
80
+ while True:
81
+ self._edge_counter += 1
82
+ edge_id = f"e{self._edge_counter}"
83
+ if not graph.has_edge(edge_id):
84
+ return edge_id
85
+
86
+ @pebble_method
87
+ def graph_add_node(self, args: list[PebbleValue]) -> PebbleValue:
88
+ """Add a node to the graph with an id and label."""
89
+ node_id = str(args[0])
90
+ label = str(args[1]) if len(args) > 1 else ""
91
+ g = self._get_graph()
92
+ g.add_node(node_id, label=label)
93
+ return node_id
94
+
95
+ @pebble_method
96
+ def graph_add_edge(self, args: list[PebbleValue]) -> PebbleValue:
97
+ """Add an edge between two nodes."""
98
+ from_id = str(args[0])
99
+ to_id = str(args[1])
100
+ rel_type = str(args[2]) if len(args) > 2 else "CONNECTED" # noqa: PLR2004
101
+ g = self._get_graph()
102
+ edge_id = self._next_edge_id()
103
+ g.add_edge(edge_id, from_id, to_id, rel_type=rel_type)
104
+ return edge_id
105
+
106
+ @pebble_method
107
+ def graph_shortest_path(self, args: list[PebbleValue]) -> PebbleValue:
108
+ """Find the shortest path between two nodes."""
109
+ from_id = str(args[0])
110
+ to_id = str(args[1])
111
+ g = self._get_graph()
112
+ path = shortest_path(g, from_id, to_id)
113
+ if not path:
114
+ return "no path"
115
+ result: list[PebbleValue] = [n.node_id for n in path]
116
+ return result
117
+
118
+ @pebble_method
119
+ def graph_bfs(self, args: list[PebbleValue]) -> PebbleValue:
120
+ """Perform breadth-first search from a start node."""
121
+ start_id = str(args[0])
122
+ g = self._get_graph()
123
+ visited = bfs(g, start_id)
124
+ result: list[PebbleValue] = [n.node_id for n in visited]
125
+ return result
126
+
127
+ def load_state(self, folder: Path) -> None:
128
+ """Load the saved graph, if there is one."""
129
+ path = folder / _GRAPH_FILE
130
+ if path.exists():
131
+ self._graph = load_graph(path)
132
+ # New edges get ids after the saved ones (e1, e2, ...).
133
+ numbers = (_counter_number(edge["edge_id"]) for edge in _saved_edges(self._graph))
134
+ self._edge_counter = max((n for n in numbers if n is not None), default=0)
135
+
136
+ def save_state(self, folder: Path) -> None:
137
+ """Save the graph, if this run used or loaded one."""
138
+ if self._graph is None:
139
+ return
140
+ folder.mkdir(parents=True, exist_ok=True)
141
+ save_graph(self._graph, folder / _GRAPH_FILE)
142
+
143
+ def info(self) -> PluginInfo:
144
+ """Return plugin metadata."""
145
+ return PluginInfo(
146
+ name="PyGraphDB",
147
+ description="Graph database for Pebble programs",
148
+ version="0.1.0",
149
+ )
150
+
151
+ def pebble_module_name(self) -> str:
152
+ """Return the Pebble import name."""
153
+ return "graphdb"
154
+
155
+ def pebble_stdlib(self) -> StdlibModule:
156
+ """Return the graphdb stdlib module with node/edge/path functions."""
157
+ return StdlibModule(
158
+ functions={
159
+ "graph_add_node": (2, self.graph_add_node),
160
+ "graph_add_edge": (3, self.graph_add_edge),
161
+ "graph_shortest_path": (2, self.graph_shortest_path),
162
+ "graph_bfs": (1, self.graph_bfs),
163
+ },
164
+ constants={},
165
+ )
166
+
167
+ def shell_commands(self) -> list[ShellCommand]:
168
+ """Return the graph shell commands."""
169
+
170
+ def _graph_cmd(args: list[str]) -> str:
171
+ """Handle graph subcommands: add-node, add-edge, path."""
172
+ if not args:
173
+ return "Usage: graph <add-node|add-edge|path> [args...]"
174
+
175
+ sub = args[0]
176
+ min_add_node_args = 3
177
+ min_add_edge_args = 4
178
+ min_path_args = 3
179
+
180
+ if sub == "add-node" and len(args) >= min_add_node_args:
181
+ node_id = args[1]
182
+ label = args[2]
183
+ self._get_graph().add_node(node_id, label=label)
184
+ return f"Added node '{node_id}' ({label})"
185
+
186
+ if sub == "add-edge" and len(args) >= min_path_args:
187
+ from_id = args[1]
188
+ to_id = args[2]
189
+ rel_type = args[3] if len(args) >= min_add_edge_args else "CONNECTED"
190
+ edge_id = self._next_edge_id()
191
+ self._get_graph().add_edge(edge_id, from_id, to_id, rel_type=rel_type)
192
+ return f"Added edge {from_id} -[{rel_type}]-> {to_id}"
193
+
194
+ if sub == "path" and len(args) >= min_path_args:
195
+ from_id = args[1]
196
+ to_id = args[2]
197
+ path = shortest_path(self._get_graph(), from_id, to_id)
198
+ if not path:
199
+ return "No path found"
200
+ return " -> ".join(n.node_id for n in path)
201
+
202
+ return "Usage: graph <add-node|add-edge|path> [args...]"
203
+
204
+ return [
205
+ ShellCommand(name="graph", handler=_graph_cmd, help_text="Graph database operations"),
206
+ ]
@@ -0,0 +1,156 @@
1
+ """PyKV integration plugin for PyStack.
2
+
3
+ Bridge PyKV's key-value store into Pebble so kids can store and retrieve
4
+ data by key, list all keys, and delete entries from their Pebble programs.
5
+
6
+ A key-value store is like a giant phonebook -- you look up a name (key)
7
+ and get back the phone number (value).
8
+
9
+ Pebble module name: ``kv``
10
+
11
+ Example Pebble usage::
12
+
13
+ import "kv"
14
+ kv_set("name", "Alice")
15
+ let who = kv_get("name")
16
+ print(who)
17
+ """
18
+
19
+ from pathlib import Path
20
+
21
+ from pebble import StdlibModule
22
+ from pebble import Value as PebbleValue
23
+ from pykv.persistence import load_store, save_store
24
+ from pykv.store import BasicStore
25
+
26
+ from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_method
27
+
28
+ _STORE_FILE = "store.json"
29
+
30
+
31
+ class KVPlugin(Plugin):
32
+ """Integrate PyKV key-value store functions into PyStack.
33
+
34
+ Register get/set/delete/keys functions in Pebble's ``kv`` stdlib
35
+ module and shell commands for interactive use.
36
+ """
37
+
38
+ def __init__(self) -> None:
39
+ """Start with no data; it is created on first use or loaded at start-up."""
40
+ self._store: BasicStore | None = None
41
+
42
+ def _get_store(self) -> BasicStore:
43
+ """Return this plugin's store, creating it on first use."""
44
+ if self._store is None:
45
+ self._store = BasicStore()
46
+ return self._store
47
+
48
+ @pebble_method
49
+ def kv_set(self, args: list[PebbleValue]) -> PebbleValue:
50
+ """Store a value under a key."""
51
+ key = str(args[0])
52
+ value = str(args[1])
53
+ self._get_store().set(key, value)
54
+ return "ok"
55
+
56
+ @pebble_method
57
+ def kv_get(self, args: list[PebbleValue]) -> PebbleValue:
58
+ """Retrieve a value by key, or 'not found' if missing."""
59
+ key = str(args[0])
60
+ store = self._get_store()
61
+ try:
62
+ return str(store.get(key))
63
+ except Exception: # noqa: BLE001
64
+ return "not found"
65
+
66
+ @pebble_method
67
+ def kv_delete(self, args: list[PebbleValue]) -> PebbleValue:
68
+ """Delete a key: answer "ok", or "error: key '<key>' not found" if it wasn't there."""
69
+ key = str(args[0])
70
+ if not self._get_store().delete(key):
71
+ return f"error: key '{key}' not found"
72
+ return "ok"
73
+
74
+ @pebble_method
75
+ def kv_keys(self, args: list[PebbleValue]) -> PebbleValue: # noqa: ARG002 -- Pebble passes args
76
+ """Return all keys in the store as a list."""
77
+ store = self._get_store()
78
+ result: list[PebbleValue] = list(store.keys())
79
+ return result
80
+
81
+ def load_state(self, folder: Path) -> None:
82
+ """Load the saved store, if there is one."""
83
+ path = folder / _STORE_FILE
84
+ if path.exists():
85
+ self._store = load_store(path)
86
+
87
+ def save_state(self, folder: Path) -> None:
88
+ """Save the store, if this run used or loaded one."""
89
+ if self._store is None:
90
+ return
91
+ folder.mkdir(parents=True, exist_ok=True)
92
+ save_store(self._store, folder / _STORE_FILE)
93
+
94
+ def info(self) -> PluginInfo:
95
+ """Return plugin metadata."""
96
+ return PluginInfo(
97
+ name="PyKV",
98
+ description="Key-value store for Pebble programs",
99
+ version="0.1.0",
100
+ )
101
+
102
+ def pebble_module_name(self) -> str:
103
+ """Return the Pebble import name."""
104
+ return "kv"
105
+
106
+ def pebble_stdlib(self) -> StdlibModule:
107
+ """Return the kv stdlib module with get/set/delete/keys functions."""
108
+ return StdlibModule(
109
+ functions={
110
+ "kv_set": (2, self.kv_set),
111
+ "kv_get": (1, self.kv_get),
112
+ "kv_delete": (1, self.kv_delete),
113
+ "kv_keys": (0, self.kv_keys),
114
+ },
115
+ constants={},
116
+ )
117
+
118
+ def shell_commands(self) -> list[ShellCommand]:
119
+ """Return the kv shell commands."""
120
+
121
+ def _kv_set_cmd(args: list[str]) -> str:
122
+ """Set a key-value pair."""
123
+ if len(args) < 2: # noqa: PLR2004
124
+ return "Usage: kv-set <key> <value>"
125
+ key, value = args[0], " ".join(args[1:])
126
+ self._get_store().set(key, value)
127
+ return f"Set '{key}' = '{value}'"
128
+
129
+ def _kv_get_cmd(args: list[str]) -> str:
130
+ """Get a value by key."""
131
+ if not args:
132
+ return "Usage: kv-get <key>"
133
+ try:
134
+ return str(self._get_store().get(args[0]))
135
+ except Exception: # noqa: BLE001
136
+ return f"Key '{args[0]}' not found"
137
+
138
+ def _kv_delete_cmd(args: list[str]) -> str:
139
+ """Delete a key: "Deleted '<key>'", or "Key '<key>' not found"."""
140
+ if not args:
141
+ return "Usage: kv-delete <key>"
142
+ if not self._get_store().delete(args[0]):
143
+ return f"Key '{args[0]}' not found"
144
+ return f"Deleted '{args[0]}'"
145
+
146
+ def _kv_keys_cmd(args: list[str]) -> str: # noqa: ARG001
147
+ """List all keys."""
148
+ keys = list(self._get_store().keys())
149
+ return ", ".join(keys) if keys else "(no keys)"
150
+
151
+ return [
152
+ ShellCommand(name="kv-set", handler=_kv_set_cmd, help_text="Set a key-value pair"),
153
+ ShellCommand(name="kv-get", handler=_kv_get_cmd, help_text="Get value by key"),
154
+ ShellCommand(name="kv-delete", handler=_kv_delete_cmd, help_text="Delete a key"),
155
+ ShellCommand(name="kv-keys", handler=_kv_keys_cmd, help_text="List all keys"),
156
+ ]