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.
- fromscratch_pystack-0.5.0.dist-info/METADATA +510 -0
- fromscratch_pystack-0.5.0.dist-info/RECORD +43 -0
- fromscratch_pystack-0.5.0.dist-info/WHEEL +4 -0
- fromscratch_pystack-0.5.0.dist-info/entry_points.txt +3 -0
- fromscratch_pystack-0.5.0.dist-info/licenses/LICENSE +21 -0
- pystack/__init__.py +1 -0
- pystack/_version.py +24 -0
- pystack/adapters/__init__.py +1 -0
- pystack/adapters/db_storage.py +157 -0
- pystack/adapters/os_pebble.py +118 -0
- pystack/adapters/pebble_db.py +85 -0
- pystack/cli.py +127 -0
- pystack/environment.py +272 -0
- pystack/plugins/__init__.py +1 -0
- pystack/plugins/_dbcrash_child.py +56 -0
- pystack/plugins/_schedagents.py +37 -0
- pystack/plugins/_schedalerts.py +103 -0
- pystack/plugins/_schedweb.py +79 -0
- pystack/plugins/_shared.py +26 -0
- pystack/plugins/_webdemo.py +171 -0
- pystack/plugins/base.py +201 -0
- pystack/plugins/coldb_plugin.py +165 -0
- pystack/plugins/crypto_plugin.py +115 -0
- pystack/plugins/docdb_plugin.py +172 -0
- pystack/plugins/git_plugin.py +94 -0
- pystack/plugins/graphdb_plugin.py +206 -0
- pystack/plugins/kv_plugin.py +156 -0
- pystack/plugins/llm_plugin.py +102 -0
- pystack/plugins/mq_plugin.py +290 -0
- pystack/plugins/net_plugin.py +247 -0
- pystack/plugins/pydb_plugin.py +111 -0
- pystack/plugins/registry.py +150 -0
- pystack/plugins/sched_plugin.py +235 -0
- pystack/plugins/search_plugin.py +151 -0
- pystack/plugins/tsdb_plugin.py +175 -0
- pystack/plugins/vecdb_plugin.py +168 -0
- pystack/plugins/web_plugin.py +95 -0
- pystack/py.typed +0 -0
- pystack/web/__init__.py +1 -0
- pystack/web/app.py +138 -0
- pystack/web/static/app.js +105 -0
- pystack/web/static/style.css +158 -0
- pystack/web/templates/index.html +59 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""PyTSDB integration plugin for PyStack.
|
|
2
|
+
|
|
3
|
+
Bridge PyTSDB's time-series database into Pebble so kids can record
|
|
4
|
+
timestamped measurements, query time ranges, and compute averages.
|
|
5
|
+
|
|
6
|
+
A time-series database is like a weather station's logbook -- every
|
|
7
|
+
few minutes you jot down the temperature along with the current time.
|
|
8
|
+
|
|
9
|
+
Pebble module name: ``tsdb``
|
|
10
|
+
|
|
11
|
+
Example Pebble usage::
|
|
12
|
+
|
|
13
|
+
import "tsdb"
|
|
14
|
+
ts_add("temperature", 72.5)
|
|
15
|
+
ts_add("temperature", 74.0)
|
|
16
|
+
let avg = ts_avg("temperature", 3600)
|
|
17
|
+
print(avg)
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from datetime import timedelta
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from pebble import StdlibModule
|
|
24
|
+
from pebble import Value as PebbleValue
|
|
25
|
+
from pytsdb.aggregation import AggFunc, aggregate
|
|
26
|
+
from pytsdb.database import TimeSeriesDB
|
|
27
|
+
from pytsdb.errors import PyTSDBError
|
|
28
|
+
from pytsdb.persistence import load, save
|
|
29
|
+
|
|
30
|
+
from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_method
|
|
31
|
+
|
|
32
|
+
_DB_FILE = "db.json"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class TSDBPlugin(Plugin):
|
|
36
|
+
"""Integrate PyTSDB time-series database functions into PyStack.
|
|
37
|
+
|
|
38
|
+
Register add/query/avg functions in Pebble's ``tsdb`` stdlib
|
|
39
|
+
module and shell commands for interactive use.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(self) -> None:
|
|
43
|
+
"""Start with no data; it is created on first use or loaded at start-up."""
|
|
44
|
+
self._db: TimeSeriesDB | None = None
|
|
45
|
+
|
|
46
|
+
def _get_db(self) -> TimeSeriesDB:
|
|
47
|
+
"""Return this plugin's TimeSeriesDB, creating it on first use."""
|
|
48
|
+
if self._db is None:
|
|
49
|
+
self._db = TimeSeriesDB()
|
|
50
|
+
return self._db
|
|
51
|
+
|
|
52
|
+
def _add_point(self, series_name: str, raw_value: str) -> float | str:
|
|
53
|
+
"""Add *raw_value* to *series_name*, creating the series if needed.
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
The value added, or an ``"error: ..."`` message when the value
|
|
57
|
+
isn't a number (``"abc"``) or PyTSDB refuses it (``"nan"``).
|
|
58
|
+
|
|
59
|
+
"""
|
|
60
|
+
try:
|
|
61
|
+
value = float(raw_value)
|
|
62
|
+
db = self._get_db()
|
|
63
|
+
# Auto-create the series if it doesn't exist.
|
|
64
|
+
if series_name not in db.list_series():
|
|
65
|
+
db.create_series(series_name)
|
|
66
|
+
db.add_point(series_name, value=value)
|
|
67
|
+
except (ValueError, PyTSDBError) as exc:
|
|
68
|
+
return f"error: {exc}"
|
|
69
|
+
return value
|
|
70
|
+
|
|
71
|
+
@pebble_method
|
|
72
|
+
def ts_add(self, args: list[PebbleValue]) -> PebbleValue:
|
|
73
|
+
"""Add a data point to a named time series: "ok", or "error: ..." for a bad value."""
|
|
74
|
+
added = self._add_point(str(args[0]), str(args[1]))
|
|
75
|
+
return added if isinstance(added, str) else "ok"
|
|
76
|
+
|
|
77
|
+
@pebble_method
|
|
78
|
+
def ts_query(self, args: list[PebbleValue]) -> PebbleValue:
|
|
79
|
+
"""Query all data points in a named time series."""
|
|
80
|
+
series_name = str(args[0])
|
|
81
|
+
db = self._get_db()
|
|
82
|
+
points = db.query(series_name)
|
|
83
|
+
result: list[PebbleValue] = [p.value for p in points]
|
|
84
|
+
return result
|
|
85
|
+
|
|
86
|
+
@pebble_method
|
|
87
|
+
def ts_avg(self, args: list[PebbleValue]) -> PebbleValue:
|
|
88
|
+
"""Compute the average of a series over a time window (in seconds)."""
|
|
89
|
+
series_name = str(args[0])
|
|
90
|
+
window_seconds = int(str(args[1]))
|
|
91
|
+
db = self._get_db()
|
|
92
|
+
points = db.query(series_name)
|
|
93
|
+
if not points:
|
|
94
|
+
return "error: no data points"
|
|
95
|
+
window = timedelta(seconds=window_seconds)
|
|
96
|
+
agg_points = aggregate(points, window=window, func=AggFunc.AVG)
|
|
97
|
+
if not agg_points:
|
|
98
|
+
return "error: no data in window"
|
|
99
|
+
result: list[PebbleValue] = [p.value for p in agg_points]
|
|
100
|
+
return result
|
|
101
|
+
|
|
102
|
+
def load_state(self, folder: Path) -> None:
|
|
103
|
+
"""Load the saved database, if there is one."""
|
|
104
|
+
path = folder / _DB_FILE
|
|
105
|
+
if path.exists():
|
|
106
|
+
self._db = load(path)
|
|
107
|
+
|
|
108
|
+
def save_state(self, folder: Path) -> None:
|
|
109
|
+
"""Save the database, if this run used or loaded one."""
|
|
110
|
+
if self._db is None:
|
|
111
|
+
return
|
|
112
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
113
|
+
save(self._db, folder / _DB_FILE)
|
|
114
|
+
|
|
115
|
+
def info(self) -> PluginInfo:
|
|
116
|
+
"""Return plugin metadata."""
|
|
117
|
+
return PluginInfo(
|
|
118
|
+
name="PyTSDB",
|
|
119
|
+
description="Time-series database for Pebble programs",
|
|
120
|
+
version="0.1.0",
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
def pebble_module_name(self) -> str:
|
|
124
|
+
"""Return the Pebble import name."""
|
|
125
|
+
return "tsdb"
|
|
126
|
+
|
|
127
|
+
def pebble_stdlib(self) -> StdlibModule:
|
|
128
|
+
"""Return the tsdb stdlib module with add/query/avg functions."""
|
|
129
|
+
return StdlibModule(
|
|
130
|
+
functions={
|
|
131
|
+
"ts_add": (2, self.ts_add),
|
|
132
|
+
"ts_query": (1, self.ts_query),
|
|
133
|
+
"ts_avg": (2, self.ts_avg),
|
|
134
|
+
},
|
|
135
|
+
constants={},
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def shell_commands(self) -> list[ShellCommand]:
|
|
139
|
+
"""Return the ts shell commands."""
|
|
140
|
+
|
|
141
|
+
def _ts_add_cmd(args: list[str]) -> str:
|
|
142
|
+
"""Add a data point to a series."""
|
|
143
|
+
if len(args) < 2: # noqa: PLR2004
|
|
144
|
+
return "Usage: ts-add <series> <value>"
|
|
145
|
+
series_name = args[0]
|
|
146
|
+
added = self._add_point(series_name, args[1])
|
|
147
|
+
if isinstance(added, str):
|
|
148
|
+
return added
|
|
149
|
+
return f"Added {added} to '{series_name}'"
|
|
150
|
+
|
|
151
|
+
def _ts_query_cmd(args: list[str]) -> str:
|
|
152
|
+
"""Query data points in a series."""
|
|
153
|
+
if not args:
|
|
154
|
+
return "Usage: ts-query <series>"
|
|
155
|
+
points = self._get_db().query(args[0])
|
|
156
|
+
if not points:
|
|
157
|
+
return "(no data points)"
|
|
158
|
+
return "\n".join(f"{p.timestamp}: {p.value}" for p in points)
|
|
159
|
+
|
|
160
|
+
def _ts_avg_cmd(args: list[str]) -> str:
|
|
161
|
+
"""Compute average over a time window."""
|
|
162
|
+
if len(args) < 2: # noqa: PLR2004
|
|
163
|
+
return "Usage: ts-avg <series> <window_seconds>"
|
|
164
|
+
points = self._get_db().query(args[0])
|
|
165
|
+
if not points:
|
|
166
|
+
return "(no data points)"
|
|
167
|
+
window = timedelta(seconds=int(args[1]))
|
|
168
|
+
agg_points = aggregate(points, window=window, func=AggFunc.AVG)
|
|
169
|
+
return "\n".join(f"{p.timestamp}: {p.value}" for p in agg_points)
|
|
170
|
+
|
|
171
|
+
return [
|
|
172
|
+
ShellCommand(name="ts-add", handler=_ts_add_cmd, help_text="Add data point"),
|
|
173
|
+
ShellCommand(name="ts-query", handler=_ts_query_cmd, help_text="Query series"),
|
|
174
|
+
ShellCommand(name="ts-avg", handler=_ts_avg_cmd, help_text="Average over window"),
|
|
175
|
+
]
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""PyVecDB integration plugin for PyStack.
|
|
2
|
+
|
|
3
|
+
Bridge PyVecDB's vector database into Pebble so kids can insert vectors,
|
|
4
|
+
search for similar ones, and compute cosine similarity.
|
|
5
|
+
|
|
6
|
+
A vector database is like a music app that turns songs into lists of
|
|
7
|
+
numbers, then finds other songs with similar numbers -- that is how
|
|
8
|
+
recommendations work!
|
|
9
|
+
|
|
10
|
+
Pebble module name: ``vecdb``
|
|
11
|
+
|
|
12
|
+
Example Pebble usage::
|
|
13
|
+
|
|
14
|
+
import "vecdb"
|
|
15
|
+
vec_insert("song1", [0.9, 0.1, 0.3])
|
|
16
|
+
vec_insert("song2", [0.2, 0.8, 0.4])
|
|
17
|
+
let results = vec_search([0.85, 0.15, 0.35], 1)
|
|
18
|
+
print(results)
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from pebble import StdlibModule
|
|
24
|
+
from pebble import Value as PebbleValue
|
|
25
|
+
from pyvecdb.distance import cosine_similarity
|
|
26
|
+
from pyvecdb.persistence import load_store, save_store
|
|
27
|
+
from pyvecdb.search import knn_search
|
|
28
|
+
from pyvecdb.store import VectorStore
|
|
29
|
+
|
|
30
|
+
from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_handler, pebble_method
|
|
31
|
+
|
|
32
|
+
DEFAULT_DIMENSIONS = 3
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _parse_vector(raw: PebbleValue) -> list[float]:
|
|
36
|
+
"""Parse a vector from a Pebble value (list of numbers or string)."""
|
|
37
|
+
if isinstance(raw, list):
|
|
38
|
+
return [float(str(item)) for item in raw]
|
|
39
|
+
# Try parsing as string like "[0.1, 0.2, 0.3]"
|
|
40
|
+
text = str(raw).strip("[]")
|
|
41
|
+
return [float(x.strip()) for x in text.split(",")]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@pebble_handler
|
|
45
|
+
def _vec_cosine(args: list[PebbleValue]) -> PebbleValue:
|
|
46
|
+
"""Compute cosine similarity between two vectors."""
|
|
47
|
+
vec_a = _parse_vector(args[0])
|
|
48
|
+
vec_b = _parse_vector(args[1])
|
|
49
|
+
return cosine_similarity(vec_a, vec_b)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
_STORE_FILE = "store.json"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class VecDBPlugin(Plugin):
|
|
56
|
+
"""Integrate PyVecDB vector database functions into PyStack.
|
|
57
|
+
|
|
58
|
+
Register insert/search/cosine functions in Pebble's ``vecdb``
|
|
59
|
+
stdlib module and shell commands for interactive use.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(self) -> None:
|
|
63
|
+
"""Start with no data; it is created on first use or loaded at start-up."""
|
|
64
|
+
self._store: VectorStore | None = None
|
|
65
|
+
|
|
66
|
+
def _get_store(self, dimensions: int = DEFAULT_DIMENSIONS) -> VectorStore:
|
|
67
|
+
"""Return this plugin's VectorStore, creating it on first use."""
|
|
68
|
+
if self._store is None:
|
|
69
|
+
self._store = VectorStore(dimensions=dimensions)
|
|
70
|
+
return self._store
|
|
71
|
+
|
|
72
|
+
@pebble_method
|
|
73
|
+
def vec_insert(self, args: list[PebbleValue]) -> PebbleValue:
|
|
74
|
+
"""Insert a vector with an id into the store."""
|
|
75
|
+
record_id = str(args[0])
|
|
76
|
+
vector = _parse_vector(args[1])
|
|
77
|
+
store = self._get_store(dimensions=len(vector))
|
|
78
|
+
store.insert(record_id, vector)
|
|
79
|
+
return record_id
|
|
80
|
+
|
|
81
|
+
@pebble_method
|
|
82
|
+
def vec_search(self, args: list[PebbleValue]) -> PebbleValue:
|
|
83
|
+
"""Search for the k most similar vectors."""
|
|
84
|
+
query_vector = _parse_vector(args[0])
|
|
85
|
+
k = int(str(args[1])) if len(args) > 1 else 1
|
|
86
|
+
if self._store is None:
|
|
87
|
+
# Don't create the store here: that would fix its vector size
|
|
88
|
+
# (and save it) just because someone searched an empty store.
|
|
89
|
+
return "error: Cannot search an empty store"
|
|
90
|
+
store = self._store
|
|
91
|
+
results = knn_search(store, query=query_vector, k=k)
|
|
92
|
+
result_list: list[PebbleValue] = [r.record_id for r, _score in results]
|
|
93
|
+
return result_list
|
|
94
|
+
|
|
95
|
+
def load_state(self, folder: Path) -> None:
|
|
96
|
+
"""Load the saved vector store, if there is one."""
|
|
97
|
+
path = folder / _STORE_FILE
|
|
98
|
+
if path.exists():
|
|
99
|
+
self._store = load_store(path)
|
|
100
|
+
|
|
101
|
+
def save_state(self, folder: Path) -> None:
|
|
102
|
+
"""Save the vector store, if this run used or loaded one."""
|
|
103
|
+
if self._store is None:
|
|
104
|
+
return
|
|
105
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
106
|
+
save_store(self._store, folder / _STORE_FILE)
|
|
107
|
+
|
|
108
|
+
def info(self) -> PluginInfo:
|
|
109
|
+
"""Return plugin metadata."""
|
|
110
|
+
return PluginInfo(
|
|
111
|
+
name="PyVecDB",
|
|
112
|
+
description="Vector database for Pebble programs",
|
|
113
|
+
version="0.1.0",
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
def pebble_module_name(self) -> str:
|
|
117
|
+
"""Return the Pebble import name."""
|
|
118
|
+
return "vecdb"
|
|
119
|
+
|
|
120
|
+
def pebble_stdlib(self) -> StdlibModule:
|
|
121
|
+
"""Return the vecdb stdlib module with insert/search/cosine functions."""
|
|
122
|
+
return StdlibModule(
|
|
123
|
+
functions={
|
|
124
|
+
"vec_insert": (2, self.vec_insert),
|
|
125
|
+
"vec_search": (2, self.vec_search),
|
|
126
|
+
"vec_cosine": (2, _vec_cosine),
|
|
127
|
+
},
|
|
128
|
+
constants={},
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
def shell_commands(self) -> list[ShellCommand]:
|
|
132
|
+
"""Return the vec shell commands."""
|
|
133
|
+
|
|
134
|
+
def _vec_cmd(args: list[str]) -> str:
|
|
135
|
+
"""Handle vec subcommands: insert, search, cosine."""
|
|
136
|
+
if not args:
|
|
137
|
+
return "Usage: vec <insert|search|cosine> [args...]"
|
|
138
|
+
|
|
139
|
+
sub = args[0]
|
|
140
|
+
min_insert_args = 3
|
|
141
|
+
min_search_args = 2
|
|
142
|
+
min_cosine_args = 3
|
|
143
|
+
|
|
144
|
+
if sub == "insert" and len(args) >= min_insert_args:
|
|
145
|
+
record_id = args[1]
|
|
146
|
+
vector = _parse_vector(args[2])
|
|
147
|
+
store = self._get_store(dimensions=len(vector))
|
|
148
|
+
store.insert(record_id, vector)
|
|
149
|
+
return f"Inserted '{record_id}'"
|
|
150
|
+
|
|
151
|
+
if sub == "search" and len(args) >= min_search_args:
|
|
152
|
+
query_vector = _parse_vector(args[1])
|
|
153
|
+
k = int(args[2]) if len(args) >= min_cosine_args else 1
|
|
154
|
+
store = self._get_store(dimensions=len(query_vector))
|
|
155
|
+
results = knn_search(store, query=query_vector, k=k)
|
|
156
|
+
return "\n".join(f"{r.record_id}: {score:.4f}" for r, score in results)
|
|
157
|
+
|
|
158
|
+
if sub == "cosine" and len(args) >= min_cosine_args:
|
|
159
|
+
vec_a = _parse_vector(args[1])
|
|
160
|
+
vec_b = _parse_vector(args[2])
|
|
161
|
+
sim = cosine_similarity(vec_a, vec_b)
|
|
162
|
+
return f"{sim:.6f}"
|
|
163
|
+
|
|
164
|
+
return "Usage: vec <insert|search|cosine> [args...]"
|
|
165
|
+
|
|
166
|
+
return [
|
|
167
|
+
ShellCommand(name="vec", handler=_vec_cmd, help_text="Vector database operations"),
|
|
168
|
+
]
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""PyWeb integration plugin for PyStack.
|
|
2
|
+
|
|
3
|
+
Bridge HTTP client functionality into Pebble so kids can fetch web
|
|
4
|
+
pages and parse URLs from their Pebble programs. Since PyWeb is a
|
|
5
|
+
server framework, the HTTP client operations use PyNet's HTTP module.
|
|
6
|
+
|
|
7
|
+
The web is like a giant library you visit by mail -- you send off the
|
|
8
|
+
address of a page and a copy of it comes back to you.
|
|
9
|
+
|
|
10
|
+
Pebble module name: ``web``
|
|
11
|
+
|
|
12
|
+
Example Pebble usage::
|
|
13
|
+
|
|
14
|
+
import "web"
|
|
15
|
+
let parsed = url_parse("https://example.com:8080/hello?name=world")
|
|
16
|
+
print(parsed["host"])
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from pebble import StdlibModule
|
|
20
|
+
from pebble import Value as PebbleValue
|
|
21
|
+
from pynet.http import get as http_get_impl
|
|
22
|
+
|
|
23
|
+
from pystack.plugins._shared import url_parse as _url_parse
|
|
24
|
+
from pystack.plugins._webdemo import webdemo as _webdemo
|
|
25
|
+
from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_handler
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@pebble_handler
|
|
29
|
+
def _http_get(args: list[PebbleValue]) -> PebbleValue:
|
|
30
|
+
"""Fetch the body of a URL via HTTP GET."""
|
|
31
|
+
url = str(args[0])
|
|
32
|
+
response = http_get_impl(url)
|
|
33
|
+
return response.body
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class WebPlugin(Plugin):
|
|
37
|
+
"""Integrate PyWeb and PyNet HTTP functions into PyStack.
|
|
38
|
+
|
|
39
|
+
Register HTTP client and URL parsing functions in Pebble's ``web``
|
|
40
|
+
stdlib module, and ``curl`` and ``webdemo`` shell commands.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def info(self) -> PluginInfo:
|
|
44
|
+
"""Return plugin metadata."""
|
|
45
|
+
return PluginInfo(
|
|
46
|
+
name="PyWeb",
|
|
47
|
+
description="HTTP client and URL parsing for Pebble programs",
|
|
48
|
+
version="0.1.0",
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
def pebble_module_name(self) -> str:
|
|
52
|
+
"""Return the Pebble import name."""
|
|
53
|
+
return "web"
|
|
54
|
+
|
|
55
|
+
def pebble_stdlib(self) -> StdlibModule:
|
|
56
|
+
"""Return the web stdlib module with http_get and url_parse."""
|
|
57
|
+
return StdlibModule(
|
|
58
|
+
functions={
|
|
59
|
+
"http_get": (1, _http_get),
|
|
60
|
+
"url_parse": (1, _url_parse),
|
|
61
|
+
},
|
|
62
|
+
constants={},
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def shell_commands(self) -> list[ShellCommand]:
|
|
66
|
+
"""Return the curl and webdemo shell commands."""
|
|
67
|
+
|
|
68
|
+
def _curl_cmd(args: list[str]) -> str:
|
|
69
|
+
"""Fetch a URL and print the response body."""
|
|
70
|
+
if not args:
|
|
71
|
+
return "Usage: curl <url>"
|
|
72
|
+
url = args[0]
|
|
73
|
+
try:
|
|
74
|
+
response = http_get_impl(url)
|
|
75
|
+
except Exception as exc: # noqa: BLE001
|
|
76
|
+
return f"error: {exc}"
|
|
77
|
+
else:
|
|
78
|
+
return response.body
|
|
79
|
+
|
|
80
|
+
def _webdemo_cmd(_args: list[str]) -> str:
|
|
81
|
+
"""Tour PyWeb's async server: login, cookie, protected API and events."""
|
|
82
|
+
return _webdemo()
|
|
83
|
+
|
|
84
|
+
return [
|
|
85
|
+
ShellCommand(
|
|
86
|
+
name="curl",
|
|
87
|
+
handler=_curl_cmd,
|
|
88
|
+
help_text="Fetch a URL (educational, may fail without network)",
|
|
89
|
+
),
|
|
90
|
+
ShellCommand(
|
|
91
|
+
name="webdemo",
|
|
92
|
+
handler=_webdemo_cmd,
|
|
93
|
+
help_text="Tour PyWeb's async server: login, cookie, private API, live events",
|
|
94
|
+
),
|
|
95
|
+
]
|
pystack/py.typed
ADDED
|
File without changes
|
pystack/web/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""PyStack web UI -- browser-based interface for the integrated platform."""
|
pystack/web/app.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Flask application for the PyStack web UI.
|
|
2
|
+
|
|
3
|
+
Provide a browser-based interface with three panels:
|
|
4
|
+
- OS Terminal: run PyOS shell commands
|
|
5
|
+
- Pebble Editor: write and run Pebble programs
|
|
6
|
+
- SQL Console: execute SQL queries
|
|
7
|
+
|
|
8
|
+
All three share the same integrated environment.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import atexit
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from flask import Flask, Response, jsonify, render_template, request
|
|
15
|
+
from py_os.kernel import KernelState
|
|
16
|
+
from py_os.shell import Shell
|
|
17
|
+
|
|
18
|
+
from pystack.environment import PyStackEnvironment
|
|
19
|
+
|
|
20
|
+
_HTTP_BAD_REQUEST = 400
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def create_app(data_dir: str | Path = "pystack_data") -> Flask:
|
|
24
|
+
"""Create the PyStack web application.
|
|
25
|
+
|
|
26
|
+
Boot the integrated environment (kernel + database + Pebble) and
|
|
27
|
+
wire up the API endpoints.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
data_dir: Where the database and plugin data are kept.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
A configured Flask application. Its environment is in
|
|
34
|
+
``app.extensions["pystack_env"]``, so whoever runs the app can
|
|
35
|
+
shut it down (which saves everything).
|
|
36
|
+
|
|
37
|
+
"""
|
|
38
|
+
env = PyStackEnvironment(db_path=data_dir, os_mode=True)
|
|
39
|
+
|
|
40
|
+
shell = env.shell
|
|
41
|
+
kernel = env.kernel
|
|
42
|
+
if not isinstance(shell, Shell):
|
|
43
|
+
msg = "Shell not available -- OS mode failed to boot"
|
|
44
|
+
raise TypeError(msg)
|
|
45
|
+
|
|
46
|
+
boot_log = "\n".join(kernel.dmesg()) if kernel else ""
|
|
47
|
+
|
|
48
|
+
app = Flask(__name__)
|
|
49
|
+
app.extensions["pystack_env"] = env
|
|
50
|
+
|
|
51
|
+
@app.route("/")
|
|
52
|
+
def index() -> str: # pyright: ignore[reportUnusedFunction]
|
|
53
|
+
"""Render the main page."""
|
|
54
|
+
return render_template("index.html", boot_log=boot_log)
|
|
55
|
+
|
|
56
|
+
@app.route("/api/shell", methods=["POST"])
|
|
57
|
+
def api_shell() -> tuple[Response, int] | Response: # pyright: ignore[reportUnusedFunction]
|
|
58
|
+
"""Execute a PyOS shell command.
|
|
59
|
+
|
|
60
|
+
Body: ``{"command": "ls /"}``
|
|
61
|
+
|
|
62
|
+
"""
|
|
63
|
+
data = request.get_json(silent=True)
|
|
64
|
+
if data is None or "command" not in data:
|
|
65
|
+
return jsonify({"error": "Missing 'command' field"}), _HTTP_BAD_REQUEST
|
|
66
|
+
|
|
67
|
+
if kernel and kernel.state is not KernelState.RUNNING:
|
|
68
|
+
return jsonify({"output": "System halted.", "halted": True})
|
|
69
|
+
|
|
70
|
+
command: str = data["command"]
|
|
71
|
+
result = shell.execute(command)
|
|
72
|
+
halted = result == Shell.EXIT_SENTINEL
|
|
73
|
+
if not halted:
|
|
74
|
+
return jsonify({"output": result, "halted": False})
|
|
75
|
+
# Save now, but leave the environment open: the Pebble and SQL panels
|
|
76
|
+
# still work after ``exit``, and stopping the server saves those too.
|
|
77
|
+
message = "System halted."
|
|
78
|
+
try:
|
|
79
|
+
env.save()
|
|
80
|
+
except ExceptionGroup as exc:
|
|
81
|
+
message += f" Warning: {exc}"
|
|
82
|
+
if kernel and kernel.state is KernelState.RUNNING:
|
|
83
|
+
kernel.shutdown()
|
|
84
|
+
return jsonify({"output": message, "halted": True})
|
|
85
|
+
|
|
86
|
+
@app.route("/api/pebble", methods=["POST"])
|
|
87
|
+
def api_pebble() -> tuple[Response, int] | Response: # pyright: ignore[reportUnusedFunction]
|
|
88
|
+
"""Execute Pebble source code.
|
|
89
|
+
|
|
90
|
+
Body: ``{"source": "print(1 + 2)"}``
|
|
91
|
+
|
|
92
|
+
"""
|
|
93
|
+
data = request.get_json(silent=True)
|
|
94
|
+
if data is None or "source" not in data:
|
|
95
|
+
return jsonify({"error": "Missing 'source' field"}), _HTTP_BAD_REQUEST
|
|
96
|
+
|
|
97
|
+
source: str = data["source"]
|
|
98
|
+
try:
|
|
99
|
+
output = env.run_pebble_source(source)
|
|
100
|
+
except Exception as exc: # noqa: BLE001
|
|
101
|
+
return jsonify({"output": f"Error: {exc}", "error": True})
|
|
102
|
+
return jsonify({"output": output, "error": False})
|
|
103
|
+
|
|
104
|
+
@app.route("/api/sql", methods=["POST"])
|
|
105
|
+
def api_sql() -> tuple[Response, int] | Response: # pyright: ignore[reportUnusedFunction]
|
|
106
|
+
"""Execute a SQL statement.
|
|
107
|
+
|
|
108
|
+
Body: ``{"sql": "SELECT * FROM cards"}``
|
|
109
|
+
|
|
110
|
+
"""
|
|
111
|
+
data = request.get_json(silent=True)
|
|
112
|
+
if data is None or "sql" not in data:
|
|
113
|
+
return jsonify({"error": "Missing 'sql' field"}), _HTTP_BAD_REQUEST
|
|
114
|
+
|
|
115
|
+
sql: str = data["sql"]
|
|
116
|
+
try:
|
|
117
|
+
output = env.run_sql(sql)
|
|
118
|
+
except Exception as exc: # noqa: BLE001
|
|
119
|
+
return jsonify({"output": f"Error: {exc}", "error": True})
|
|
120
|
+
return jsonify({"output": output, "error": False})
|
|
121
|
+
|
|
122
|
+
return app
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def main(data_dir: str | Path = "pystack_data") -> None:
|
|
126
|
+
"""Run the web UI development server, saving everything when it stops.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
data_dir: Where the database and plugin data are kept.
|
|
130
|
+
|
|
131
|
+
"""
|
|
132
|
+
app = create_app(data_dir)
|
|
133
|
+
env: PyStackEnvironment = app.extensions["pystack_env"]
|
|
134
|
+
atexit.register(env.shutdown) # backstop; shutdown() only runs once
|
|
135
|
+
try:
|
|
136
|
+
app.run(port=8080)
|
|
137
|
+
finally:
|
|
138
|
+
env.shutdown()
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// PyStack Web UI -- connects the three panels to the API.
|
|
2
|
+
|
|
3
|
+
// -- Tab switching --
|
|
4
|
+
document.querySelectorAll('.tab').forEach(tab => {
|
|
5
|
+
tab.addEventListener('click', () => {
|
|
6
|
+
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
|
|
7
|
+
document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
|
|
8
|
+
tab.classList.add('active');
|
|
9
|
+
document.getElementById(tab.dataset.panel).classList.add('active');
|
|
10
|
+
|
|
11
|
+
// Focus the right input.
|
|
12
|
+
const panel = tab.dataset.panel;
|
|
13
|
+
if (panel === 'terminal') document.getElementById('terminal-input').focus();
|
|
14
|
+
if (panel === 'sql') document.getElementById('sql-input').focus();
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
// -- Helpers --
|
|
19
|
+
function appendOutput(elementId, text, className) {
|
|
20
|
+
const el = document.getElementById(elementId);
|
|
21
|
+
const line = document.createElement('div');
|
|
22
|
+
line.textContent = text;
|
|
23
|
+
if (className) line.className = className;
|
|
24
|
+
el.appendChild(line);
|
|
25
|
+
el.scrollTop = el.scrollHeight;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function postJSON(url, body) {
|
|
29
|
+
const resp = await fetch(url, {
|
|
30
|
+
method: 'POST',
|
|
31
|
+
headers: { 'Content-Type': 'application/json' },
|
|
32
|
+
body: JSON.stringify(body),
|
|
33
|
+
});
|
|
34
|
+
return resp.json();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// -- Terminal --
|
|
38
|
+
const terminalInput = document.getElementById('terminal-input');
|
|
39
|
+
const terminalHistory = [];
|
|
40
|
+
let historyIndex = -1;
|
|
41
|
+
|
|
42
|
+
terminalInput.addEventListener('keydown', async (e) => {
|
|
43
|
+
if (e.key === 'Enter') {
|
|
44
|
+
const cmd = terminalInput.value.trim();
|
|
45
|
+
if (!cmd) return;
|
|
46
|
+
terminalHistory.push(cmd);
|
|
47
|
+
historyIndex = terminalHistory.length;
|
|
48
|
+
appendOutput('terminal-output', `pystack-os> ${cmd}`);
|
|
49
|
+
terminalInput.value = '';
|
|
50
|
+
|
|
51
|
+
const data = await postJSON('/api/shell', { command: cmd });
|
|
52
|
+
if (data.output) {
|
|
53
|
+
appendOutput('terminal-output', data.output);
|
|
54
|
+
}
|
|
55
|
+
if (data.halted) {
|
|
56
|
+
appendOutput('terminal-output', '[System halted]', 'error');
|
|
57
|
+
terminalInput.disabled = true;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (e.key === 'ArrowUp') {
|
|
61
|
+
e.preventDefault();
|
|
62
|
+
if (historyIndex > 0) {
|
|
63
|
+
historyIndex--;
|
|
64
|
+
terminalInput.value = terminalHistory[historyIndex];
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (e.key === 'ArrowDown') {
|
|
68
|
+
e.preventDefault();
|
|
69
|
+
if (historyIndex < terminalHistory.length - 1) {
|
|
70
|
+
historyIndex++;
|
|
71
|
+
terminalInput.value = terminalHistory[historyIndex];
|
|
72
|
+
} else {
|
|
73
|
+
historyIndex = terminalHistory.length;
|
|
74
|
+
terminalInput.value = '';
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// -- Pebble Editor --
|
|
80
|
+
document.getElementById('pebble-run').addEventListener('click', async () => {
|
|
81
|
+
const source = document.getElementById('pebble-source').value;
|
|
82
|
+
const output = document.getElementById('pebble-output');
|
|
83
|
+
output.textContent = 'Running...\n';
|
|
84
|
+
|
|
85
|
+
const data = await postJSON('/api/pebble', { source });
|
|
86
|
+
output.textContent = data.output || '(no output)';
|
|
87
|
+
if (data.error) output.classList.add('error');
|
|
88
|
+
else output.classList.remove('error');
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
// -- SQL Console --
|
|
92
|
+
const sqlInput = document.getElementById('sql-input');
|
|
93
|
+
|
|
94
|
+
sqlInput.addEventListener('keydown', async (e) => {
|
|
95
|
+
if (e.key === 'Enter') {
|
|
96
|
+
const sql = sqlInput.value.trim();
|
|
97
|
+
if (!sql) return;
|
|
98
|
+
appendOutput('sql-output', `sql> ${sql}`);
|
|
99
|
+
sqlInput.value = '';
|
|
100
|
+
|
|
101
|
+
const data = await postJSON('/api/sql', { sql });
|
|
102
|
+
const cls = data.error ? 'error' : '';
|
|
103
|
+
appendOutput('sql-output', data.output || '(no output)', cls);
|
|
104
|
+
}
|
|
105
|
+
});
|