plexi-sdk 0.2.0__tar.gz → 0.3.0__tar.gz
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.
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/.gitignore +1 -1
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/PKG-INFO +2 -2
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/__init__.py +9 -9
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/_adapter.py +2 -1
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/_theme.py +15 -1
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/_v3_runtime.py +198 -16
- plexi_sdk-0.3.0/plexi_sdk/_v3_state.py +93 -0
- plexi_sdk-0.3.0/plexi_sdk/_version.py +65 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/effects.py +52 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/events.py +48 -0
- plexi_sdk-0.3.0/plexi_sdk/state_format.py +57 -0
- plexi_sdk-0.3.0/plexi_sdk/tools.py +170 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/ui.py +158 -159
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/pyproject.toml +1 -1
- plexi_sdk-0.2.0/plexi_sdk/_constants.py +0 -52
- plexi_sdk-0.2.0/plexi_sdk/_v3_state.py +0 -66
- plexi_sdk-0.2.0/plexi_sdk/_version.py +0 -40
- plexi_sdk-0.2.0/plexi_sdk/widgets/__init__.py +0 -25
- plexi_sdk-0.2.0/plexi_sdk/widgets/keymap.py +0 -51
- plexi_sdk-0.2.0/plexi_sdk/widgets/list_view.py +0 -159
- plexi_sdk-0.2.0/plexi_sdk/widgets/scroll.py +0 -100
- plexi_sdk-0.2.0/plexi_sdk/widgets/text_area.py +0 -219
- plexi_sdk-0.2.0/plexi_sdk/widgets/text_buffer.py +0 -337
- plexi_sdk-0.2.0/plexi_sdk/widgets/text_input.py +0 -11
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/README.md +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/_keys.py +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/_protocol.py +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/_types.py +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/_v3_delta.py +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/_v3_process.py +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/midi.py +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/py.typed +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/templates/AGENTS.md +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/templates/__init__.py +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/templates/agent_init.py +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/templates/app_init.py +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/templates/gitignore +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/templates/manifest.toml +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/templates/test_app_init.py +0 -0
- {plexi_sdk-0.2.0 → plexi_sdk-0.3.0}/plexi_sdk/testing.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: plexi-sdk
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Python SDK v3 for Plexi apps running through the CPython-in-WASM runtime
|
|
5
5
|
Project-URL: Homepage, https://github.com/ianjamesburke/PLEXI
|
|
6
6
|
Project-URL: Repository, https://github.com/ianjamesburke/PLEXI
|
|
@@ -14,20 +14,15 @@ is no ambient process access to escape to. See `docs/wasm-runtime.md`
|
|
|
14
14
|
§ Security Model for the full boundary.
|
|
15
15
|
"""
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
from ._version import __version__
|
|
18
|
+
|
|
18
19
|
SDK_ID = f"plexi-sdk-py/{__version__}"
|
|
19
20
|
|
|
20
21
|
from ._v3_state import StateSnapshot, log, state
|
|
21
22
|
from . import effects as effects
|
|
22
23
|
from . import events as events
|
|
24
|
+
from . import tools as tools
|
|
23
25
|
|
|
24
|
-
from ._constants import (
|
|
25
|
-
TITLE, HEADING, BODY, CAPTION, HINT, MONO_BODY, MONO_SMALL,
|
|
26
|
-
PAD, PAD_TIGHT, HEADER_H, STATUS_H,
|
|
27
|
-
PRIORITY_LOW, PRIORITY_NORMAL, PRIORITY_HIGH, PRIORITY_CRITICAL,
|
|
28
|
-
BG, FG, ACCENT, SURFACE, HIGHLIGHT, MUTED, GREEN, RED, YELLOW,
|
|
29
|
-
rgba, dim,
|
|
30
|
-
)
|
|
31
26
|
from ._types import (
|
|
32
27
|
CapabilityDeniedError, VideoHandle,
|
|
33
28
|
RectCommand, TextCommand, BadgeCommand, ShortcutPair, NotifyOption,
|
|
@@ -40,4 +35,9 @@ from .ui import (
|
|
|
40
35
|
ProgressBar as ProgressBar,
|
|
41
36
|
TextEdit as TextEdit,
|
|
42
37
|
)
|
|
43
|
-
from ._theme import theme, Theme, AppPalette
|
|
38
|
+
from ._theme import theme, Theme, AppPalette, rgba, dim
|
|
39
|
+
from .state_format import (
|
|
40
|
+
ChecklistItem as ChecklistItem,
|
|
41
|
+
parse_checklist as parse_checklist,
|
|
42
|
+
render_checklist as render_checklist,
|
|
43
|
+
)
|
|
@@ -65,7 +65,7 @@ def _decode_state(encoded: dict[str, str]) -> StateSnapshot:
|
|
|
65
65
|
payload = base64.b64decode(value)
|
|
66
66
|
raw[key] = payload
|
|
67
67
|
values[key] = json.loads(payload.decode("utf-8"))
|
|
68
|
-
return StateSnapshot(values, raw)
|
|
68
|
+
return StateSnapshot(values, raw, {"global": values}, ("global",))
|
|
69
69
|
|
|
70
70
|
|
|
71
71
|
def _encode_effect(effect: Any) -> dict[str, Any]:
|
|
@@ -232,6 +232,7 @@ def _normalize_node_data(data: dict[str, Any], key: str, flatten) -> dict[str, A
|
|
|
232
232
|
"on_change": data.get("on_change", data.get("on-change", "")),
|
|
233
233
|
"on_submit": data.get("on_submit", data.get("on-submit", "")),
|
|
234
234
|
"password": data.get("password", False),
|
|
235
|
+
"autofocus": data.get("autofocus", False),
|
|
235
236
|
}
|
|
236
237
|
if node_type == "select_list":
|
|
237
238
|
items = data.get("items", [])
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Live theme singleton.
|
|
1
|
+
"""Live theme singleton and color helpers.
|
|
2
2
|
|
|
3
3
|
Populated from the host Init payload so app chrome tracks the host theme
|
|
4
4
|
(light/dark + user overrides in config.toml). Until Init arrives the
|
|
@@ -122,3 +122,17 @@ class AppPalette:
|
|
|
122
122
|
|
|
123
123
|
# Process-wide singleton. Mutated in place on Init — do not rebind.
|
|
124
124
|
theme = Theme()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
# ── Color helpers ──────────────────────────────────────────────────────────
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def rgba(r: int, g: int, b: int, a: int = 255) -> str:
|
|
131
|
+
"""Return an 8-digit hex color string #rrggbbaa."""
|
|
132
|
+
return f"#{r:02x}{g:02x}{b:02x}{a:02x}"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def dim(hex_color: str, alpha: int) -> str:
|
|
136
|
+
"""Return hex_color with the given alpha (0-255). Strips existing alpha."""
|
|
137
|
+
h = hex_color.lstrip("#")[:6]
|
|
138
|
+
return f"#{h}{alpha:02x}"
|
|
@@ -27,15 +27,39 @@ from plexi_sdk._v3_state import StateSnapshot
|
|
|
27
27
|
|
|
28
28
|
|
|
29
29
|
_LOCK = threading.Lock()
|
|
30
|
-
_EMIT_BATCH: list[
|
|
30
|
+
_EMIT_BATCH: list[str] | None = None
|
|
31
|
+
|
|
32
|
+
#: Protocol output carries no human reader, so the default `", "` / `": "`
|
|
33
|
+
#: separators are pure wire weight on every key of every frame.
|
|
34
|
+
_JSON_SEPARATORS = (",", ":")
|
|
35
|
+
|
|
36
|
+
#: How many delta-eligible frames ride a previously measured full-vs-delta
|
|
37
|
+
#: verdict before it is re-measured. Measuring means serialising the frame
|
|
38
|
+
#: both ways, which costs more guest CPU than the byte difference it can
|
|
39
|
+
#: recover — on a full-motion canvas the double serialisation alone measurably
|
|
40
|
+
#: lowered achievable guest_fps. The winner is a property of the app's frame
|
|
41
|
+
#: shape, not of any single frame, so it is stable between structural changes;
|
|
42
|
+
#: every full frame resets the countdown so the first delta-eligible frame
|
|
43
|
+
#: after one always re-measures.
|
|
44
|
+
_TREE_SIZE_CHECK_INTERVAL = 30
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _dump_line(obj: dict) -> str:
|
|
48
|
+
"""Serialise one protocol message to its exact wire line."""
|
|
49
|
+
return json.dumps(obj, separators=_JSON_SEPARATORS) + "\n"
|
|
31
50
|
|
|
32
51
|
|
|
33
52
|
def _emit(obj: dict) -> None:
|
|
53
|
+
_emit_line(_dump_line(obj))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _emit_line(line: str) -> None:
|
|
57
|
+
"""Write an already-serialised protocol line, or queue it in the batch."""
|
|
34
58
|
with _LOCK:
|
|
35
59
|
if _EMIT_BATCH is not None:
|
|
36
|
-
_EMIT_BATCH.append(
|
|
60
|
+
_EMIT_BATCH.append(line)
|
|
37
61
|
return
|
|
38
|
-
sys.stdout.write(
|
|
62
|
+
sys.stdout.write(line)
|
|
39
63
|
sys.stdout.flush()
|
|
40
64
|
|
|
41
65
|
|
|
@@ -54,7 +78,7 @@ def _finish_emit_batch() -> None:
|
|
|
54
78
|
_EMIT_BATCH = None
|
|
55
79
|
if not batch:
|
|
56
80
|
return
|
|
57
|
-
sys.stdout.write("".join(
|
|
81
|
+
sys.stdout.write("".join(batch))
|
|
58
82
|
sys.stdout.flush()
|
|
59
83
|
|
|
60
84
|
|
|
@@ -77,10 +101,16 @@ class V3AppRuntime:
|
|
|
77
101
|
def __init__(self, app_path: Path, launch_args: list[str] | None = None) -> None:
|
|
78
102
|
self._module = _load_module(app_path)
|
|
79
103
|
self._launch_args = launch_args or []
|
|
80
|
-
|
|
104
|
+
# Per-scope state, keyed by declared scope name. The first entry of
|
|
105
|
+
# ``_scopes`` is the app's default scope; ``_values`` always aliases
|
|
106
|
+
# the default scope's dict.
|
|
107
|
+
self._scopes: list[str] = ["global"]
|
|
108
|
+
self._scoped_values: dict[str, dict] = {"global": {}}
|
|
81
109
|
self._last_render_time: float | None = None
|
|
82
110
|
self._last_tree: dict | None = None
|
|
83
111
|
self._force_full_tree = True
|
|
112
|
+
self._prefer_full_tree = False
|
|
113
|
+
self._tree_size_check_in = 0
|
|
84
114
|
self._frame_id = 0
|
|
85
115
|
self._app_id = ""
|
|
86
116
|
self._workspace_root = ""
|
|
@@ -126,6 +156,19 @@ class V3AppRuntime:
|
|
|
126
156
|
self._handle_text_submitted(ev)
|
|
127
157
|
elif t == "http_response":
|
|
128
158
|
self._handle_http_response(ev)
|
|
159
|
+
elif t == "mcp_connected":
|
|
160
|
+
self._dispatch(events.McpConnected(
|
|
161
|
+
request_id=ev.get("request_id", ""),
|
|
162
|
+
server_id=ev.get("server_id", ""),
|
|
163
|
+
error=ev.get("error"),
|
|
164
|
+
))
|
|
165
|
+
elif t == "mcp_message":
|
|
166
|
+
self._handle_mcp_message(ev)
|
|
167
|
+
elif t == "mcp_closed":
|
|
168
|
+
self._dispatch(events.McpClosed(
|
|
169
|
+
server_id=ev.get("server_id", ""),
|
|
170
|
+
reason=ev.get("reason", ""),
|
|
171
|
+
))
|
|
129
172
|
elif t == "tool_call":
|
|
130
173
|
self._dispatch(events.ToolCall(
|
|
131
174
|
call_id=ev.get("call_id", ""),
|
|
@@ -223,11 +266,43 @@ class V3AppRuntime:
|
|
|
223
266
|
elif t == "theme":
|
|
224
267
|
from ._theme import theme as _theme
|
|
225
268
|
_theme.update_from(ev.get("colors"))
|
|
269
|
+
_emit({"type": "schedule_render", "after_ms": 16})
|
|
226
270
|
elif t == "inject_state":
|
|
227
271
|
payload = ev.get("payload") or {}
|
|
228
272
|
if isinstance(payload, dict):
|
|
229
|
-
self.
|
|
273
|
+
self._default_values().update(payload)
|
|
230
274
|
self._set_state(in_view=False)
|
|
275
|
+
elif t == "state_changed":
|
|
276
|
+
self._handle_state_changed(ev)
|
|
277
|
+
|
|
278
|
+
def _handle_state_changed(self, ev: dict) -> None:
|
|
279
|
+
"""A scope's backing file changed outside our own persist flow.
|
|
280
|
+
|
|
281
|
+
Replaces the scope's values WHOLESALE (deleted keys must vanish —
|
|
282
|
+
never a merge), then dispatches ``events.StateChanged`` through the
|
|
283
|
+
normal update path so ``update()`` runs against the fresh snapshot
|
|
284
|
+
and a render is scheduled. On a decode error the host kept the
|
|
285
|
+
previous values, so we keep ours too and only surface the error.
|
|
286
|
+
"""
|
|
287
|
+
scope = ev.get("scope") or self._scopes[0]
|
|
288
|
+
if scope not in self._scoped_values:
|
|
289
|
+
_host_log(
|
|
290
|
+
"error",
|
|
291
|
+
f"state_changed for undeclared scope '{scope}' ignored "
|
|
292
|
+
f"(declared: {self._scopes})",
|
|
293
|
+
)
|
|
294
|
+
return
|
|
295
|
+
payload = ev.get("payload")
|
|
296
|
+
error = ev.get("error")
|
|
297
|
+
values = dict(payload) if isinstance(payload, dict) else {}
|
|
298
|
+
if error is None:
|
|
299
|
+
self._scoped_values[scope] = values
|
|
300
|
+
self._dispatch(events.StateChanged(
|
|
301
|
+
scope=scope,
|
|
302
|
+
values=dict(self._scoped_values[scope]),
|
|
303
|
+
source=str(ev.get("source", "external")),
|
|
304
|
+
error=error,
|
|
305
|
+
))
|
|
231
306
|
|
|
232
307
|
def _handle_init(self, ev: dict) -> None:
|
|
233
308
|
self._app_id = ev.get("app_id", "")
|
|
@@ -245,9 +320,16 @@ class V3AppRuntime:
|
|
|
245
320
|
from ._theme import theme as _theme
|
|
246
321
|
_theme.update_from(ev.get("theme"))
|
|
247
322
|
|
|
248
|
-
|
|
249
|
-
if
|
|
250
|
-
self.
|
|
323
|
+
scopes = ev.get("state_scopes")
|
|
324
|
+
if isinstance(scopes, list) and scopes:
|
|
325
|
+
self._scopes = [str(s) for s in scopes]
|
|
326
|
+
self._scoped_values = {s: {} for s in self._scopes}
|
|
327
|
+
states = ev.get("states")
|
|
328
|
+
if isinstance(states, dict):
|
|
329
|
+
for scope_name in self._scopes:
|
|
330
|
+
scoped_state = states.get(scope_name)
|
|
331
|
+
if isinstance(scoped_state, dict):
|
|
332
|
+
self._scoped_values[scope_name] = dict(scoped_state)
|
|
251
333
|
|
|
252
334
|
_emit({
|
|
253
335
|
"type": "ready",
|
|
@@ -301,29 +383,57 @@ class V3AppRuntime:
|
|
|
301
383
|
the host never has to guess what a patch applies to. Relies on the
|
|
302
384
|
documented `view()` purity contract: nodes are rebuilt every frame,
|
|
303
385
|
never cached and mutated in place across frames.
|
|
386
|
+
|
|
387
|
+
A delta is only a win when it is actually smaller than the frame it
|
|
388
|
+
replaces. On a full-motion canvas, where every command changes every
|
|
389
|
+
frame, each changed command is re-sent wrapped in its own index — so
|
|
390
|
+
the delta can come out slightly *larger* than the full frame. Both
|
|
391
|
+
encodings are already supported by the host decoder, so the smaller of
|
|
392
|
+
the two wins — measured by serialising both on the first delta-eligible
|
|
393
|
+
frame after any full frame and every `_TREE_SIZE_CHECK_INTERVAL` frames
|
|
394
|
+
after, and remembered in between (see the interval's docstring for why
|
|
395
|
+
measuring every frame is not affordable).
|
|
304
396
|
"""
|
|
305
397
|
prev = self._last_tree
|
|
306
398
|
self._last_tree = encoded
|
|
307
399
|
nodes = encoded["nodes"]
|
|
308
400
|
force_full = self._force_full_tree
|
|
309
401
|
self._force_full_tree = False
|
|
402
|
+
full = {"type": "component_tree", "frame_id": frame_id, "tree": encoded}
|
|
310
403
|
if (
|
|
311
404
|
force_full
|
|
312
405
|
or prev is None
|
|
313
406
|
or encoded["root"] != prev["root"]
|
|
314
407
|
or len(nodes) != len(prev["nodes"])
|
|
315
408
|
):
|
|
316
|
-
|
|
409
|
+
self._tree_size_check_in = 0
|
|
410
|
+
_emit(full)
|
|
411
|
+
return
|
|
412
|
+
measure = self._tree_size_check_in <= 0
|
|
413
|
+
if self._prefer_full_tree and not measure:
|
|
414
|
+
self._tree_size_check_in -= 1
|
|
415
|
+
_emit(full)
|
|
317
416
|
return
|
|
318
417
|
changed: list[dict] = []
|
|
319
418
|
for node, old in zip(nodes, prev["nodes"]):
|
|
320
419
|
if node == old:
|
|
321
420
|
continue
|
|
322
421
|
if node["key"] != old["key"]:
|
|
323
|
-
|
|
422
|
+
self._tree_size_check_in = 0
|
|
423
|
+
_emit(full)
|
|
324
424
|
return
|
|
325
425
|
changed.append(_node_patch(node, old))
|
|
326
|
-
|
|
426
|
+
delta_line = _dump_line(
|
|
427
|
+
{"type": "tree_delta", "frame_id": frame_id, "changed": changed}
|
|
428
|
+
)
|
|
429
|
+
if measure:
|
|
430
|
+
full_line = _dump_line(full)
|
|
431
|
+
self._prefer_full_tree = len(full_line) <= len(delta_line)
|
|
432
|
+
self._tree_size_check_in = _TREE_SIZE_CHECK_INTERVAL
|
|
433
|
+
_emit_line(full_line if self._prefer_full_tree else delta_line)
|
|
434
|
+
return
|
|
435
|
+
self._tree_size_check_in -= 1
|
|
436
|
+
_emit_line(delta_line)
|
|
327
437
|
|
|
328
438
|
def _handle_key(self, ev: dict, *, schedule_render: bool = True) -> None:
|
|
329
439
|
key = _normalize_key(ev.get("key", ""))
|
|
@@ -416,6 +526,29 @@ class V3AppRuntime:
|
|
|
416
526
|
status = 200
|
|
417
527
|
self._dispatch(events.HttpResponse(status=status, headers=[], body=body))
|
|
418
528
|
|
|
529
|
+
def _handle_mcp_message(self, ev: dict) -> None:
|
|
530
|
+
"""Parse one server line. A server that emits non-JSON is a protocol
|
|
531
|
+
violation the app must see — it is reported as a close, never dropped,
|
|
532
|
+
because a silently skipped reply strands the request that asked for
|
|
533
|
+
it."""
|
|
534
|
+
server_id = ev.get("server_id", "")
|
|
535
|
+
raw = ev.get("message", "")
|
|
536
|
+
try:
|
|
537
|
+
message = json.loads(raw)
|
|
538
|
+
except json.JSONDecodeError as e:
|
|
539
|
+
self._dispatch(events.McpClosed(
|
|
540
|
+
server_id=server_id,
|
|
541
|
+
reason=f"MCP server sent a line that is not JSON: {e}",
|
|
542
|
+
))
|
|
543
|
+
return
|
|
544
|
+
if not isinstance(message, dict):
|
|
545
|
+
self._dispatch(events.McpClosed(
|
|
546
|
+
server_id=server_id,
|
|
547
|
+
reason=f"MCP server sent a {type(message).__name__}, expected a JSON-RPC object",
|
|
548
|
+
))
|
|
549
|
+
return
|
|
550
|
+
self._dispatch(events.McpMessage(server_id=server_id, message=message, raw=raw))
|
|
551
|
+
|
|
419
552
|
def _handle_capability_decision(self, ev: dict) -> None:
|
|
420
553
|
granted = ev.get("granted", False)
|
|
421
554
|
capability = ev.get("capability", "")
|
|
@@ -438,8 +571,29 @@ class V3AppRuntime:
|
|
|
438
571
|
if schedule_render:
|
|
439
572
|
_emit({"type": "schedule_render", "after_ms": 16})
|
|
440
573
|
|
|
574
|
+
def _default_values(self) -> dict:
|
|
575
|
+
return self._scoped_values[self._scopes[0]]
|
|
576
|
+
|
|
577
|
+
def _resolve_scope(self, scope: "str | None") -> str:
|
|
578
|
+
if scope is None:
|
|
579
|
+
return self._scopes[0]
|
|
580
|
+
if scope not in self._scoped_values:
|
|
581
|
+
raise ValueError(
|
|
582
|
+
f"state scope '{scope}' is not declared in this app's manifest "
|
|
583
|
+
f"[state] scopes {self._scopes}"
|
|
584
|
+
)
|
|
585
|
+
return scope
|
|
586
|
+
|
|
587
|
+
def _scope_dict(self, scope: "str | None") -> dict:
|
|
588
|
+
return self._scoped_values[self._resolve_scope(scope)]
|
|
589
|
+
|
|
441
590
|
def _set_state(self, in_view: bool) -> None:
|
|
442
|
-
snapshot = StateSnapshot(
|
|
591
|
+
snapshot = StateSnapshot(
|
|
592
|
+
dict(self._default_values()),
|
|
593
|
+
{},
|
|
594
|
+
{name: dict(values) for name, values in self._scoped_values.items()},
|
|
595
|
+
tuple(self._scopes),
|
|
596
|
+
)
|
|
443
597
|
setattr(sdk, "_state", snapshot)
|
|
444
598
|
setattr(sdk, "_in_view", in_view)
|
|
445
599
|
_v3_state._state = snapshot
|
|
@@ -449,12 +603,18 @@ class V3AppRuntime:
|
|
|
449
603
|
state_changed = False
|
|
450
604
|
for effect in app_effects or []:
|
|
451
605
|
if isinstance(effect, effects.SetState):
|
|
452
|
-
self.
|
|
606
|
+
self._scope_dict(getattr(effect, "scope", None)).update(effect.data)
|
|
453
607
|
state_changed = True
|
|
454
608
|
elif isinstance(effect, effects.PersistState):
|
|
455
|
-
self.
|
|
609
|
+
scope_name = self._resolve_scope(getattr(effect, "scope", None))
|
|
610
|
+
scoped = self._scoped_values[scope_name]
|
|
611
|
+
scoped.update(effect.data)
|
|
456
612
|
state_changed = True
|
|
457
|
-
_emit({
|
|
613
|
+
_emit({
|
|
614
|
+
"type": "save_app_state",
|
|
615
|
+
"scope": scope_name,
|
|
616
|
+
"payload": dict(scoped),
|
|
617
|
+
})
|
|
458
618
|
elif isinstance(effect, effects.SetStatus):
|
|
459
619
|
_emit({"type": "status_summary", "text": effect.text})
|
|
460
620
|
elif isinstance(effect, effects.SetTitle):
|
|
@@ -485,6 +645,28 @@ class V3AppRuntime:
|
|
|
485
645
|
if effect.body is not None:
|
|
486
646
|
payload["body"] = effect.body.decode("utf-8")
|
|
487
647
|
_emit(payload)
|
|
648
|
+
elif isinstance(effect, effects.McpConnect):
|
|
649
|
+
_emit({
|
|
650
|
+
"type": "mcp_connect",
|
|
651
|
+
"request_id": effect.request_id,
|
|
652
|
+
"server_id": effect.server_id,
|
|
653
|
+
})
|
|
654
|
+
elif isinstance(effect, effects.McpSend):
|
|
655
|
+
# Serialized here, not host-side: the app owns the MCP
|
|
656
|
+
# protocol, and the transport only moves lines.
|
|
657
|
+
line = json.dumps(effect.message, separators=(",", ":"))
|
|
658
|
+
if "\n" in line:
|
|
659
|
+
raise ValueError(
|
|
660
|
+
"McpSend.message serializes to a string containing a newline; "
|
|
661
|
+
"JSON-RPC framing is line-delimited and the message would split"
|
|
662
|
+
)
|
|
663
|
+
_emit({
|
|
664
|
+
"type": "mcp_send",
|
|
665
|
+
"server_id": effect.server_id,
|
|
666
|
+
"message": line,
|
|
667
|
+
})
|
|
668
|
+
elif isinstance(effect, effects.McpDisconnect):
|
|
669
|
+
_emit({"type": "mcp_disconnect", "server_id": effect.server_id})
|
|
488
670
|
elif isinstance(effect, effects.FileRead):
|
|
489
671
|
_emit({"type": "file_read", "path": effect.path})
|
|
490
672
|
elif isinstance(effect, effects.OpenFilePicker):
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Any, Mapping, Optional
|
|
5
|
+
|
|
6
|
+
from .effects import SetState
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class StateSnapshot:
|
|
11
|
+
values: Mapping[str, Any]
|
|
12
|
+
raw_values: Mapping[str, bytes]
|
|
13
|
+
# Per-scope snapshots keyed by declared scope name; ``values`` aliases the
|
|
14
|
+
# default scope's mapping.
|
|
15
|
+
scoped: Mapping[str, Mapping[str, Any]] = field(default_factory=dict)
|
|
16
|
+
# Declared scope names, ordered; the first entry is the default scope.
|
|
17
|
+
scopes: tuple[str, ...] = ("global",)
|
|
18
|
+
|
|
19
|
+
@classmethod
|
|
20
|
+
def empty(cls) -> "StateSnapshot":
|
|
21
|
+
return cls({}, {}, {"global": {}}, ("global",))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class StateProxy:
|
|
25
|
+
def get(self, key: str, default: Any = None, scope: Optional[str] = None) -> Any:
|
|
26
|
+
return _scope_values(scope).get(key, default)
|
|
27
|
+
|
|
28
|
+
def raw(self, key: str) -> Optional[bytes]:
|
|
29
|
+
snapshot = _require_state()
|
|
30
|
+
return snapshot.raw_values.get(key)
|
|
31
|
+
|
|
32
|
+
def all(self, scope: Optional[str] = None) -> dict[str, Any]:
|
|
33
|
+
return dict(_scope_values(scope))
|
|
34
|
+
|
|
35
|
+
def set(self, key: str, value: Any, scope: Optional[str] = None) -> SetState:
|
|
36
|
+
if _in_view:
|
|
37
|
+
raise RuntimeError("state.set() called inside view() - return SetState from update() instead")
|
|
38
|
+
if scope is not None:
|
|
39
|
+
_require_declared(scope)
|
|
40
|
+
return SetState({key: value}, scope=scope)
|
|
41
|
+
|
|
42
|
+
def scopes(self) -> tuple[str, ...]:
|
|
43
|
+
"""The scopes this app declared in its manifest, ordered; the first
|
|
44
|
+
entry is the default scope."""
|
|
45
|
+
return _require_state().scopes
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class LogProxy:
|
|
49
|
+
def debug(self, msg: str) -> None:
|
|
50
|
+
_host_log("debug", msg)
|
|
51
|
+
|
|
52
|
+
def info(self, msg: str) -> None:
|
|
53
|
+
_host_log("info", msg)
|
|
54
|
+
|
|
55
|
+
def warn(self, msg: str) -> None:
|
|
56
|
+
_host_log("warn", msg)
|
|
57
|
+
|
|
58
|
+
def error(self, msg: str) -> None:
|
|
59
|
+
_host_log("error", msg)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _host_log(level: str, msg: str) -> None:
|
|
63
|
+
# The host runtime replaces this hook with a host-log bridge at launch.
|
|
64
|
+
print(f"[{level}] {msg}")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _require_state() -> StateSnapshot:
|
|
68
|
+
if _state is None:
|
|
69
|
+
raise RuntimeError("plexi_sdk.state is only available inside init/update/view")
|
|
70
|
+
return _state
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _require_declared(scope: str) -> None:
|
|
74
|
+
snapshot = _require_state()
|
|
75
|
+
if scope not in snapshot.scopes:
|
|
76
|
+
raise ValueError(
|
|
77
|
+
f"state scope '{scope}' is not declared in this app's manifest "
|
|
78
|
+
f"[state] scopes {list(snapshot.scopes)}"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _scope_values(scope: Optional[str]) -> Mapping[str, Any]:
|
|
83
|
+
snapshot = _require_state()
|
|
84
|
+
if scope is None:
|
|
85
|
+
return snapshot.values
|
|
86
|
+
_require_declared(scope)
|
|
87
|
+
return snapshot.scoped.get(scope, {})
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
_state: Optional[StateSnapshot] = None
|
|
91
|
+
_in_view = False
|
|
92
|
+
state = StateProxy()
|
|
93
|
+
log = LogProxy()
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Single source of truth for the SDK version.
|
|
2
|
+
|
|
3
|
+
The version is declared once, in ``pyproject.toml`` (``[project].version``), and
|
|
4
|
+
reaches the running package by one of two routes:
|
|
5
|
+
|
|
6
|
+
- **Host / source layout** — the host copies ``pyproject.toml`` beside the
|
|
7
|
+
package directory, so it is read from there.
|
|
8
|
+
- **Installed distribution** — a wheel carries that same declared value in its
|
|
9
|
+
``dist-info`` metadata, so it is read via ``importlib.metadata``.
|
|
10
|
+
|
|
11
|
+
Both routes resolve the same declaration. There is deliberately no literal
|
|
12
|
+
default: a missing version is an installation error, and returning a made-up one
|
|
13
|
+
would make the SDK claim a version that was never declared.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import tomllib
|
|
19
|
+
from importlib.metadata import PackageNotFoundError, version as _distribution_version
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
_DISTRIBUTION_NAME = "plexi-sdk"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _from_pyproject() -> str | None:
|
|
26
|
+
"""Read the version from ``pyproject.toml`` beside the package, if present."""
|
|
27
|
+
pyproject = Path(__file__).resolve().parent.parent / "pyproject.toml"
|
|
28
|
+
if not pyproject.is_file():
|
|
29
|
+
return None
|
|
30
|
+
with pyproject.open("rb") as f:
|
|
31
|
+
data = tomllib.load(f)
|
|
32
|
+
try:
|
|
33
|
+
declared = data["project"]["version"]
|
|
34
|
+
except KeyError as e:
|
|
35
|
+
raise RuntimeError(
|
|
36
|
+
f"Plexi SDK metadata is invalid: {pyproject} has no project.version."
|
|
37
|
+
) from e
|
|
38
|
+
if not isinstance(declared, str) or not declared:
|
|
39
|
+
raise RuntimeError(
|
|
40
|
+
f"Plexi SDK metadata is invalid: {pyproject} has an empty project.version."
|
|
41
|
+
)
|
|
42
|
+
return declared
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _from_distribution() -> str | None:
|
|
46
|
+
"""Read the version from installed distribution metadata, if installed."""
|
|
47
|
+
try:
|
|
48
|
+
return _distribution_version(_DISTRIBUTION_NAME)
|
|
49
|
+
except PackageNotFoundError:
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _resolve_version() -> str:
|
|
54
|
+
resolved = _from_pyproject() or _from_distribution()
|
|
55
|
+
if resolved is None:
|
|
56
|
+
package_dir = Path(__file__).resolve().parent
|
|
57
|
+
raise RuntimeError(
|
|
58
|
+
"Plexi SDK metadata is missing: no pyproject.toml beside "
|
|
59
|
+
f"{package_dir} and no installed '{_DISTRIBUTION_NAME}' distribution. "
|
|
60
|
+
"Reinstall Plexi to restore the bundled SDK."
|
|
61
|
+
)
|
|
62
|
+
return resolved
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
__version__ = _resolve_version()
|
|
@@ -6,12 +6,30 @@ from typing import Any, Optional
|
|
|
6
6
|
|
|
7
7
|
@dataclass
|
|
8
8
|
class SetState:
|
|
9
|
+
"""Merge ``data`` into in-memory state. ``scope`` selects which declared
|
|
10
|
+
state scope receives the keys; ``None`` means the app's default scope
|
|
11
|
+
(the first entry of the manifest's ``[state] scopes``). Using a scope the
|
|
12
|
+
app did not declare raises at apply time — never a silent fallback."""
|
|
9
13
|
data: dict
|
|
14
|
+
scope: str | None = None
|
|
10
15
|
|
|
11
16
|
|
|
12
17
|
@dataclass
|
|
13
18
|
class PersistState:
|
|
19
|
+
"""Merge ``data`` into a scope's state and persist that scope's snapshot
|
|
20
|
+
to disk. The host owns path construction: ``global`` state lives in
|
|
21
|
+
``~/.plexi/app_states/``, ``context`` state in
|
|
22
|
+
``<context_root>/.plexi/app_states/`` — resolved against the pane's
|
|
23
|
+
context root at call time. ``scope=None`` targets the default scope.
|
|
24
|
+
|
|
25
|
+
Read-back rule (disk wins): the host checks the file before writing. A
|
|
26
|
+
persist that loses to a concurrent external write is dropped — the host
|
|
27
|
+
reloads the on-disk state instead and answers with an
|
|
28
|
+
``events.StateChanged``, so re-apply your change from that event rather
|
|
29
|
+
than assuming the persist landed. Writes are atomic (temp + rename) in
|
|
30
|
+
both directions; a reader never sees a partial file."""
|
|
14
31
|
data: dict
|
|
32
|
+
scope: str | None = None
|
|
15
33
|
|
|
16
34
|
|
|
17
35
|
@dataclass
|
|
@@ -103,6 +121,40 @@ class HttpFetch:
|
|
|
103
121
|
body: Optional[bytes] = None
|
|
104
122
|
|
|
105
123
|
|
|
124
|
+
@dataclass
|
|
125
|
+
class McpConnect:
|
|
126
|
+
"""Open a connection to an MCP server the *user* configured (stint 0382).
|
|
127
|
+
|
|
128
|
+
``server_id`` names a ``[servers.<id>]`` entry in the user's
|
|
129
|
+
``mcp_servers.toml``. The host resolves it to a command and owns the
|
|
130
|
+
resulting process; the app never supplies argv. Requires the
|
|
131
|
+
``mcp.client`` capability. Answered by :class:`events.McpConnected`.
|
|
132
|
+
"""
|
|
133
|
+
request_id: str
|
|
134
|
+
server_id: str
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass
|
|
138
|
+
class McpSend:
|
|
139
|
+
"""Send one JSON-RPC message to a connected MCP server.
|
|
140
|
+
|
|
141
|
+
``message`` is a JSON-RPC object; the SDK serializes it. The transport is
|
|
142
|
+
line-delimited, so the serialized form must not contain a newline — the
|
|
143
|
+
host rejects one rather than splitting the message. Replies arrive
|
|
144
|
+
asynchronously as :class:`events.McpMessage`, correlated by the app
|
|
145
|
+
through the JSON-RPC ``id`` it chose.
|
|
146
|
+
"""
|
|
147
|
+
server_id: str
|
|
148
|
+
message: dict
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@dataclass
|
|
152
|
+
class McpDisconnect:
|
|
153
|
+
"""Close a connection and kill the server process. Answered by
|
|
154
|
+
:class:`events.McpClosed`."""
|
|
155
|
+
server_id: str
|
|
156
|
+
|
|
157
|
+
|
|
106
158
|
@dataclass
|
|
107
159
|
class AiMessage:
|
|
108
160
|
role: str
|