Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add OpenClaw operator chat MVP slice [skip ci]
[._.]/ Adam Eivye09d3cfd945f
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 5ee7e3f2a9..b32724a1e1 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -62,6 +62,7 @@ const FeatureAgentDetail = lazyWithReload(() => import('./pages/FeatureAgentDetaconst CalendarPage = lazyWithReload(() => import('./pages/Calendar'));const Messages = lazyWithReload(() => import('./pages/Messages'));const Goals = lazyWithReload(() => import('./pages/Goals'));+const OpenClawPage = lazyWithReload(() => import('./pages/OpenClaw'));// Loading fallback for lazy-loaded pagesconst PageLoader = () => (@@ -131,6 +132,7 @@ export default function App() {<Route path="review" element={<Review />} /><Route path="messages" element={<Navigate to="/messages/inbox" replace />} /><Route path="messages/:tab" element={<Messages />} />+ <Route path="openclaw" element={<OpenClawPage />} /><Route path="datadog" element={<Navigate to="/devtools/datadog" replace />} /><Route path="jira" element={<Navigate to="/devtools/jira" replace />} /><Route path="devtools/jira" element={<Jira />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 4abe681a84..3e7211084e 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -68,7 +68,8 @@ import {MessageCircle,Swords,Image as ImageIcon,- HardDrive+ HardDrive,+ MessagesSquare} from 'lucide-react';/* global __APP_VERSION__ */import Logo from './Logo';@@ -206,6 +207,7 @@ const navItems = [{ to: '/messages/sync', label: 'Sync', icon: RefreshCw }]},+ { to: '/openclaw', label: 'OpenClaw', icon: MessagesSquare, single: true },{label: 'POST',icon: Zap,diff --git a/client/src/pages/OpenClaw.jsx b/client/src/pages/OpenClaw.jsxnew file mode 100644index 0000000000..a2641f8d8c--- /dev/null+++ b/client/src/pages/OpenClaw.jsx@@ -0,0 +1,380 @@+import { useCallback, useEffect, useMemo, useState } from 'react';+import { Bot, RefreshCw, Send, AlertCircle, MessageSquareText, PlugZap } from 'lucide-react';+import * as api from '../services/api';++function formatTimestamp(value) {+ if (!value) return 'Unknown time';++ const date = new Date(value);+ if (Number.isNaN(date.getTime())) return String(value);++ return new Intl.DateTimeFormat(undefined, {+ dateStyle: 'medium',+ timeStyle: 'short'+ }).format(date);+}++function getRuntimeState(status) {+ if (!status?.configured) {+ return {+ label: 'Unconfigured',+ classes: 'bg-gray-500/15 text-gray-300 border-gray-500/30'+ };+ }++ if (status.reachable) {+ return {+ label: 'Connected',+ classes: 'bg-emerald-500/15 text-emerald-300 border-emerald-500/30'+ };+ }++ return {+ label: 'Unavailable',+ classes: 'bg-amber-500/15 text-amber-300 border-amber-500/30'+ };+}++export default function OpenClaw() {+ const [status, setStatus] = useState(null);+ const [sessions, setSessions] = useState([]);+ const [selectedSessionId, setSelectedSessionId] = useState('');+ const [messages, setMessages] = useState([]);+ const [composer, setComposer] = useState('');+ const [statusLoading, setStatusLoading] = useState(true);+ const [sessionsLoading, setSessionsLoading] = useState(false);+ const [messagesLoading, setMessagesLoading] = useState(false);+ const [sending, setSending] = useState(false);+ const [pageError, setPageError] = useState('');+ const [messagesError, setMessagesError] = useState('');++ const runtimeState = useMemo(() => getRuntimeState(status), [status]);++ const loadMessages = useCallback(async (sessionId) => {+ if (!sessionId) {+ setMessages([]);+ setMessagesError('');+ return;+ }++ setMessagesLoading(true);+ setMessagesError('');++ try {+ const data = await api.getOpenClawMessages(sessionId, { limit: 50 });+ setMessages(data?.messages || []);+ } catch (err) {+ setMessages([]);+ setMessagesError(err.message || 'Failed to load messages');+ } finally {+ setMessagesLoading(false);+ }+ }, []);++ const loadRuntime = useCallback(async () => {+ setStatusLoading(true);+ setSessionsLoading(true);+ setPageError('');++ try {+ const statusData = await api.getOpenClawStatus();+ setStatus(statusData);++ if (!statusData?.configured) {+ setSessions([]);+ setSelectedSessionId('');+ setMessages([]);+ setMessagesError('');+ return;+ }++ const sessionsData = await api.getOpenClawSessions();+ const nextSessions = sessionsData?.sessions || [];+ setSessions(nextSessions);++ const validIds = new Set(nextSessions.map(session => session.id).filter(Boolean));+ const preferredSessionId = [+ selectedSessionId,+ statusData.defaultSession,+ nextSessions[0]?.id+ ].find(id => id && (validIds.size === 0 || validIds.has(id)));++ const fallbackSessionId = preferredSessionId || statusData.defaultSession || '';+ setSelectedSessionId(fallbackSessionId);+ } catch (err) {+ setStatus(null);+ setSessions([]);+ setSelectedSessionId('');+ setMessages([]);+ setPageError(err.message || 'Failed to load OpenClaw status');+ } finally {+ setStatusLoading(false);+ setSessionsLoading(false);+ }+ }, [selectedSessionId]);++ useEffect(() => {+ loadRuntime();+ }, [loadRuntime]);++ useEffect(() => {+ if (!status?.configured || !selectedSessionId) {+ setMessages([]);+ setMessagesError('');+ return;+ }++ loadMessages(selectedSessionId);+ }, [loadMessages, selectedSessionId, status?.configured]);++ const handleSend = async (event) => {+ event.preventDefault();++ const message = composer.trim();+ if (!message || !selectedSessionId || sending) return;++ setSending(true);+ setMessagesError('');++ try {+ await api.sendOpenClawMessage(selectedSessionId, message);+ setComposer('');+ await loadMessages(selectedSessionId);+ await loadRuntime();+ } catch (err) {+ setMessagesError(err.message || 'Failed to send message');+ } finally {+ setSending(false);+ }+ };++ const selectedSession = sessions.find(session => session.id === selectedSessionId);++ return (+ <div className="flex h-full flex-col">+ <div className="flex flex-col gap-4 border-b border-port-border p-4 lg:flex-row lg:items-center lg:justify-between">+ <div className="flex items-center gap-3">+ <Bot className="h-8 w-8 text-port-accent" />+ <div>+ <h1 className="text-xl font-bold text-white">OpenClaw</h1>+ <p className="text-sm text-gray-500">Operator chat surface for an optional runtime.</p>+ </div>+ </div>++ <div className="flex items-center gap-3">+ <span className={`inline-flex items-center rounded-full border px-3 py-1 text-sm font-medium ${runtimeState.classes}`}>+ {runtimeState.label}+ </span>+ <button+ type="button"+ onClick={loadRuntime}+ disabled={statusLoading || sessionsLoading}+ className="inline-flex items-center gap-2 rounded-lg border border-port-border bg-port-card px-3 py-2 text-sm text-gray-200 transition-colors hover:border-gray-500 hover:text-white disabled:cursor-not-allowed disabled:opacity-60"+ >+ <RefreshCw size={16} className={statusLoading || sessionsLoading ? 'animate-spin' : ''} />+ Refresh+ </button>+ </div>+ </div>++ <div className="grid flex-1 gap-4 overflow-hidden p-4 lg:grid-cols-[320px_minmax(0,1fr)]">+ <aside className="flex min-h-0 flex-col gap-4">+ <section className="rounded-xl border border-port-border bg-port-card p-4">+ <div className="mb-3 flex items-center gap-2">+ <PlugZap size={16} className="text-port-accent" />+ <h2 className="text-sm font-semibold text-white">Runtime Status</h2>+ </div>++ {statusLoading ? (+ <div className="flex items-center gap-2 text-sm text-gray-400">+ <RefreshCw size={14} className="animate-spin" />+ Loading runtime status…+ </div>+ ) : (+ <div className="space-y-2 text-sm text-gray-300">+ <div className="flex justify-between gap-3">+ <span className="text-gray-500">Label</span>+ <span className="text-right text-white">{status?.label || 'OpenClaw Runtime'}</span>+ </div>+ <div className="flex justify-between gap-3">+ <span className="text-gray-500">Configured</span>+ <span>{status?.configured ? 'Yes' : 'No'}</span>+ </div>+ <div className="flex justify-between gap-3">+ <span className="text-gray-500">Reachable</span>+ <span>{status?.reachable ? 'Yes' : 'No'}</span>+ </div>+ <div className="flex justify-between gap-3">+ <span className="text-gray-500">Default Session</span>+ <span className="text-right">{status?.defaultSession || 'None'}</span>+ </div>+ {status?.message && (+ <div className="rounded-lg border border-port-border bg-port-bg px-3 py-2 text-xs text-gray-400">+ {status.message}+ </div>+ )}+ </div>+ )}+ </section>++ <section className="flex min-h-0 flex-1 flex-col rounded-xl border border-port-border bg-port-card">+ <div className="flex items-center justify-between border-b border-port-border px-4 py-3">+ <div className="flex items-center gap-2">+ <MessageSquareText size={16} className="text-port-accent" />+ <h2 className="text-sm font-semibold text-white">Sessions</h2>+ </div>+ <span className="text-xs text-gray-500">{sessions.length}</span>+ </div>++ <div className="min-h-0 flex-1 overflow-auto">+ {sessionsLoading ? (+ <div className="flex items-center gap-2 p-4 text-sm text-gray-400">+ <RefreshCw size={14} className="animate-spin" />+ Loading sessions…+ </div>+ ) : !status?.configured ? (+ <div className="p-4 text-sm text-gray-400">+ Add local OpenClaw config to enable session discovery.+ </div>+ ) : sessions.length === 0 ? (+ <div className="p-4 text-sm text-gray-400">+ No sessions available.+ </div>+ ) : (+ sessions.map((session) => {+ const isActive = session.id === selectedSessionId;+ return (+ <button+ key={session.id}+ type="button"+ onClick={() => setSelectedSessionId(session.id)}+ className={`block w-full border-b border-port-border px-4 py-3 text-left transition-colors last:border-b-0 ${+ isActive ? 'bg-port-accent/10 text-white' : 'text-gray-300 hover:bg-port-border/20 hover:text-white'+ }`}+ >+ <div className="truncate text-sm font-medium">{session.title || session.label || session.id}</div>+ <div className="mt-1 flex items-center justify-between gap-3 text-xs text-gray-500">+ <span className="truncate">{session.id}</span>+ <span>{session.messageCount ?? 0} msgs</span>+ </div>+ </button>+ );+ })+ )}+ </div>+ </section>+ </aside>++ <section className="flex min-h-0 flex-col rounded-xl border border-port-border bg-port-card">+ <div className="border-b border-port-border px-4 py-3">+ <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between">+ <div>+ <h2 className="text-base font-semibold text-white">+ {selectedSession?.title || selectedSession?.label || selectedSessionId || 'No session selected'}+ </h2>+ <p className="text-sm text-gray-500">+ {selectedSessionId ? `Session ID: ${selectedSessionId}` : 'Choose a session to load recent messages.'}+ </p>+ </div>+ {selectedSession?.lastMessageAt && (+ <div className="text-xs text-gray-500">+ Last activity {formatTimestamp(selectedSession.lastMessageAt)}+ </div>+ )}+ </div>+ </div>++ {pageError && (+ <div className="mx-4 mt-4 flex items-start gap-2 rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-200">+ <AlertCircle size={16} className="mt-0.5 shrink-0" />+ <span>{pageError}</span>+ </div>+ )}++ {messagesError && (+ <div className="mx-4 mt-4 flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-100">+ <AlertCircle size={16} className="mt-0.5 shrink-0" />+ <span>{messagesError}</span>+ </div>+ )}++ <div className="min-h-0 flex-1 overflow-auto p-4">+ {messagesLoading ? (+ <div className="flex h-full items-center justify-center gap-2 text-sm text-gray-400">+ <RefreshCw size={16} className="animate-spin" />+ Loading messages…+ </div>+ ) : !status?.configured ? (+ <div className="flex h-full items-center justify-center rounded-xl border border-dashed border-port-border bg-port-bg/40 p-6 text-center text-sm text-gray-400">+ OpenClaw is not configured for this PortOS instance.+ </div>+ ) : !selectedSessionId ? (+ <div className="flex h-full items-center justify-center rounded-xl border border-dashed border-port-border bg-port-bg/40 p-6 text-center text-sm text-gray-400">+ Select a session to load recent messages.+ </div>+ ) : messages.length === 0 ? (+ <div className="flex h-full items-center justify-center rounded-xl border border-dashed border-port-border bg-port-bg/40 p-6 text-center text-sm text-gray-400">+ No recent messages found for this session.+ </div>+ ) : (+ <div className="space-y-3">+ {messages.map((message, index) => {+ const role = message.role || 'assistant';+ const isUser = role === 'user';+ const key = message.id || `${message.createdAt || 'message'}-${index}`;++ return (+ <div+ key={key}+ className={`rounded-xl border px-4 py-3 ${+ isUser+ ? 'ml-auto max-w-3xl border-port-accent/30 bg-port-accent/10'+ : 'max-w-3xl border-port-border bg-port-bg/60'+ }`}+ >+ <div className="mb-2 flex items-center justify-between gap-3 text-xs uppercase tracking-wide">+ <span className={isUser ? 'text-port-accent' : 'text-gray-400'}>{role}</span>+ <span className="text-gray-500">{formatTimestamp(message.createdAt)}</span>+ </div>+ <div className="whitespace-pre-wrap text-sm leading-6 text-gray-100">+ {message.content || '[Empty message]'}+ </div>+ </div>+ );+ })}+ </div>+ )}+ </div>++ <form onSubmit={handleSend} className="border-t border-port-border p-4">+ <label className="mb-2 block text-sm font-medium text-white" htmlFor="openclaw-composer">+ Send message+ </label>+ <textarea+ id="openclaw-composer"+ value={composer}+ onChange={(event) => setComposer(event.target.value)}+ rows={4}+ placeholder={status?.configured ? 'Send a message to the selected session…' : 'OpenClaw is not configured'}+ disabled={!status?.configured || !selectedSessionId || sending}+ className="w-full resize-none rounded-lg border border-port-border bg-port-bg px-3 py-3 text-sm text-white focus:border-port-accent focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-60"+ />+ <div className="mt-3 flex items-center justify-between gap-3">+ <span className="text-xs text-gray-500">+ {status?.configured && selectedSessionId ? 'Messages are proxied through PortOS.' : 'Select a configured session to send.'}+ </span>+ <button+ type="submit"+ disabled={!composer.trim() || !status?.configured || !selectedSessionId || sending}+ className="inline-flex items-center gap-2 rounded-lg bg-port-accent px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-port-accent/80 disabled:cursor-not-allowed disabled:opacity-60"+ >+ {sending ? <RefreshCw size={16} className="animate-spin" /> : <Send size={16} />}+ {sending ? 'Sending…' : 'Send'}+ </button>+ </div>+ </form>+ </section>+ </div>+ </div>+ );+}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 1ec482a00c..650a7cc8c8 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1962,6 +1962,21 @@ export const completeReviewItem = (id) => request(`/review/items/${id}/complete`export const dismissReviewItem = (id) => request(`/review/items/${id}/dismiss`, { method: 'POST' });export const deleteReviewItem = (id) => request(`/review/items/${id}`, { method: 'DELETE' });+// OpenClaw+export const getOpenClawStatus = () => request('/openclaw/status', { silent: true });+export const getOpenClawSessions = () => request('/openclaw/sessions', { silent: true });+export const getOpenClawMessages = (sessionId, options = {}) => {+ const params = new URLSearchParams();+ if (options.limit) params.set('limit', options.limit);+ const query = params.toString();+ return request(`/openclaw/sessions/${encodeURIComponent(sessionId)}/messages${query ? `?${query}` : ''}`, { silent: true });+};+export const sendOpenClawMessage = (sessionId, message, context) => request(`/openclaw/sessions/${encodeURIComponent(sessionId)}/messages`, {+ method: 'POST',+ body: JSON.stringify({ message, context }),+ silent: true+});+// Default export for simplified importsexport default {get: (endpoint, options) => request(endpoint, { method: 'GET', ...options }),diff --git a/data.sample/openclaw/config.json b/data.sample/openclaw/config.jsonnew file mode 100644index 0000000000..cf7ef82ef7--- /dev/null+++ b/data.sample/openclaw/config.json@@ -0,0 +1,13 @@+{+ "enabled": false,+ "baseUrl": "http://private-runtime",+ "authToken": "",+ "defaultSession": "main",+ "label": "Local Operator Runtime",+ "paths": {+ "status": "/status",+ "sessions": "/sessions",+ "sessionMessages": "/sessions/:sessionId/messages",+ "sendMessage": "/sessions/:sessionId/messages"+ }+}diff --git a/docs/features/openclaw-operator-chat-audit.md b/docs/features/openclaw-operator-chat-audit.mdnew file mode 100644index 0000000000..27f2ceab37--- /dev/null+++ b/docs/features/openclaw-operator-chat-audit.md@@ -0,0 +1,427 @@+# OpenClaw Operator Chat — Extension Point Audit++This audit maps the real PortOS insertion points for a generic OpenClaw/operator chat feature.++It is a companion to:+- `docs/features/openclaw-operator-chat.md`++## Summary++PortOS already has the major primitives needed for a first-party OpenClaw/operator chat surface:++- top-level routed pages+- server-side API proxy patterns+- Socket.IO real-time plumbing+- CoS/agent UI patterns for operational state+- Messages UI patterns for threaded communication+- Tailscale/private-network assumptions++That means the MVP does **not** require a new architectural subsystem. It can be added as a conventional PortOS page + server route pair.++## Best fit in current architecture++### Recommended route/page+Add a new top-level page:++- `/openclaw`++Why top-level instead of nesting under CoS:+- CoS is an autonomous system manager+- OpenClaw/operator chat is a direct operator conversation surface+- keeping them separate preserves product clarity+- it avoids forcing OpenClaw into a Chief-of-Staff mental model++### Recommended server route+Add a new API route group:++- `/api/openclaw`++Why:+- matches existing route conventions in `server/index.js`+- keeps browser-side config simple+- lets PortOS proxy requests to OpenClaw without exposing runtime topology/auth in the frontend++## Concrete insertion points++## 1. Frontend routing++### Existing file+- `client/src/App.jsx`++### Recommended change+Add:+- lazy-loaded page import or static import for `./pages/OpenClaw`+- route:+ - `<Route path="openclaw" element={<OpenClawPage />} />`++### Why this is the right place+`App.jsx` is already the top-level router for:+- `messages`+- `cos`+- `brain`+- `shell`+- `instances`+- etc.++OpenClaw belongs at the same tier.++## 2. Frontend page++### Recommended new file+- `client/src/pages/OpenClaw.jsx`++### MVP responsibilities+- load runtime status+- load available sessions+- select a session+- load recent messages+- send a message+- show assistant replies+- show connection errors cleanly++### Best UI references in current codebase+Use these as patterns rather than duplicating their semantics:++#### Operational shell patterns+- `client/src/pages/ChiefOfStaff.jsx`+- `client/src/components/cos/*`++Useful patterns there:+- status banners+- event logs+- live operational feedback+- left/right panel layout ideas+- tabbed operational workflows++#### Communication UI patterns+- `client/src/pages/Messages.jsx`+- `client/src/components/messages/*`++Useful patterns there:+- threaded/timeline communication views+- account/session selection concepts+- message detail handling+- draft/send interaction patterns++### Recommendation+For MVP, bias more toward:+- **CoS operational shell feel**+than toward:+- email/inbox complexity++This should feel like an operator console, not a normal messaging product.++## 3. Frontend API wrapper++### Existing file+- `client/src/services/api.js`++### Recommended additions+Add a small OpenClaw section with helpers like:++- `getOpenClawStatus()`+- `getOpenClawSessions()`+- `getOpenClawMessages(sessionId, options)`+- `sendOpenClawMessage(sessionId, message, context)`+- optional later:+ - `getOpenClawJobs()`+ - `getOpenClawSubagents()`+ - `createOpenClawSession(payload)`++### Why here+This file is the existing client-side API facade for nearly all PortOS features.+Adding OpenClaw here follows the same convention and avoids one-off fetch logic scattered through the page.++## 4. Server route mounting++### Existing file+- `server/index.js`++### Recommended change+Add:+- `import openclawRoutes from './routes/openclaw.js';`+- `app.use('/api/openclaw', openclawRoutes);`++### Why here+This is the normal route registration point for all PortOS API features.++## 5. Server route module++### Recommended new file+- `server/routes/openclaw.js`++### MVP responsibilities+- status endpoint+- list sessions endpoint+- get session history/messages endpoint+- send message endpoint++### Thin-adapter rule+This route should be a **thin integration adapter**, not a new assistant runtime.+Its job is to:+- validate PortOS-side requests+- consult local config+- proxy to OpenClaw runtime+- normalize responses for PortOS UI++## 6. Server integration layer++### Recommended new directory/files+- `server/integrations/openclaw/api.js`+- optional later:+ - `server/integrations/openclaw/config.js`+ - `server/integrations/openclaw/normalize.js`++### Why add this layer+Keeps route handlers clean and prevents OpenClaw-specific HTTP shapes from leaking all over PortOS.++### MVP responsibilities+- build runtime base URL from local config+- attach auth if configured+- perform fetches to OpenClaw+- normalize common failures:+ - unconfigured+ - unreachable+ - unauthorized+ - malformed response++## 7. Local/private configuration++This is the most important boundary.++### What should NOT go in public product defaults+- actual local/private OpenClaw endpoint+- machine-specific hostnames/IPs+- auth tokens+- assistant identity name/persona+- machine-role semantics tied to one user++### Best likely fit+Use existing local data/config conventions under PortOS data storage, not committed source defaults.++Relevant existing server-side patterns:+- `PATHS.data` in `server/lib/fileUtils.js`+- PortOS already uses local data directories for instance-specific state++### Recommended approach+Keep a git-ignored config file under local data, something conceptually like:++- `data/openclaw/config.json`++Example shape:++```json+{+ "enabled": true,+ "baseUrl": "http://private-runtime",+ "authToken": "...",+ "defaultSession": "main",+ "label": "Local Operator Runtime"+}+```++If a sample/public config exists, it should contain only generic placeholders and no private topology.++## 8. Real-time events / streaming++### Existing infrastructure+- `client/src/services/socket.js`+- `server/services/socket.js`+- `server/index.js` Socket.IO initialization++### Recommendation for MVP+Do **not** start with full token streaming if it complicates delivery.++MVP can work with:+- request/response message send+- subsequent message refresh/history fetch++### Later phase+If OpenClaw supports streaming or event subscription cleanly, PortOS can add:+- live reply streaming+- tool activity summaries+- session state updates++This should reuse existing Socket.IO patterns rather than invent a parallel browser transport.++## 9. Navigation / discoverability++### Existing likely insertion point+- `client/src/components/Layout.jsx`++### Recommended change+Add a nav item for:+- OpenClaw+- or Operator Chat++Use a generic icon/label.+Do not use private assistant identity in shared UI.++## 10. Security posture++### Existing assumptions+PortOS already assumes:+- self-hosted+- private-network/Tailscale usage+- server-side route mediation++### Recommended posture for this feature+- browser talks only to PortOS `/api/openclaw`+- PortOS server talks to OpenClaw runtime+- runtime details stay server-side+- local config stays git-ignored+- page should degrade cleanly if runtime is absent++### Why this is better than direct browser-to-OpenClaw+- no leaking runtime endpoint/auth to client bundle+- simpler multi-instance behavior+- consistent error handling+- better future room for policy/context filtering++## 11. Existing feature boundaries to preserve++### Keep separate from Messages+Why:+- `Messages` is about external communication accounts and inboxes+- OpenClaw operator chat is internal/local runtime communication++Do not merge these domains in MVP.++### Keep separate from CoS+Why:+- CoS is autonomous system orchestration+- OpenClaw chat is direct operator conversation++They can link to each other, but should not be the same page.++## 12. MVP file plan++### Frontend+New:+- `client/src/pages/OpenClaw.jsx`++Modify:+- `client/src/App.jsx`+- `client/src/services/api.js`+- likely `client/src/components/Layout.jsx`++Optional new components if needed:+- `client/src/components/openclaw/SessionList.jsx`+- `client/src/components/openclaw/ChatTimeline.jsx`+- `client/src/components/openclaw/Composer.jsx`+- `client/src/components/openclaw/RuntimeStatusCard.jsx`++### Backend+New:+- `server/routes/openclaw.js`+- `server/integrations/openclaw/api.js`++Modify:+- `server/index.js`++Optional later:+- `server/integrations/openclaw/config.js`+- `server/integrations/openclaw/errors.js`++### Data/config+Local/private only:+- `data/openclaw/config.json` (git-ignored or machine-local)++Optional public-safe sample:+- `data.sample/openclaw/config.json` with placeholders only++## 13. MVP endpoint sketch++Inside PortOS:++- `GET /api/openclaw/status`+ - configured?+ - reachable?+ - default session?+ - label?++- `GET /api/openclaw/sessions`+ - list sessions available to PortOS++- `GET /api/openclaw/sessions/:id/messages?limit=...`+ - get recent session history++- `POST /api/openclaw/sessions/:id/messages`+ - send a message+ - optional context attachments payload++Optional:+- `POST /api/openclaw/sessions`+ - create/bind a session++## 14. Suggested MVP UI shape++### Header+- runtime label+- connection state+- session selector++### Main body+- message list+- composer++### Side panel (optional but useful)+- current page context toggle+- session metadata+- quick links to relevant PortOS surfaces++## 15. Risks and watchouts++### 1. Identity leakage into product code+Avoid:+- hardcoded private assistant names+- private relationship language in public UI++### 2. Feature becoming too CoS-specific+Avoid:+- assuming all assistant interaction is through the Chief of Staff model++### 3. Context oversharing+Avoid:+- silently attaching full page/system state without explicit user action++### 4. Tight runtime coupling+Avoid:+- making PortOS unusable when OpenClaw is missing++### 5. Premature streaming complexity+Avoid:+- shipping a fragile streaming layer before simple request/response works++## 16. Recommended implementation order++### Phase A — thin vertical slice+1. local config loader+2. server integration adapter+3. `/api/openclaw/status`+4. `/api/openclaw/sessions`+5. `/api/openclaw/sessions/:id/messages`+6. `/api/openclaw/sessions/:id/messages` POST+7. basic `/openclaw` page+8. nav link++### Phase B — usability+9. session persistence in UI+10. better error states+11. optional context attachment controls+12. runtime metadata/status card++### Phase C — deeper operator integration+13. socket-driven live updates+14. subagent/job visibility+15. links to Review / Apps / CoS / DevTools++## Recommendation+The MVP should be:+- a new top-level `/openclaw` page+- backed by `/api/openclaw` routes+- implemented through a thin server-side integration adapter+- configured through local/private instance config+- visually aligned with CoS operational patterns, not Messages inbox complexity++That is the cleanest way to add first-party assistant chat to PortOS without contaminating the public project with private identity or machine-specific assumptions.diff --git a/docs/features/openclaw-operator-chat.md b/docs/features/openclaw-operator-chat.mdnew file mode 100644index 0000000000..64aacb7a1c--- /dev/null+++ b/docs/features/openclaw-operator-chat.md@@ -0,0 +1,441 @@+# OpenClaw Operator Chat++A generic, first-party operator chat surface inside PortOS that allows a user to communicate with a local or privately reachable OpenClaw runtime without relying on third-party messaging providers like Telegram.++## Why this exists++PortOS is already reachable over Tailscale and is intended to be a secure, self-hosted operating surface. For sensitive operator work, routing chat through Telegram or another third-party messaging network adds avoidable privacy and security exposure.++This feature adds a **generic** assistant/operator chat module to PortOS so users can:++- chat with their assistant directly inside PortOS+- inspect session state without leaving the app+- keep sensitive machine/admin context off third-party transports+- use PortOS as a first-party local operator console++## Critical product constraint++PortOS is a public open-source project used by many people.++Therefore:++- **do not bake any private assistant identity into product features**+- **do not assume one specific assistant persona or relationship model**+- **do not assume one specific machine/network topology**+- **do not assume OpenClaw is always present**++This feature must remain:++- generic+- optional+- instance-configurable+- safe for users running their own OpenClaw or no assistant at all++Identity, assistant naming, local network details, and machine-specific behavior must live in local/private configuration or git-ignored instance data.++## Product framing++This should be presented as something like:++- **Operator Chat**+- **Assistant Console**+- **OpenClaw**+- **Runtime Chat**++Not:++- a hardcoded persona name+- a product-level "Rowan" feature+- a fixed Chief-of-Staff replacement++## Goals++1. Provide a first-party chat UI inside PortOS for talking to an assistant/runtime.+2. Reduce reliance on Telegram for operator/admin conversations.+3. Keep the feature generic enough for any PortOS instance to connect to its own OpenClaw deployment.+4. Preserve clean boundaries between:+ - PortOS UI+ - assistant runtime+ - private instance config+5. Make chat adjacent to PortOS state, apps, repos, tasks, and services.++## Non-goals++- replacing all external messaging integrations+- embedding assistant identity into PortOS core+- making PortOS depend on OpenClaw to function+- exposing private machine details through public/open-source defaults+- coupling this feature tightly to one user's workflow++## Existing PortOS extension points that make this feasible++PortOS already has several relevant building blocks:++### UI patterns+- `client/src/pages/ChiefOfStaff.jsx`+- `client/src/components/cos/*`+- existing tabbed operational UI patterns+- event logs, terminal-style panels, status indicators++### Networking and real-time+- `client/src/services/socket.js` uses relative paths and is already Tailscale-friendly+- `server/index.js` already mounts Socket.IO and API routes for local/private access++### Agent/runtime patterns+- CoS page and agent runner already model:+ - status+ - running jobs+ - event streams+ - agent outputs+- `server/cos-runner/` already provides a process/runtime management pattern++### Messaging patterns+- `client/src/pages/Messages.jsx`+- `server/routes/messages.js`+- existing draft/message/thread models can inform UX, even if operator chat is a separate domain++### Security assumptions+- PortOS already assumes trusted-network/private access via Tailscale+- this is compatible with a local-first assistant console++## High-level architecture++### Separation of concerns++#### PortOS is responsible for:+- operator UI+- session list UI+- message history UI+- context attachment UX+- runtime connection status+- local authentication to PortOS itself+- optional linking between chat and PortOS pages/apps/tasks++#### OpenClaw is responsible for:+- session runtime+- message handling+- tool execution+- subagent/session orchestration+- response generation+- runtime-side security/policy enforcement++### Integration model++PortOS should talk to OpenClaw through a small adapter/integration layer, not by reimplementing assistant logic.++Suggested shape:++- **server integration module**+ - `server/integrations/openclaw/*`+- **PortOS API routes**+ - `server/routes/openclaw.js`+- **client service wrapper**+ - `client/src/services/openclaw.js`+- **UI page**+ - `client/src/pages/OpenClaw.jsx` or `client/src/pages/OperatorChat.jsx`++## Proposed capabilities++### Phase 1 — MVP: first-party assistant chat++A page inside PortOS where the user can:++- see whether an OpenClaw runtime is configured/reachable+- view available sessions or a default session+- load recent message history+- send a message+- receive assistant replies+- see timestamps and basic status++Suggested features:++- session selector+- message timeline+- input composer+- connection status badge+- send/receive loading states+- optional "reply in current session" mode++### Phase 2 — operator-aware context++Allow the user to send a message with attached PortOS context such as:++- current page/app+- selected repo/app+- active task+- system status summary+- current machine/app metadata++Examples:++- "look at this app"+- "review the current queue"+- "inspect the service behind this page"+- "summarize what changed here"++This context should be explicit and user-controlled, not silently leaked.++### Phase 3 — runtime visibility and controls++Expose runtime information such as:++- connected runtime endpoint+- active sessions+- spawned subagents/jobs+- recent tool actions+- execution status+- reminders/cron job visibility if supported++This should feel like an operator console, not just a basic chat box.++### Phase 4 — structured PortOS actions++Optional future capabilities:++- ask assistant to inspect a repo and open linked results+- pass page context to assistant with one click+- show inline approvals/review items+- link assistant output to Review / Goals / Apps / Brain surfaces++## Privacy and security model++### Public/open-source code may contain+- generic OpenClaw connector support+- generic UI for assistant/runtime chat+- generic settings for endpoint/auth/session behavior+- generic local data storage hooks++### Private instance-local data must contain+- assistant identity/persona+- local machine topology+- hostnames, ports, URLs, tokens+- role preferences+- private operator notes+- machine-specific context mapping++### Rules+- no private assistant identity in product defaults+- no machine-specific hostnames or ports in committed code/docs beyond generic examples+- no assumptions about Telegram or other third-party transports+- no assumptions that all users want autonomous operator chat+- fail gracefully when OpenClaw is unconfigured or unreachable++## Configuration model++### Public-safe config surface+PortOS can expose generic settings like:++```json+{+ "enabled": true,+ "provider": "openclaw",+ "transport": "http",+ "sessionMode": "default",+ "allowContextAttachments": true,+ "showRuntimeStatus": true+}+```++### Private instance-local config+Actual endpoint/auth/session defaults should live in local, git-ignored config, for example:++```json+{+ "openclaw": {+ "baseUrl": "http://100.x.x.x:PORT",+ "authToken": "...",+ "defaultSession": "main",+ "label": "Local Operator Runtime"+ }+}+```++The exact file/location should align with PortOS local config conventions, but must remain out of public repo defaults if it contains private topology or credentials.++## Suggested API surface inside PortOS++These would be PortOS routes that proxy or adapt to an OpenClaw runtime.++### Status+- `GET /api/openclaw/status`+ - runtime reachable?+ - configured?+ - default session?++### Sessions+- `GET /api/openclaw/sessions`+- `GET /api/openclaw/sessions/:id/messages`+- `POST /api/openclaw/sessions/:id/messages`+- `POST /api/openclaw/sessions`+ - create or bind a new operator session if needed++### Optional runtime actions+- `GET /api/openclaw/jobs`+- `GET /api/openclaw/subagents`+- `POST /api/openclaw/context/compose`+ - build a safe context bundle from current PortOS state++These should remain thin adapters where possible.++## UI proposal++### New page+A new page such as:++- `/openclaw`+- `/operator-chat`+- `/assistant`++I recommend **`/openclaw`** or **`/operator-chat`**.++### Page layout++#### Left rail+- runtime status+- session list+- quick actions+- optional recent tasks/subagents++#### Main panel+- message timeline+- streamed assistant replies+- tool activity summaries (optional)+- context chips++#### Right rail (future)+- current page/app context+- recent system events+- inspectable attachments++### UX principles+- chat should feel calm and operational, not social-media-like+- context attachments should be explicit+- runtime status should be visible+- errors should be actionable+- chat must not block normal PortOS use++## Integration with existing PortOS surfaces++### Chief of Staff+Relationship:+- CoS remains an autonomous/managed system surface+- OpenClaw chat is a direct operator conversation surface++Possible links:+- "Ask about this CoS task"+- "Open in Operator Chat"+- "Send BTW / additional context"++### Messages+Relationship:+- Messages page manages external communications/accounts+- OpenClaw Operator Chat is an internal/local console++This distinction should stay clear in the UI.++### Review+Assistant outputs that need human attention could eventually create Review items.++### Apps / Instances / DevTools / Shell+These are strong context sources for chat attachments and operator actions.++## Failure modes to design for++- OpenClaw unreachable+- OpenClaw configured incorrectly+- runtime session missing/expired+- streaming disconnects+- PortOS page context too large/noisy+- user accidentally sharing more context than intended+- partial feature deployment on instances without OpenClaw++## Graceful degradation++If OpenClaw is not configured:+- hide the page by default or show a setup screen+- do not break PortOS navigation+- do not throw noisy errors in unrelated pages++If runtime is unavailable:+- show disconnected status+- preserve local UI state where possible+- allow retry/reconnect++## Suggested implementation order++### Step 1 — Spec and extension-point audit+- confirm PortOS route/page placement+- confirm local config pattern+- confirm whether proxying through PortOS server is preferable to direct browser calls++### Step 2 — Thin server adapter+- add OpenClaw integration module+- add status/session/message proxy routes+- keep adapter minimal++### Step 3 — MVP UI page+- session list+- message timeline+- composer+- status badge++### Step 4 — context attachments+- current page/app/task context chips+- explicit attach/send flow++### Step 5 — runtime/operator extras+- subagents+- jobs+- session status+- linked review actions++## Recommended design decisions++1. **Keep the product generic**+ - no private assistant identity in public code++2. **Use local/private config for identity and topology**+ - assistant name, endpoint, role, machine map stay local++3. **Proxy through PortOS server first**+ - keeps auth/config simpler+ - avoids browser-side exposure of private runtime details+ - fits existing PortOS API patterns++4. **Do not merge this into Messages**+ - operator chat is a different domain than email/SMS/Telegram messaging++5. **Keep OpenClaw optional**+ - PortOS must still work cleanly without it++## Open questions++1. Should OpenClaw chat live as a top-level page or under Chief of Staff?+ - My recommendation: top-level page or top-level tool, not hidden under CoS++2. Should PortOS support multiple runtimes or one default runtime first?+ - My recommendation: one default runtime first, design for future plurality++3. Should chat sessions be created/managed by PortOS or discovered from OpenClaw?+ - My recommendation: discover existing sessions first, optionally allow PortOS to create a dedicated operator session++4. Should tool activity be shown in the timeline from the start?+ - My recommendation: basic status first, detailed tool activity later++## Initial deliverables++- this feature spec+- PortOS extension-point audit+- minimal server-side OpenClaw adapter+- minimal `/openclaw` page+- local private config example (git-ignored)++## Bottom line++PortOS should gain a **generic, optional, first-party OpenClaw operator chat surface** so users can communicate with their assistant/runtime directly over their private network instead of depending on Telegram.++That feature should be:+- generic in product code+- private in identity/config+- optional per instance+- aligned with existing PortOS CoS, socket, and Tailscale architecturediff --git a/server/index.js b/server/index.jsindex db88f2ff3c..484e8365bf 100644--- a/server/index.js+++ b/server/index.js@@ -68,6 +68,7 @@ import loopsRoutes from './routes/loops.js';import characterRoutes from './routes/character.js';import toolsRoutes from './routes/tools.js';import imageGenRoutes from './routes/imageGen.js';+import openclawRoutes from './routes/openclaw.js';import { ensureSelf, startPolling } from './services/instances.js';import { initSyncLog } from './services/brainSyncLog.js';import { backfillOriginInstanceId } from './services/brainStorage.js';@@ -272,6 +273,7 @@ app.use('/api/loops', loopsRoutes);app.use('/api/character', characterRoutes);app.use('/api/tools', toolsRoutes);app.use('/api/image-gen', imageGenRoutes);+app.use('/api/openclaw', openclawRoutes);// Initialize agent automation scheduler and action executorautomationScheduler.init().catch(err => console.error(`❌ Agent scheduler init failed: ${err.message}`));diff --git a/server/integrations/openclaw/api.js b/server/integrations/openclaw/api.jsnew file mode 100644index 0000000000..6b6a9e77d8--- /dev/null+++ b/server/integrations/openclaw/api.js@@ -0,0 +1,318 @@+import { join } from 'path';+import { readJSONFile, PATHS } from '../../lib/fileUtils.js';+import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';+import { ServerError } from '../../lib/errorHandler.js';++const CONFIG_FILE = join(PATHS.data, 'openclaw', 'config.json');+const DEFAULT_TIMEOUT_MS = 15000;+const DEFAULT_PATHS = {+ status: '/status',+ sessions: '/sessions',+ sessionMessages: '/sessions/:sessionId/messages',+ sendMessage: '/sessions/:sessionId/messages'+};++function parseBoolean(value) {+ if (typeof value === 'boolean') return value;+ if (typeof value !== 'string') return undefined;+ if (value === 'true') return true;+ if (value === 'false') return false;+ return undefined;+}++function pickFirst(...values) {+ for (const value of values) {+ if (value !== undefined && value !== null && value !== '') {+ return value;+ }+ }+ return undefined;+}++function withLeadingSlash(path) {+ if (!path) return '';+ return path.startsWith('/') ? path : `/${path}`;+}++function joinUrl(baseUrl, path) {+ return new URL(withLeadingSlash(path), baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`).toString();+}++function buildPath(template, params = {}) {+ return Object.entries(params).reduce(+ (path, [key, value]) => path.replaceAll(`:${key}`, encodeURIComponent(String(value))),+ template+ );+}++function toArray(value) {+ if (Array.isArray(value)) return value;+ if (Array.isArray(value?.items)) return value.items;+ if (Array.isArray(value?.sessions)) return value.sessions;+ if (Array.isArray(value?.messages)) return value.messages;+ if (Array.isArray(value?.data)) return value.data;+ return [];+}++function parseUpstreamBody(text) {+ if (!text) return null;++ try {+ return JSON.parse(text);+ } catch {+ return { message: text };+ }+}++function extractMessageContent(value) {+ if (typeof value === 'string') return value;+ if (!value) return '';++ if (Array.isArray(value)) {+ return value.map(extractMessageContent).filter(Boolean).join('\n\n');+ }++ if (typeof value === 'object') {+ if (typeof value.text === 'string') return value.text;+ if (typeof value.content === 'string') return value.content;+ if (typeof value.body === 'string') return value.body;+ if (typeof value.message === 'string') return value.message;+ if (value.parts) return extractMessageContent(value.parts);+ if (value.content?.parts) return extractMessageContent(value.content.parts);+ }++ return '';+}++function normalizeRole(input) {+ const role = String(input || '').toLowerCase();+ if (['assistant', 'model', 'agent', 'bot'].includes(role)) return 'assistant';+ if (['user', 'operator', 'human'].includes(role)) return 'user';+ if (['system', 'tool'].includes(role)) return role;+ return role || 'assistant';+}++function normalizeSession(session) {+ const id = pickFirst(session?.id, session?.sessionId, session?.slug, session?.name, session?.title);+ if (!id) return null;++ return {+ id: String(id),+ title: pickFirst(session?.title, session?.label, session?.name, session?.sessionId, id),+ label: pickFirst(session?.label, session?.name, session?.title, id),+ status: pickFirst(session?.status, session?.state, null) || null,+ messageCount: pickFirst(session?.messageCount, session?.messagesCount, session?.count, null),+ lastMessageAt: pickFirst(session?.lastMessageAt, session?.updatedAt, session?.lastActivityAt, session?.createdAt, null),+ raw: session+ };+}++function normalizeMessage(message, index = 0) {+ return {+ id: pickFirst(message?.id, message?.messageId, `${message?.createdAt || message?.timestamp || 'message'}-${index}`),+ role: normalizeRole(pickFirst(message?.role, message?.author, message?.sender, message?.type)),+ content: extractMessageContent(pickFirst(message?.content, message?.text, message?.body, message?.message, message)),+ createdAt: pickFirst(message?.createdAt, message?.timestamp, message?.time, message?.date, null),+ status: pickFirst(message?.status, message?.state, null),+ raw: message+ };+}++function normalizeStatusPayload(payload, config, reachable, errorMessage) {+ return {+ configured: config.configured,+ enabled: config.enabled,+ reachable,+ label: pickFirst(payload?.label, payload?.name, config.label, 'OpenClaw Runtime'),+ defaultSession: pickFirst(payload?.defaultSession, payload?.defaultSessionId, config.defaultSession, null) || null,+ message: errorMessage || pickFirst(payload?.message, payload?.statusMessage, null) || null,+ runtime: payload && typeof payload === 'object' ? payload : null+ };+}++async function loadConfig() {+ const fileConfig = await readJSONFile(CONFIG_FILE, {}, { logError: false });+ const envEnabled = parseBoolean(process.env.OPENCLAW_ENABLED);+ const enabled = pickFirst(envEnabled, fileConfig.enabled, true);+ const baseUrl = pickFirst(process.env.OPENCLAW_BASE_URL, fileConfig.baseUrl, '').trim();+ const configured = enabled !== false && Boolean(baseUrl);++ return {+ enabled,+ configured,+ baseUrl,+ authToken: pickFirst(process.env.OPENCLAW_AUTH_TOKEN, fileConfig.authToken, ''),+ authHeader: pickFirst(process.env.OPENCLAW_AUTH_HEADER, fileConfig.authHeader, 'Authorization'),+ authScheme: pickFirst(process.env.OPENCLAW_AUTH_SCHEME, fileConfig.authScheme, 'Bearer'),+ label: pickFirst(process.env.OPENCLAW_LABEL, fileConfig.label, 'OpenClaw Runtime'),+ defaultSession: pickFirst(process.env.OPENCLAW_DEFAULT_SESSION, fileConfig.defaultSession, null),+ timeoutMs: Number.parseInt(String(pickFirst(process.env.OPENCLAW_TIMEOUT_MS, fileConfig.timeoutMs, DEFAULT_TIMEOUT_MS)), 10) || DEFAULT_TIMEOUT_MS,+ paths: {+ ...DEFAULT_PATHS,+ ...(fileConfig.paths || {})+ }+ };+}++function getAuthHeaders(config) {+ if (!config.authToken) return {};+ const headerValue = config.authScheme === null || config.authScheme === ''+ ? config.authToken+ : `${config.authScheme} ${config.authToken}`;+ return {+ [config.authHeader]: headerValue+ };+}++async function openClawRequest(config, path, { method = 'GET', query, body } = {}) {+ if (!config.configured) {+ throw new ServerError('OpenClaw is not configured', {+ status: 503,+ code: 'OPENCLAW_UNCONFIGURED'+ });+ }++ const url = new URL(joinUrl(config.baseUrl, path));+ if (query) {+ for (const [key, value] of Object.entries(query)) {+ if (value !== undefined && value !== null && value !== '') {+ url.searchParams.set(key, String(value));+ }+ }+ }++ let response;+ try {+ response = await fetchWithTimeout(url.toString(), {+ method,+ headers: {+ Accept: 'application/json',+ ...getAuthHeaders(config),+ ...(body ? { 'Content-Type': 'application/json' } : {})+ },+ ...(body ? { body: JSON.stringify(body) } : {})+ }, config.timeoutMs);+ } catch (err) {+ if (err?.name === 'AbortError') {+ throw new ServerError('OpenClaw request timed out', {+ status: 504,+ code: 'OPENCLAW_TIMEOUT'+ });+ }++ throw new ServerError('OpenClaw runtime is unreachable', {+ status: 502,+ code: 'OPENCLAW_UNREACHABLE'+ });+ }++ let payload = null;+ if (response.status !== 204) {+ const text = await response.text();+ payload = parseUpstreamBody(text);+ }++ if (!response.ok) {+ const upstreamMessage = pickFirst(payload?.error, payload?.message, null);+ let code = 'OPENCLAW_REQUEST_FAILED';+ let message = upstreamMessage || `OpenClaw request failed with HTTP ${response.status}`;+ let status = 502;++ if (response.status === 401 || response.status === 403) {+ code = 'OPENCLAW_UNAUTHORIZED';+ message = upstreamMessage || 'OpenClaw rejected the configured credentials';+ } else if (response.status === 404) {+ code = 'OPENCLAW_NOT_FOUND';+ message = upstreamMessage || 'OpenClaw endpoint is not available';+ } else if (response.status >= 500) {+ code = 'OPENCLAW_UPSTREAM_ERROR';+ message = upstreamMessage || 'OpenClaw runtime failed to process the request';+ status = 503;+ }++ throw new ServerError(message, { status, code });+ }++ return payload;+}++export async function getRuntimeStatus() {+ const config = await loadConfig();+ if (!config.configured) {+ return normalizeStatusPayload(null, config, false, 'OpenClaw is not configured');+ }++ try {+ const payload = await openClawRequest(config, config.paths.status);+ return normalizeStatusPayload(payload, config, true, null);+ } catch (err) {+ if (err.code === 'OPENCLAW_NOT_FOUND') {+ try {+ await openClawRequest(config, config.paths.sessions);+ return normalizeStatusPayload(null, config, true, null);+ } catch (fallbackErr) {+ return normalizeStatusPayload(null, config, false, fallbackErr.message);+ }+ }++ return normalizeStatusPayload(null, config, false, err.message);+ }+}++export async function listSessions() {+ const config = await loadConfig();+ const payload = await openClawRequest(config, config.paths.sessions);+ const sessions = toArray(payload)+ .map(normalizeSession)+ .filter(Boolean);++ return {+ configured: true,+ reachable: true,+ label: config.label,+ defaultSession: config.defaultSession,+ sessions+ };+}++export async function getSessionMessages(sessionId, { limit = 50 } = {}) {+ const config = await loadConfig();+ const path = buildPath(config.paths.sessionMessages, { sessionId });+ const payload = await openClawRequest(config, path, { query: { limit } });+ const messages = toArray(payload)+ .map((message, index) => normalizeMessage(message, index))+ .filter(message => message.content || message.role || message.createdAt);++ return {+ configured: true,+ reachable: true,+ sessionId,+ messages+ };+}++export async function sendSessionMessage(sessionId, { message, context } = {}) {+ const config = await loadConfig();+ const path = buildPath(config.paths.sendMessage, { sessionId });+ const payload = await openClawRequest(config, path, {+ method: 'POST',+ body: {+ sessionId,+ message,+ text: message,+ content: message,+ role: 'user',+ ...(context !== undefined ? { context } : {})+ }+ });++ const normalizedReply = payload ? normalizeMessage(payload) : null;++ return {+ ok: true,+ configured: true,+ reachable: true,+ sessionId,+ message: normalizedReply+ };+}diff --git a/server/routes/openclaw.js b/server/routes/openclaw.jsnew file mode 100644index 0000000000..ff03ce20c8--- /dev/null+++ b/server/routes/openclaw.js@@ -0,0 +1,83 @@+import express from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import {+ getRuntimeStatus,+ listSessions,+ getSessionMessages,+ sendSessionMessage+} from '../integrations/openclaw/api.js';++const router = express.Router();++const sendMessageSchema = z.object({+ message: z.string().trim().min(1),+ context: z.unknown().optional()+});++router.get('/status', asyncHandler(async (req, res) => {+ const status = await getRuntimeStatus();+ res.json(status);+}));++router.get('/sessions', asyncHandler(async (req, res) => {+ const status = await getRuntimeStatus();+ if (!status.configured) {+ return res.json({+ configured: false,+ reachable: false,+ sessions: [],+ defaultSession: status.defaultSession || null,+ label: status.label+ });+ }++ const result = await listSessions();+ res.json(result);+}));++router.get('/sessions/:id/messages', asyncHandler(async (req, res) => {+ const sessionId = req.params.id?.trim();+ if (!sessionId) {+ throw new ServerError('Session ID is required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ let limit = req.query.limit !== undefined ? Number.parseInt(String(req.query.limit), 10) : 50;+ if (Number.isNaN(limit) || limit <= 0) limit = 50;+ if (limit > 200) limit = 200;++ const status = await getRuntimeStatus();+ if (!status.configured) {+ return res.json({+ configured: false,+ reachable: false,+ sessionId,+ messages: []+ });+ }++ const result = await getSessionMessages(sessionId, { limit });+ res.json(result);+}));++router.post('/sessions/:id/messages', asyncHandler(async (req, res) => {+ const sessionId = req.params.id?.trim();+ if (!sessionId) {+ throw new ServerError('Session ID is required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ const payload = validateRequest(sendMessageSchema, req.body);+ const status = await getRuntimeStatus();+ if (!status.configured) {+ throw new ServerError('OpenClaw is not configured for this PortOS instance', {+ status: 503,+ code: 'OPENCLAW_UNCONFIGURED'+ });+ }++ const result = await sendSessionMessage(sessionId, payload);+ res.json(result);+}));++export default router;