diff --git a/app.py b/app.py index 3ac883a..54a5312 100644 --- a/app.py +++ b/app.py @@ -690,16 +690,7 @@ app.include_router(setup_note_routes(task_scheduler)) # Email from routes.email_routes import setup_email_routes -email_router = setup_email_routes() -app.include_router(email_router) - -# Codex integration — HTTP surface for the Codex plugin/MCP bridge. Reuses -# api_token scopes (todos:read|write, email:read|draft|send) so external -# Codex sessions can only touch the data the user explicitly allowed. Mounted -# AFTER email so the codex_routes can borrow the email router for shared -# search/threading helpers. -from routes.codex_routes import setup_codex_routes -app.include_router(setup_codex_routes(email_router=email_router)) +app.include_router(setup_email_routes()) from routes.vault_routes import setup_vault_routes app.include_router(setup_vault_routes()) diff --git a/integrations/codex/.codex-plugin/plugin.json b/integrations/codex/.codex-plugin/plugin.json deleted file mode 100644 index 239451f..0000000 --- a/integrations/codex/.codex-plugin/plugin.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "odysseus", - "version": "0.1.1", - "description": "Connect Codex to a scoped Odysseus instance.", - "author": { - "name": "Odysseus" - }, - "skills": "./skills/", - "interface": { - "displayName": "Odysseus", - "shortDescription": "Use scoped Odysseus tools from Codex.", - "longDescription": "Connects Codex terminal sessions to Odysseus through user-controlled scoped API tokens. Codex must use /api/codex/* endpoints so Odysseus Settings can enforce tool access.", - "developerName": "Odysseus", - "category": "Productivity", - "capabilities": [ - "todos", - "email", - "scoped-api" - ], - "defaultPrompt": "Use Odysseus only through configured scoped access. Check capabilities before reading or writing data." - } -} diff --git a/integrations/codex/README.md b/integrations/codex/README.md deleted file mode 100644 index fff4e84..0000000 --- a/integrations/codex/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# Odysseus Codex Integration - -This directory contains the Codex plugin/skill bundle for Odysseus. - -## User Flow - -1. Open Odysseus Settings > Integrations. -2. Add a Codex Agent. -3. Copy the full setup commands shown after the generated token. -4. Toggle the tools Codex is allowed to use. -5. Configure the terminal Codex session: - -```bash -export ODYSSEUS_URL=http://your-odysseus-host:7000 -export ODYSSEUS_API_TOKEN=ody_generated_token -mkdir -p ~/plugins -curl -fsSL -H "Authorization: Bearer $ODYSSEUS_API_TOKEN" "$ODYSSEUS_URL/api/codex/plugin.zip" -o /tmp/odysseus-codex-plugin.zip -python3 -m zipfile -e /tmp/odysseus-codex-plugin.zip ~/plugins -python3 - <<'PY' -import json -from pathlib import Path - -p = Path.home() / ".agents" / "plugins" / "marketplace.json" -p.parent.mkdir(parents=True, exist_ok=True) -if p.exists(): - data = json.loads(p.read_text()) -else: - data = {"name": "personal", "interface": {"displayName": "Personal"}, "plugins": []} - -data.setdefault("name", "personal") -data.setdefault("interface", {}).setdefault("displayName", "Personal") -plugins = data.setdefault("plugins", []) -entry = { - "name": "odysseus", - "source": {"source": "local", "path": "./plugins/odysseus"}, - "policy": {"installation": "AVAILABLE", "authentication": "ON_INSTALL"}, - "category": "Productivity", -} -data["plugins"] = [item for item in plugins if item.get("name") != "odysseus"] + [entry] -p.write_text(json.dumps(data, indent=2) + "\n") -PY -codex plugin add odysseus@personal -``` - -6. Verify: - -```bash -python3 ~/plugins/odysseus/scripts/odysseus_api.py capabilities -``` - -Codex must use `/api/codex/*` endpoints. SSH, Docker, direct Python imports, database queries, and MCP internals bypass Odysseus Settings and must not be used for user data access. diff --git a/integrations/codex/scripts/odysseus_api.py b/integrations/codex/scripts/odysseus_api.py deleted file mode 100755 index 5fdd632..0000000 --- a/integrations/codex/scripts/odysseus_api.py +++ /dev/null @@ -1,122 +0,0 @@ -#!/usr/bin/env python3 -"""Small Odysseus scoped API helper for Codex terminal sessions.""" - -from __future__ import annotations - -import json -import os -import sys -import urllib.error -import urllib.request - - -def _usage() -> int: - print("usage:", file=sys.stderr) - print(" odysseus_api.py capabilities", file=sys.stderr) - print(" odysseus_api.py todos list", file=sys.stderr) - print(" odysseus_api.py todos add TITLE", file=sys.stderr) - print(" odysseus_api.py emails list [limit]", file=sys.stderr) - print(" odysseus_api.py emails read UID", file=sys.stderr) - print(" odysseus_api.py METHOD /api/codex/path [json-body]", file=sys.stderr) - return 2 - - -def _config() -> tuple[str, str] | None: - base_url = os.environ.get("ODYSSEUS_URL", "").strip().rstrip("/") - token = os.environ.get("ODYSSEUS_API_TOKEN", "").strip() - missing = [] - if not base_url: - missing.append("ODYSSEUS_URL") - if not token: - missing.append("ODYSSEUS_API_TOKEN") - if missing: - print(f"missing {', '.join(missing)}; create a Codex Agent token in Odysseus Settings", file=sys.stderr) - return None - return base_url, token - - -def main() -> int: - if len(sys.argv) < 2: - return _usage() - - command = sys.argv[1].lower() - if command == "capabilities": - method = "GET" - path = "/api/codex/capabilities" - body = None - elif command == "todos": - if len(sys.argv) < 3: - return _usage() - action = sys.argv[2].lower() - path = "/api/codex/todos" - if action == "list": - method = "GET" - body = None - elif action == "add" and len(sys.argv) >= 4: - method = "POST" - body = json.dumps({"action": "add", "title": " ".join(sys.argv[3:])}) - else: - return _usage() - elif command == "emails": - if len(sys.argv) < 3: - return _usage() - action = sys.argv[2].lower() - if action == "list": - method = "GET" - limit = sys.argv[3] if len(sys.argv) >= 4 else "10" - path = f"/api/codex/emails?folder=INBOX&limit={limit}&offset=0&filter=all" - body = None - elif action == "read" and len(sys.argv) >= 4: - method = "GET" - path = f"/api/codex/emails/{sys.argv[3]}" - body = None - else: - return _usage() - else: - if len(sys.argv) < 3: - return _usage() - method = sys.argv[1].upper() - path = sys.argv[2] - body = sys.argv[3] if len(sys.argv) > 3 else None - - if not path.startswith("/"): - path = "/" + path - if not path.startswith("/api/codex/"): - print("refusing non-/api/codex path; use scoped Odysseus integration endpoints only", file=sys.stderr) - return 2 - - config = _config() - if config is None: - return 2 - base_url, token = config - - data = None - headers = { - "Accept": "application/json", - "Authorization": f"Bearer {token}", - } - if body is not None: - try: - parsed = json.loads(body) - except json.JSONDecodeError as exc: - print(f"invalid json body: {exc}", file=sys.stderr) - return 2 - data = json.dumps(parsed).encode("utf-8") - headers["Content-Type"] = "application/json" - - req = urllib.request.Request(base_url + path, data=data, headers=headers, method=method) - try: - with urllib.request.urlopen(req, timeout=20) as resp: - print(resp.read().decode("utf-8")) - return 0 - except urllib.error.HTTPError as exc: - text = exc.read().decode("utf-8", errors="replace") - print(text or f"HTTP {exc.code}", file=sys.stderr) - return 1 - except OSError as exc: - print(f"request failed: {exc}", file=sys.stderr) - return 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/integrations/codex/skills/odysseus/SKILL.md b/integrations/codex/skills/odysseus/SKILL.md deleted file mode 100644 index cf87248..0000000 --- a/integrations/codex/skills/odysseus/SKILL.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -name: odysseus -description: Use when the user asks Codex to read or write Odysseus data from a terminal Codex session through the scoped Codex Agent API. Requires ODYSSEUS_URL and ODYSSEUS_API_TOKEN. ---- - -# Odysseus - -Use this skill when a user asks to interact with Odysseus from Codex. - -## Configuration - -Expect these environment variables: - -- `ODYSSEUS_URL`: Base URL for the user's Odysseus instance, for example `http://127.0.0.1:7000`. -- `ODYSSEUS_API_TOKEN`: Scoped API token created in Odysseus Settings > Integrations > Add Integration > Codex Agent. - -If either value is missing, do not guess credentials. Tell the user to create a Codex Agent token in Odysseus Settings and expose both values to the terminal session. - -## Safety - -- All Odysseus data access MUST go through the scoped HTTP API under `/api/codex/*`. -- Check `/api/codex/capabilities` before using a tool surface. -- Treat `403` as an intentional Settings restriction. Do not work around it. -- Do not use SSH, Docker, direct Python imports, SQLite queries, MCP internals, browser cookies, or local files to read/write Odysseus user data. -- Do not call helpers like `do_manage_notes`, email MCP internals, or database sessions directly for user data, even if shell access exists. -- Never send email directly unless the user explicitly asks to send and the token has a send-capable scope. -- Keep actions scoped to the token owner. - -## Todos - -The Codex API supports todos/checklists: - -- `GET /api/codex/todos` -- `POST /api/codex/todos` - -Use the bundled helper script when available: - -```bash -python3 integrations/codex/scripts/odysseus_api.py capabilities -python3 integrations/codex/scripts/odysseus_api.py todos list -python3 integrations/codex/scripts/odysseus_api.py todos add "Follow up" -``` - -Supported todo actions are `list`, `add`, `update`, `delete`, and `toggle_item`. - -## Email - -The Codex API supports scoped email reads: - -- `GET /api/codex/emails?folder=INBOX&limit=10&offset=0&filter=all` -- `GET /api/codex/emails/{uid}?folder=INBOX` - -Use the bundled helper script when available: - -```bash -python3 integrations/codex/scripts/odysseus_api.py emails list 5 -python3 integrations/codex/scripts/odysseus_api.py emails read UID -``` - -If `/api/codex/capabilities` does not show `email.read: true`, do not inspect email. Ask the user to enable Email read in the Codex Agent settings. - -## Forbidden Bypass Pattern - -If you are about to reach the Odysseus host/container, import app internals, query the database, or call MCP helper modules directly, stop. Those paths bypass Odysseus Settings and token scopes. Ask the user to enable the relevant Codex Agent tool toggle instead. diff --git a/routes/api_token_routes.py b/routes/api_token_routes.py index 68d1503..ba412a4 100644 --- a/routes/api_token_routes.py +++ b/routes/api_token_routes.py @@ -12,61 +12,6 @@ from src.auth_helpers import get_current_user MAX_NAME_LEN = 100 DEFAULT_SCOPES = "chat" -ALLOWED_SCOPES = { - "chat", - "todos:read", - "todos:write", - "documents:read", - "documents:write", - "email:read", - "email:draft", - "email:send", - "calendar:read", - "calendar:write", - "memory:read", - "memory:write", -} -TOKEN_PROFILES = { - "chat": ["chat"], - "codex_todos": ["todos:read", "todos:write"], - "codex_email_drafts": ["email:read", "email:draft", "documents:read", "documents:write"], -} - - -def _normalize_scopes(scopes: str | list[str] | None = None, profile: str | None = None) -> list[str]: - profile = profile if isinstance(profile, str) else None - profile_key = (profile or "").strip() - if profile_key: - if profile_key not in TOKEN_PROFILES: - raise HTTPException(400, "Unknown token profile") - requested = list(TOKEN_PROFILES[profile_key]) - elif isinstance(scopes, list): - requested = [str(s).strip() for s in scopes if str(s).strip()] - elif isinstance(scopes, str) and scopes: - requested = [s.strip() for s in scopes.replace(" ", ",").split(",") if s.strip()] - else: - requested = [DEFAULT_SCOPES] - - normalized = [] - for scope in requested: - if scope not in ALLOWED_SCOPES: - raise HTTPException(400, f"Unknown token scope: {scope}") - if scope not in normalized: - normalized.append(scope) - - def ensure_before(write_scope: str, read_scope: str): - if write_scope not in normalized or read_scope in normalized: - return - idx = normalized.index(write_scope) - normalized.insert(idx, read_scope) - - ensure_before("todos:write", "todos:read") - ensure_before("documents:write", "documents:read") - ensure_before("calendar:write", "calendar:read") - ensure_before("memory:write", "memory:read") - ensure_before("email:draft", "email:read") - - return normalized or [DEFAULT_SCOPES] def setup_api_token_routes() -> APIRouter: @@ -100,28 +45,13 @@ def setup_api_token_routes() -> APIRouter: except Exception: pass - @router.get("/tokens/profiles") - def token_profiles(request: Request): - require_admin(request) - return { - "profiles": TOKEN_PROFILES, - "allowed_scopes": sorted(ALLOWED_SCOPES), - } - @router.post("/tokens") - def create_token( - request: Request, - name: str = Form(""), - scopes: str = Form(None), - profile: str = Form(None), - ): + def create_token(request: Request, name: str = Form("")): require_admin(request) name = name.strip()[:MAX_NAME_LEN] if not name: raise HTTPException(400, "Token name is required") owner = get_current_user(request) - scope_list = _normalize_scopes(scopes, profile) - scopes_value = ",".join(scope_list) raw_token = "ody_" + secrets.token_urlsafe(32) token_hash = bcrypt.hashpw(raw_token.encode(), bcrypt.gensalt()).decode() @@ -134,7 +64,7 @@ def setup_api_token_routes() -> APIRouter: name=name, token_hash=token_hash, token_prefix=raw_token[:8], - scopes=scopes_value, + scopes=DEFAULT_SCOPES, is_active=True, )) _invalidate_cache(request) @@ -145,36 +75,9 @@ def setup_api_token_routes() -> APIRouter: "owner": owner, "token": raw_token, "token_prefix": raw_token[:8], - "scopes": scope_list, + "scopes": DEFAULT_SCOPES.split(","), } - @router.patch("/tokens/{token_id}") - async def update_token(request: Request, token_id: str): - require_admin(request) - try: - payload = await request.json() - except Exception: - payload = {} - scope_list = _normalize_scopes(payload.get("scopes")) - scopes_value = ",".join(scope_list) - with get_db_session() as db: - token = db.query(ApiToken).filter(ApiToken.id == token_id).first() - if not token: - raise HTTPException(404, "Token not found") - if isinstance(payload.get("name"), str) and payload["name"].strip(): - token.name = payload["name"].strip()[:MAX_NAME_LEN] - token.scopes = scopes_value - db.add(token) - response = { - "id": token_id, - "name": getattr(token, "name", ""), - "owner": getattr(token, "owner", None), - "token_prefix": getattr(token, "token_prefix", ""), - "scopes": scope_list, - } - _invalidate_cache(request) - return response - @router.delete("/tokens/{token_id}") def delete_token(request: Request, token_id: str): require_admin(request) diff --git a/routes/codex_routes.py b/routes/codex_routes.py deleted file mode 100644 index 35e6570..0000000 --- a/routes/codex_routes.py +++ /dev/null @@ -1,169 +0,0 @@ -"""Codex integration routes. - -These are small HTTP surfaces intended for the Codex plugin/MCP bridge. They -reuse existing Odysseus helpers and enforce API-token scopes before touching -user data. -""" - -import json -import zipfile -from io import BytesIO -from pathlib import Path -from typing import Any - -from fastapi import APIRouter, Body, HTTPException, Request -from fastapi.responses import StreamingResponse - -from src.auth_helpers import require_user -from src.tool_implementations import do_manage_notes - - -TODO_READ_SCOPES = {"todos:read", "todos:write"} -TODO_WRITE_SCOPES = {"todos:write"} -EMAIL_READ_SCOPES = {"email:read", "email:draft", "email:send"} -WRITE_ACTIONS = {"add", "create", "new", "save", "remind", "update", "delete", "toggle_item", "remove", "remove_item"} - - -def _scope_owner(request: Request, allowed: set[str]) -> str: - """Return the data owner if the caller is allowed for this Codex action.""" - if getattr(request.state, "api_token", False): - scopes = set(getattr(request.state, "api_token_scopes", []) or []) - if not scopes.intersection(allowed): - required = " or ".join(sorted(allowed)) - raise HTTPException(403, f"API token missing required scope: {required}") - owner = getattr(request.state, "api_token_owner", None) - if not owner: - raise HTTPException(403, "API token has no owner") - return owner - return require_user(request) - - -def _find_endpoint(router: APIRouter | None, method: str, path: str): - if router is None: - return None - for route in getattr(router, "routes", []): - if getattr(route, "path", "") == path and method in getattr(route, "methods", set()): - return route.endpoint - return None - - -def setup_codex_routes(email_router: APIRouter | None = None) -> APIRouter: - router = APIRouter(prefix="/api/codex", tags=["codex"]) - email_list_endpoint = _find_endpoint(email_router, "GET", "/api/email/list") - email_read_endpoint = _find_endpoint(email_router, "GET", "/api/email/read/{uid}") - - @router.get("/capabilities") - def capabilities(request: Request): - token_scopes = set(getattr(request.state, "api_token_scopes", []) or []) - has_token = bool(getattr(request.state, "api_token", False)) - return { - "integration": "codex", - "token_scopes": sorted(token_scopes), - "tools": { - "todos": { - "read": bool(token_scopes.intersection(TODO_READ_SCOPES)) if has_token else True, - "write": bool(token_scopes.intersection(TODO_WRITE_SCOPES)) if has_token else True, - "actions": ["list", "add", "update", "delete", "toggle_item"], - }, - "email": { - "read": bool(token_scopes.intersection(EMAIL_READ_SCOPES)) if has_token else True, - "draft": "email:draft" in token_scopes if has_token else True, - "send": "email:send" in token_scopes if has_token else True, - "actions": ["list", "read"], - } - }, - "safety": { - "email_send_requires_confirmation": True, - "destructive_actions_should_confirm": True, - }, - } - - @router.get("/plugin.zip") - def plugin_zip(request: Request): - require_user(request) - root = Path(__file__).resolve().parent.parent / "integrations" / "codex" - if not root.exists(): - raise HTTPException(404, "Codex plugin bundle not found") - buf = BytesIO() - with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf: - for path in sorted(root.rglob("*")): - if path.is_dir() or "__pycache__" in path.parts or path.suffix == ".pyc": - continue - zf.write(path, Path("odysseus") / path.relative_to(root)) - buf.seek(0) - headers = {"Content-Disposition": 'attachment; filename="odysseus-codex-plugin.zip"'} - return StreamingResponse(buf, media_type="application/zip", headers=headers) - - @router.get("/todos") - async def list_todos(request: Request, archived: bool = False, label: str | None = None): - owner = _scope_owner(request, TODO_READ_SCOPES) - args: dict[str, Any] = {"action": "list", "archived": archived} - if label: - args["label"] = label - return await do_manage_notes(json.dumps(args), owner=owner) - - @router.post("/todos") - async def manage_todos(request: Request, body: dict[str, Any] = Body(default_factory=dict)): - action = str(body.get("action") or "add").replace("-", "_").strip().lower() - allowed = TODO_WRITE_SCOPES if action in WRITE_ACTIONS else TODO_READ_SCOPES - owner = _scope_owner(request, allowed) - args = dict(body) - args["action"] = action - return await do_manage_notes(json.dumps(args), owner=owner) - - @router.get("/emails") - async def list_emails( - request: Request, - folder: str = "INBOX", - limit: int = 10, - offset: int = 0, - filter: str = "all", - from_addr: str | None = None, - account_id: str | None = None, - has_attachments: int = 0, - ): - owner = _scope_owner(request, EMAIL_READ_SCOPES) - if email_list_endpoint is None: - raise HTTPException(503, "Email integration is not available") - limit = max(1, min(int(limit or 10), 50)) - offset = max(0, int(offset or 0)) - if account_id: - from routes.email_helpers import _assert_owns_account - - _assert_owns_account(account_id, owner) - return await email_list_endpoint( - folder=folder, - limit=limit, - offset=offset, - filter=filter, - from_addr=from_addr, - account_id=account_id, - has_attachments=has_attachments, - cache_bust=None, - owner=owner, - ) - - @router.get("/emails/{uid}") - async def read_email( - request: Request, - uid: str, - folder: str = "INBOX", - account_id: str | None = None, - mark_seen: bool = False, - ): - owner = _scope_owner(request, EMAIL_READ_SCOPES) - if email_read_endpoint is None: - raise HTTPException(503, "Email integration is not available") - if account_id: - from routes.email_helpers import _assert_owns_account - - _assert_owns_account(account_id, owner) - return await email_read_endpoint( - uid=uid, - folder=folder, - account_id=account_id, - mark_seen=mark_seen, - owner=owner, - ) - - return router diff --git a/static/js/settings.js b/static/js/settings.js index 49fea63..36d6c69 100644 --- a/static/js/settings.js +++ b/static/js/settings.js @@ -3093,7 +3093,6 @@ const INTG_TYPES = { carddav: { label: 'CardDAV', icon: '' }, email: { label: 'Email', icon: '' }, mcp: { label: 'MCP', icon: '' }, - codex: { label: 'Codex', icon: '' }, vault: { label: 'Vault', icon: '' }, }; @@ -3114,7 +3113,7 @@ async function initUnifiedIntegrations() { } async function fetchAll() { - const [apiRes, calRes, cardRes, contactsRes, emailAccountsRes, mcpRes, vaultRes, tokenRes] = await Promise.all([ + const [apiRes, calRes, cardRes, contactsRes, emailAccountsRes, mcpRes, vaultRes] = await Promise.all([ fetch('/api/auth/integrations', { credentials: 'same-origin' }).then(r => r.ok ? r.json() : { integrations: [] }).catch(() => ({ integrations: [] })), fetch('/api/calendar/config', { credentials: 'same-origin' }).then(r => r.ok ? r.json() : {}).catch(() => ({})), fetch('/api/contacts/config', { credentials: 'same-origin' }).then(r => r.ok ? r.json() : {}).catch(() => ({})), @@ -3122,7 +3121,6 @@ async function initUnifiedIntegrations() { fetch('/api/email/accounts', { credentials: 'same-origin' }).then(r => r.ok ? r.json() : { accounts: [] }).catch(() => ({ accounts: [] })), fetch('/api/mcp/servers', { credentials: 'same-origin' }).then(r => r.ok ? r.json() : []).catch(() => []), fetch('/api/vault/config', { credentials: 'same-origin' }).then(r => r.ok ? r.json() : {}).catch(() => ({})), - fetch('/api/tokens', { credentials: 'same-origin' }).then(r => r.ok ? r.json() : []).catch(() => []), ]); const items = []; // API integrations @@ -3167,13 +3165,6 @@ async function initUnifiedIntegrations() { const statusText = srv.needs_oauth ? 'needs auth' : srv.status === 'connected' ? `${srv.enabled_tool_count}/${srv.tool_count} tools` : srv.status === 'error' ? 'error' : 'disconnected'; items.push({ type: 'mcp', id: srv.id || srv.name, name: srv.name || 'MCP Server', detail: statusText, enabled: srv.is_enabled !== false, data: srv }); } - for (const tok of (Array.isArray(tokenRes) ? tokenRes : [])) { - const scopes = tok.scopes || []; - const isCodex = (tok.name || '').toLowerCase().includes('codex') || scopes.some(s => String(s || '').startsWith('todos:') || String(s || '').startsWith('email:') || String(s || '').startsWith('documents:')); - if (!isCodex) continue; - const detail = `${tok.token_prefix || 'token'}... - ${scopes.join(', ') || 'chat'}`; - items.push({ type: 'codex', id: tok.id, name: tok.name || 'Codex Agent', detail, enabled: true, data: tok }); - } // Vaultwarden removed as an integration option. return items; } @@ -3245,7 +3236,6 @@ async function initUnifiedIntegrations() { } else if (type === 'email') await fetch(`/api/email/accounts/${id}`, { method: 'DELETE', credentials: 'same-origin' }); else if (type === 'mcp') await fetch(`/api/mcp/servers/${id}`, { method: 'DELETE', credentials: 'same-origin' }); - else if (type === 'codex') await fetch(`/api/tokens/${id}`, { method: 'DELETE', credentials: 'same-origin' }); else if (type === 'vault') await fetch('/api/vault/logout', { method: 'POST', credentials: 'same-origin' }); } catch (_) {} formEl.style.display = 'none'; @@ -3262,7 +3252,6 @@ async function initUnifiedIntegrations() { else if (type === 'contacts' || type === 'carddav') showCardDavForm(); else if (type === 'email') showEmailForm(editId); else if (type === 'mcp') showMcpForm(editId); - else if (type === 'codex') showCodexForm(editId); else if (type === 'vault') showVaultForm(); } @@ -4313,245 +4302,6 @@ async function initUnifiedIntegrations() { } } - async function showCodexForm(editId) { - let tokens = []; - try { - const tokRes = await fetch('/api/tokens', { credentials: 'same-origin' }); - if (tokRes.ok) tokens = await tokRes.json(); - } catch (_) {} - - const toolScopes = [ - { key: 'todos:read', label: 'Todos', detail: 'Read notes and checklists' }, - { key: 'todos:write', label: 'Todos write', detail: 'Create, update, delete, and toggle todo items' }, - { key: 'documents:read', label: 'Documents', detail: 'Read documents when a Codex document API is enabled' }, - { key: 'documents:write', label: 'Documents write', detail: 'Create and update draft documents' }, - { key: 'email:read', label: 'Email', detail: 'Read email when a Codex email API is enabled' }, - { key: 'email:draft', label: 'Email drafts', detail: 'Create email reply drafts without sending' }, - { key: 'email:send', label: 'Email send', detail: 'Send email directly' }, - { key: 'calendar:read', label: 'Calendar', detail: 'Read calendar events when enabled' }, - { key: 'calendar:write', label: 'Calendar write', detail: 'Create and update calendar events' }, - { key: 'memory:read', label: 'Memory', detail: 'Read memory when enabled' }, - { key: 'memory:write', label: 'Memory write', detail: 'Write memory when enabled' }, - ]; - const codexTokens = (Array.isArray(tokens) ? tokens : []).filter(tok => { - const scopes = tok.scopes || []; - return (tok.name || '').toLowerCase().includes('codex') || scopes.some(s => String(s || '').startsWith('todos:') || String(s || '').startsWith('email:') || String(s || '').startsWith('documents:')); - }); - const current = codexTokens.find(t => String(t.id) === String(editId)); - const scopeToggles = (t) => { - const scopes = new Set(t.scopes || []); - return toolScopes.map(scope => ` - `).join(''); - }; - const tokenRows = codexTokens.length ? codexTokens.map(t => ` -
-
-
-
${esc(t.name || 'Codex Agent')}
-
${esc(t.token_prefix || 'token')}...${t.last_used_at ? ` · Last used ${new Date(t.last_used_at).toLocaleDateString()}` : ' · Never used'}
-
- -
-
Tool access
- ${scopeToggles(t)} -
-
`).join('') : '
No Codex tokens yet.
'; - const origin = window.location.origin || ''; - const setupForToken = (token) => `export ODYSSEUS_URL=${origin} -export ODYSSEUS_API_TOKEN='${token}' -mkdir -p ~/plugins -curl -fsSL -H "Authorization: Bearer $ODYSSEUS_API_TOKEN" "$ODYSSEUS_URL/api/codex/plugin.zip" -o /tmp/odysseus-codex-plugin.zip -python3 -m zipfile -e /tmp/odysseus-codex-plugin.zip ~/plugins -python3 - <<'PY' -import json -from pathlib import Path - -p = Path.home() / ".agents" / "plugins" / "marketplace.json" -p.parent.mkdir(parents=True, exist_ok=True) -if p.exists(): - data = json.loads(p.read_text()) -else: - data = {"name": "personal", "interface": {"displayName": "Personal"}, "plugins": []} - -data.setdefault("name", "personal") -data.setdefault("interface", {}).setdefault("displayName", "Personal") -plugins = data.setdefault("plugins", []) -entry = { - "name": "odysseus", - "source": {"source": "local", "path": "./plugins/odysseus"}, - "policy": {"installation": "AVAILABLE", "authentication": "ON_INSTALL"}, - "category": "Productivity", -} -data["plugins"] = [item for item in plugins if item.get("name") != "odysseus"] + [entry] -p.write_text(json.dumps(data, indent=2) + "\\n") -PY -codex plugin add odysseus@personal -python3 ~/plugins/odysseus/scripts/odysseus_api.py capabilities`; - const setupPlaceholder = `Add an agent to generate a one-time token and copy the full setup commands.`; - - formEl.innerHTML = ` -
-

${current ? 'Codex Agent' : 'Add Codex Agent'}

-
-
Create a Codex agent token, then toggle exactly which Odysseus tools it can use.
-
-
Codex setup
-
Odysseus ships a Codex plugin in integrations/codex. Download plugin bundle, then set this instance URL and the token shown after adding an agent in the terminal where Codex runs.
-
${esc(setupPlaceholder)}
- -
-
-
- - - -
- -
Agents
-
${tokenRows}
-
-
`; - - el('uf-codex-cancel')?.addEventListener('click', () => { formEl.style.display = 'none'; }); - el('uf-codex-create')?.addEventListener('click', async () => { - const msg = el('uf-codex-msg'); - const name = el('uf-codex-name').value.trim(); - if (!name) { msg.textContent = 'Name required'; msg.style.color = 'var(--red)'; return; } - const fd = new FormData(); - fd.append('name', name); - fd.append('scopes', 'chat'); - try { - const r = await fetch('/api/tokens', { method: 'POST', credentials: 'same-origin', body: fd }); - const d = await r.json(); - if (!r.ok) throw new Error(d.detail || 'Failed'); - el('uf-codex-token').textContent = d.token || ''; - el('uf-codex-reveal').style.display = ''; - const configureBtn = el('uf-codex-configure'); - if (configureBtn) { - configureBtn.dataset.tokenId = d.id || ''; - configureBtn.style.display = ''; - } - const setupBtn = el('uf-codex-copy-setup'); - if (setupBtn) { - setupBtn.dataset.token = d.token || ''; - setupBtn.style.opacity = ''; - } - const setupCode = el('uf-codex-setup-code'); - if (setupCode) setupCode.textContent = setupForToken(d.token || ''); - msg.textContent = 'Created. Configure access before testing tools.'; - msg.style.color = 'var(--green, #50fa7b)'; - await renderList(); - } catch (err) { - msg.textContent = err?.message || 'Failed'; - msg.style.color = 'var(--red)'; - } - }); - const _copyCodexToken = async (text) => { - const value = String(text || ''); - if (!value) return false; - if (navigator.clipboard && window.isSecureContext) { - try { - await navigator.clipboard.writeText(value); - return true; - } catch (_) {} - } - const ta = document.createElement('textarea'); - ta.value = value; - ta.setAttribute('readonly', 'readonly'); - ta.style.cssText = 'position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;z-index:-1;'; - document.body.appendChild(ta); - ta.focus(); - ta.select(); - ta.setSelectionRange(0, value.length); - let ok = false; - try { ok = document.execCommand('copy'); } catch (_) { ok = false; } - ta.remove(); - return ok; - }; - const _selectTextFallback = (text, containerId) => { - const code = document.createElement('pre'); - code.textContent = text; - code.style.cssText = 'white-space:pre-wrap;word-break:break-word;font-size:10px;margin:6px 0 0;'; - el(containerId)?.appendChild(code); - const range = document.createRange(); - range.selectNodeContents(code); - const selection = window.getSelection(); - selection.removeAllRanges(); - selection.addRange(range); - }; - el('uf-codex-copy-setup')?.addEventListener('click', async () => { - const token = el('uf-codex-copy-setup')?.dataset.token || ''; - const btn = el('uf-codex-copy-setup'); - if (!token) { - if (btn) { - btn.textContent = 'Add agent first'; - setTimeout(() => { const latest = el('uf-codex-copy-setup'); if (latest) latest.textContent = 'Copy setup'; }, 1600); - } - return; - } - const setup = setupForToken(token); - const ok = await _copyCodexToken(setup); - if (!btn) return; - btn.textContent = ok ? 'Copied setup' : 'Select setup'; - if (!ok) _selectTextFallback(setup, 'uf-codex-reveal'); - setTimeout(() => { const latest = el('uf-codex-copy-setup'); if (latest) latest.textContent = 'Copy setup'; }, 1600); - }); - el('uf-codex-copy-token')?.addEventListener('click', async () => { - const token = el('uf-codex-token')?.textContent || ''; - const ok = await _copyCodexToken(token); - const btn = el('uf-codex-copy-token'); - if (!btn) return; - btn.textContent = ok ? 'Copied token' : 'Select token'; - if (!ok) _selectTextFallback(token, 'uf-codex-reveal'); - setTimeout(() => { const latest = el('uf-codex-copy-token'); if (latest) latest.textContent = 'Copy token'; }, 1600); - }); - el('uf-codex-configure')?.addEventListener('click', async () => { - await showCodexForm(el('uf-codex-configure')?.dataset.tokenId || null); - }); - formEl.querySelectorAll('.uf-codex-revoke').forEach(btn => { - btn.addEventListener('click', async () => { - if (!await window.styledConfirm('Revoke this Codex token? Terminal agents using it will lose access.', { confirmText: 'Revoke', danger: true })) return; - await fetch(`/api/tokens/${btn.dataset.tokenId}`, { method: 'DELETE', credentials: 'same-origin' }); - await showCodexForm(null); - await renderList(); - }); - }); - formEl.querySelectorAll('.uf-codex-scope').forEach(cb => { - cb.addEventListener('change', async () => { - const tokenId = cb.dataset.tokenId; - const panel = formEl.querySelector(`.uf-codex-token[data-token-id="${CSS.escape(tokenId)}"]`); - const msg = formEl.querySelector(`.uf-codex-scope-msg[data-token-id="${CSS.escape(tokenId)}"]`); - const scopes = Array.from(panel.querySelectorAll('.uf-codex-scope:checked')).map(input => input.dataset.scope); - try { - const r = await fetch(`/api/tokens/${tokenId}`, { - method: 'PATCH', - credentials: 'same-origin', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ scopes }), - }); - const d = await r.json().catch(() => ({})); - if (!r.ok) throw new Error(d.detail || 'Failed'); - if (msg) { msg.textContent = 'Saved'; msg.style.color = 'var(--green, #50fa7b)'; } - await renderList(); - } catch (err) { - cb.checked = !cb.checked; - if (msg) { msg.textContent = err?.message || 'Failed'; msg.style.color = 'var(--red)'; } - } - }); - }); - } - // ── Add button with type picker ── if (addBtn) { addBtn.addEventListener('click', () => { @@ -4569,7 +4319,6 @@ python3 ~/plugins/odysseus/scripts/odysseus_api.py capabilities`; -