Skip to content

Commit 3c8df11

Browse files
feat(services): add isolated venvs and host shell
1 parent 399ef5d commit 3c8df11

15 files changed

Lines changed: 2735 additions & 14 deletions

‎ACKNOWLEDGMENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,8 @@ Vendored in `static/lib/` and served directly:
7575
| [node-qrcode](https://github.com/soldair/node-qrcode) (`qrcode.min.js`) | QR-code rendering (2FA setup) | MIT |
7676
| [KaTeX](https://github.com/KaTeX/KaTeX) v0.16.22 (`katex/katex.min.{js,css}` + `katex/fonts/*.woff2`) | Math typesetting | MIT ([`licenses/KaTeX-MIT-LICENSE.txt`](licenses/KaTeX-MIT-LICENSE.txt)) |
7777
| [Mermaid](https://github.com/mermaid-js/mermaid) v11.16.1 (`mermaid.min.js`) | Diagrams from text | MIT ([`licenses/Mermaid-MIT-LICENSE.txt`](licenses/Mermaid-MIT-LICENSE.txt)) |
78+
| [xterm.js](https://github.com/xtermjs/xterm.js) v6.0.0 (`vendor/xterm/xterm.mjs`, `xterm.css`) | Browser terminal emulator for the admin-only operator shell | MIT ([`licenses/xterm-MIT-LICENSE.txt`](licenses/xterm-MIT-LICENSE.txt)) |
79+
| [@xterm/addon-fit](https://www.npmjs.com/package/@xterm/addon-fit) v0.11.0 (`vendor/xterm/addon-fit.mjs`) | Fits the operator terminal to its pane | MIT ([`licenses/xterm-MIT-LICENSE.txt`](licenses/xterm-MIT-LICENSE.txt)) |
7880

7981
KaTeX and Mermaid are loaded on first use by `static/js/markdown.js` rather than
8082
from `index.html`, so a session that renders no math and no diagram never fetches

‎README.md‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@
3030
**Ɗiogenēs** is a `dev`-based extension that keeps Odysseus routes and data
3131
contracts intact while adding a native, admin-only workstation control plane:
3232

33-
- Docker, Bun/NPX, native, tmux, and Hermes runtimes in the **Services** window;
33+
- Docker, Bun/NPX, native, tmux, and Hermes runtimes in the **Services** window,
34+
plus a separate operator-only mm-tools venv and host-shell tab;
3435
- a standalone [Sandwich](https://github.com/CommanderTurtle/sandwich) Bun
3536
compatibility layer—system Node, npm, pnpm, and yarn are not required;
3637
- separate Colibri GLM, Colibri Hy3, and PrismML native model engines;
@@ -70,7 +71,14 @@ plane built around native Bun. [Sandwich](https://github.com/CommanderTurtle/san
7071
itself adds no telemetry and keeps the JavaScript ecosystem as low-friction as
7172
practical. The **Services** window discovers and manages Docker Compose
7273
projects, interactive tmux services, Git checkouts, configuration files,
73-
updates, and native integration jobs without conflating their runtimes.
74+
updates, and native integration jobs without conflating their runtimes. The
75+
**Venvs** tab starts only a fixed `~/multimedia` service catalog and persistent
76+
human-admin operator shell tabs on the named `diogenes-operator` tmux socket.
77+
The internal-agent token cannot enter this plane. It neither
78+
lists nor mutates the default tmux server, and it removes Diogenes' `.venv`
79+
from each launch environment before sourcing the selected project's own venv.
80+
`DIOGENES_MM_TOOLS_ROOT` and `DIOGENES_OPERATOR_TMUX_SOCKET` override the two
81+
defaults when a workstation uses a different checkout or socket name.
7482

7583
![aviv2](https://huggingface.co/sHEL1562/shelling/resolve/main/src/2-services.avif)
7684

‎licenses/xterm-MIT-LICENSE.txt‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
2+
Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
3+
Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in
13+
all copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
THE SOFTWARE.

‎routes/ulysses_routes.py‎

Lines changed: 212 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,19 @@
22

33
from __future__ import annotations
44

5+
import asyncio
56
from collections.abc import Callable
7+
from contextlib import suppress
8+
import json
9+
from urllib.parse import urlsplit
610

7-
from fastapi import APIRouter, HTTPException, Request
11+
from fastapi import APIRouter, HTTPException, Request, WebSocket, WebSocketDisconnect
812
from pydantic import BaseModel, Field
913
from starlette.concurrency import run_in_threadpool
1014

11-
from core.middleware import require_admin
15+
from core.middleware import INTERNAL_TOOL_HEADER, require_admin
16+
from routes.auth_routes import SESSION_COOKIE
17+
from src.diogenes_host_services import HostServiceError, HostServicesManager
1218
from src.diogenes_docker_projects import (
1319
DockerProjectControl,
1420
DockerResourceControl,
@@ -57,6 +63,7 @@
5763
from src.ulysses_sandwich_control import SandwichControl
5864
from src.ulysses_topology import build_topology_report
5965
from src.tmux_ownership import list_owned_sessions, shutdown_owned_sessions
66+
from src.owner_identity import INTERNAL_TOOL_USER, auth_disabled
6067

6168

6269
class HermesAdoptionApplyRequest(BaseModel):
@@ -160,6 +167,17 @@ class TmuxShutdownRequest(BaseModel):
160167
identities: list[str] | None = None
161168

162169

170+
class HostServiceActionRequest(BaseModel):
171+
action: str
172+
173+
174+
class HostShellCreateRequest(BaseModel):
175+
title: str = ""
176+
cwd: str = ""
177+
cols: int = Field(default=100, ge=20, le=400)
178+
rows: int = Field(default=30, ge=8, le=200)
179+
180+
163181
def _job_http_error(exc: RuntimeJobError) -> HTTPException:
164182
if isinstance(exc, RuntimeJobConflict):
165183
return HTTPException(409, str(exc))
@@ -168,6 +186,27 @@ def _job_http_error(exc: RuntimeJobError) -> HTTPException:
168186
return HTTPException(400, str(exc))
169187

170188

189+
def _require_operator_admin(request: Request) -> None:
190+
"""Require a human admin; internal agent and bearer-token bypasses stay out."""
191+
user = getattr(request.state, "current_user", None)
192+
if (
193+
user == INTERNAL_TOOL_USER
194+
or getattr(request.state, "api_token", False)
195+
or request.headers.get(INTERNAL_TOOL_HEADER)
196+
):
197+
raise HTTPException(403, "Operator admin only")
198+
require_admin(request)
199+
if auth_disabled():
200+
return
201+
auth_manager = getattr(request.app.state, "auth_manager", None)
202+
if (
203+
not user
204+
or auth_manager is None
205+
or not auth_manager.is_admin(user)
206+
):
207+
raise HTTPException(403, "Operator admin only")
208+
209+
171210
def setup_ulysses_routes(
172211
*,
173212
collector: Callable[[], HostDiscoverySnapshot] = collect_host_discovery,
@@ -196,6 +235,9 @@ def setup_ulysses_routes(
196235
sandwich_collector: Callable[[], dict] = collect_sandwich_status,
197236
managed_runtime_collector: Callable[[], dict] = collect_managed_runtimes,
198237
docker_project_collector: Callable[[], dict] = collect_docker_projects,
238+
host_services_manager_factory: Callable[
239+
[], HostServicesManager
240+
] = HostServicesManager,
199241
) -> APIRouter:
200242
router = APIRouter(prefix="/api/odysseus", tags=["odysseus"])
201243

@@ -775,4 +817,172 @@ async def execute_runtime_job(
775817
except RuntimeJobError as exc:
776818
raise _job_http_error(exc) from exc
777819

820+
@router.get("/host-services")
821+
async def get_host_services(request: Request) -> dict:
822+
_require_operator_admin(request)
823+
return await run_in_threadpool(host_services_manager_factory().observe)
824+
825+
@router.post("/host-services/{service_id}")
826+
async def control_host_service(
827+
request: Request,
828+
service_id: str,
829+
body: HostServiceActionRequest,
830+
) -> dict:
831+
_require_operator_admin(request)
832+
try:
833+
return await run_in_threadpool(
834+
host_services_manager_factory().act,
835+
service_id,
836+
body.action,
837+
)
838+
except HostServiceError as exc:
839+
raise HTTPException(400, str(exc)) from exc
840+
841+
@router.get("/host-services/{service_id}/log")
842+
async def get_host_service_log(
843+
request: Request,
844+
service_id: str,
845+
max_chars: int = 40000,
846+
) -> dict:
847+
_require_operator_admin(request)
848+
try:
849+
return await run_in_threadpool(
850+
host_services_manager_factory().read_log,
851+
service_id,
852+
max_chars=max_chars,
853+
)
854+
except HostServiceError as exc:
855+
raise HTTPException(404, str(exc)) from exc
856+
857+
@router.get("/host-shell/sessions")
858+
async def get_host_shells(request: Request) -> dict:
859+
_require_operator_admin(request)
860+
return await run_in_threadpool(host_services_manager_factory().list_shells)
861+
862+
@router.post("/host-shell/sessions")
863+
async def create_host_shell(
864+
request: Request,
865+
body: HostShellCreateRequest,
866+
) -> dict:
867+
_require_operator_admin(request)
868+
try:
869+
return await run_in_threadpool(
870+
host_services_manager_factory().create_shell,
871+
title=body.title,
872+
cwd=body.cwd,
873+
cols=body.cols,
874+
rows=body.rows,
875+
)
876+
except HostServiceError as exc:
877+
raise HTTPException(400, str(exc)) from exc
878+
879+
@router.delete("/host-shell/sessions/{shell_id}")
880+
async def delete_host_shell(request: Request, shell_id: str) -> dict:
881+
_require_operator_admin(request)
882+
try:
883+
return await run_in_threadpool(
884+
host_services_manager_factory().delete_shell,
885+
shell_id,
886+
)
887+
except HostServiceError as exc:
888+
raise HTTPException(400, str(exc)) from exc
889+
890+
async def _authorize_host_shell(websocket: WebSocket) -> bool:
891+
# Cookies alone must not authorize a cross-site WebSocket connection.
892+
origin = websocket.headers.get("origin", "")
893+
if origin:
894+
origin_host = urlsplit(origin).netloc.lower()
895+
request_host = websocket.headers.get("host", "").lower()
896+
forwarded_host = websocket.headers.get("x-forwarded-host", "").split(",")[0].strip().lower()
897+
allowed_hosts = {value for value in (request_host, forwarded_host) if value}
898+
if not origin_host or origin_host not in allowed_hosts:
899+
await websocket.close(code=4403, reason="Origin rejected")
900+
return False
901+
if auth_disabled():
902+
return True
903+
app = websocket.scope.get("app")
904+
manager = getattr(getattr(app, "state", None), "auth_manager", None)
905+
token = websocket.cookies.get(SESSION_COOKIE)
906+
if manager is not None and manager.validate_token(token):
907+
username = manager.get_username_for_token(token)
908+
if username and manager.is_admin(username):
909+
return True
910+
await websocket.close(code=4403, reason="Admin only")
911+
return False
912+
913+
@router.websocket("/host-shell/sessions/{shell_id}/ws")
914+
async def attach_host_shell(websocket: WebSocket, shell_id: str) -> None:
915+
if not await _authorize_host_shell(websocket):
916+
return
917+
try:
918+
cols = max(20, min(int(websocket.query_params.get("cols", "100")), 400))
919+
rows = max(8, min(int(websocket.query_params.get("rows", "30")), 200))
920+
attachment = await run_in_threadpool(
921+
host_services_manager_factory().attach_shell,
922+
shell_id,
923+
cols=cols,
924+
rows=rows,
925+
)
926+
except (HostServiceError, TypeError, ValueError):
927+
await websocket.close(code=4404, reason="Operator shell unavailable")
928+
return
929+
930+
await websocket.accept()
931+
loop = asyncio.get_running_loop()
932+
output: asyncio.Queue[bytes | None] = asyncio.Queue()
933+
934+
def terminal_ready() -> None:
935+
try:
936+
chunk = attachment.read()
937+
except BlockingIOError:
938+
return
939+
except OSError:
940+
chunk = b""
941+
output.put_nowait(chunk or None)
942+
943+
async def send_terminal() -> None:
944+
while True:
945+
chunk = await output.get()
946+
if chunk is None:
947+
return
948+
await websocket.send_bytes(chunk)
949+
950+
async def receive_terminal() -> None:
951+
while True:
952+
message = await websocket.receive()
953+
if message["type"] == "websocket.disconnect":
954+
return
955+
raw = message.get("text")
956+
if not raw or len(raw) > 131072:
957+
continue
958+
try:
959+
event = json.loads(raw)
960+
except (TypeError, json.JSONDecodeError):
961+
continue
962+
if event.get("type") == "input" and isinstance(event.get("data"), str):
963+
attachment.write(event["data"].encode("utf-8")[:65536])
964+
elif event.get("type") == "resize":
965+
try:
966+
attachment.resize(int(event.get("cols", 100)), int(event.get("rows", 30)))
967+
except (TypeError, ValueError):
968+
continue
969+
970+
loop.add_reader(attachment.fileno(), terminal_ready)
971+
tasks = {
972+
asyncio.create_task(send_terminal()),
973+
asyncio.create_task(receive_terminal()),
974+
}
975+
try:
976+
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
977+
for task in pending:
978+
task.cancel()
979+
for task in done | pending:
980+
with suppress(asyncio.CancelledError, WebSocketDisconnect, RuntimeError):
981+
await task
982+
finally:
983+
loop.remove_reader(attachment.fileno())
984+
attachment.close()
985+
with suppress(RuntimeError):
986+
await websocket.close()
987+
778988
return router

‎specs/runtime.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ This spec covers current app runtime wiring in:
1414
- `src/constants.py`;
1515
- `src/interactive_gate.py`;
1616
- `src/host_docker_access.py`;
17+
- `src/diogenes_host_services.py`;
1718
- `core/middleware.py`;
1819
- all route setup functions registered from `app.py`, including canonical
1920
`routes/admin_wipe/`, `routes/cleanup/`, `routes/compare/`, `routes/contacts/`, `routes/document/`, `routes/gallery/`, `routes/history/`, `routes/mcp/`, `routes/memory/`, `routes/note/`, `routes/research/`, `routes/search/`, `routes/task/`, `routes/vault/`, and `routes/webhook/` packages plus top-level compatibility shims;
@@ -30,6 +31,13 @@ This spec covers current app runtime wiring in:
3031

3132
`app.py` separately owns runtime singletons and integration hooks for auth, vector RAG, TTS/STT, webhooks, scheduled tasks, MCP, assistant log globals, event bus wiring, AI interaction globals, API-token cache invalidation, and foreground activity tracking. `src.runtime_paths` owns source-versus-frozen app/data path resolution; `src.constants` derives `DATA_DIR` from `ODYSSEUS_DATA_DIR` or that runtime default. `core/constants.py` and `src/constants.py` are both live import paths and are not fully identical today, so new constants need explicit placement/compatibility decisions.
3233

34+
`src.diogenes_host_services` owns the admin-only **Venvs** operator plane. Its
35+
fixed mm-tools catalog starts each selected project through its own launcher and
36+
virtual environment. Services and interactive host-shell tabs live on the named
37+
`diogenes-operator` tmux socket, with wrappers and logs under
38+
`DATA_DIR/diogenes-operator`; no command in this plane lists, attaches to, or
39+
kills a session on Diogenes' default tmux server.
40+
3341
The shared upload handler is also installed on the session manager and tool
3442
helper, and `app.py` injects it into attachment-bearing route factories so
3543
durable writers and cleanup use one lifecycle owner.
@@ -56,6 +64,15 @@ Effective middleware order matters. CORS, `SecurityHeadersMiddleware`, `_Request
5664

5765
Security headers include HSTS and a restrictive `Permissions-Policy` that disables camera/geolocation and only allows microphone from self.
5866

67+
The operator-service HTTP routes require a human cookie-authenticated admin and
68+
explicitly reject the internal-agent and bearer-token bypass identities.
69+
Interactive
70+
terminal WebSockets independently validate the session cookie and admin role,
71+
and reject browser `Origin` hosts that do not match the request host. The named
72+
tmux socket is a control-plane boundary rather than an OS-user sandbox: another
73+
process deliberately running as the same Unix account could address that socket
74+
by name, while it remains absent from Diogenes agent/runtime controls.
75+
5976
`_TIMEOUT_EXEMPT_PREFIXES` owns hard-timeout bypass policy. It is prefix-based and currently exempts all subroutes under `/api/chat`, `/api/shell/stream`, `/api/research`, `/api/model/download`, `/api/model/probe`, `/api/model-endpoints`, `/api/cookbook/setup`, `/api/upload`, `/api/image`, and `/api/memory/audit`. Memory audit has its own longer inactivity timeout.
6077

6178
Generated-image path resolution fails closed for invalid names, path escape, and missing files. Ownership checks are best-effort when a current user exists: gallery rows owned by a different user return 404, rowless generated files are allowed, and DB/helper failures fail open. See `auth-security.md` for `LOCALHOST_BYPASS`, internal-tool loopback, proxy-header exclusion, and owner-impersonation policy.
@@ -64,6 +81,9 @@ Generated-image path resolution fails closed for invalid names, path escape, and
6481

6582
- Request hard timeout applies to non-exempt paths that reach `_RequestTimeoutMiddleware`.
6683
- `src.interactive_gate` tracks foreground requests, browser heartbeats, and active chat streams. Background task/email work can wait for a quiet window so scheduled jobs do not compete with visible browser or model activity. Status polling and `/api/email/unread-state` are passive reads: they do not cancel running scheduled work or manufacture foreground pressure.
84+
- Operator shell browser attachments are disposable PTYs connected to persistent
85+
tmux sessions. Closing a browser or Services window ends only that attachment;
86+
closing the shell tab explicitly ends the corresponding tmux session.
6787
- YouTube support is initialized through `services.youtube.init_youtube()`.
6888
- Vector document RAG is initialized lazily through `src.rag_singleton.get_rag_manager()` and may be unavailable at startup.
6989
- `routes.workspace_routes` lets the browser choose a server directory for agent turns; execution confinement is enforced below the route layer by tool execution.

0 commit comments

Comments
 (0)