datasette-agent-micropython 0.1a0__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.
- datasette_agent_micropython/__init__.py +511 -0
- datasette_agent_micropython-0.1a0.dist-info/METADATA +141 -0
- datasette_agent_micropython-0.1a0.dist-info/RECORD +7 -0
- datasette_agent_micropython-0.1a0.dist-info/WHEEL +5 -0
- datasette_agent_micropython-0.1a0.dist-info/entry_points.txt +2 -0
- datasette_agent_micropython-0.1a0.dist-info/licenses/LICENSE +201 -0
- datasette_agent_micropython-0.1a0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import builtins
|
|
3
|
+
from collections import OrderedDict
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
import html
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import keyword
|
|
9
|
+
import threading
|
|
10
|
+
import tokenize
|
|
11
|
+
|
|
12
|
+
from datasette import hookimpl
|
|
13
|
+
from datasette.resources import DatabaseResource
|
|
14
|
+
from micropython_wasm import MicroPythonSession, MicroPythonWasmError
|
|
15
|
+
|
|
16
|
+
DEFAULT_MEMORY_BYTES = 16 * 1024 * 1024
|
|
17
|
+
DEFAULT_FUEL = 10_000_000
|
|
18
|
+
DEFAULT_WALL_CLOCK_TIMEOUT_SECONDS = 5.0
|
|
19
|
+
DEFAULT_MAX_SESSIONS = 16
|
|
20
|
+
DEFAULT_MAX_OUTPUT_CHARS = 10000
|
|
21
|
+
PYTHON_BUILTINS = set(dir(builtins))
|
|
22
|
+
|
|
23
|
+
EXECUTE_MICROPYTHON_DESCRIPTION = """\
|
|
24
|
+
Execute Python code using a sandboxed MicroPython interpreter compiled to WASM.
|
|
25
|
+
Use this for pure computation, parsing, data transformation, math, and checking
|
|
26
|
+
algorithms. Output is captured from stdout and stderr, so use print() to show
|
|
27
|
+
values.
|
|
28
|
+
|
|
29
|
+
State persists within the current Datasette Agent conversation: variables,
|
|
30
|
+
imports, and functions defined in one call can be reused in later calls. State
|
|
31
|
+
is not shared with other conversations. Set reset_context=true to clear the
|
|
32
|
+
conversation's interpreter before running code. If execution times out or traps,
|
|
33
|
+
that conversation's interpreter is discarded and the next call starts fresh.
|
|
34
|
+
|
|
35
|
+
The MicroPython environment includes read_only_sql_query(name_of_database, sql,
|
|
36
|
+
params=None) for querying Datasette databases using the current actor's
|
|
37
|
+
execute-sql permissions. It returns a dict with columns, rows, and truncated,
|
|
38
|
+
or an error key.
|
|
39
|
+
|
|
40
|
+
No network APIs are available, and no host filesystem is exposed by default.
|
|
41
|
+
|
|
42
|
+
Set show_result=true when the user asked to see the MicroPython code, asked to
|
|
43
|
+
see the execution output directly, or when showing both would help with
|
|
44
|
+
explanation, teaching, debugging, or reproducibility. When show_result=true,
|
|
45
|
+
the code and stdout are displayed to the user, so do not repeat the raw output
|
|
46
|
+
in your response unless the user explicitly asks for it. Leave show_result
|
|
47
|
+
false for private scratch calculations.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
EXECUTE_MICROPYTHON_SCHEMA = {
|
|
51
|
+
"type": "object",
|
|
52
|
+
"properties": {
|
|
53
|
+
"python": {
|
|
54
|
+
"type": "string",
|
|
55
|
+
"description": (
|
|
56
|
+
"MicroPython code to execute. Use print() to show values in "
|
|
57
|
+
"the captured stdout."
|
|
58
|
+
),
|
|
59
|
+
},
|
|
60
|
+
"reset_context": {
|
|
61
|
+
"type": "boolean",
|
|
62
|
+
"description": (
|
|
63
|
+
"If true, clear the current conversation's MicroPython "
|
|
64
|
+
"interpreter before running this code."
|
|
65
|
+
),
|
|
66
|
+
},
|
|
67
|
+
"show_result": {
|
|
68
|
+
"type": "boolean",
|
|
69
|
+
"description": (
|
|
70
|
+
"If true, render the MicroPython code and captured output "
|
|
71
|
+
"visibly in the chat. Use when the user asked to see the "
|
|
72
|
+
"code/output, or when visible code plus output helps with "
|
|
73
|
+
"explanation, teaching, debugging, or reproducibility. "
|
|
74
|
+
"Leave false for private scratch work."
|
|
75
|
+
),
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
"required": ["python"],
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass
|
|
83
|
+
class SessionEntry:
|
|
84
|
+
session: MicroPythonSession
|
|
85
|
+
lock: threading.Lock
|
|
86
|
+
host_functions_installed: bool = False
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
_sessions = OrderedDict()
|
|
90
|
+
_sessions_lock = threading.Lock()
|
|
91
|
+
_conversation_locks = {}
|
|
92
|
+
_conversation_locks_lock = threading.Lock()
|
|
93
|
+
_conversation_contexts = {}
|
|
94
|
+
_conversation_contexts_lock = threading.Lock()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _default_config():
|
|
98
|
+
return {
|
|
99
|
+
"memory_bytes": DEFAULT_MEMORY_BYTES,
|
|
100
|
+
"fuel": DEFAULT_FUEL,
|
|
101
|
+
"wall_clock_timeout_seconds": DEFAULT_WALL_CLOCK_TIMEOUT_SECONDS,
|
|
102
|
+
"max_sessions": DEFAULT_MAX_SESSIONS,
|
|
103
|
+
"max_output_chars": DEFAULT_MAX_OUTPUT_CHARS,
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _coerce_int(value, default, minimum=0):
|
|
108
|
+
try:
|
|
109
|
+
value = int(value)
|
|
110
|
+
except (TypeError, ValueError):
|
|
111
|
+
return default
|
|
112
|
+
return max(minimum, value)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _coerce_float(value, default, minimum=0.0):
|
|
116
|
+
try:
|
|
117
|
+
value = float(value)
|
|
118
|
+
except (TypeError, ValueError):
|
|
119
|
+
return default
|
|
120
|
+
return max(minimum, value)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _config_from_datasette(datasette):
|
|
124
|
+
config = _default_config()
|
|
125
|
+
try:
|
|
126
|
+
plugin_config = datasette.plugin_config("datasette-agent-micropython") or {}
|
|
127
|
+
except Exception:
|
|
128
|
+
plugin_config = {}
|
|
129
|
+
|
|
130
|
+
config["memory_bytes"] = _coerce_int(
|
|
131
|
+
plugin_config.get("memory_bytes"),
|
|
132
|
+
config["memory_bytes"],
|
|
133
|
+
minimum=1024 * 1024,
|
|
134
|
+
)
|
|
135
|
+
config["fuel"] = _coerce_int(plugin_config.get("fuel"), config["fuel"], minimum=1)
|
|
136
|
+
config["wall_clock_timeout_seconds"] = _coerce_float(
|
|
137
|
+
plugin_config.get("wall_clock_timeout_seconds"),
|
|
138
|
+
config["wall_clock_timeout_seconds"],
|
|
139
|
+
minimum=0.01,
|
|
140
|
+
)
|
|
141
|
+
config["max_sessions"] = _coerce_int(
|
|
142
|
+
plugin_config.get("max_sessions"),
|
|
143
|
+
config["max_sessions"],
|
|
144
|
+
minimum=1,
|
|
145
|
+
)
|
|
146
|
+
config["max_output_chars"] = _coerce_int(
|
|
147
|
+
plugin_config.get("max_output_chars"),
|
|
148
|
+
config["max_output_chars"],
|
|
149
|
+
minimum=1000,
|
|
150
|
+
)
|
|
151
|
+
return config
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _truncate_string(value, max_chars):
|
|
155
|
+
if len(value) <= max_chars:
|
|
156
|
+
return value
|
|
157
|
+
return value[:max_chars] + "\n... (truncated)"
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _limit_payload(payload, max_chars):
|
|
161
|
+
for key in ("stdout", "stderr", "error"):
|
|
162
|
+
value = payload.get(key)
|
|
163
|
+
if isinstance(value, str):
|
|
164
|
+
payload[key] = _truncate_string(value, max_chars)
|
|
165
|
+
return payload
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _source_segment(lines, start, end):
|
|
169
|
+
start_line, start_col = start
|
|
170
|
+
end_line, end_col = end
|
|
171
|
+
if start_line > len(lines):
|
|
172
|
+
return ""
|
|
173
|
+
if end_line > len(lines):
|
|
174
|
+
end_line = len(lines)
|
|
175
|
+
end_col = len(lines[-1])
|
|
176
|
+
if start_line == end_line:
|
|
177
|
+
return lines[start_line - 1][start_col:end_col]
|
|
178
|
+
return "".join(
|
|
179
|
+
[
|
|
180
|
+
lines[start_line - 1][start_col:],
|
|
181
|
+
*lines[start_line : end_line - 1],
|
|
182
|
+
lines[end_line - 1][:end_col],
|
|
183
|
+
]
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _token_class(token_info):
|
|
188
|
+
token_type = token_info.type
|
|
189
|
+
token_text = token_info.string
|
|
190
|
+
if token_type == tokenize.NAME:
|
|
191
|
+
if keyword.iskeyword(token_text):
|
|
192
|
+
return "agent-micropython-token-keyword"
|
|
193
|
+
if token_text in PYTHON_BUILTINS:
|
|
194
|
+
return "agent-micropython-token-builtin"
|
|
195
|
+
if token_type == tokenize.STRING:
|
|
196
|
+
return "agent-micropython-token-string"
|
|
197
|
+
if token_type == tokenize.NUMBER:
|
|
198
|
+
return "agent-micropython-token-number"
|
|
199
|
+
if token_type == tokenize.COMMENT:
|
|
200
|
+
return "agent-micropython-token-comment"
|
|
201
|
+
if token_type == tokenize.OP:
|
|
202
|
+
return "agent-micropython-token-operator"
|
|
203
|
+
if token_type == tokenize.ERRORTOKEN:
|
|
204
|
+
return "agent-micropython-token-error"
|
|
205
|
+
return None
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _highlight_python(source):
|
|
209
|
+
lines = source.splitlines(keepends=True) or [""]
|
|
210
|
+
highlighted = []
|
|
211
|
+
current = (1, 0)
|
|
212
|
+
try:
|
|
213
|
+
tokens = tokenize.generate_tokens(io.StringIO(source).readline)
|
|
214
|
+
for token_info in tokens:
|
|
215
|
+
if token_info.type == tokenize.ENDMARKER:
|
|
216
|
+
break
|
|
217
|
+
if token_info.start >= current:
|
|
218
|
+
highlighted.append(
|
|
219
|
+
html.escape(_source_segment(lines, current, token_info.start))
|
|
220
|
+
)
|
|
221
|
+
token_text = token_info.string
|
|
222
|
+
token_class = _token_class(token_info)
|
|
223
|
+
if token_text and token_class:
|
|
224
|
+
highlighted.append(
|
|
225
|
+
f'<span class="{token_class}">{html.escape(token_text)}</span>'
|
|
226
|
+
)
|
|
227
|
+
else:
|
|
228
|
+
highlighted.append(html.escape(token_text))
|
|
229
|
+
if token_info.end > current:
|
|
230
|
+
current = token_info.end
|
|
231
|
+
except tokenize.TokenError:
|
|
232
|
+
return html.escape(source)
|
|
233
|
+
|
|
234
|
+
end = (len(lines), len(lines[-1]))
|
|
235
|
+
if current < end:
|
|
236
|
+
highlighted.append(html.escape(_source_segment(lines, current, end)))
|
|
237
|
+
return "".join(highlighted)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _build_result_html(python, output_payload, max_chars=DEFAULT_MAX_OUTPUT_CHARS):
|
|
241
|
+
code = _truncate_string(python, max_chars)
|
|
242
|
+
stdout = _truncate_string(output_payload.get("stdout") or "", max_chars)
|
|
243
|
+
return (
|
|
244
|
+
'<div class="agent-micropython-result">'
|
|
245
|
+
"<style>"
|
|
246
|
+
".agent-micropython-result code{white-space:pre-wrap;}"
|
|
247
|
+
".agent-micropython-token-keyword{color:#7c3aed;font-weight:600;}"
|
|
248
|
+
".agent-micropython-token-builtin{color:#0369a1;}"
|
|
249
|
+
".agent-micropython-token-string{color:#047857;}"
|
|
250
|
+
".agent-micropython-token-number{color:#b45309;}"
|
|
251
|
+
".agent-micropython-token-comment{color:#6b7280;font-style:italic;}"
|
|
252
|
+
".agent-micropython-token-operator{color:#4b5563;}"
|
|
253
|
+
".agent-micropython-token-error{color:#dc2626;text-decoration:underline;}"
|
|
254
|
+
"</style>"
|
|
255
|
+
f'<pre><code class="language-python">{_highlight_python(code)}</code></pre>'
|
|
256
|
+
"<hr>"
|
|
257
|
+
f"<pre><code>{html.escape(stdout)}</code></pre>"
|
|
258
|
+
"</div>"
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _new_session(config):
|
|
263
|
+
return MicroPythonSession(
|
|
264
|
+
memory_bytes=config["memory_bytes"],
|
|
265
|
+
fuel=config["fuel"],
|
|
266
|
+
wall_timeout_seconds=config["wall_clock_timeout_seconds"],
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _close_entry(entry):
|
|
271
|
+
with entry.lock:
|
|
272
|
+
try:
|
|
273
|
+
entry.session.close()
|
|
274
|
+
except Exception:
|
|
275
|
+
pass
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _drop_session(conversation_id, expected_entry=None):
|
|
279
|
+
with _sessions_lock:
|
|
280
|
+
entry = _sessions.get(conversation_id)
|
|
281
|
+
if entry is None:
|
|
282
|
+
return
|
|
283
|
+
if expected_entry is not None and entry is not expected_entry:
|
|
284
|
+
return
|
|
285
|
+
_sessions.pop(conversation_id, None)
|
|
286
|
+
_close_entry(entry)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _shutdown_all_sessions():
|
|
290
|
+
with _sessions_lock:
|
|
291
|
+
entries = list(_sessions.values())
|
|
292
|
+
_sessions.clear()
|
|
293
|
+
with _conversation_locks_lock:
|
|
294
|
+
_conversation_locks.clear()
|
|
295
|
+
with _conversation_contexts_lock:
|
|
296
|
+
_conversation_contexts.clear()
|
|
297
|
+
for entry in entries:
|
|
298
|
+
_close_entry(entry)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _get_session(conversation_id, config):
|
|
302
|
+
evicted = []
|
|
303
|
+
with _sessions_lock:
|
|
304
|
+
entry = _sessions.get(conversation_id)
|
|
305
|
+
if entry is not None and not entry.session.closed:
|
|
306
|
+
_sessions.move_to_end(conversation_id)
|
|
307
|
+
else:
|
|
308
|
+
if entry is not None:
|
|
309
|
+
_sessions.pop(conversation_id, None)
|
|
310
|
+
evicted.append(entry)
|
|
311
|
+
entry = SessionEntry(session=_new_session(config), lock=threading.Lock())
|
|
312
|
+
_sessions[conversation_id] = entry
|
|
313
|
+
|
|
314
|
+
while len(_sessions) > config["max_sessions"]:
|
|
315
|
+
_, old_entry = _sessions.popitem(last=False)
|
|
316
|
+
evicted.append(old_entry)
|
|
317
|
+
|
|
318
|
+
for old_entry in evicted:
|
|
319
|
+
_close_entry(old_entry)
|
|
320
|
+
return entry
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _session_has_stopped(error):
|
|
324
|
+
text = str(error)
|
|
325
|
+
return "MicroPythonSession stopped" in text or "guest trapped" in text
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _get_conversation_lock(conversation_id):
|
|
329
|
+
with _conversation_locks_lock:
|
|
330
|
+
lock = _conversation_locks.get(conversation_id)
|
|
331
|
+
if lock is None:
|
|
332
|
+
lock = threading.Lock()
|
|
333
|
+
_conversation_locks[conversation_id] = lock
|
|
334
|
+
return lock
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _json_safe_value(value):
|
|
338
|
+
if isinstance(value, bytes):
|
|
339
|
+
return {"type": "bytes", "hex": value.hex()}
|
|
340
|
+
if isinstance(value, (str, int, float, bool)) or value is None:
|
|
341
|
+
return value
|
|
342
|
+
if isinstance(value, list):
|
|
343
|
+
return [_json_safe_value(item) for item in value]
|
|
344
|
+
if isinstance(value, tuple):
|
|
345
|
+
return [_json_safe_value(item) for item in value]
|
|
346
|
+
if isinstance(value, dict):
|
|
347
|
+
return {str(key): _json_safe_value(item) for key, item in value.items()}
|
|
348
|
+
return str(value)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
async def _read_only_sql_query(datasette, actor, name_of_database, sql, params=None):
|
|
352
|
+
if params is None:
|
|
353
|
+
params = {}
|
|
354
|
+
if not isinstance(params, dict):
|
|
355
|
+
return {"error": "params must be a dict"}
|
|
356
|
+
if not await datasette.allowed(
|
|
357
|
+
action="execute-sql",
|
|
358
|
+
resource=DatabaseResource(database=name_of_database),
|
|
359
|
+
actor=actor,
|
|
360
|
+
):
|
|
361
|
+
return {"error": "Permission denied"}
|
|
362
|
+
if name_of_database not in datasette.databases:
|
|
363
|
+
return {
|
|
364
|
+
"error": f"Database '{name_of_database}' not found",
|
|
365
|
+
"available_databases": list(datasette.databases),
|
|
366
|
+
}
|
|
367
|
+
db = datasette.get_database(name_of_database)
|
|
368
|
+
try:
|
|
369
|
+
result = await db.execute(sql, params=params, truncate=True)
|
|
370
|
+
rows = [_json_safe_value(dict(row)) for row in result.rows]
|
|
371
|
+
return {
|
|
372
|
+
"columns": result.columns,
|
|
373
|
+
"rows": rows,
|
|
374
|
+
"truncated": result.truncated,
|
|
375
|
+
}
|
|
376
|
+
except Exception as ex:
|
|
377
|
+
return {"error": str(ex)}
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _make_read_only_sql_query_host_function(conversation_id):
|
|
381
|
+
def read_only_sql_query(name_of_database, sql, params=None):
|
|
382
|
+
with _conversation_contexts_lock:
|
|
383
|
+
context = _conversation_contexts.get(conversation_id)
|
|
384
|
+
if context is None:
|
|
385
|
+
return {"error": "No current Datasette Agent conversation context"}
|
|
386
|
+
datasette, actor, loop = context
|
|
387
|
+
future = asyncio.run_coroutine_threadsafe(
|
|
388
|
+
_read_only_sql_query(datasette, actor, name_of_database, sql, params),
|
|
389
|
+
loop,
|
|
390
|
+
)
|
|
391
|
+
return future.result()
|
|
392
|
+
|
|
393
|
+
return read_only_sql_query
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _install_host_functions(entry, conversation_id):
|
|
397
|
+
if entry.host_functions_installed:
|
|
398
|
+
return
|
|
399
|
+
if not hasattr(entry.session, "register_function"):
|
|
400
|
+
return
|
|
401
|
+
with entry.lock:
|
|
402
|
+
if entry.host_functions_installed:
|
|
403
|
+
return
|
|
404
|
+
entry.session.register_function(
|
|
405
|
+
_make_read_only_sql_query_host_function(conversation_id),
|
|
406
|
+
name="read_only_sql_query",
|
|
407
|
+
)
|
|
408
|
+
entry.host_functions_installed = True
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _run_session(conversation_id, entry, python):
|
|
412
|
+
reset_entry = False
|
|
413
|
+
with entry.lock:
|
|
414
|
+
try:
|
|
415
|
+
result = entry.session.run(python)
|
|
416
|
+
payload = {
|
|
417
|
+
"ok": True,
|
|
418
|
+
"stdout": result.stdout,
|
|
419
|
+
"stderr": result.stderr,
|
|
420
|
+
"fuel_remaining": result.fuel_remaining,
|
|
421
|
+
"interpreter_reset": False,
|
|
422
|
+
}
|
|
423
|
+
except MicroPythonWasmError as ex:
|
|
424
|
+
reset = _session_has_stopped(ex)
|
|
425
|
+
reset_entry = reset
|
|
426
|
+
payload = {
|
|
427
|
+
"ok": False,
|
|
428
|
+
"error": str(ex),
|
|
429
|
+
"stdout": "",
|
|
430
|
+
"stderr": "",
|
|
431
|
+
"interpreter_reset": reset,
|
|
432
|
+
}
|
|
433
|
+
if reset_entry:
|
|
434
|
+
_drop_session(conversation_id, entry)
|
|
435
|
+
return payload
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _execute_micropython_locked(
|
|
439
|
+
conversation_id, config, datasette, actor, loop, python, reset_context
|
|
440
|
+
):
|
|
441
|
+
conversation_lock = _get_conversation_lock(conversation_id)
|
|
442
|
+
with conversation_lock:
|
|
443
|
+
with _conversation_contexts_lock:
|
|
444
|
+
_conversation_contexts[conversation_id] = (datasette, actor, loop)
|
|
445
|
+
if reset_context:
|
|
446
|
+
_drop_session(conversation_id)
|
|
447
|
+
entry = _get_session(conversation_id, config)
|
|
448
|
+
_install_host_functions(entry, conversation_id)
|
|
449
|
+
return _run_session(conversation_id, entry, python)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
async def _execute_micropython(
|
|
453
|
+
datasette, actor, python, reset_context=False, show_result=False
|
|
454
|
+
):
|
|
455
|
+
from datasette_agent.context import current_conversation_id
|
|
456
|
+
|
|
457
|
+
conversation_id = current_conversation_id.get()
|
|
458
|
+
if not conversation_id:
|
|
459
|
+
payload = {
|
|
460
|
+
"ok": False,
|
|
461
|
+
"error": "No current Datasette Agent conversation ID",
|
|
462
|
+
"stdout": "",
|
|
463
|
+
"stderr": "",
|
|
464
|
+
"interpreter_reset": False,
|
|
465
|
+
}
|
|
466
|
+
if show_result:
|
|
467
|
+
payload["output_displayed_to_user"] = True
|
|
468
|
+
payload["display_note"] = (
|
|
469
|
+
"The MicroPython code and stdout have already been shown to "
|
|
470
|
+
"the user; do not repeat the raw output unless asked."
|
|
471
|
+
)
|
|
472
|
+
payload["_html"] = _build_result_html(python, payload)
|
|
473
|
+
return json.dumps(payload, ensure_ascii=False)
|
|
474
|
+
|
|
475
|
+
config = _config_from_datasette(datasette)
|
|
476
|
+
loop = asyncio.get_running_loop()
|
|
477
|
+
payload = await asyncio.to_thread(
|
|
478
|
+
_execute_micropython_locked,
|
|
479
|
+
conversation_id,
|
|
480
|
+
config,
|
|
481
|
+
datasette,
|
|
482
|
+
actor,
|
|
483
|
+
loop,
|
|
484
|
+
python,
|
|
485
|
+
reset_context,
|
|
486
|
+
)
|
|
487
|
+
payload = _limit_payload(payload, config["max_output_chars"])
|
|
488
|
+
if show_result:
|
|
489
|
+
payload["output_displayed_to_user"] = True
|
|
490
|
+
payload["display_note"] = (
|
|
491
|
+
"The MicroPython code and stdout have already been shown to the "
|
|
492
|
+
"user; do not repeat the raw output unless asked."
|
|
493
|
+
)
|
|
494
|
+
payload["_html"] = _build_result_html(
|
|
495
|
+
python, payload, max_chars=config["max_output_chars"]
|
|
496
|
+
)
|
|
497
|
+
return json.dumps(payload, ensure_ascii=False)
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
@hookimpl
|
|
501
|
+
def register_agent_tools(datasette):
|
|
502
|
+
from datasette_agent.tools import AgentTool
|
|
503
|
+
|
|
504
|
+
return [
|
|
505
|
+
AgentTool(
|
|
506
|
+
name="execute_micropython",
|
|
507
|
+
description=EXECUTE_MICROPYTHON_DESCRIPTION,
|
|
508
|
+
input_schema=EXECUTE_MICROPYTHON_SCHEMA,
|
|
509
|
+
fn=_execute_micropython,
|
|
510
|
+
)
|
|
511
|
+
]
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datasette-agent-micropython
|
|
3
|
+
Version: 0.1a0
|
|
4
|
+
Summary: Run Python code in a MicroPython/WASM sandbox
|
|
5
|
+
Author: Simon Willison
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/datasette/datasette-agent-micropython
|
|
8
|
+
Project-URL: Changelog, https://github.com/datasette/datasette-agent-micropython/releases
|
|
9
|
+
Project-URL: Issues, https://github.com/datasette/datasette-agent-micropython/issues
|
|
10
|
+
Project-URL: CI, https://github.com/datasette/datasette-agent-micropython/actions
|
|
11
|
+
Classifier: Framework :: Datasette
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: datasette>=1.0a31
|
|
16
|
+
Requires-Dist: datasette-agent>=0.1a4
|
|
17
|
+
Requires-Dist: micropython-wasm>=0.1a1
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# datasette-agent-micropython
|
|
21
|
+
|
|
22
|
+
[](https://pypi.org/project/datasette-agent-micropython/)
|
|
23
|
+
[](https://github.com/datasette/datasette-agent-micropython/releases)
|
|
24
|
+
[](https://github.com/datasette/datasette-agent-micropython/actions/workflows/test.yml)
|
|
25
|
+
[](https://github.com/datasette/datasette-agent-micropython/blob/main/LICENSE)
|
|
26
|
+
|
|
27
|
+
Run Python code in a MicroPython/WASM sandbox
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
Install this plugin in the same environment as Datasette.
|
|
32
|
+
```bash
|
|
33
|
+
datasette install datasette-agent-micropython
|
|
34
|
+
```
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
This plugin adds an `execute_micropython` tool to
|
|
38
|
+
[Datasette Agent](https://github.com/datasette/datasette-agent). The tool runs
|
|
39
|
+
Python code using a sandboxed MicroPython interpreter compiled to WASM.
|
|
40
|
+
|
|
41
|
+
Use it for pure computation, parsing, data transformation, math, and checking
|
|
42
|
+
algorithms. Output is captured from stdout and stderr, so code should use
|
|
43
|
+
`print()` to return values:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
print(sum(range(10)))
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Each Datasette Agent conversation gets its own persistent MicroPython
|
|
50
|
+
interpreter. Variables, imports, and functions defined in one tool call can be
|
|
51
|
+
reused later in the same conversation:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
def fib(n):
|
|
55
|
+
a, b = 0, 1
|
|
56
|
+
out = []
|
|
57
|
+
for _ in range(n):
|
|
58
|
+
out.append(a)
|
|
59
|
+
a, b = b, a + b
|
|
60
|
+
return out
|
|
61
|
+
|
|
62
|
+
print(fib(10))
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
That state is not shared with other conversations. Use `reset_context=true` to
|
|
66
|
+
clear the current conversation's interpreter before running code. If execution
|
|
67
|
+
times out, exhausts fuel, or traps the WASM runtime, that conversation's
|
|
68
|
+
interpreter is discarded and the next call starts fresh.
|
|
69
|
+
|
|
70
|
+
No network APIs are available, and no host filesystem is exposed by default.
|
|
71
|
+
|
|
72
|
+
The MicroPython environment includes a `read_only_sql_query()` helper for
|
|
73
|
+
querying Datasette databases:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
result = read_only_sql_query(
|
|
77
|
+
"data",
|
|
78
|
+
"select name, qty from items where qty > :min_qty",
|
|
79
|
+
{"min_qty": 2},
|
|
80
|
+
)
|
|
81
|
+
print(result["columns"])
|
|
82
|
+
print(result["rows"])
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
It accepts `name_of_database`, `sql`, and an optional params dict. It uses the
|
|
86
|
+
current actor's `execute-sql` permission and returns a dict containing
|
|
87
|
+
`columns`, `rows`, and `truncated`, or an `error` key.
|
|
88
|
+
|
|
89
|
+
The tool accepts:
|
|
90
|
+
|
|
91
|
+
- `python` - MicroPython code to execute
|
|
92
|
+
- `reset_context` - clear this conversation's interpreter before running
|
|
93
|
+
- `show_result` - render the code and captured output inline for the user
|
|
94
|
+
|
|
95
|
+
Use `show_result=true` when the user asked to see the code or output, or when
|
|
96
|
+
showing both would help with explanation, debugging, teaching, or
|
|
97
|
+
reproducibility. The rendered HTML shows the executed code, then the captured
|
|
98
|
+
stdout. When this is set, the tool result tells the agent that the output has
|
|
99
|
+
already been shown to the user and does not need to be repeated. Leave it unset
|
|
100
|
+
for scratch calculations.
|
|
101
|
+
|
|
102
|
+
## Configuration
|
|
103
|
+
|
|
104
|
+
Configure the plugin using Datasette plugin settings:
|
|
105
|
+
|
|
106
|
+
```yaml
|
|
107
|
+
plugins:
|
|
108
|
+
datasette-agent-micropython:
|
|
109
|
+
max_sessions: 16
|
|
110
|
+
wall_clock_timeout_seconds: 5.0
|
|
111
|
+
memory_bytes: 16777216
|
|
112
|
+
fuel: 10000000
|
|
113
|
+
max_output_chars: 10000
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Settings:
|
|
117
|
+
|
|
118
|
+
- `max_sessions` - maximum live conversation interpreters to keep; defaults to
|
|
119
|
+
`16`. The least recently used interpreter is closed when the limit is
|
|
120
|
+
exceeded.
|
|
121
|
+
- `wall_clock_timeout_seconds` - timeout for each code execution; defaults to
|
|
122
|
+
`5.0`.
|
|
123
|
+
- `memory_bytes` - maximum WebAssembly linear memory for each interpreter;
|
|
124
|
+
defaults to `16777216` (16MB).
|
|
125
|
+
- `fuel` - Wasmtime fuel budget refreshed for each execution; defaults to
|
|
126
|
+
`10000000`.
|
|
127
|
+
- `max_output_chars` - maximum captured output/error characters returned to the
|
|
128
|
+
model; defaults to `10000`.
|
|
129
|
+
|
|
130
|
+
## Development
|
|
131
|
+
|
|
132
|
+
To set up this plugin locally, first checkout the code. You can confirm it is available like this:
|
|
133
|
+
```bash
|
|
134
|
+
cd datasette-agent-micropython
|
|
135
|
+
# Confirm the plugin is visible
|
|
136
|
+
uv run datasette plugins
|
|
137
|
+
```
|
|
138
|
+
To run the tests:
|
|
139
|
+
```bash
|
|
140
|
+
uv run pytest
|
|
141
|
+
```
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
datasette_agent_micropython/__init__.py,sha256=eK1buY1XbfUvjgJMB8E3zye1pvCjGgntm53gbzfvBno,16984
|
|
2
|
+
datasette_agent_micropython-0.1a0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
3
|
+
datasette_agent_micropython-0.1a0.dist-info/METADATA,sha256=_zxt7gpFY73OYeN9gk6y2v52a3pv0LMjH_aw88aWk6k,4982
|
|
4
|
+
datasette_agent_micropython-0.1a0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
5
|
+
datasette_agent_micropython-0.1a0.dist-info/entry_points.txt,sha256=bwoTyuDo4u0ZEHwtyjTKzNCm4d2YByqrjAxhzgA4uWw,60
|
|
6
|
+
datasette_agent_micropython-0.1a0.dist-info/top_level.txt,sha256=yZUTXBPmZeLURCfyiQHO1ov_iTNEhqdn7II9RA82uHY,28
|
|
7
|
+
datasette_agent_micropython-0.1a0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
datasette_agent_micropython
|