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,102 @@
1
+ """PyStack plugin exposing PyLLM (the brain) to Pebble as the ``llm`` module.
2
+
3
+ A language model is like an imaginative friend who has read tons of text and
4
+ can keep writing in the same style -- give it a few words and it dreams up
5
+ what might come next.
6
+
7
+ This is the loop-closing plugin: it lets a Pebble program ``import "llm"`` and ask
8
+ PyLLM to write text -- including *more Pebble code*. The brain of the series
9
+ writing the language of the series. It calls PyLLM's cached public API, so the
10
+ model is loaded once and reused.
11
+ """
12
+
13
+ import pyllm
14
+ from pebble import StdlibModule
15
+ from pebble import Value as PebbleValue
16
+
17
+ from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_handler
18
+
19
+
20
+ @pebble_handler
21
+ def _llm_generate(args: list[PebbleValue]) -> PebbleValue:
22
+ """Write Pebble-flavoured code from a prompt string."""
23
+ prompt = str(args[0]) if args else "let "
24
+ return pyllm.generate_pebble(prompt=prompt, max_new_tokens=120)
25
+
26
+
27
+ def _as_comment(request: str) -> str:
28
+ """Turn a plain-English request into a one-line Pebble comment.
29
+
30
+ Like writing the task at the top of your page: ``# add two numbers``. Any
31
+ line breaks are squashed into spaces so the request can't leak into the code.
32
+ """
33
+ return "# " + " ".join(request.split()) + "\n"
34
+
35
+
36
+ @pebble_handler
37
+ def _llm_write_pebble(args: list[PebbleValue]) -> PebbleValue:
38
+ """Write Pebble code that is guaranteed to parse (the referee is watching).
39
+
40
+ PyLLM's grammar referee only lets the model write legal Pebble. If the prompt
41
+ is already the start of some code (``"let "``) we carry on from it; if it's a
42
+ plain-English request the referee rejects it, so we pin it to the top as a
43
+ comment and let the model write real code underneath.
44
+ """
45
+ prompt = str(args[0]) if args else "let "
46
+ try:
47
+ return pyllm.generate_pebble(prompt=prompt, max_new_tokens=120, constrained=True)
48
+ except ValueError: # the referee blew the whistle on the prompt itself
49
+ return pyllm.generate_pebble(
50
+ prompt=_as_comment(prompt), max_new_tokens=120, constrained=True
51
+ )
52
+
53
+
54
+ @pebble_handler
55
+ def _llm_dream(args: list[PebbleValue]) -> PebbleValue:
56
+ """Dream up Pokemon-ish names from a prompt string."""
57
+ prompt = str(args[0]) if args else ""
58
+ return pyllm.generate_pokemon(prompt=prompt, max_new_tokens=40)
59
+
60
+
61
+ class LLMPlugin(Plugin):
62
+ """Wires PyLLM into PyStack as the Pebble ``llm`` module (and a shell command)."""
63
+
64
+ def info(self) -> PluginInfo:
65
+ """Return metadata naming PyLLM the brain of the series."""
66
+ return PluginInfo(
67
+ name="PyLLM",
68
+ description="A from-scratch language model -- the brain of the series.",
69
+ )
70
+
71
+ def pebble_module_name(self) -> str:
72
+ """Pebble programs reach PyLLM via ``import "llm"``."""
73
+ return "llm"
74
+
75
+ def pebble_stdlib(self) -> StdlibModule:
76
+ """Expose ``llm_generate`` / ``llm_write_pebble`` (Pebble) and ``llm_dream``."""
77
+ return StdlibModule(
78
+ functions={
79
+ "llm_generate": (1, _llm_generate),
80
+ "llm_write_pebble": (1, _llm_write_pebble),
81
+ "llm_dream": (1, _llm_dream),
82
+ },
83
+ constants={},
84
+ )
85
+
86
+ def shell_commands(self) -> list[ShellCommand]:
87
+ """Add a ``dream`` shell command that generates Pokemon names."""
88
+
89
+ def _dream_cmd(args: list[str]) -> str:
90
+ """Dream up new Pokemon names, returning a friendly error on failure."""
91
+ try:
92
+ return pyllm.generate_pokemon(prompt=" ".join(args), max_new_tokens=40)
93
+ except Exception as exc: # noqa: BLE001
94
+ return f"error: {exc}"
95
+
96
+ return [
97
+ ShellCommand(
98
+ name="dream",
99
+ handler=_dream_cmd,
100
+ help_text="Dream up new Pokemon names with PyLLM.",
101
+ )
102
+ ]
@@ -0,0 +1,290 @@
1
+ """PyMQ integration plugin for PyStack.
2
+
3
+ Bridge PyMQ's message queue and pub/sub primitives into Pebble so kids
4
+ can create queues, put and get messages, and publish/subscribe to topics
5
+ from their Pebble programs.
6
+
7
+ A message queue is like the order rail at a busy kitchen -- cooks pin up
8
+ tickets and chefs grab them one at a time, in order.
9
+
10
+ Shell command ``mqnet`` runs PyMQ's networked broker -- a real post office
11
+ with a front door -- on a free local port. Two workers collect parcels
12
+ (jobs): worker A takes the first job and crashes before finishing it (its
13
+ connection is lost), so the broker takes the lease back and worker B gets
14
+ the job on its second attempt. A poison job nobody can do ends up in the
15
+ dead-letter box.
16
+
17
+ Messages still waiting when PyStack stops are saved in
18
+ ``pystack_data/mq/queues.json`` and are there again next time, like a real
19
+ broker. Pub/sub subscriptions are live only, like a radio: they don't
20
+ outlive the run.
21
+
22
+ Pebble module name: ``mq``
23
+
24
+ Example Pebble usage::
25
+
26
+ import "mq"
27
+ let q = mq_create("orders")
28
+ mq_put("orders", "one coffee please")
29
+ let msg = mq_get("orders")
30
+ print(msg)
31
+ """
32
+
33
+ from pathlib import Path
34
+
35
+ from pebble import StdlibModule
36
+ from pebble import Value as PebbleValue
37
+ from pymq.broker import BrokerClient, BrokerServer, Delivery, QueueConfig, TopicEvent
38
+ from pymq.persistence import load_queues, save_queues
39
+ from pymq.pubsub import PubSub
40
+ from pymq.queue import BaseMessageQueue, MessageQueue
41
+ from pynet.loop import Event, run, sleep, timeout
42
+
43
+ from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_method
44
+
45
+ LOOPBACK = "127.0.0.1"
46
+ MQNET_TIMEOUT = 5.0
47
+ MQNET_MAX_ATTEMPTS = 2
48
+ MQNET_ACK_TIMEOUT = 0.5
49
+ MQNET_RETRY_DELAY = 0.1
50
+ MQNET_POLL = 0.01
51
+ POISON_JOB = "job-boom"
52
+ _QUEUES_FILE = "queues.json"
53
+
54
+
55
+ async def _mqnet_story(out: list[str]) -> None:
56
+ """Tell the mqnet story, appending one line per step to ``out``."""
57
+ a_has_job = Event()
58
+ job_done = Event()
59
+ dead_seen = Event()
60
+ dead_topics: list[str] = []
61
+
62
+ async def worker_a(delivery: Delivery) -> None:
63
+ """Take the first job and never settle it: worker A is about to crash."""
64
+ out.append(
65
+ f"worker A: took {delivery.body} (attempt {delivery.attempt})"
66
+ " and crashed - connection lost"
67
+ )
68
+ a_has_job.set()
69
+
70
+ async def worker_b(delivery: Delivery) -> None:
71
+ """Finish every job except the poison one, which is handed back each time."""
72
+ if delivery.body == POISON_JOB:
73
+ out.append(f"worker B: {delivery.body} failed (attempt {delivery.attempt})")
74
+ await delivery.nack(error="poison job")
75
+ return
76
+ out.append(f"worker B: {delivery.body} done (attempt {delivery.attempt})")
77
+ job_done.set()
78
+
79
+ async def on_dead(event: TopicEvent) -> None:
80
+ """Remember the dead-letter announcement."""
81
+ dead_topics.append(event.topic)
82
+ dead_seen.set()
83
+
84
+ server = BrokerServer()
85
+ await server.start(LOOPBACK, 0)
86
+ try:
87
+ async with (
88
+ timeout(MQNET_TIMEOUT),
89
+ BrokerClient(LOOPBACK, server.port) as boss,
90
+ BrokerClient(LOOPBACK, server.port) as ann,
91
+ BrokerClient(LOOPBACK, server.port) as bob,
92
+ ):
93
+ out.append("broker: listening on a free local port")
94
+ config = QueueConfig(
95
+ max_attempts=MQNET_MAX_ATTEMPTS,
96
+ ack_timeout=MQNET_ACK_TIMEOUT,
97
+ retry_delay=MQNET_RETRY_DELAY,
98
+ )
99
+ await boss.declare_queue("jobs", config)
100
+ await boss.subscribe("$sys.dead.*", on_dead)
101
+ out.append("boss: declared queue 'jobs' (2 attempts per job)")
102
+ await ann.consume("jobs", worker_a, prefetch=1, auto_ack=False)
103
+ await boss.put("jobs", "job-1")
104
+ await a_has_job.wait()
105
+ await ann.close() # the crash: worker A's connection drops, job-1 unacked
106
+ while (await boss.stats("jobs")).ready != 1:
107
+ await sleep(MQNET_POLL) # wait for the broker to take the lease back
108
+ out.append("broker: took job-1 back from worker A (lease returned, attempt 1 used up)")
109
+ await bob.consume("jobs", worker_b, prefetch=1)
110
+ await job_done.wait()
111
+ job_done.clear()
112
+ await boss.put("jobs", "job-2")
113
+ await job_done.wait()
114
+ await boss.put("jobs", POISON_JOB)
115
+ await dead_seen.wait()
116
+ letters = await boss.dead_letters("jobs")
117
+ out.extend(f"dead: {d.envelope.body} ({d.reason}) - {d.error}" for d in letters)
118
+ out.append(f"announced: {dead_topics[0]}")
119
+ finally:
120
+ await server.close()
121
+ out.append("broker: closed")
122
+
123
+
124
+ def _mqnet_cmd(_args: list[str]) -> str:
125
+ """Run a small job-queue story against a real PyMQ broker on localhost."""
126
+ lines: list[str] = []
127
+ try:
128
+ run(_mqnet_story(lines))
129
+ except Exception as exc: # noqa: BLE001
130
+ lines.append(f"error: {exc}")
131
+ return "\n".join(lines)
132
+
133
+
134
+ class MQPlugin(Plugin):
135
+ """Integrate PyMQ message queue functions into PyStack.
136
+
137
+ Register queue and pub/sub functions in Pebble's ``mq`` stdlib
138
+ module, and ``mq-put`` / ``mq-get`` / ``mqnet`` shell commands.
139
+ """
140
+
141
+ def __init__(self) -> None:
142
+ """Start with no queues; they are created on first use or loaded at start-up."""
143
+ self._queues: dict[str, BaseMessageQueue] | None = None
144
+ self._pubsub = PubSub()
145
+ self._inboxes: dict[str, list[str]] = {}
146
+
147
+ def _get_queues(self) -> dict[str, BaseMessageQueue]:
148
+ """Return this plugin's queues, creating the table on first use."""
149
+ if self._queues is None:
150
+ self._queues = {}
151
+ return self._queues
152
+
153
+ def _put(self, name: str, message: str) -> None:
154
+ """Put *message* on queue *name*, creating the queue if needed."""
155
+ self._get_queues().setdefault(name, MessageQueue(name)).put(message)
156
+
157
+ def _take(self, name: str) -> str | None:
158
+ """Take and acknowledge the next message body, or None if the queue is empty."""
159
+ queue = self._get_queues()[name]
160
+ msg = queue.get()
161
+ if msg is None:
162
+ return None
163
+ queue.acknowledge(msg)
164
+ return msg.body
165
+
166
+ @pebble_method
167
+ def mq_create(self, args: list[PebbleValue]) -> PebbleValue:
168
+ """Create a named message queue and return its name."""
169
+ name = str(args[0])
170
+ self._get_queues().setdefault(name, MessageQueue(name))
171
+ return name
172
+
173
+ @pebble_method
174
+ def mq_put(self, args: list[PebbleValue]) -> PebbleValue:
175
+ """Put a message on a named queue."""
176
+ name = str(args[0])
177
+ if name not in self._get_queues():
178
+ return f"error: queue '{name}' not found"
179
+ self._put(name, str(args[1]))
180
+ return "ok"
181
+
182
+ @pebble_method
183
+ def mq_get(self, args: list[PebbleValue]) -> PebbleValue:
184
+ """Get the next message body from a named queue, or 'empty'."""
185
+ name = str(args[0])
186
+ if name not in self._get_queues():
187
+ return f"error: queue '{name}' not found"
188
+ body = self._take(name)
189
+ return "empty" if body is None else body
190
+
191
+ @pebble_method
192
+ def mq_publish(self, args: list[PebbleValue]) -> PebbleValue:
193
+ """Publish a message to a topic."""
194
+ self._pubsub.publish(str(args[0]), str(args[1]))
195
+ return "ok"
196
+
197
+ @pebble_method
198
+ def mq_subscribe(self, args: list[PebbleValue]) -> PebbleValue:
199
+ """Subscribe to a topic and store messages for later retrieval."""
200
+ topic = str(args[0])
201
+ if topic not in self._inboxes:
202
+ inbox: list[str] = []
203
+ self._inboxes[topic] = inbox
204
+
205
+ def _handler(_t: str, msg: str) -> None:
206
+ inbox.append(msg)
207
+
208
+ self._pubsub.subscribe(topic, _handler)
209
+ return topic
210
+
211
+ @pebble_method
212
+ def mq_receive(self, args: list[PebbleValue]) -> PebbleValue:
213
+ """Get all stored messages for a subscribed topic."""
214
+ topic = str(args[0])
215
+ if topic not in self._inboxes:
216
+ return f"error: not subscribed to '{topic}'"
217
+ result: list[PebbleValue] = list(self._inboxes[topic])
218
+ self._inboxes[topic].clear()
219
+ return result
220
+
221
+ def load_state(self, folder: Path) -> None:
222
+ """Load the saved queues, if there are any."""
223
+ path = folder / _QUEUES_FILE
224
+ if path.exists():
225
+ self._queues = load_queues(path)
226
+
227
+ def save_state(self, folder: Path) -> None:
228
+ """Save the queues, if this run used or loaded any."""
229
+ if self._queues is None:
230
+ return
231
+ folder.mkdir(parents=True, exist_ok=True)
232
+ save_queues(self._queues.values(), folder / _QUEUES_FILE)
233
+
234
+ def info(self) -> PluginInfo:
235
+ """Return plugin metadata."""
236
+ return PluginInfo(
237
+ name="PyMQ",
238
+ description="Message queue and pub/sub for Pebble programs",
239
+ version="0.1.0",
240
+ )
241
+
242
+ def pebble_module_name(self) -> str:
243
+ """Return the Pebble import name."""
244
+ return "mq"
245
+
246
+ def pebble_stdlib(self) -> StdlibModule:
247
+ """Return the mq stdlib module with queue and pub/sub functions."""
248
+ return StdlibModule(
249
+ functions={
250
+ "mq_create": (1, self.mq_create),
251
+ "mq_put": (2, self.mq_put),
252
+ "mq_get": (1, self.mq_get),
253
+ "mq_publish": (2, self.mq_publish),
254
+ "mq_subscribe": (1, self.mq_subscribe),
255
+ "mq_receive": (1, self.mq_receive),
256
+ },
257
+ constants={},
258
+ )
259
+
260
+ def shell_commands(self) -> list[ShellCommand]:
261
+ """Return the mq-put, mq-get and mqnet shell commands."""
262
+
263
+ def _mq_put_cmd(args: list[str]) -> str:
264
+ """Put a message on a named queue."""
265
+ if len(args) < 2: # noqa: PLR2004
266
+ return "Usage: mq-put <queue> <message>"
267
+ name = args[0]
268
+ message = " ".join(args[1:])
269
+ self._put(name, message)
270
+ return f"Queued on '{name}': {message}"
271
+
272
+ def _mq_get_cmd(args: list[str]) -> str:
273
+ """Get the next message from a named queue."""
274
+ if not args:
275
+ return "Usage: mq-get <queue>"
276
+ name = args[0]
277
+ if name not in self._get_queues():
278
+ return f"Queue '{name}' not found"
279
+ body = self._take(name)
280
+ return "Queue is empty" if body is None else body
281
+
282
+ return [
283
+ ShellCommand(
284
+ name="mqnet",
285
+ handler=_mqnet_cmd,
286
+ help_text="Run a networked PyMQ broker with crashing workers",
287
+ ),
288
+ ShellCommand(name="mq-put", handler=_mq_put_cmd, help_text="Put message on a queue"),
289
+ ShellCommand(name="mq-get", handler=_mq_get_cmd, help_text="Get message from a queue"),
290
+ ]
@@ -0,0 +1,247 @@
1
+ """PyNet integration plugin for PyStack.
2
+
3
+ Bridge PyNet's networking utilities into Pebble so kids can resolve
4
+ DNS names, parse URLs, and encode/decode Base64 from their Pebble
5
+ programs.
6
+
7
+ Networking is like the postal system of the internet -- it looks up
8
+ addresses, reads the envelope, and packs messages into a format that
9
+ travels safely.
10
+
11
+ Shell command ``overlap`` shows off PyNet's event loop: it starts several
12
+ ``sleep`` programs at the same moment and times them. Think of putting
13
+ three kettles on the stove at once instead of waiting for each to boil
14
+ before starting the next -- the whole job takes as long as one kettle.
15
+
16
+ Shell command ``netecho`` sends a message to a tiny PyNet server and waits
17
+ for it to come back. Think of shouting into a canyon and timing how long
18
+ the echo takes to return.
19
+
20
+ Shell command ``wsecho`` sends a text message over a WebSocket to a tiny
21
+ PyNet server and prints the reply. Think of a walkie-talkie left switched
22
+ on: once the call is connected, either side can talk whenever it likes.
23
+
24
+ Pebble module name: ``net``
25
+
26
+ Example Pebble usage::
27
+
28
+ import "net"
29
+ let encoded = base64_encode("Hello, world!")
30
+ print(encoded)
31
+
32
+ let decoded = base64_decode(encoded)
33
+ print(decoded)
34
+ """
35
+
36
+ import time
37
+
38
+ from pebble import StdlibModule
39
+ from pebble import Value as PebbleValue
40
+ from pynet.base64 import b64_decode, b64_encode
41
+ from pynet.dns import resolve
42
+ from pynet.loop import gather, run
43
+ from pynet.messaging import JsonValue, Message, Peer, connect, serve
44
+ from pynet.process import create_process
45
+ from pynet.ws import WebSocket, connect_websocket, serve_websocket
46
+
47
+ from pystack.plugins._shared import url_parse as _url_parse
48
+ from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_handler
49
+
50
+ DEFAULT_OVERLAP = 3
51
+ DEFAULT_SECONDS = 1.0
52
+ MAX_OVERLAP = 20
53
+ MAX_SECONDS = 10.0
54
+ MAX_ARGS = 2
55
+ ECHO_USAGE = "Usage: netecho <text...>"
56
+ WS_ECHO_USAGE = "Usage: wsecho <text...>"
57
+ MS_PER_SECOND = 1000
58
+ LOOPBACK = "127.0.0.1"
59
+ OVERLAP_USAGE = f"Usage: overlap [n 1-{MAX_OVERLAP}] [seconds 0-{MAX_SECONDS:g}]"
60
+
61
+
62
+ async def _sleep_once(seconds: float) -> int:
63
+ """Run one ``sleep`` subprocess and return its exit code."""
64
+ proc = await create_process(["sleep", f"{seconds:g}"], stdout=False, stderr=False)
65
+ return await proc.wait()
66
+
67
+
68
+ async def _sleep_many(count: int, seconds: float) -> None:
69
+ """Run ``count`` sleeps concurrently and wait for all of them."""
70
+ await gather(*(_sleep_once(seconds) for _ in range(count)))
71
+
72
+
73
+ def _overlap_cmd(args: list[str]) -> str:
74
+ """Run n sleeps at once on PyNet's event loop and report the timing."""
75
+ try:
76
+ count = int(args[0]) if args else DEFAULT_OVERLAP
77
+ seconds = float(args[1]) if len(args) > 1 else DEFAULT_SECONDS
78
+ except ValueError:
79
+ return OVERLAP_USAGE
80
+ if len(args) > MAX_ARGS or not 1 <= count <= MAX_OVERLAP or not 0 <= seconds <= MAX_SECONDS:
81
+ return OVERLAP_USAGE
82
+ started = time.monotonic()
83
+ try:
84
+ run(_sleep_many(count, seconds))
85
+ except Exception as exc: # noqa: BLE001
86
+ return f"error: {exc}"
87
+ elapsed = time.monotonic() - started
88
+ return (
89
+ f"ran {count} \u00d7 sleep {seconds:g} at once in {elapsed:.2f}s "
90
+ f"(one after another would take {count * seconds:g}s)"
91
+ )
92
+
93
+
94
+ async def _echo_handler(msg: Message) -> JsonValue:
95
+ """Return the request body unchanged."""
96
+ return msg.body
97
+
98
+
99
+ def _echo_setup(peer: Peer) -> None:
100
+ """Register the ``echo`` handler on each accepted connection."""
101
+ peer.on("echo", _echo_handler)
102
+
103
+
104
+ async def _echo_round_trip(text: str) -> tuple[str, float]:
105
+ """Send ``text`` to a local echo server and return the reply and seconds taken."""
106
+ server = await serve(LOOPBACK, 0, _echo_setup, heartbeat_interval=None)
107
+ client: Peer | None = None
108
+ try:
109
+ client = await connect(LOOPBACK, server.port, heartbeat_interval=None)
110
+ started = time.perf_counter()
111
+ reply = await client.request("echo", text)
112
+ elapsed = time.perf_counter() - started
113
+ return str(reply.body), elapsed
114
+ finally:
115
+ if client is not None:
116
+ await client.close()
117
+ server.close()
118
+ await server.wait_closed()
119
+
120
+
121
+ def _netecho_cmd(args: list[str]) -> str:
122
+ """Round-trip a message through a local PyNet server and report the timing."""
123
+ if not args:
124
+ return ECHO_USAGE
125
+ try:
126
+ text, elapsed = run(_echo_round_trip(" ".join(args)))
127
+ except Exception as exc: # noqa: BLE001
128
+ return f"error: {exc}"
129
+ return f"echo: {text} (round trip {elapsed * MS_PER_SECOND:.1f} ms)"
130
+
131
+
132
+ async def _ws_echo_handler(ws: WebSocket) -> None:
133
+ """Send the first message received straight back, as text or bytes."""
134
+ msg = await ws.recv()
135
+ if isinstance(msg, str):
136
+ await ws.send_text(msg)
137
+ else:
138
+ await ws.send_bytes(msg)
139
+
140
+
141
+ async def _ws_echo_round_trip(text: str) -> str:
142
+ """Send ``text`` to a local WebSocket echo server and return the reply."""
143
+ server = await serve_websocket(_ws_echo_handler, LOOPBACK, 0)
144
+ try:
145
+ client = await connect_websocket(LOOPBACK, server.port)
146
+ try:
147
+ await client.send_text(text)
148
+ reply = await client.recv()
149
+ return reply if isinstance(reply, str) else reply.decode(errors="replace")
150
+ finally:
151
+ await client.close()
152
+ finally:
153
+ server.close()
154
+ await server.wait_closed()
155
+
156
+
157
+ def _wsecho_cmd(args: list[str]) -> str:
158
+ """Round-trip a text message through a local PyNet WebSocket server."""
159
+ if not args:
160
+ return WS_ECHO_USAGE
161
+ try:
162
+ reply = run(_ws_echo_round_trip(" ".join(args)))
163
+ except Exception as exc: # noqa: BLE001
164
+ return f"error: {exc}"
165
+ return f"ws echo: {reply}"
166
+
167
+
168
+ @pebble_handler
169
+ def _dns_lookup(args: list[PebbleValue]) -> PebbleValue:
170
+ """Resolve a hostname to an IPv4 address."""
171
+ hostname = str(args[0])
172
+ return resolve(hostname)
173
+
174
+
175
+ @pebble_handler
176
+ def _base64_encode(args: list[PebbleValue]) -> PebbleValue:
177
+ """Encode a text string to Base64."""
178
+ return b64_encode(str(args[0]))
179
+
180
+
181
+ @pebble_handler
182
+ def _base64_decode(args: list[PebbleValue]) -> PebbleValue:
183
+ """Decode a Base64 string back to plain text."""
184
+ return b64_decode(str(args[0]))
185
+
186
+
187
+ class NetPlugin(Plugin):
188
+ """Integrate PyNet networking utilities into PyStack.
189
+
190
+ Register DNS, URL parsing, and Base64 functions in Pebble's ``net``
191
+ stdlib module, and ``dns``, ``overlap``, ``netecho``, and ``wsecho`` shell commands.
192
+ """
193
+
194
+ def info(self) -> PluginInfo:
195
+ """Return plugin metadata."""
196
+ return PluginInfo(
197
+ name="PyNet",
198
+ description="DNS, URL parsing, Base64, and a run-things-at-once event loop demo",
199
+ version="0.1.0",
200
+ )
201
+
202
+ def pebble_module_name(self) -> str:
203
+ """Return the Pebble import name."""
204
+ return "net"
205
+
206
+ def pebble_stdlib(self) -> StdlibModule:
207
+ """Return the net stdlib module with dns, url, and base64 functions."""
208
+ return StdlibModule(
209
+ functions={
210
+ "dns_lookup": (1, _dns_lookup),
211
+ "url_parse": (1, _url_parse),
212
+ "base64_encode": (1, _base64_encode),
213
+ "base64_decode": (1, _base64_decode),
214
+ },
215
+ constants={},
216
+ )
217
+
218
+ def shell_commands(self) -> list[ShellCommand]:
219
+ """Return the dns, overlap, netecho, and wsecho shell commands."""
220
+
221
+ def _dns_cmd(args: list[str]) -> str:
222
+ """Resolve a hostname to an IP address."""
223
+ if not args:
224
+ return "Usage: dns <hostname>"
225
+ try:
226
+ return resolve(args[0])
227
+ except Exception as exc: # noqa: BLE001
228
+ return f"error: {exc}"
229
+
230
+ return [
231
+ ShellCommand(name="dns", handler=_dns_cmd, help_text="Resolve hostname to IP"),
232
+ ShellCommand(
233
+ name="overlap",
234
+ handler=_overlap_cmd,
235
+ help_text="Run n sleeps at once on PyNet's event loop",
236
+ ),
237
+ ShellCommand(
238
+ name="netecho",
239
+ handler=_netecho_cmd,
240
+ help_text="Echo text through a local PyNet message server",
241
+ ),
242
+ ShellCommand(
243
+ name="wsecho",
244
+ handler=_wsecho_cmd,
245
+ help_text="Echo text through a local PyNet WebSocket server",
246
+ ),
247
+ ]