Skip to content

Personal AI, On Personal Devices

Python

feat: add GatewayDaemon, SessionExpiryHook, and service file generation

Tarun Suresh5df86886270c
diff --git a/src/openjarvis/daemon/__init__.py b/src/openjarvis/daemon/__init__.py
new file mode 100644
index 00000000..9d48db4f
--- /dev/null
+++ b/src/openjarvis/daemon/__init__.py
@@ -0,0 +1 @@
+from __future__ import annotations
diff --git a/src/openjarvis/daemon/gateway.py b/src/openjarvis/daemon/gateway.py
new file mode 100644
index 00000000..189a8dc7
--- /dev/null
+++ b/src/openjarvis/daemon/gateway.py
@@ -0,0 +1,39 @@
+from __future__ import annotations
+
+from typing import Any, Optional
+
+
+class GatewayDaemon:
+ """Composes channels, sessions, agents, and scheduler into a daemon."""
+
+ def __init__(
+ self,
+ config: Any = None,
+ session_store: Any = None,
+ agent_manager: Any = None,
+ agent_scheduler: Any = None,
+ event_bus: Any = None,
+ ) -> None:
+ self._config = config
+ self._session_store = session_store
+ self._agent_manager = agent_manager
+ self._agent_scheduler = agent_scheduler
+ self._event_bus = event_bus
+ self._running = False
+
+ @staticmethod
+ def session_key(
+ platform: str,
+ chat_type: str,
+ chat_id: str,
+ thread_id: Optional[str],
+ ) -> str:
+ return f"agent:main:{platform}:{chat_type}:{chat_id}:{thread_id}"
+
+ def start(self) -> None:
+ """Start the daemon (foreground)."""
+ self._running = True
+
+ def stop(self) -> None:
+ """Stop the daemon."""
+ self._running = False
diff --git a/src/openjarvis/daemon/service.py b/src/openjarvis/daemon/service.py
new file mode 100644
index 00000000..3c88809b
--- /dev/null
+++ b/src/openjarvis/daemon/service.py
@@ -0,0 +1,57 @@
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+SYSTEMD_TEMPLATE = """\
+[Unit]
+Description=OpenJarvis Gateway Daemon
+After=network.target
+
+[Service]
+Type=simple
+ExecStart={python} -m openjarvis.daemon.gateway
+Restart=on-failure
+RestartSec=5
+
+[Install]
+WantedBy=default.target
+"""
+
+LAUNCHD_TEMPLATE = """\
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" \
+"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>com.openjarvis.gateway</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>{python}</string>
+ <string>-m</string>
+ <string>openjarvis.daemon.gateway</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <true/>
+</dict>
+</plist>
+"""
+
+
+def generate_systemd_service(output: Path | None = None) -> str:
+ content = SYSTEMD_TEMPLATE.format(python=sys.executable)
+ if output:
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(content)
+ return content
+
+
+def generate_launchd_plist(output: Path | None = None) -> str:
+ content = LAUNCHD_TEMPLATE.format(python=sys.executable)
+ if output:
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(content)
+ return content
diff --git a/src/openjarvis/daemon/session_expiry.py b/src/openjarvis/daemon/session_expiry.py
new file mode 100644
index 00000000..87614ae9
--- /dev/null
+++ b/src/openjarvis/daemon/session_expiry.py
@@ -0,0 +1,34 @@
+from __future__ import annotations
+
+from typing import Any, List
+
+from openjarvis.core.types import Message
+
+
+class SessionExpiryHook:
+ """Proactive memory flush before session reset."""
+
+ FLUSH_PROMPT = (
+ "This session is about to be reset. Review the conversation below "
+ "and save anything important to memory or skills. Use memory_manage "
+ "to save facts/preferences and skill_manage to save reusable procedures."
+ )
+
+ def __init__(self, executor: Any, flush_min_turns: int = 6) -> None:
+ self._executor = executor
+ self._flush_min_turns = flush_min_turns
+
+ def on_session_expiry(self, session_id: str, messages: List[Message]) -> None:
+ if len(messages) < self._flush_min_turns:
+ return
+ transcript = "\n".join(f"[{m.role}]: {m.content}" for m in messages)
+ input_text = f"{self.FLUSH_PROMPT}\n\n---\n\n{transcript}"
+ self._executor.run_ephemeral(
+ agent_type="simple",
+ system_prompt=(
+ "You are a memory management agent. "
+ "Save important information."
+ ),
+ input_text=input_text,
+ tools=["memory_manage", "skill_manage"],
+ )
diff --git a/tests/daemon/__init__.py b/tests/daemon/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/daemon/test_gateway.py b/tests/daemon/test_gateway.py
new file mode 100644
index 00000000..f024b0e3
--- /dev/null
+++ b/tests/daemon/test_gateway.py
@@ -0,0 +1,18 @@
+from __future__ import annotations
+
+
+def test_gateway_session_key_format():
+ from openjarvis.daemon.gateway import GatewayDaemon
+
+ key = GatewayDaemon.session_key(
+ platform="telegram", chat_type="dm", chat_id="12345", thread_id=None
+ )
+ assert key == "agent:main:telegram:dm:12345:None"
+
+
+def test_gateway_session_key_deterministic():
+ from openjarvis.daemon.gateway import GatewayDaemon
+
+ key1 = GatewayDaemon.session_key("discord", "group", "abc", "thread1")
+ key2 = GatewayDaemon.session_key("discord", "group", "abc", "thread1")
+ assert key1 == key2
diff --git a/tests/daemon/test_session_expiry.py b/tests/daemon/test_session_expiry.py
new file mode 100644
index 00000000..10da40e6
--- /dev/null
+++ b/tests/daemon/test_session_expiry.py
@@ -0,0 +1,28 @@
+from __future__ import annotations
+
+from unittest.mock import MagicMock
+from openjarvis.core.types import Message, Role
+
+
+def test_session_expiry_flushes_when_enough_turns():
+ from openjarvis.daemon.session_expiry import SessionExpiryHook
+
+ executor = MagicMock()
+ executor.run_ephemeral.return_value = MagicMock(content="Saved 2 memories.")
+
+ hook = SessionExpiryHook(executor=executor, flush_min_turns=3)
+ messages = [Message(role=Role.USER, content=f"msg {i}") for i in range(5)]
+ hook.on_session_expiry(session_id="test-session", messages=messages)
+
+ executor.run_ephemeral.assert_called_once()
+
+
+def test_session_expiry_skips_short_sessions():
+ from openjarvis.daemon.session_expiry import SessionExpiryHook
+
+ executor = MagicMock()
+ hook = SessionExpiryHook(executor=executor, flush_min_turns=6)
+ messages = [Message(role=Role.USER, content="hi")]
+ hook.on_session_expiry(session_id="test-session", messages=messages)
+
+ executor.run_ephemeral.assert_not_called()