temps-plugin-sdk 0.1.0b1__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.
- temps_plugin/__init__.py +35 -0
- temps_plugin/client.py +133 -0
- temps_plugin/context.py +33 -0
- temps_plugin/manifest_builder.py +59 -0
- temps_plugin/protocol.py +49 -0
- temps_plugin/runtime.py +323 -0
- temps_plugin/types.py +136 -0
- temps_plugin/ui.py +81 -0
- temps_plugin_sdk-0.1.0b1.dist-info/METADATA +11 -0
- temps_plugin_sdk-0.1.0b1.dist-info/RECORD +11 -0
- temps_plugin_sdk-0.1.0b1.dist-info/WHEEL +4 -0
temps_plugin/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024-2026 Temps Contributors
|
|
2
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Temps Plugin SDK for Python.
|
|
5
|
+
|
|
6
|
+
Build external plugins for the Temps platform that compile into
|
|
7
|
+
single self-contained binaries via PyInstaller.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from temps_plugin.types import (
|
|
11
|
+
PluginManifest,
|
|
12
|
+
NavEntry,
|
|
13
|
+
NavSection,
|
|
14
|
+
PluginArgs,
|
|
15
|
+
PluginEvent,
|
|
16
|
+
AuthContext,
|
|
17
|
+
)
|
|
18
|
+
from temps_plugin.manifest_builder import ManifestBuilder, create_manifest
|
|
19
|
+
from temps_plugin.context import PluginContext
|
|
20
|
+
from temps_plugin.runtime import run_plugin
|
|
21
|
+
from temps_plugin.protocol import extract_auth_context
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"PluginManifest",
|
|
25
|
+
"NavEntry",
|
|
26
|
+
"NavSection",
|
|
27
|
+
"PluginArgs",
|
|
28
|
+
"PluginEvent",
|
|
29
|
+
"AuthContext",
|
|
30
|
+
"ManifestBuilder",
|
|
31
|
+
"create_manifest",
|
|
32
|
+
"PluginContext",
|
|
33
|
+
"run_plugin",
|
|
34
|
+
"extract_auth_context",
|
|
35
|
+
]
|
temps_plugin/client.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024-2026 Temps Contributors
|
|
2
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""TempsClient — async WebSocket client for platform queries.
|
|
5
|
+
|
|
6
|
+
Mirrors: sdks/node/packages/plugin-sdk/src/client.ts
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import json
|
|
13
|
+
import uuid
|
|
14
|
+
from typing import Any, Callable
|
|
15
|
+
|
|
16
|
+
import aiohttp
|
|
17
|
+
|
|
18
|
+
from temps_plugin.types import ChannelRequest, ChannelResponse, PluginEvent
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TempsClient:
|
|
22
|
+
"""Client for communicating with the Temps host via the WebSocket channel."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, ws: aiohttp.web.WebSocketResponse) -> None:
|
|
25
|
+
self._ws = ws
|
|
26
|
+
self._pending: dict[str, asyncio.Future[ChannelResponse]] = {}
|
|
27
|
+
self._event_handlers: list[Callable[[PluginEvent], None]] = []
|
|
28
|
+
self._reader_task: asyncio.Task[None] | None = None
|
|
29
|
+
|
|
30
|
+
def start_reader(self) -> None:
|
|
31
|
+
"""Start the background message reader task."""
|
|
32
|
+
self._reader_task = asyncio.get_event_loop().create_task(self._read_loop())
|
|
33
|
+
|
|
34
|
+
async def _read_loop(self) -> None:
|
|
35
|
+
"""Read messages from the WebSocket and dispatch them."""
|
|
36
|
+
try:
|
|
37
|
+
async for msg in self._ws:
|
|
38
|
+
if msg.type == aiohttp.WSMsgType.TEXT:
|
|
39
|
+
self._dispatch(msg.data)
|
|
40
|
+
elif msg.type in (
|
|
41
|
+
aiohttp.WSMsgType.CLOSE,
|
|
42
|
+
aiohttp.WSMsgType.CLOSING,
|
|
43
|
+
aiohttp.WSMsgType.CLOSED,
|
|
44
|
+
):
|
|
45
|
+
break
|
|
46
|
+
except Exception:
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
def _dispatch(self, raw: str) -> None:
|
|
50
|
+
"""Dispatch a raw JSON message."""
|
|
51
|
+
try:
|
|
52
|
+
data = json.loads(raw)
|
|
53
|
+
except json.JSONDecodeError:
|
|
54
|
+
return
|
|
55
|
+
|
|
56
|
+
# Response to a pending request
|
|
57
|
+
if "id" in data and "id" in data and data["id"] in self._pending:
|
|
58
|
+
resp = ChannelResponse(
|
|
59
|
+
id=data["id"],
|
|
60
|
+
result=data.get("result"),
|
|
61
|
+
error=data.get("error"),
|
|
62
|
+
)
|
|
63
|
+
fut = self._pending.pop(data["id"])
|
|
64
|
+
if not fut.done():
|
|
65
|
+
fut.set_result(resp)
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
# Event from the host
|
|
69
|
+
if "event_type" in data:
|
|
70
|
+
event = PluginEvent(
|
|
71
|
+
id=data.get("id", ""),
|
|
72
|
+
event_type=data["event_type"],
|
|
73
|
+
timestamp=data.get("timestamp", ""),
|
|
74
|
+
project_id=data.get("project_id"),
|
|
75
|
+
data=data.get("data", {}),
|
|
76
|
+
)
|
|
77
|
+
for handler in self._event_handlers:
|
|
78
|
+
try:
|
|
79
|
+
handler(event)
|
|
80
|
+
except Exception:
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
def on_event(self, handler: Callable[[PluginEvent], None]) -> None:
|
|
84
|
+
"""Register an event handler."""
|
|
85
|
+
self._event_handlers.append(handler)
|
|
86
|
+
|
|
87
|
+
async def request(self, method: str, params: dict[str, Any] | None = None) -> Any:
|
|
88
|
+
"""Send a request to the host and wait for the response."""
|
|
89
|
+
req_id = str(uuid.uuid4())
|
|
90
|
+
req = ChannelRequest(id=req_id, method=method, params=params or {})
|
|
91
|
+
|
|
92
|
+
loop = asyncio.get_event_loop()
|
|
93
|
+
fut: asyncio.Future[ChannelResponse] = loop.create_future()
|
|
94
|
+
self._pending[req_id] = fut
|
|
95
|
+
|
|
96
|
+
payload = json.dumps(
|
|
97
|
+
{"id": req.id, "method": req.method, "params": req.params},
|
|
98
|
+
separators=(",", ":"),
|
|
99
|
+
)
|
|
100
|
+
await self._ws.send_str(payload)
|
|
101
|
+
|
|
102
|
+
try:
|
|
103
|
+
resp = await asyncio.wait_for(fut, timeout=10.0)
|
|
104
|
+
except asyncio.TimeoutError:
|
|
105
|
+
self._pending.pop(req_id, None)
|
|
106
|
+
raise TimeoutError(f"Request {method} timed out")
|
|
107
|
+
|
|
108
|
+
if resp.error:
|
|
109
|
+
raise RuntimeError(f"Channel error: {resp.error}")
|
|
110
|
+
return resp.result
|
|
111
|
+
|
|
112
|
+
async def list_projects(self) -> list[dict[str, Any]]:
|
|
113
|
+
"""Query the host for the list of projects."""
|
|
114
|
+
result = await self.request("list_projects")
|
|
115
|
+
return result if isinstance(result, list) else []
|
|
116
|
+
|
|
117
|
+
async def list_deployments(
|
|
118
|
+
self, project_id: int, *, limit: int = 20
|
|
119
|
+
) -> list[dict[str, Any]]:
|
|
120
|
+
"""Query the host for deployments of a project."""
|
|
121
|
+
result = await self.request(
|
|
122
|
+
"list_deployments", {"project_id": project_id, "limit": limit}
|
|
123
|
+
)
|
|
124
|
+
return result if isinstance(result, list) else []
|
|
125
|
+
|
|
126
|
+
async def close(self) -> None:
|
|
127
|
+
"""Close the WebSocket connection."""
|
|
128
|
+
if self._reader_task:
|
|
129
|
+
self._reader_task.cancel()
|
|
130
|
+
try:
|
|
131
|
+
await self._ws.close()
|
|
132
|
+
except Exception:
|
|
133
|
+
pass
|
temps_plugin/context.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024-2026 Temps Contributors
|
|
2
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""PluginContext — provides access to platform client and plugin metadata.
|
|
5
|
+
|
|
6
|
+
Mirrors: sdks/node/packages/plugin-sdk/src/context.ts
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from temps_plugin.client import TempsClient
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PluginContext:
|
|
15
|
+
"""Context object passed to plugin lifecycle hooks and handlers."""
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
*,
|
|
20
|
+
plugin_name: str,
|
|
21
|
+
data_dir: str,
|
|
22
|
+
auth_secret: str,
|
|
23
|
+
client: TempsClient | None = None,
|
|
24
|
+
) -> None:
|
|
25
|
+
self.plugin_name = plugin_name
|
|
26
|
+
self.data_dir = data_dir
|
|
27
|
+
self.auth_secret = auth_secret
|
|
28
|
+
self.temps = client
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def has_client(self) -> bool:
|
|
32
|
+
"""Whether the platform client is available."""
|
|
33
|
+
return self.temps is not None
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024-2026 Temps Contributors
|
|
2
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Fluent manifest builder.
|
|
5
|
+
|
|
6
|
+
Mirrors: sdks/node/packages/plugin-sdk/src/manifest-builder.ts
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from temps_plugin.types import NavEntry, NavSection, PluginManifest
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ManifestBuilder:
|
|
15
|
+
"""Fluent builder for PluginManifest."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, name: str, version: str) -> None:
|
|
18
|
+
self._manifest = PluginManifest(name=name, version=version)
|
|
19
|
+
|
|
20
|
+
def display_name(self, name: str) -> ManifestBuilder:
|
|
21
|
+
self._manifest.display_name = name
|
|
22
|
+
return self
|
|
23
|
+
|
|
24
|
+
def description(self, desc: str) -> ManifestBuilder:
|
|
25
|
+
self._manifest.description = desc
|
|
26
|
+
return self
|
|
27
|
+
|
|
28
|
+
def requires_db(self, val: bool = True) -> ManifestBuilder:
|
|
29
|
+
self._manifest.requires_db = val
|
|
30
|
+
return self
|
|
31
|
+
|
|
32
|
+
def health_path(self, path: str) -> ManifestBuilder:
|
|
33
|
+
self._manifest.health_path = path
|
|
34
|
+
return self
|
|
35
|
+
|
|
36
|
+
def add_nav(
|
|
37
|
+
self,
|
|
38
|
+
label: str,
|
|
39
|
+
icon: str,
|
|
40
|
+
path: str,
|
|
41
|
+
section: NavSection = NavSection.PLATFORM,
|
|
42
|
+
order: int = 50,
|
|
43
|
+
) -> ManifestBuilder:
|
|
44
|
+
self._manifest.nav.append(
|
|
45
|
+
NavEntry(label=label, icon=icon, path=path, section=section, order=order)
|
|
46
|
+
)
|
|
47
|
+
return self
|
|
48
|
+
|
|
49
|
+
def event(self, event_type: str) -> ManifestBuilder:
|
|
50
|
+
self._manifest.events.append(event_type)
|
|
51
|
+
return self
|
|
52
|
+
|
|
53
|
+
def build(self) -> PluginManifest:
|
|
54
|
+
return self._manifest
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def create_manifest(name: str, version: str) -> ManifestBuilder:
|
|
58
|
+
"""Create a new ManifestBuilder."""
|
|
59
|
+
return ManifestBuilder(name, version)
|
temps_plugin/protocol.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024-2026 Temps Contributors
|
|
2
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Protocol helpers for the Temps plugin handshake.
|
|
5
|
+
|
|
6
|
+
Mirrors: sdks/node/packages/plugin-sdk/src/protocol.ts
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from temps_plugin.types import AuthContext, PluginManifest
|
|
16
|
+
|
|
17
|
+
# Header constants (set by the Temps host on proxied requests)
|
|
18
|
+
HEADER_USER_ID = "x-temps-user-id"
|
|
19
|
+
HEADER_USER_EMAIL = "x-temps-user-email"
|
|
20
|
+
HEADER_USER_ROLE = "x-temps-user-role"
|
|
21
|
+
HEADER_REQUEST_ID = "x-temps-request-id"
|
|
22
|
+
|
|
23
|
+
# WebSocket channel path
|
|
24
|
+
PLUGIN_CHANNEL_PATH = "/_temps/channel"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def emit_manifest(manifest: PluginManifest) -> None:
|
|
28
|
+
"""Emit the manifest JSON to stdout (handshake phase 1)."""
|
|
29
|
+
line = json.dumps(manifest.to_dict(), separators=(",", ":"))
|
|
30
|
+
sys.stdout.write(line + "\n")
|
|
31
|
+
sys.stdout.flush()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def emit_ready(has_ui: bool) -> None:
|
|
35
|
+
"""Emit the ready message to stdout (handshake phase 2)."""
|
|
36
|
+
msg: dict[str, Any] = {"type": "ready", "ready": True, "has_ui": has_ui}
|
|
37
|
+
line = json.dumps(msg, separators=(",", ":"))
|
|
38
|
+
sys.stdout.write(line + "\n")
|
|
39
|
+
sys.stdout.flush()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def extract_auth_context(headers: dict[str, str]) -> AuthContext:
|
|
43
|
+
"""Extract authentication context from request headers."""
|
|
44
|
+
return AuthContext(
|
|
45
|
+
user_id=headers.get(HEADER_USER_ID),
|
|
46
|
+
user_email=headers.get(HEADER_USER_EMAIL),
|
|
47
|
+
user_role=headers.get(HEADER_USER_ROLE),
|
|
48
|
+
request_id=headers.get(HEADER_REQUEST_ID),
|
|
49
|
+
)
|
temps_plugin/runtime.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024-2026 Temps Contributors
|
|
2
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Plugin runtime — handles the full lifecycle of a Temps external plugin.
|
|
5
|
+
|
|
6
|
+
Mirrors: sdks/node/packages/plugin-sdk/src/runtime.ts
|
|
7
|
+
|
|
8
|
+
Lifecycle:
|
|
9
|
+
1. Parse CLI arguments (--socket-path, --auth-secret, --data-dir)
|
|
10
|
+
2. Emit manifest to stdout (handshake phase 1)
|
|
11
|
+
3. Start aiohttp server on Unix domain socket
|
|
12
|
+
4. Emit ready to stdout (handshake phase 2)
|
|
13
|
+
5. Accept WebSocket connection from host on /_temps/channel
|
|
14
|
+
6. Create PluginContext with TempsClient
|
|
15
|
+
7. Call plugin.on_start()
|
|
16
|
+
8. Serve plugin routes, health, events, and embedded UI
|
|
17
|
+
9. Handle SIGTERM for graceful shutdown
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import asyncio
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import signal
|
|
26
|
+
import sys
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any, Awaitable, Callable, Protocol
|
|
29
|
+
|
|
30
|
+
from aiohttp import web
|
|
31
|
+
|
|
32
|
+
from temps_plugin.client import TempsClient
|
|
33
|
+
from temps_plugin.context import PluginContext
|
|
34
|
+
from temps_plugin.protocol import (
|
|
35
|
+
PLUGIN_CHANNEL_PATH,
|
|
36
|
+
emit_manifest,
|
|
37
|
+
emit_ready,
|
|
38
|
+
extract_auth_context,
|
|
39
|
+
)
|
|
40
|
+
from temps_plugin.types import (
|
|
41
|
+
EmbeddedAssets,
|
|
42
|
+
PluginArgs,
|
|
43
|
+
PluginEvent,
|
|
44
|
+
PluginManifest,
|
|
45
|
+
)
|
|
46
|
+
from temps_plugin.ui import serve_embedded_ui
|
|
47
|
+
|
|
48
|
+
# Type aliases for plugin callbacks
|
|
49
|
+
RequestHandler = Callable[[web.Request], Awaitable[web.Response]]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class TempsPlugin(Protocol):
|
|
53
|
+
"""Protocol that plugin implementations must satisfy."""
|
|
54
|
+
|
|
55
|
+
def manifest(self) -> PluginManifest: ...
|
|
56
|
+
def handler(self, ctx: PluginContext) -> RequestHandler: ...
|
|
57
|
+
def embedded_ui_assets(self) -> EmbeddedAssets | None: ...
|
|
58
|
+
|
|
59
|
+
async def on_start(self, ctx: PluginContext) -> None: ...
|
|
60
|
+
def on_event(self, ctx: PluginContext, event: PluginEvent) -> None: ...
|
|
61
|
+
async def on_shutdown(self) -> None: ...
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def run_plugin(plugin: TempsPlugin) -> None:
|
|
65
|
+
"""Run a Temps plugin. This is the main entry point."""
|
|
66
|
+
asyncio.run(_run_plugin_async(plugin))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def _run_plugin_async(plugin: TempsPlugin) -> None:
|
|
70
|
+
# 1. Parse CLI arguments
|
|
71
|
+
args = _parse_args(sys.argv[1:])
|
|
72
|
+
os.makedirs(args.data_dir, exist_ok=True)
|
|
73
|
+
|
|
74
|
+
manifest = plugin.manifest()
|
|
75
|
+
|
|
76
|
+
# 2. Emit manifest (handshake phase 1)
|
|
77
|
+
emit_manifest(manifest)
|
|
78
|
+
|
|
79
|
+
# Ensure socket directory exists and clean up stale socket
|
|
80
|
+
socket_dir = str(Path(args.socket_path).parent)
|
|
81
|
+
os.makedirs(socket_dir, exist_ok=True)
|
|
82
|
+
if os.path.exists(args.socket_path):
|
|
83
|
+
os.unlink(args.socket_path)
|
|
84
|
+
|
|
85
|
+
# Channel connection tracking
|
|
86
|
+
channel_connected: asyncio.Future[TempsClient] = (
|
|
87
|
+
asyncio.get_event_loop().create_future()
|
|
88
|
+
)
|
|
89
|
+
context: PluginContext | None = None
|
|
90
|
+
plugin_ready = False
|
|
91
|
+
|
|
92
|
+
# Embedded UI
|
|
93
|
+
embedded_assets = plugin.embedded_ui_assets()
|
|
94
|
+
has_ui = embedded_assets is not None
|
|
95
|
+
|
|
96
|
+
# Plugin request handler (set after initialization)
|
|
97
|
+
plugin_handler: RequestHandler | None = None
|
|
98
|
+
|
|
99
|
+
# -- aiohttp request handlers --
|
|
100
|
+
|
|
101
|
+
async def handle_health(_request: web.Request) -> web.Response:
|
|
102
|
+
return web.json_response({"status": "ok", "plugin": manifest.name})
|
|
103
|
+
|
|
104
|
+
async def handle_ws_channel(request: web.Request) -> web.WebSocketResponse:
|
|
105
|
+
ws = web.WebSocketResponse()
|
|
106
|
+
await ws.prepare(request)
|
|
107
|
+
|
|
108
|
+
client = TempsClient(ws)
|
|
109
|
+
client.start_reader()
|
|
110
|
+
|
|
111
|
+
if not channel_connected.done():
|
|
112
|
+
channel_connected.set_result(client)
|
|
113
|
+
|
|
114
|
+
# Keep the WebSocket open until it closes
|
|
115
|
+
await client._reader_task
|
|
116
|
+
return ws
|
|
117
|
+
|
|
118
|
+
async def handle_events(request: web.Request) -> web.Response:
|
|
119
|
+
try:
|
|
120
|
+
data = await request.json()
|
|
121
|
+
event = PluginEvent(
|
|
122
|
+
id=data.get("id", ""),
|
|
123
|
+
event_type=data.get("event_type", ""),
|
|
124
|
+
timestamp=data.get("timestamp", ""),
|
|
125
|
+
project_id=data.get("project_id"),
|
|
126
|
+
data=data.get("data", {}),
|
|
127
|
+
)
|
|
128
|
+
if context:
|
|
129
|
+
plugin.on_event(context, event)
|
|
130
|
+
return web.json_response({"ok": True})
|
|
131
|
+
except Exception as e:
|
|
132
|
+
return web.json_response(
|
|
133
|
+
{"error": "Invalid event payload", "detail": str(e)},
|
|
134
|
+
status=400,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
async def handle_ui(request: web.Request) -> web.Response:
|
|
138
|
+
if embedded_assets is None:
|
|
139
|
+
return web.Response(text="Not Found", status=404)
|
|
140
|
+
return serve_embedded_ui(request.path, embedded_assets)
|
|
141
|
+
|
|
142
|
+
async def handle_catch_all(request: web.Request) -> web.Response:
|
|
143
|
+
path = request.path
|
|
144
|
+
|
|
145
|
+
# UI redirect
|
|
146
|
+
if path == "/ui":
|
|
147
|
+
raise web.HTTPFound("/ui/")
|
|
148
|
+
|
|
149
|
+
# Embedded UI
|
|
150
|
+
if path.startswith("/ui/") and embedded_assets:
|
|
151
|
+
return serve_embedded_ui(path, embedded_assets)
|
|
152
|
+
|
|
153
|
+
# Not initialized yet
|
|
154
|
+
if not plugin_ready or plugin_handler is None:
|
|
155
|
+
return web.Response(text="Plugin initializing", status=503)
|
|
156
|
+
|
|
157
|
+
# Delegate to plugin handler
|
|
158
|
+
return await plugin_handler(request)
|
|
159
|
+
|
|
160
|
+
# 3. Build and start the aiohttp app
|
|
161
|
+
app = web.Application()
|
|
162
|
+
app.router.add_get(manifest.health_path, handle_health)
|
|
163
|
+
if manifest.health_path != "/health":
|
|
164
|
+
app.router.add_get("/health", handle_health)
|
|
165
|
+
app.router.add_get(PLUGIN_CHANNEL_PATH, handle_ws_channel)
|
|
166
|
+
app.router.add_post("/_events", handle_events)
|
|
167
|
+
# Catch-all for plugin routes and UI
|
|
168
|
+
app.router.add_route("*", "/{path_info:.*}", handle_catch_all)
|
|
169
|
+
|
|
170
|
+
runner = web.AppRunner(app)
|
|
171
|
+
await runner.setup()
|
|
172
|
+
site = web.UnixSite(runner, args.socket_path)
|
|
173
|
+
await site.start()
|
|
174
|
+
|
|
175
|
+
# 4. Emit ready (handshake phase 2)
|
|
176
|
+
emit_ready(has_ui)
|
|
177
|
+
|
|
178
|
+
# Set up signal handlers early so SIGTERM works during any phase
|
|
179
|
+
shutdown_event = asyncio.Event()
|
|
180
|
+
|
|
181
|
+
def _signal_handler() -> None:
|
|
182
|
+
shutdown_event.set()
|
|
183
|
+
|
|
184
|
+
loop = asyncio.get_event_loop()
|
|
185
|
+
for sig in (signal.SIGTERM, signal.SIGINT):
|
|
186
|
+
loop.add_signal_handler(sig, _signal_handler)
|
|
187
|
+
|
|
188
|
+
# 5. Wait for the host to connect via WebSocket channel
|
|
189
|
+
# If SIGTERM arrives during this wait, we abort and shut down.
|
|
190
|
+
client: TempsClient | None = None
|
|
191
|
+
try:
|
|
192
|
+
channel_or_shutdown = asyncio.ensure_future(channel_connected)
|
|
193
|
+
shutdown_task = asyncio.create_task(shutdown_event.wait())
|
|
194
|
+
done, _ = await asyncio.wait(
|
|
195
|
+
{channel_or_shutdown, shutdown_task},
|
|
196
|
+
timeout=30.0,
|
|
197
|
+
return_when=asyncio.FIRST_COMPLETED,
|
|
198
|
+
)
|
|
199
|
+
if shutdown_task in done:
|
|
200
|
+
# SIGTERM received during channel wait
|
|
201
|
+
channel_or_shutdown.cancel()
|
|
202
|
+
await _shutdown(plugin, manifest, None, runner, args)
|
|
203
|
+
return
|
|
204
|
+
if channel_or_shutdown in done:
|
|
205
|
+
client = channel_or_shutdown.result()
|
|
206
|
+
else:
|
|
207
|
+
# Timeout — no host connected
|
|
208
|
+
channel_or_shutdown.cancel()
|
|
209
|
+
shutdown_task.cancel()
|
|
210
|
+
print(
|
|
211
|
+
"[temps-plugin] Warning: platform channel not connected, "
|
|
212
|
+
"running without platform data access",
|
|
213
|
+
file=sys.stderr,
|
|
214
|
+
)
|
|
215
|
+
except Exception:
|
|
216
|
+
print(
|
|
217
|
+
"[temps-plugin] Warning: platform channel not connected, "
|
|
218
|
+
"running without platform data access",
|
|
219
|
+
file=sys.stderr,
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
# 6. Create PluginContext
|
|
223
|
+
ctx = PluginContext(
|
|
224
|
+
plugin_name=manifest.name,
|
|
225
|
+
data_dir=args.data_dir,
|
|
226
|
+
auth_secret=args.auth_secret,
|
|
227
|
+
client=client,
|
|
228
|
+
)
|
|
229
|
+
context = ctx
|
|
230
|
+
|
|
231
|
+
if client:
|
|
232
|
+
client.on_event(lambda event: plugin.on_event(ctx, event))
|
|
233
|
+
|
|
234
|
+
# 7. Call plugin.on_start()
|
|
235
|
+
try:
|
|
236
|
+
await plugin.on_start(ctx)
|
|
237
|
+
except Exception as e:
|
|
238
|
+
print(f"[temps-plugin] Error in on_start: {e}", file=sys.stderr)
|
|
239
|
+
raise
|
|
240
|
+
|
|
241
|
+
# 8. Mount the plugin handler
|
|
242
|
+
plugin_handler = plugin.handler(ctx)
|
|
243
|
+
plugin_ready = True
|
|
244
|
+
|
|
245
|
+
print(
|
|
246
|
+
f"[temps-plugin] {manifest.display_name or manifest.name} "
|
|
247
|
+
f"v{manifest.version} running on {args.socket_path}",
|
|
248
|
+
file=sys.stderr,
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
# 9. Graceful shutdown -- wait until signal
|
|
252
|
+
await shutdown_event.wait()
|
|
253
|
+
|
|
254
|
+
await _shutdown(plugin, manifest, client, runner, args)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
async def _shutdown(
|
|
258
|
+
plugin: TempsPlugin,
|
|
259
|
+
manifest: PluginManifest,
|
|
260
|
+
client: TempsClient | None,
|
|
261
|
+
runner: web.AppRunner,
|
|
262
|
+
args: PluginArgs,
|
|
263
|
+
) -> None:
|
|
264
|
+
"""Run graceful shutdown sequence."""
|
|
265
|
+
print(f"[temps-plugin] Shutting down {manifest.name}...", file=sys.stderr)
|
|
266
|
+
try:
|
|
267
|
+
await plugin.on_shutdown()
|
|
268
|
+
except Exception as e:
|
|
269
|
+
print(f"[temps-plugin] Error during shutdown: {e}", file=sys.stderr)
|
|
270
|
+
|
|
271
|
+
if client:
|
|
272
|
+
await client.close()
|
|
273
|
+
|
|
274
|
+
await runner.cleanup()
|
|
275
|
+
|
|
276
|
+
# Clean up socket file
|
|
277
|
+
if os.path.exists(args.socket_path):
|
|
278
|
+
try:
|
|
279
|
+
os.unlink(args.socket_path)
|
|
280
|
+
except OSError:
|
|
281
|
+
pass
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _parse_args(argv: list[str]) -> PluginArgs:
|
|
285
|
+
"""Parse CLI arguments."""
|
|
286
|
+
socket_path: str | None = None
|
|
287
|
+
auth_secret: str | None = None
|
|
288
|
+
data_dir: str | None = None
|
|
289
|
+
database_url: str | None = None
|
|
290
|
+
|
|
291
|
+
i = 0
|
|
292
|
+
while i < len(argv):
|
|
293
|
+
arg = argv[i]
|
|
294
|
+
next_val = argv[i + 1] if i + 1 < len(argv) else None
|
|
295
|
+
|
|
296
|
+
if arg == "--socket-path" and next_val:
|
|
297
|
+
socket_path = next_val
|
|
298
|
+
i += 2
|
|
299
|
+
elif arg == "--auth-secret" and next_val:
|
|
300
|
+
auth_secret = next_val
|
|
301
|
+
i += 2
|
|
302
|
+
elif arg == "--data-dir" and next_val:
|
|
303
|
+
data_dir = next_val
|
|
304
|
+
i += 2
|
|
305
|
+
elif arg == "--database-url" and next_val:
|
|
306
|
+
database_url = next_val
|
|
307
|
+
i += 2
|
|
308
|
+
else:
|
|
309
|
+
i += 1
|
|
310
|
+
|
|
311
|
+
if not socket_path:
|
|
312
|
+
raise SystemExit("Error: --socket-path is required")
|
|
313
|
+
if not auth_secret:
|
|
314
|
+
raise SystemExit("Error: --auth-secret is required")
|
|
315
|
+
if not data_dir:
|
|
316
|
+
raise SystemExit("Error: --data-dir is required")
|
|
317
|
+
|
|
318
|
+
return PluginArgs(
|
|
319
|
+
socket_path=socket_path,
|
|
320
|
+
auth_secret=auth_secret,
|
|
321
|
+
data_dir=data_dir,
|
|
322
|
+
database_url=database_url,
|
|
323
|
+
)
|
temps_plugin/types.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024-2026 Temps Contributors
|
|
2
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Protocol types matching the Rust plugin SDK.
|
|
5
|
+
|
|
6
|
+
Mirrors: crates/temps-plugin-protocol/src/manifest.rs
|
|
7
|
+
crates/temps-plugin-protocol/src/channel.rs
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from enum import Enum
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class NavSection(str, Enum):
|
|
18
|
+
"""Where a navigation entry appears in the Temps sidebar."""
|
|
19
|
+
|
|
20
|
+
PLATFORM = "platform"
|
|
21
|
+
SETTINGS = "settings"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class NavEntry:
|
|
26
|
+
"""A navigation entry for the plugin UI."""
|
|
27
|
+
|
|
28
|
+
label: str
|
|
29
|
+
icon: str
|
|
30
|
+
path: str
|
|
31
|
+
section: NavSection = NavSection.PLATFORM
|
|
32
|
+
order: int = 50
|
|
33
|
+
|
|
34
|
+
def to_dict(self) -> dict[str, Any]:
|
|
35
|
+
return {
|
|
36
|
+
"label": self.label,
|
|
37
|
+
"icon": self.icon,
|
|
38
|
+
"path": self.path,
|
|
39
|
+
"section": self.section.value,
|
|
40
|
+
"order": self.order,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class PluginManifest:
|
|
46
|
+
"""Plugin manifest sent to the host during handshake."""
|
|
47
|
+
|
|
48
|
+
name: str
|
|
49
|
+
version: str
|
|
50
|
+
display_name: str | None = None
|
|
51
|
+
description: str | None = None
|
|
52
|
+
nav: list[NavEntry] = field(default_factory=list)
|
|
53
|
+
requires_db: bool = False
|
|
54
|
+
health_path: str = "/health"
|
|
55
|
+
events: list[str] = field(default_factory=list)
|
|
56
|
+
|
|
57
|
+
def to_dict(self) -> dict[str, Any]:
|
|
58
|
+
return {
|
|
59
|
+
"type": "manifest",
|
|
60
|
+
"name": self.name,
|
|
61
|
+
"version": self.version,
|
|
62
|
+
"display_name": self.display_name or self.name,
|
|
63
|
+
"description": self.description or "",
|
|
64
|
+
"nav": [n.to_dict() for n in self.nav],
|
|
65
|
+
"requires_db": self.requires_db,
|
|
66
|
+
"health_path": self.health_path,
|
|
67
|
+
"events": self.events,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class PluginArgs:
|
|
73
|
+
"""CLI arguments passed by the Temps host."""
|
|
74
|
+
|
|
75
|
+
socket_path: str
|
|
76
|
+
auth_secret: str
|
|
77
|
+
data_dir: str
|
|
78
|
+
database_url: str | None = None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class PluginEvent:
|
|
83
|
+
"""An event delivered from the Temps platform."""
|
|
84
|
+
|
|
85
|
+
id: str
|
|
86
|
+
event_type: str
|
|
87
|
+
timestamp: str
|
|
88
|
+
project_id: int | None = None
|
|
89
|
+
data: dict[str, Any] = field(default_factory=dict)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass
|
|
93
|
+
class AuthContext:
|
|
94
|
+
"""Authentication context extracted from request headers."""
|
|
95
|
+
|
|
96
|
+
user_id: str | None = None
|
|
97
|
+
user_email: str | None = None
|
|
98
|
+
user_role: str | None = None
|
|
99
|
+
request_id: str | None = None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# -- Channel message types (WebSocket) --
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass
|
|
106
|
+
class ChannelRequest:
|
|
107
|
+
"""A request from the plugin to the host via the WebSocket channel."""
|
|
108
|
+
|
|
109
|
+
id: str
|
|
110
|
+
method: str
|
|
111
|
+
params: dict[str, Any] = field(default_factory=dict)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass
|
|
115
|
+
class ChannelResponse:
|
|
116
|
+
"""A response from the host to the plugin via the WebSocket channel."""
|
|
117
|
+
|
|
118
|
+
id: str
|
|
119
|
+
result: Any = None
|
|
120
|
+
error: str | None = None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# Embedded UI types
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass
|
|
127
|
+
class EmbeddedFile:
|
|
128
|
+
"""A file embedded into the binary at build time."""
|
|
129
|
+
|
|
130
|
+
content: bytes
|
|
131
|
+
content_type: str
|
|
132
|
+
immutable: bool = False
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# Type alias for the embedded assets map
|
|
136
|
+
EmbeddedAssets = dict[str, EmbeddedFile]
|
temps_plugin/ui.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024-2026 Temps Contributors
|
|
2
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Embedded UI serving.
|
|
5
|
+
|
|
6
|
+
Mirrors: sdks/node/packages/plugin-sdk/src/ui.ts
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from aiohttp import web
|
|
12
|
+
|
|
13
|
+
from temps_plugin.types import EmbeddedAssets
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _parse_content_type(value: str) -> tuple[str, str | None]:
|
|
17
|
+
"""Split 'text/html; charset=utf-8' into ('text/html', 'utf-8').
|
|
18
|
+
|
|
19
|
+
aiohttp's ``web.Response`` requires charset to be passed separately.
|
|
20
|
+
"""
|
|
21
|
+
parts = [p.strip() for p in value.split(";")]
|
|
22
|
+
mime = parts[0]
|
|
23
|
+
charset: str | None = None
|
|
24
|
+
for part in parts[1:]:
|
|
25
|
+
if part.lower().startswith("charset="):
|
|
26
|
+
charset = part.split("=", 1)[1].strip()
|
|
27
|
+
return mime, charset
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def serve_embedded_ui(path: str, assets: EmbeddedAssets) -> web.Response:
|
|
31
|
+
"""Serve an embedded UI asset, with SPA fallback."""
|
|
32
|
+
|
|
33
|
+
# Redirect /ui to /ui/
|
|
34
|
+
if path == "/ui":
|
|
35
|
+
raise web.HTTPFound("/ui/")
|
|
36
|
+
|
|
37
|
+
if not path.startswith("/ui/"):
|
|
38
|
+
return web.Response(text="Not Found", status=404)
|
|
39
|
+
|
|
40
|
+
relative_path = path[len("/ui/") :] or "index.html"
|
|
41
|
+
|
|
42
|
+
# Block path traversal
|
|
43
|
+
if ".." in relative_path:
|
|
44
|
+
return web.Response(text="Forbidden", status=403)
|
|
45
|
+
|
|
46
|
+
# Exact match
|
|
47
|
+
file = assets.get(relative_path)
|
|
48
|
+
if file:
|
|
49
|
+
cache = (
|
|
50
|
+
"public, max-age=31536000, immutable"
|
|
51
|
+
if file.immutable
|
|
52
|
+
else "no-cache, no-store, must-revalidate"
|
|
53
|
+
)
|
|
54
|
+
content_type, charset = _parse_content_type(file.content_type)
|
|
55
|
+
return web.Response(
|
|
56
|
+
body=file.content,
|
|
57
|
+
content_type=content_type,
|
|
58
|
+
charset=charset,
|
|
59
|
+
headers={
|
|
60
|
+
"Content-Length": str(len(file.content)),
|
|
61
|
+
"Cache-Control": cache,
|
|
62
|
+
},
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# SPA fallback for paths without file extensions
|
|
66
|
+
last_segment = relative_path.rsplit("/", 1)[-1]
|
|
67
|
+
if "." not in last_segment:
|
|
68
|
+
index = assets.get("index.html")
|
|
69
|
+
if index:
|
|
70
|
+
content_type, charset = _parse_content_type(index.content_type)
|
|
71
|
+
return web.Response(
|
|
72
|
+
body=index.content,
|
|
73
|
+
content_type=content_type,
|
|
74
|
+
charset=charset,
|
|
75
|
+
headers={
|
|
76
|
+
"Content-Length": str(len(index.content)),
|
|
77
|
+
"Cache-Control": "no-cache, no-store, must-revalidate",
|
|
78
|
+
},
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
return web.Response(text="Not Found", status=404)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: temps-plugin-sdk
|
|
3
|
+
Version: 0.1.0b1
|
|
4
|
+
Summary: Python SDK for building Temps external plugins
|
|
5
|
+
Project-URL: Repository, https://github.com/gotempsh/temps
|
|
6
|
+
License-Expression: MIT OR Apache-2.0
|
|
7
|
+
Requires-Python: >=3.12
|
|
8
|
+
Requires-Dist: aiohttp>=3.14.0
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
Build Temps external plugins in Python with manifest builders, typed context, a platform WebSocket client and an aiohttp runtime. Source and usage: https://github.com/gotempsh/temps
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
temps_plugin/__init__.py,sha256=4h_cckIeiQ0-hmKIwE-wjZ02BW5msbE5ORZnb80ffrA,847
|
|
2
|
+
temps_plugin/client.py,sha256=AfQWMdPMruou74oc4OgQMCLRMeMMRtXM9dTAf1ohp-s,4544
|
|
3
|
+
temps_plugin/context.py,sha256=wCrb2Q3BAsEO413SuQNVph-Xxr_Yydde7vh5evSJXlg,872
|
|
4
|
+
temps_plugin/manifest_builder.py,sha256=5TaLBzgCNTIJ3DMuiw0g4hh_AncG_gVVQXmCGEDvnwI,1675
|
|
5
|
+
temps_plugin/protocol.py,sha256=dIiE5jQxqoxMPboIdxGHdg42VPm2sw49ODGI1XGG8Ro,1528
|
|
6
|
+
temps_plugin/runtime.py,sha256=Fyot9jvZdQuLNqDPq1MTFCkvWwvth47cm6sxDXc3on8,10026
|
|
7
|
+
temps_plugin/types.py,sha256=Ft9RdPL1ZArXIL2ot95PGZoSnZVng_C0dL-OUb8tYpA,3103
|
|
8
|
+
temps_plugin/ui.py,sha256=IWxMWFRdx55fLFdtE0d0jwrXlAUceO7v3_BuA3IviSs,2490
|
|
9
|
+
temps_plugin_sdk-0.1.0b1.dist-info/METADATA,sha256=Q76HEI8TGFdfhCqDG-ii-xe_OwGdU2_uUtv8bVVXo3g,492
|
|
10
|
+
temps_plugin_sdk-0.1.0b1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
11
|
+
temps_plugin_sdk-0.1.0b1.dist-info/RECORD,,
|