magiplace 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- magiplace/__init__.py +5 -0
- magiplace/auth.py +79 -0
- magiplace/automations.py +91 -0
- magiplace/boot.py +124 -0
- magiplace/cli.py +179 -0
- magiplace/contract.py +180 -0
- magiplace/desktop.py +118 -0
- magiplace/events.py +241 -0
- magiplace/host.py +92 -0
- magiplace/inline_views.py +1153 -0
- magiplace/liveshare.py +138 -0
- magiplace/liveshare_viewer.py +151 -0
- magiplace/marketplace.py +314 -0
- magiplace/mcp_accounts.py +152 -0
- magiplace/pages.py +407 -0
- magiplace/providers.py +129 -0
- magiplace/settings_modal.py +699 -0
- magiplace/shell_controller.py +1615 -0
- magiplace/shortcuts_modal.py +330 -0
- magiplace/startup.py +146 -0
- magiplace/web_app.py +77 -0
- magiplace-0.1.0.dist-info/METADATA +50 -0
- magiplace-0.1.0.dist-info/RECORD +25 -0
- magiplace-0.1.0.dist-info/WHEEL +4 -0
- magiplace-0.1.0.dist-info/entry_points.txt +4 -0
magiplace/__init__.py
ADDED
magiplace/auth.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Desktop and Web credential verification helpers for magiplace."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hmac
|
|
6
|
+
import re
|
|
7
|
+
import secrets
|
|
8
|
+
from collections.abc import Callable, Mapping
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from hashlib import sha256
|
|
11
|
+
|
|
12
|
+
COOKIE_NAME = "mth-desktop-session"
|
|
13
|
+
WEB_COOKIE_NAME = "mth-web-session"
|
|
14
|
+
SECRET_RE = re.compile(r"^[A-Za-z0-9_-]{43}$")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def make_secret() -> str:
|
|
18
|
+
"""Create one 43-character urlsafe startup credential."""
|
|
19
|
+
return secrets.token_urlsafe(32)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DesktopAuth:
|
|
23
|
+
"""Verify the owner credential supplied on a host request."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, read_secret: Callable[[], str]) -> None:
|
|
26
|
+
self.read_secret = read_secret
|
|
27
|
+
|
|
28
|
+
def authenticate(self, cookie_header: str | None) -> bool:
|
|
29
|
+
"""Return True only for one well-formed, matching owner cookie."""
|
|
30
|
+
if not isinstance(cookie_header, str):
|
|
31
|
+
return False
|
|
32
|
+
value: str | None = None
|
|
33
|
+
for part in cookie_header.split(";"):
|
|
34
|
+
key, separator, raw = part.partition("=")
|
|
35
|
+
if not separator or key.strip() != COOKIE_NAME:
|
|
36
|
+
continue
|
|
37
|
+
if value is not None:
|
|
38
|
+
return False
|
|
39
|
+
value = raw.strip()
|
|
40
|
+
if value is None or not SECRET_RE.fullmatch(value):
|
|
41
|
+
return False
|
|
42
|
+
return hmac.compare_digest(value, self.read_secret())
|
|
43
|
+
|
|
44
|
+
def public_view(self) -> dict[str, str]:
|
|
45
|
+
"""Renderer-safe descriptor that never carries the credential."""
|
|
46
|
+
return {
|
|
47
|
+
"kind": "desktop-owner",
|
|
48
|
+
"cookie": COOKIE_NAME,
|
|
49
|
+
"credential": "<redacted>",
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class WebAuth:
|
|
55
|
+
"""Tokenized startup authentication gate matching `dsh web` security model."""
|
|
56
|
+
|
|
57
|
+
token: str = field(default_factory=make_secret)
|
|
58
|
+
|
|
59
|
+
def is_valid_token(self, candidate: str | None) -> bool:
|
|
60
|
+
"""Verify an incoming query or form startup token."""
|
|
61
|
+
if not candidate:
|
|
62
|
+
return False
|
|
63
|
+
return hmac.compare_digest(candidate, self.token)
|
|
64
|
+
|
|
65
|
+
def cookie_value(self) -> str:
|
|
66
|
+
"""Return the HttpOnly cookie digest exchanged for a valid token."""
|
|
67
|
+
return sha256(f"web-cookie:{self.token}".encode()).hexdigest()
|
|
68
|
+
|
|
69
|
+
def is_authorized(self, cookies: Mapping[str, str]) -> bool:
|
|
70
|
+
"""Validate the active browser session cookie."""
|
|
71
|
+
presented = cookies.get(WEB_COOKIE_NAME)
|
|
72
|
+
if not presented:
|
|
73
|
+
return False
|
|
74
|
+
return hmac.compare_digest(presented, self.cookie_value())
|
|
75
|
+
|
|
76
|
+
def entry_url(self, base_url: str) -> str:
|
|
77
|
+
"""Attach the startup `?token=...` query parameter to a root URL."""
|
|
78
|
+
sep = "&" if "?" in base_url else "?"
|
|
79
|
+
return f"{base_url}{sep}token={self.token}"
|
magiplace/automations.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Host-backed automations over the contract's ``schedule/*`` surface.
|
|
2
|
+
|
|
3
|
+
Active only when the transport exposes controllers with a mounted schedule
|
|
4
|
+
service (a ``magimoire.schedule.engine:ScheduleService`` profile row);
|
|
5
|
+
otherwise the Automations page shows an honest unavailable state instead of a
|
|
6
|
+
local-only list that silently persists to UI settings.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from magiplace.contract import HostContract, Principal
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AutomationsHost:
|
|
17
|
+
"""Host-backed schedule model over the ``schedule/*`` methods."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, contract: HostContract, principal: Principal) -> None:
|
|
20
|
+
self.contract = contract
|
|
21
|
+
self.principal = principal
|
|
22
|
+
self.tasks: list[dict[str, Any]] | None = None
|
|
23
|
+
|
|
24
|
+
async def refresh(self) -> list[dict[str, Any]]:
|
|
25
|
+
result = await self.contract.invoke(self.principal, "schedule.list")
|
|
26
|
+
tasks = result.get("tasks", []) if isinstance(result, dict) else []
|
|
27
|
+
self.tasks = [dict(task) for task in tasks if isinstance(task, dict)]
|
|
28
|
+
return self.tasks
|
|
29
|
+
|
|
30
|
+
async def create(
|
|
31
|
+
self, name: str, instruction: str, cron: str, timezone: str
|
|
32
|
+
) -> dict[str, Any]:
|
|
33
|
+
timing: dict[str, Any] = {"kind": "cron", "expression": cron}
|
|
34
|
+
if timezone:
|
|
35
|
+
timing["time_zone"] = timezone
|
|
36
|
+
result = await self.contract.invoke(
|
|
37
|
+
self.principal,
|
|
38
|
+
"schedule.create",
|
|
39
|
+
{"name": name, "instruction": instruction, "timing": timing},
|
|
40
|
+
)
|
|
41
|
+
return dict(result.get("task", {})) if isinstance(result, dict) else {}
|
|
42
|
+
|
|
43
|
+
async def update(
|
|
44
|
+
self, task_id: str, title: str, instruction: str, cron: str, timezone: str
|
|
45
|
+
) -> dict[str, Any]:
|
|
46
|
+
timing: dict[str, Any] = {"kind": "cron", "expression": cron}
|
|
47
|
+
if timezone:
|
|
48
|
+
timing["time_zone"] = timezone
|
|
49
|
+
result = await self.contract.invoke(
|
|
50
|
+
self.principal,
|
|
51
|
+
"schedule.edit",
|
|
52
|
+
{
|
|
53
|
+
"taskId": task_id,
|
|
54
|
+
"action": "update",
|
|
55
|
+
"patch": {"title": title, "prompt": instruction, "timing": timing},
|
|
56
|
+
},
|
|
57
|
+
)
|
|
58
|
+
return dict(result.get("task", {})) if isinstance(result, dict) else {}
|
|
59
|
+
|
|
60
|
+
async def set_active(self, task_id: str, active: bool) -> dict[str, Any]:
|
|
61
|
+
result = await self.contract.invoke(
|
|
62
|
+
self.principal,
|
|
63
|
+
"schedule.edit",
|
|
64
|
+
{"taskId": task_id, "action": "resume" if active else "pause"},
|
|
65
|
+
)
|
|
66
|
+
return dict(result.get("task", {})) if isinstance(result, dict) else {}
|
|
67
|
+
|
|
68
|
+
async def delete(self, task_id: str) -> dict[str, Any]:
|
|
69
|
+
result = await self.contract.invoke(
|
|
70
|
+
self.principal,
|
|
71
|
+
"schedule.edit",
|
|
72
|
+
{"taskId": task_id, "action": "delete"},
|
|
73
|
+
)
|
|
74
|
+
return dict(result) if isinstance(result, dict) else {}
|
|
75
|
+
|
|
76
|
+
async def run(self, task_id: str) -> dict[str, Any]:
|
|
77
|
+
result = await self.contract.invoke(
|
|
78
|
+
self.principal, "schedule.run", {"taskId": task_id}
|
|
79
|
+
)
|
|
80
|
+
return dict(result) if isinstance(result, dict) else {}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def automations_host_from_transport(
|
|
84
|
+
contract: HostContract, principal: Principal
|
|
85
|
+
) -> AutomationsHost | None:
|
|
86
|
+
"""Build a host automations model when the transport owns a schedule."""
|
|
87
|
+
controllers = getattr(contract.transport, "controllers", None)
|
|
88
|
+
ctx = getattr(controllers, "ctx", None)
|
|
89
|
+
if ctx is None or ctx.get("schedule", None, strict=False) is None:
|
|
90
|
+
return None
|
|
91
|
+
return AutomationsHost(contract, principal)
|
magiplace/boot.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Two-stage client boot kernel with a module table and activation audit.
|
|
2
|
+
|
|
3
|
+
The dsh browser boot kernel is re-expressed in Python: immediate-tier prefetch,
|
|
4
|
+
concurrent activation, and a required-entry audit before renderer handoff.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
|
|
13
|
+
Loader = Callable[[], Awaitable[object]]
|
|
14
|
+
Prefetch = Callable[[str], Awaitable[None]]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class BootError(Exception):
|
|
18
|
+
"""Boot failed with a stable machine code."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, code: str, message: str) -> None:
|
|
21
|
+
super().__init__(f"{code}: {message}")
|
|
22
|
+
self.code = code
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class ModuleEntry:
|
|
27
|
+
"""One client module in the boot table."""
|
|
28
|
+
|
|
29
|
+
id: str
|
|
30
|
+
required: bool = True
|
|
31
|
+
immediately: bool = False
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class BootManifest:
|
|
36
|
+
"""The accepted module table handed to the renderer."""
|
|
37
|
+
|
|
38
|
+
plugins: tuple[ModuleEntry, ...]
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def names(self) -> tuple[str, ...]:
|
|
42
|
+
return tuple(entry.id for entry in self.plugins)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class BootPage:
|
|
47
|
+
"""Framework-free boot page state; the NiceGUI page renders from it."""
|
|
48
|
+
|
|
49
|
+
total: int = 0
|
|
50
|
+
states: dict[str, str] = field(default_factory=dict)
|
|
51
|
+
failure: str | None = None
|
|
52
|
+
|
|
53
|
+
def set_total(self, value: int) -> None:
|
|
54
|
+
self.total = value
|
|
55
|
+
|
|
56
|
+
def set_state(self, name: str, state: str) -> None:
|
|
57
|
+
self.states[name] = state
|
|
58
|
+
|
|
59
|
+
def fail(self, reason: str) -> None:
|
|
60
|
+
self.failure = reason
|
|
61
|
+
|
|
62
|
+
def dispose(self) -> None:
|
|
63
|
+
self.states.clear()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class BootKernel:
|
|
67
|
+
"""Load and audit the client module table before renderer handoff."""
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
entries: Sequence[ModuleEntry],
|
|
72
|
+
loaders: Mapping[str, Loader],
|
|
73
|
+
*,
|
|
74
|
+
prefetch: Prefetch | None = None,
|
|
75
|
+
page: BootPage | None = None,
|
|
76
|
+
) -> None:
|
|
77
|
+
self.entries = tuple(entries)
|
|
78
|
+
self.loaders = dict(loaders)
|
|
79
|
+
self.prefetch = prefetch
|
|
80
|
+
self.page = page or BootPage()
|
|
81
|
+
self.failures: dict[str, str] = {}
|
|
82
|
+
|
|
83
|
+
async def run(self) -> BootManifest:
|
|
84
|
+
"""Prefetch immediate entries, activate all, then audit required ones."""
|
|
85
|
+
self.page.set_total(len(self.entries))
|
|
86
|
+
if self.prefetch is not None:
|
|
87
|
+
await asyncio.gather(
|
|
88
|
+
*(
|
|
89
|
+
self.prefetch(entry.id)
|
|
90
|
+
for entry in self.entries
|
|
91
|
+
if entry.immediately
|
|
92
|
+
),
|
|
93
|
+
return_exceptions=True,
|
|
94
|
+
)
|
|
95
|
+
await asyncio.gather(*(self._activate(entry) for entry in self.entries))
|
|
96
|
+
required_failed = [
|
|
97
|
+
entry.id
|
|
98
|
+
for entry in self.entries
|
|
99
|
+
if entry.required and entry.id in self.failures
|
|
100
|
+
]
|
|
101
|
+
if required_failed:
|
|
102
|
+
reason = f"required client entries failed: {', '.join(required_failed)}"
|
|
103
|
+
self.page.fail(reason)
|
|
104
|
+
raise BootError("REQUIRED_ENTRY_FAILED", reason)
|
|
105
|
+
accepted = tuple(
|
|
106
|
+
entry for entry in self.entries if entry.id not in self.failures
|
|
107
|
+
)
|
|
108
|
+
return BootManifest(accepted)
|
|
109
|
+
|
|
110
|
+
async def _activate(self, entry: ModuleEntry) -> None:
|
|
111
|
+
loader = self.loaders.get(entry.id)
|
|
112
|
+
if loader is None:
|
|
113
|
+
self._record(entry, "missing loader")
|
|
114
|
+
return
|
|
115
|
+
try:
|
|
116
|
+
await loader()
|
|
117
|
+
except Exception as exc: # noqa: BLE001 - module boundary
|
|
118
|
+
self._record(entry, str(exc))
|
|
119
|
+
else:
|
|
120
|
+
self.page.set_state(entry.id, "active")
|
|
121
|
+
|
|
122
|
+
def _record(self, entry: ModuleEntry, reason: str) -> None:
|
|
123
|
+
self.failures[entry.id] = reason
|
|
124
|
+
self.page.set_state(entry.id, "failed")
|
magiplace/cli.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""`magi-web` and `magi-desktop` entry points."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
from collections.abc import Callable, Sequence
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from dotenv import load_dotenv
|
|
10
|
+
from nicegui import ui
|
|
11
|
+
|
|
12
|
+
from magiplace.auth import WebAuth
|
|
13
|
+
from magiplace.contract import HostContract, InProcessTransport, Principal
|
|
14
|
+
from magiplace.desktop import DesktopApplication
|
|
15
|
+
from magiplace.events import EventProjector, SessionEventFeed
|
|
16
|
+
from magiplace.marketplace import InMemoryMarketplace, Marketplace
|
|
17
|
+
from magiplace.mcp_accounts import McpContractAccounts
|
|
18
|
+
from magiplace.pages import register_pages
|
|
19
|
+
from magiplace.providers import mount_configured_providers
|
|
20
|
+
from magiplace.startup import (
|
|
21
|
+
DesktopStartup,
|
|
22
|
+
WebStartup,
|
|
23
|
+
parse_desktop_args,
|
|
24
|
+
parse_web_args,
|
|
25
|
+
)
|
|
26
|
+
from magiplace.web_app import WebApp, WebEntryUrl
|
|
27
|
+
|
|
28
|
+
RunFn = Callable[..., None]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def load_host_env() -> None:
|
|
32
|
+
"""Load the host's `.env` before provider configuration is read."""
|
|
33
|
+
load_dotenv(".env")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def default_contract(profile: str | None = None) -> HostContract:
|
|
37
|
+
"""Build the contract over a freshly created harness context.
|
|
38
|
+
|
|
39
|
+
Configured provider components mount before the transport wraps the
|
|
40
|
+
controllers, so the composer's model picker lists only models discovered
|
|
41
|
+
from routes the host actually serves (dsh picker parity).
|
|
42
|
+
"""
|
|
43
|
+
from magimoire import create_harness
|
|
44
|
+
from magimoire.remote.controllers import RemoteControllers
|
|
45
|
+
|
|
46
|
+
if profile:
|
|
47
|
+
from magimoire.profiles.launcher import (
|
|
48
|
+
PROFILE_FILE,
|
|
49
|
+
prepare_profile,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
profile_directory = prepare_profile(profile)
|
|
53
|
+
ctx = create_harness(profile=profile_directory / PROFILE_FILE)
|
|
54
|
+
else:
|
|
55
|
+
ctx = create_harness()
|
|
56
|
+
mount_configured_providers(ctx)
|
|
57
|
+
return HostContract(InProcessTransport(RemoteControllers(ctx, interactions=True)))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def serve_web(
|
|
61
|
+
argv: Sequence[str] | None = None,
|
|
62
|
+
*,
|
|
63
|
+
contract: HostContract | None = None,
|
|
64
|
+
principal: Principal | None = None,
|
|
65
|
+
marketplace: Marketplace | None = None,
|
|
66
|
+
run: RunFn | None = None,
|
|
67
|
+
out: Any = None,
|
|
68
|
+
) -> WebStartup:
|
|
69
|
+
"""Parse, announce and serve the Web GUI."""
|
|
70
|
+
load_host_env()
|
|
71
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
72
|
+
startup = parse_web_args(args)
|
|
73
|
+
host_contract = contract or default_contract(startup.profile)
|
|
74
|
+
caller = principal or Principal("owner", "web")
|
|
75
|
+
components = marketplace or InMemoryMarketplace()
|
|
76
|
+
feed = SessionEventFeed(host_contract, caller, "web-session", EventProjector())
|
|
77
|
+
web_app = WebApp(startup)
|
|
78
|
+
warning = web_app.exposure_warning()
|
|
79
|
+
web_auth = None if startup.no_auth else WebAuth()
|
|
80
|
+
stream = out or sys.stdout
|
|
81
|
+
if warning is not None:
|
|
82
|
+
print(warning, file=sys.stderr)
|
|
83
|
+
for entry in web_app.collect_entry_urls():
|
|
84
|
+
printed_url = (
|
|
85
|
+
web_auth.entry_url(entry.url) if web_auth is not None else entry.url
|
|
86
|
+
)
|
|
87
|
+
print(f"{entry.label}: {printed_url}", file=stream)
|
|
88
|
+
browser_url = next(
|
|
89
|
+
(
|
|
90
|
+
web_auth.entry_url(entry.url) if web_auth is not None else entry.url
|
|
91
|
+
for entry in web_app.collect_entry_urls()
|
|
92
|
+
if entry.open
|
|
93
|
+
),
|
|
94
|
+
None,
|
|
95
|
+
)
|
|
96
|
+
register_pages(
|
|
97
|
+
host_contract,
|
|
98
|
+
principal=caller,
|
|
99
|
+
marketplace=components,
|
|
100
|
+
mcp_accounts=McpContractAccounts(host_contract, caller),
|
|
101
|
+
projector=feed.projector,
|
|
102
|
+
event_feed=feed,
|
|
103
|
+
web_auth=web_auth,
|
|
104
|
+
ui_profile=startup.profile,
|
|
105
|
+
)
|
|
106
|
+
options: dict[str, Any] = {
|
|
107
|
+
"host": startup.host,
|
|
108
|
+
"port": startup.port,
|
|
109
|
+
"title": "Magimoire",
|
|
110
|
+
"dark": True,
|
|
111
|
+
"reload": False,
|
|
112
|
+
"show": (
|
|
113
|
+
browser_url if startup.open_browser and browser_url is not None else False
|
|
114
|
+
),
|
|
115
|
+
}
|
|
116
|
+
if startup.tls_cert is not None and startup.tls_key is not None:
|
|
117
|
+
options["ssl_certfile"] = startup.tls_cert
|
|
118
|
+
options["ssl_keyfile"] = startup.tls_key
|
|
119
|
+
(run or ui.run)(**options)
|
|
120
|
+
return startup
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def serve_desktop(
|
|
124
|
+
argv: Sequence[str] | None = None,
|
|
125
|
+
*,
|
|
126
|
+
contract: HostContract | None = None,
|
|
127
|
+
principal: Principal | None = None,
|
|
128
|
+
marketplace: Marketplace | None = None,
|
|
129
|
+
run: RunFn | None = None,
|
|
130
|
+
) -> DesktopApplication:
|
|
131
|
+
"""Parse, assemble and serve the Desktop GUI."""
|
|
132
|
+
load_host_env()
|
|
133
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
134
|
+
startup: DesktopStartup = parse_desktop_args(args)
|
|
135
|
+
host_contract = contract or default_contract()
|
|
136
|
+
caller = principal or Principal("owner", "desktop")
|
|
137
|
+
components = marketplace or InMemoryMarketplace()
|
|
138
|
+
feed = SessionEventFeed(host_contract, caller, "desktop-session", EventProjector())
|
|
139
|
+
app = DesktopApplication(
|
|
140
|
+
startup,
|
|
141
|
+
host_contract,
|
|
142
|
+
caller,
|
|
143
|
+
components,
|
|
144
|
+
projector=feed.projector,
|
|
145
|
+
event_feed=feed,
|
|
146
|
+
)
|
|
147
|
+
app.register()
|
|
148
|
+
(run or ui.run)(
|
|
149
|
+
host=startup.host,
|
|
150
|
+
port=startup.port,
|
|
151
|
+
title=app.window.title,
|
|
152
|
+
dark=True,
|
|
153
|
+
reload=False,
|
|
154
|
+
show=False,
|
|
155
|
+
native=True,
|
|
156
|
+
window_size=startup.window_size,
|
|
157
|
+
frameless=app.window.frameless,
|
|
158
|
+
)
|
|
159
|
+
return app
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def web_main() -> None:
|
|
163
|
+
"""Console-script entry for ``magi-web``."""
|
|
164
|
+
serve_web()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def desktop_main() -> None:
|
|
168
|
+
"""Console-script entry for ``magi-desktop``."""
|
|
169
|
+
serve_desktop()
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
__all__ = [
|
|
173
|
+
"WebEntryUrl",
|
|
174
|
+
"default_contract",
|
|
175
|
+
"desktop_main",
|
|
176
|
+
"serve_desktop",
|
|
177
|
+
"serve_web",
|
|
178
|
+
"web_main",
|
|
179
|
+
]
|
magiplace/contract.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Versioned, fail-closed host-facing contract shared by both UIs.
|
|
2
|
+
|
|
3
|
+
ADR 0025 decision 4: every call carries an explicit principal, there is no
|
|
4
|
+
implicit fallback, and an unknown method or principal fails closed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any, Protocol
|
|
12
|
+
|
|
13
|
+
API_VERSION = "1.0"
|
|
14
|
+
PRINCIPAL_KINDS = ("owner", "guest", "service")
|
|
15
|
+
|
|
16
|
+
_METHOD_MAP = {
|
|
17
|
+
"session.list": "session_list",
|
|
18
|
+
"session.get": "session_get",
|
|
19
|
+
"session.create": "session_create",
|
|
20
|
+
"session.close": "session_close",
|
|
21
|
+
"session.prompt": "session_prompt",
|
|
22
|
+
"session.cancel": "session_cancel",
|
|
23
|
+
"session.events": "session_events",
|
|
24
|
+
"session.fork": "session/fork",
|
|
25
|
+
"session.history": "session/history",
|
|
26
|
+
"session.rename": "session/rename",
|
|
27
|
+
"workspace.pinSession": "workspace/pinSession",
|
|
28
|
+
"workspace.unpinSession": "workspace/unpinSession",
|
|
29
|
+
"workspace.archiveSession": "workspace/archiveSession",
|
|
30
|
+
"workspace.unarchiveSession": "workspace/unarchiveSession",
|
|
31
|
+
"deliverables.list": "deliverables/list",
|
|
32
|
+
"workflow.list": "workflow/list",
|
|
33
|
+
"workflow.cancel": "workflow/cancel",
|
|
34
|
+
"session.export": "session/export",
|
|
35
|
+
"present.host": "present/host",
|
|
36
|
+
"present.open": "present/open",
|
|
37
|
+
"feedback.record": "feedback/record",
|
|
38
|
+
"recommendations.list": "recommendations/list",
|
|
39
|
+
"agentPreset.catalog": "agentPreset/catalog",
|
|
40
|
+
"agentPreset.select": "agentPreset/select",
|
|
41
|
+
"agentPreset.current": "agentPreset/current",
|
|
42
|
+
"account.status": "account/status",
|
|
43
|
+
"account.authorizeUrl": "account/authorizeUrl",
|
|
44
|
+
"account.complete": "account/complete",
|
|
45
|
+
"account.refresh": "account/refresh",
|
|
46
|
+
"account.signOut": "account/signOut",
|
|
47
|
+
"workspace.stat": "workspace_stat",
|
|
48
|
+
"workspace.read": "workspace_read",
|
|
49
|
+
"workspace.readBinary": "workspace/readBinary",
|
|
50
|
+
"workspace.list": "workspace_list",
|
|
51
|
+
"workspace.changes": "workspace/changes",
|
|
52
|
+
"workspace.changes.close": "workspace/changes/close",
|
|
53
|
+
"workspace.changes.events": "workspace/changes/events",
|
|
54
|
+
"job.list": "job_list",
|
|
55
|
+
"job.get": "job_get",
|
|
56
|
+
"job.read": "job_read",
|
|
57
|
+
"job.kill": "job_kill",
|
|
58
|
+
"subagent.list": "subagent/list",
|
|
59
|
+
"team.task.list": "team/task/list",
|
|
60
|
+
"team.setEnabled": "team/setEnabled",
|
|
61
|
+
"settings.get": "settings_get",
|
|
62
|
+
"settings.set": "settings_set",
|
|
63
|
+
"terminal.open": "terminal_open",
|
|
64
|
+
"terminal.read": "terminal/read",
|
|
65
|
+
"terminal.write": "terminal/write",
|
|
66
|
+
"terminal.reconnect": "terminal/reconnect",
|
|
67
|
+
"terminal.close": "terminal/close",
|
|
68
|
+
"mcp.accounts.list": "mcp/accounts/list",
|
|
69
|
+
"mcp.accounts.action": "mcp/accounts/action",
|
|
70
|
+
"plugins.list": "plugins/list",
|
|
71
|
+
"plugins.install": "plugins/install",
|
|
72
|
+
"plugins.enable": "plugins/enable",
|
|
73
|
+
"plugins.disable": "plugins/disable",
|
|
74
|
+
"plugins.remove": "plugins/remove",
|
|
75
|
+
"plugins.detail": "plugins/detail",
|
|
76
|
+
"schedule.list": "schedule/list",
|
|
77
|
+
"schedule.create": "schedule/create",
|
|
78
|
+
"schedule.edit": "schedule/edit",
|
|
79
|
+
"schedule.run": "schedule/run",
|
|
80
|
+
"goal.get": "goal/get",
|
|
81
|
+
"goal.apply": "goal/apply",
|
|
82
|
+
"permission.catalog": "permission/catalog",
|
|
83
|
+
"permission.set": "permission/set",
|
|
84
|
+
"host.capabilities": "host/capabilities",
|
|
85
|
+
"approval.decide": "approval/decide",
|
|
86
|
+
"question.answer": "question/answer",
|
|
87
|
+
"interactions.list": "interactions/list",
|
|
88
|
+
"liveshare.shares.list": "liveshare/shares/list",
|
|
89
|
+
"liveshare.shares.create": "liveshare/shares/create",
|
|
90
|
+
"liveshare.shares.update": "liveshare/shares/update",
|
|
91
|
+
"liveshare.shares.remove": "liveshare/shares/remove",
|
|
92
|
+
"liveshare.shares.access": "liveshare/shares/access",
|
|
93
|
+
"llm.providers.list": "llm/providers/list",
|
|
94
|
+
"llm.models.list": "llm/models/list",
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class HostError(Exception):
|
|
99
|
+
"""A contract-level rejection with a stable machine code."""
|
|
100
|
+
|
|
101
|
+
def __init__(self, code: str, message: str) -> None:
|
|
102
|
+
super().__init__(f"{code}: {message}")
|
|
103
|
+
self.code = code
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclass(frozen=True)
|
|
107
|
+
class Principal:
|
|
108
|
+
"""The explicit caller identity attached to every host-facing call."""
|
|
109
|
+
|
|
110
|
+
kind: str
|
|
111
|
+
id: str = ""
|
|
112
|
+
|
|
113
|
+
def __post_init__(self) -> None:
|
|
114
|
+
if self.kind not in PRINCIPAL_KINDS:
|
|
115
|
+
raise HostError("INVALID_PRINCIPAL", f"unknown principal kind: {self.kind}")
|
|
116
|
+
|
|
117
|
+
def as_dict(self) -> dict[str, str]:
|
|
118
|
+
return {"kind": self.kind, "id": self.id}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class HostTransport(Protocol):
|
|
122
|
+
"""Transport boundary behind the contract."""
|
|
123
|
+
|
|
124
|
+
async def call(
|
|
125
|
+
self, method: str, params: Mapping[str, Any]
|
|
126
|
+
) -> Any: ... # pragma: no cover
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class InProcessTransport:
|
|
130
|
+
"""Transport over the harness's remote controller service."""
|
|
131
|
+
|
|
132
|
+
def __init__(self, controllers: Any) -> None:
|
|
133
|
+
self.controllers = controllers
|
|
134
|
+
self.context = getattr(controllers, "ctx", None)
|
|
135
|
+
|
|
136
|
+
async def call(self, method: str, params: Mapping[str, Any]) -> Any:
|
|
137
|
+
handlers = getattr(self.controllers, "handlers", None)
|
|
138
|
+
target = method
|
|
139
|
+
if isinstance(handlers, Mapping) and target not in handlers:
|
|
140
|
+
slash_target = target.replace("_", "/")
|
|
141
|
+
if slash_target in handlers:
|
|
142
|
+
target = slash_target
|
|
143
|
+
return await self.controllers.call(target, dict(params))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class HostContract:
|
|
147
|
+
"""Single explicit entry point for host-facing UI calls."""
|
|
148
|
+
|
|
149
|
+
def __init__(
|
|
150
|
+
self,
|
|
151
|
+
transport: HostTransport,
|
|
152
|
+
*,
|
|
153
|
+
version: str = API_VERSION,
|
|
154
|
+
) -> None:
|
|
155
|
+
self.transport = transport
|
|
156
|
+
self.version = version
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def methods(self) -> tuple[str, ...]:
|
|
160
|
+
return tuple(sorted(_METHOD_MAP))
|
|
161
|
+
|
|
162
|
+
async def invoke(
|
|
163
|
+
self,
|
|
164
|
+
principal: Principal,
|
|
165
|
+
method: str,
|
|
166
|
+
params: Mapping[str, Any] | None = None,
|
|
167
|
+
) -> Any:
|
|
168
|
+
if self.version != API_VERSION:
|
|
169
|
+
raise HostError(
|
|
170
|
+
"VERSION_MISMATCH", f"unsupported contract version: {self.version}"
|
|
171
|
+
)
|
|
172
|
+
if not isinstance(principal, Principal):
|
|
173
|
+
raise HostError("MISSING_PRINCIPAL", "an explicit principal is required")
|
|
174
|
+
target = _METHOD_MAP.get(method)
|
|
175
|
+
if target is None:
|
|
176
|
+
raise HostError("UNKNOWN_METHOD", f"unknown host method: {method}")
|
|
177
|
+
call_params = dict(params) if params else {}
|
|
178
|
+
# The verified principal always wins: caller params may not spoof it.
|
|
179
|
+
call_params["principal"] = principal.as_dict()
|
|
180
|
+
return await self.transport.call(target, call_params)
|