Add chat sidecar and verified inference routes
This commit is contained in:
@@ -0,0 +1,346 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
|
||||
export const STORE_DIR = process.env.NEMOCLAW_DASHBOARD_STATE_DIR || path.join(os.homedir(), ".nemoclaw-dashboard")
|
||||
export const STORE_PATH = process.env.INTER_SANDBOX_CHAT_STORE || path.join(STORE_DIR, "inter-sandbox-chat.json")
|
||||
export const MAX_MESSAGES_PER_ROOM = Number.parseInt(process.env.INTER_SANDBOX_CHAT_ROOM_LIMIT || "500", 10)
|
||||
export const MAX_MESSAGE_LENGTH = Number.parseInt(process.env.INTER_SANDBOX_CHAT_MESSAGE_LIMIT || "8000", 10)
|
||||
|
||||
const ACK_STATUSES = new Set(["received", "processed", "failed"])
|
||||
|
||||
export function nowIso() {
|
||||
return new Date().toISOString()
|
||||
}
|
||||
|
||||
export function cleanRoom(value) {
|
||||
const room = String(value || "lobby")
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9._-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 80)
|
||||
return room || "lobby"
|
||||
}
|
||||
|
||||
export function cleanText(value, fallback = "") {
|
||||
return String(value ?? fallback).trim()
|
||||
}
|
||||
|
||||
export function cleanOrigin(value) {
|
||||
return cleanText(value, "sandbox").toLowerCase() === "operator" ? "operator" : "sandbox"
|
||||
}
|
||||
|
||||
export function cleanAckStatus(value) {
|
||||
const status = cleanText(value, "received").toLowerCase()
|
||||
return ACK_STATUSES.has(status) ? status : "received"
|
||||
}
|
||||
|
||||
export function normalizeStringArray(value) {
|
||||
if (!Array.isArray(value)) return []
|
||||
return Array.from(new Set(value.map((entry) => cleanText(entry)).filter(Boolean)))
|
||||
}
|
||||
|
||||
export function messageNeedsAck(message) {
|
||||
return message?.origin === "operator" && message?.requiresAck === true
|
||||
}
|
||||
|
||||
export function messageMatchesOrigins(message, origins = ["operator"]) {
|
||||
const allowedOrigins = normalizeStringArray(origins).map((origin) => cleanOrigin(origin))
|
||||
return allowedOrigins.includes(cleanOrigin(message?.origin))
|
||||
}
|
||||
|
||||
export function messageFromActor(message, { agentId, sandboxId, sandboxName } = {}) {
|
||||
const sender = cleanText(message?.sender)
|
||||
if (!sender) return false
|
||||
return (
|
||||
Boolean(agentId && sender === cleanText(agentId)) ||
|
||||
Boolean(sandboxId && sender === cleanText(sandboxId)) ||
|
||||
Boolean(sandboxName && sender === cleanText(sandboxName))
|
||||
)
|
||||
}
|
||||
|
||||
export function roomData(store, roomId) {
|
||||
const existing = store.rooms?.[roomId] && typeof store.rooms[roomId] === "object" ? store.rooms[roomId] : {}
|
||||
const messages = Array.isArray(existing.messages) ? existing.messages : []
|
||||
const receipts = existing.receipts && typeof existing.receipts === "object" ? existing.receipts : {}
|
||||
const cursors = existing.cursors && typeof existing.cursors === "object" ? existing.cursors : {}
|
||||
return { ...existing, messages, receipts, cursors }
|
||||
}
|
||||
|
||||
export async function readStore() {
|
||||
try {
|
||||
const raw = await readFile(STORE_PATH, "utf8")
|
||||
const parsed = JSON.parse(raw)
|
||||
return parsed && typeof parsed === "object" && parsed.rooms && typeof parsed.rooms === "object"
|
||||
? parsed
|
||||
: { rooms: {} }
|
||||
} catch {
|
||||
return { rooms: {} }
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeStore(store) {
|
||||
await mkdir(path.dirname(STORE_PATH), { recursive: true, mode: 0o700 })
|
||||
await writeFile(STORE_PATH, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 })
|
||||
}
|
||||
|
||||
export function messageTargetsAgent(message, { agentId, sandboxId, sandboxName, includeBroadcast = false } = {}) {
|
||||
const targets = message?.targets && typeof message.targets === "object" ? message.targets : {}
|
||||
const targetAgentIds = normalizeStringArray(targets.agentIds)
|
||||
const targetSandboxIds = normalizeStringArray(targets.sandboxIds)
|
||||
const targetSandboxNames = normalizeStringArray(targets.sandboxNames)
|
||||
const hasExplicitTargets = targetAgentIds.length > 0 || targetSandboxIds.length > 0 || targetSandboxNames.length > 0
|
||||
if (!hasExplicitTargets) {
|
||||
if (includeBroadcast) return true
|
||||
const room = cleanRoom(message?.room)
|
||||
return Boolean(
|
||||
room &&
|
||||
(
|
||||
(sandboxId && room === cleanRoom(sandboxId)) ||
|
||||
(sandboxName && room === cleanRoom(sandboxName)) ||
|
||||
(agentId && room === cleanRoom(agentId))
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
const agent = cleanText(agentId)
|
||||
const sandbox = cleanText(sandboxId)
|
||||
const name = cleanText(sandboxName)
|
||||
return (
|
||||
Boolean(agent && targetAgentIds.includes(agent)) ||
|
||||
Boolean(sandbox && targetSandboxIds.includes(sandbox)) ||
|
||||
Boolean(name && targetSandboxNames.includes(name))
|
||||
)
|
||||
}
|
||||
|
||||
export function receiptForActor(room, messageId, actorId) {
|
||||
const receipts = room.receipts?.[messageId] && typeof room.receipts[messageId] === "object" ? room.receipts[messageId] : {}
|
||||
return receipts[actorId] && typeof receipts[actorId] === "object" ? receipts[actorId] : null
|
||||
}
|
||||
|
||||
export async function postChatMessage({
|
||||
room,
|
||||
sender,
|
||||
message,
|
||||
origin = "sandbox",
|
||||
ackToken,
|
||||
targetAgentIds,
|
||||
targetSandboxIds,
|
||||
targetSandboxNames,
|
||||
}) {
|
||||
const store = await readStore()
|
||||
const roomId = cleanRoom(room)
|
||||
const senderName = cleanText(sender, "anonymous-sandbox").slice(0, 120) || "anonymous-sandbox"
|
||||
const text = cleanText(message).slice(0, MAX_MESSAGE_LENGTH)
|
||||
if (!text) return { ok: false, error: "message is required" }
|
||||
|
||||
const currentRoom = roomData(store, roomId)
|
||||
const messageOrigin = cleanOrigin(origin)
|
||||
const requiresAck = messageOrigin === "operator"
|
||||
const targets = {
|
||||
agentIds: normalizeStringArray(targetAgentIds),
|
||||
sandboxIds: normalizeStringArray(targetSandboxIds),
|
||||
sandboxNames: normalizeStringArray(targetSandboxNames),
|
||||
}
|
||||
const hasTargets = targets.agentIds.length > 0 || targets.sandboxIds.length > 0 || targets.sandboxNames.length > 0
|
||||
const entry = {
|
||||
id: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,
|
||||
at: nowIso(),
|
||||
room: roomId,
|
||||
sender: senderName,
|
||||
origin: messageOrigin,
|
||||
requiresAck,
|
||||
...(requiresAck ? { ackToken: cleanText(ackToken).slice(0, 160) || undefined } : {}),
|
||||
...(hasTargets ? { targets } : {}),
|
||||
message: text,
|
||||
}
|
||||
|
||||
store.rooms[roomId] = {
|
||||
...currentRoom,
|
||||
updatedAt: entry.at,
|
||||
messages: [...currentRoom.messages, entry].slice(-Math.max(1, MAX_MESSAGES_PER_ROOM)),
|
||||
receipts: currentRoom.receipts,
|
||||
cursors: currentRoom.cursors,
|
||||
}
|
||||
await writeStore(store)
|
||||
return { ok: true, room: roomId, message: entry }
|
||||
}
|
||||
|
||||
function writeReceiptToRoom(currentRoom, message, actorId, { agentId, sandboxId, status = "received", note }) {
|
||||
const roomId = cleanRoom(message.room)
|
||||
const receiptAt = nowIso()
|
||||
const existingReceipts = currentRoom.receipts[message.id] && typeof currentRoom.receipts[message.id] === "object"
|
||||
? currentRoom.receipts[message.id]
|
||||
: {}
|
||||
const existing = existingReceipts[actorId] && typeof existingReceipts[actorId] === "object" ? existingReceipts[actorId] : {}
|
||||
const receipt = {
|
||||
...existing,
|
||||
room: roomId,
|
||||
messageId: message.id,
|
||||
ackToken: message.ackToken || null,
|
||||
agentId: cleanText(agentId, actorId) || actorId,
|
||||
sandboxId: cleanText(sandboxId) || null,
|
||||
status: cleanAckStatus(status),
|
||||
at: receiptAt,
|
||||
firstReceivedAt: existing.firstReceivedAt || receiptAt,
|
||||
...(note ? { note: cleanText(note).slice(0, 1000) } : {}),
|
||||
}
|
||||
|
||||
currentRoom.receipts[message.id] = {
|
||||
...existingReceipts,
|
||||
[actorId]: receipt,
|
||||
}
|
||||
return { receipt, receiptAt }
|
||||
}
|
||||
|
||||
export async function recordChatMessageReceipt({ room, messageId, agentId, sandboxId, status = "received", note }) {
|
||||
const store = await readStore()
|
||||
const roomId = cleanRoom(room)
|
||||
const currentRoom = roomData(store, roomId)
|
||||
const message = currentRoom.messages.find((entry) => entry.id === messageId)
|
||||
if (!message) return { ok: false, error: "message not found", room: roomId, messageId }
|
||||
|
||||
const actorId = cleanText(sandboxId) || cleanText(agentId, "anonymous-agent") || "anonymous-agent"
|
||||
const { receipt, receiptAt } = writeReceiptToRoom(currentRoom, message, actorId, {
|
||||
agentId,
|
||||
sandboxId,
|
||||
status,
|
||||
note,
|
||||
})
|
||||
store.rooms[roomId] = {
|
||||
...currentRoom,
|
||||
updatedAt: receiptAt,
|
||||
}
|
||||
await writeStore(store)
|
||||
return { ok: true, room: roomId, messageId, receipt }
|
||||
}
|
||||
|
||||
export async function ackChatMessage({ room, messageId, ackToken, agentId, sandboxId, status = "received", note }) {
|
||||
const store = await readStore()
|
||||
const roomId = cleanRoom(room)
|
||||
const currentRoom = roomData(store, roomId)
|
||||
const message = currentRoom.messages.find((entry) => entry.id === messageId)
|
||||
if (!message) return { ok: false, error: "message not found", room: roomId, messageId }
|
||||
if (!messageNeedsAck(message)) {
|
||||
return {
|
||||
ok: false,
|
||||
error: "message does not require acknowledgement",
|
||||
room: roomId,
|
||||
messageId,
|
||||
origin: message.origin || "sandbox",
|
||||
}
|
||||
}
|
||||
|
||||
const providedAckToken = cleanText(ackToken)
|
||||
if (providedAckToken && message.ackToken && providedAckToken !== message.ackToken) {
|
||||
return { ok: false, error: "ack token does not match message", room: roomId, messageId }
|
||||
}
|
||||
|
||||
const actorId = cleanText(sandboxId) || cleanText(agentId, "anonymous-agent") || "anonymous-agent"
|
||||
const { receipt, receiptAt } = writeReceiptToRoom(currentRoom, message, actorId, {
|
||||
agentId,
|
||||
sandboxId,
|
||||
status,
|
||||
note,
|
||||
})
|
||||
store.rooms[roomId] = {
|
||||
...currentRoom,
|
||||
updatedAt: receiptAt,
|
||||
}
|
||||
await writeStore(store)
|
||||
return { ok: true, room: roomId, messageId, receipt }
|
||||
}
|
||||
|
||||
export async function claimTargetedMessages({
|
||||
room = "lobby",
|
||||
agentId,
|
||||
sandboxId,
|
||||
sandboxName,
|
||||
limit = 5,
|
||||
includeBroadcast = false,
|
||||
autoAck = true,
|
||||
origins = ["operator"],
|
||||
excludeSelf = true,
|
||||
latestOnly = false,
|
||||
cursorId,
|
||||
receiptNote = "claimed by inter-sandbox chat cursor",
|
||||
}) {
|
||||
const store = await readStore()
|
||||
const roomId = cleanRoom(room)
|
||||
const currentRoom = roomData(store, roomId)
|
||||
const actorId = cleanText(sandboxId) || cleanText(agentId, "anonymous-agent") || "anonymous-agent"
|
||||
const cursorKey = cleanText(cursorId) || actorId
|
||||
const cursor = currentRoom.cursors[cursorKey] && typeof currentRoom.cursors[cursorKey] === "object" ? currentRoom.cursors[cursorKey] : {}
|
||||
const afterId = cleanText(cursor.lastSeenMessageId)
|
||||
const start = afterId ? currentRoom.messages.findIndex((message) => message.id === afterId) + 1 : 0
|
||||
const matchedMessages = currentRoom.messages
|
||||
.slice(Math.max(0, start))
|
||||
.filter((message) => messageMatchesOrigins(message, origins))
|
||||
.filter((message) => messageTargetsAgent(message, { agentId, sandboxId, sandboxName, includeBroadcast }))
|
||||
.filter((message) => !excludeSelf || !messageFromActor(message, { agentId, sandboxId, sandboxName }))
|
||||
.filter((message) => !["processed", "failed"].includes(receiptForActor(currentRoom, message.id, actorId)?.status))
|
||||
const messages = (latestOnly ? matchedMessages.slice(-1) : matchedMessages)
|
||||
.slice(0, Math.max(1, Math.min(50, Number(limit) || 5)))
|
||||
|
||||
if (messages.length === 0) {
|
||||
return { ok: true, room: roomId, agentId: cleanText(agentId), sandboxId: cleanText(sandboxId), count: 0, messages: [] }
|
||||
}
|
||||
|
||||
const receiptAt = nowIso()
|
||||
let receiptsChanged = false
|
||||
if (autoAck) {
|
||||
for (const message of messages) {
|
||||
const existing = receiptForActor(currentRoom, message.id, actorId) || {}
|
||||
if (existing.status) continue
|
||||
writeReceiptToRoom(currentRoom, message, actorId, {
|
||||
agentId,
|
||||
sandboxId,
|
||||
status: "received",
|
||||
note: receiptNote,
|
||||
})
|
||||
receiptsChanged = true
|
||||
}
|
||||
}
|
||||
|
||||
currentRoom.cursors[cursorKey] = {
|
||||
...cursor,
|
||||
lastSeenMessageId: messages[messages.length - 1].id,
|
||||
updatedAt: receiptAt,
|
||||
}
|
||||
store.rooms[roomId] = {
|
||||
...currentRoom,
|
||||
updatedAt: receiptsChanged ? receiptAt : currentRoom.updatedAt,
|
||||
}
|
||||
await writeStore(store)
|
||||
return {
|
||||
ok: true,
|
||||
room: roomId,
|
||||
agentId: cleanText(agentId),
|
||||
sandboxId: cleanText(sandboxId),
|
||||
count: messages.length,
|
||||
messages,
|
||||
}
|
||||
}
|
||||
|
||||
export async function claimOperatorMessages(options) {
|
||||
return await claimTargetedMessages({
|
||||
...options,
|
||||
origins: ["operator"],
|
||||
excludeSelf: false,
|
||||
})
|
||||
}
|
||||
|
||||
export async function listRooms() {
|
||||
const store = await readStore()
|
||||
return Object.entries(store.rooms)
|
||||
.map(([room, value]) => ({
|
||||
room,
|
||||
updatedAt: value?.updatedAt || null,
|
||||
messageCount: Array.isArray(value?.messages) ? value.messages.length : 0,
|
||||
latestMessageId: Array.isArray(value?.messages) && value.messages.length > 0
|
||||
? value.messages[value.messages.length - 1].id
|
||||
: null,
|
||||
}))
|
||||
.sort((a, b) => String(b.updatedAt || "").localeCompare(String(a.updatedAt || "")))
|
||||
}
|
||||
@@ -1,50 +1,19 @@
|
||||
#!/usr/bin/env node
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
||||
import { z } from "zod"
|
||||
|
||||
const STORE_DIR = process.env.NEMOCLAW_DASHBOARD_STATE_DIR || path.join(os.homedir(), ".nemoclaw-dashboard")
|
||||
const STORE_PATH = process.env.INTER_SANDBOX_CHAT_STORE || path.join(STORE_DIR, "inter-sandbox-chat.json")
|
||||
const MAX_MESSAGES_PER_ROOM = Number.parseInt(process.env.INTER_SANDBOX_CHAT_ROOM_LIMIT || "500", 10)
|
||||
const MAX_MESSAGE_LENGTH = Number.parseInt(process.env.INTER_SANDBOX_CHAT_MESSAGE_LIMIT || "8000", 10)
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString()
|
||||
}
|
||||
|
||||
function cleanRoom(value) {
|
||||
const room = String(value || "lobby")
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9._-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 80)
|
||||
return room || "lobby"
|
||||
}
|
||||
|
||||
function cleanText(value, fallback = "") {
|
||||
return String(value ?? fallback).trim()
|
||||
}
|
||||
|
||||
async function readStore() {
|
||||
try {
|
||||
const raw = await readFile(STORE_PATH, "utf8")
|
||||
const parsed = JSON.parse(raw)
|
||||
return parsed && typeof parsed === "object" && parsed.rooms && typeof parsed.rooms === "object"
|
||||
? parsed
|
||||
: { rooms: {} }
|
||||
} catch {
|
||||
return { rooms: {} }
|
||||
}
|
||||
}
|
||||
|
||||
async function writeStore(store) {
|
||||
await mkdir(path.dirname(STORE_PATH), { recursive: true, mode: 0o700 })
|
||||
await writeFile(STORE_PATH, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 })
|
||||
}
|
||||
import {
|
||||
MAX_MESSAGE_LENGTH,
|
||||
ackChatMessage,
|
||||
claimOperatorMessages,
|
||||
cleanRoom,
|
||||
cleanText,
|
||||
listRooms,
|
||||
messageNeedsAck,
|
||||
postChatMessage,
|
||||
readStore,
|
||||
roomData,
|
||||
} from "./inter-sandbox-chat-core.mjs"
|
||||
|
||||
function asText(payload) {
|
||||
return {
|
||||
@@ -59,42 +28,65 @@ function asText(payload) {
|
||||
|
||||
const server = new McpServer({
|
||||
name: "inter-sandbox-chat",
|
||||
version: "0.1.0",
|
||||
version: "0.3.0",
|
||||
})
|
||||
|
||||
server.registerTool(
|
||||
"post_message",
|
||||
{
|
||||
title: "Post Message",
|
||||
description: "Post a message into an inter-sandbox chat room. Use a stable sender name such as the sandbox name.",
|
||||
description: "Post a message into an inter-sandbox chat room. Sandbox-to-sandbox messages are normal chat and do not need acknowledgements. Operator-injected messages should set origin='operator'; only those messages are marked for agent acknowledgement.",
|
||||
inputSchema: {
|
||||
room: z.string().default("lobby").describe("Chat room name. Defaults to lobby."),
|
||||
sender: z.string().default("anonymous-sandbox").describe("Sender name, usually the sandbox or agent name."),
|
||||
message: z.string().min(1).max(MAX_MESSAGE_LENGTH).describe("Message text to share with other sandboxes."),
|
||||
origin: z.enum(["sandbox", "operator"]).default("sandbox").describe("Message origin. Use 'operator' only for human/operator-injected chats that agents should acknowledge."),
|
||||
ackToken: z.string().optional().describe("Optional stable token supplied by the operator UI. Stored only for operator messages; omitted sandbox messages do not need receipts."),
|
||||
targetSandboxIds: z.array(z.string()).default([]).describe("Optional sandbox ids to notify. Use this for direct sandbox-to-sandbox chat without broadcasting a room."),
|
||||
targetSandboxNames: z.array(z.string()).default([]).describe("Optional sandbox names to notify. A room named for a sandbox also counts as targeted."),
|
||||
targetAgentIds: z.array(z.string()).default([]).describe("Optional sidecar/agent ids to notify."),
|
||||
},
|
||||
},
|
||||
async ({ room, sender, message }) => {
|
||||
const store = await readStore()
|
||||
const roomId = cleanRoom(room)
|
||||
const senderName = cleanText(sender, "anonymous-sandbox").slice(0, 120) || "anonymous-sandbox"
|
||||
const text = cleanText(message).slice(0, MAX_MESSAGE_LENGTH)
|
||||
if (!text) return asText({ ok: false, error: "message is required" })
|
||||
async ({ room, sender, message, origin, ackToken, targetSandboxIds, targetSandboxNames, targetAgentIds }) => {
|
||||
return asText(await postChatMessage({
|
||||
room,
|
||||
sender,
|
||||
message,
|
||||
origin,
|
||||
ackToken,
|
||||
targetSandboxIds,
|
||||
targetSandboxNames,
|
||||
targetAgentIds,
|
||||
}))
|
||||
},
|
||||
)
|
||||
|
||||
const messages = Array.isArray(store.rooms[roomId]?.messages) ? store.rooms[roomId].messages : []
|
||||
const entry = {
|
||||
id: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,
|
||||
at: nowIso(),
|
||||
room: roomId,
|
||||
sender: senderName,
|
||||
message: text,
|
||||
}
|
||||
|
||||
store.rooms[roomId] = {
|
||||
updatedAt: entry.at,
|
||||
messages: [...messages, entry].slice(-Math.max(1, MAX_MESSAGES_PER_ROOM)),
|
||||
}
|
||||
await writeStore(store)
|
||||
return asText({ ok: true, room: roomId, message: entry })
|
||||
server.registerTool(
|
||||
"post_operator_message",
|
||||
{
|
||||
title: "Post Operator Message",
|
||||
description: "Post a human/operator-injected chat into a room. Messages created by this tool always have origin='operator' and requiresAck=true so agents know to acknowledge receipt with ack_message. Use post_message for normal sandbox-to-sandbox chat.",
|
||||
inputSchema: {
|
||||
room: z.string().default("lobby").describe("Chat room name. Defaults to lobby."),
|
||||
sender: z.string().default("operator").describe("Operator or UI sender label."),
|
||||
message: z.string().min(1).max(MAX_MESSAGE_LENGTH).describe("Operator message text to share with agents."),
|
||||
ackToken: z.string().optional().describe("Optional stable token supplied by the operator UI for correlating receipts."),
|
||||
targetSandboxIds: z.array(z.string()).default([]).describe("Optional sandbox ids that should be woken by the controller sidecar."),
|
||||
targetSandboxNames: z.array(z.string()).default([]).describe("Optional sandbox names that should be woken by the controller sidecar."),
|
||||
targetAgentIds: z.array(z.string()).default([]).describe("Optional agent ids that should be woken by the controller sidecar."),
|
||||
},
|
||||
},
|
||||
async ({ room, sender, message, ackToken, targetSandboxIds, targetSandboxNames, targetAgentIds }) => {
|
||||
return asText(await postChatMessage({
|
||||
room,
|
||||
sender,
|
||||
message,
|
||||
origin: "operator",
|
||||
ackToken,
|
||||
targetSandboxIds,
|
||||
targetSandboxNames,
|
||||
targetAgentIds,
|
||||
}))
|
||||
},
|
||||
)
|
||||
|
||||
@@ -102,7 +94,7 @@ server.registerTool(
|
||||
"read_messages",
|
||||
{
|
||||
title: "Read Messages",
|
||||
description: "Read recent messages from an inter-sandbox chat room.",
|
||||
description: "Read recent messages from an inter-sandbox chat room. Important model behavior: acknowledge only operator-originated messages. If a returned message has origin='operator' and requiresAck=true, call ack_message immediately with status='received'. Do not acknowledge sandbox-originated messages.",
|
||||
inputSchema: {
|
||||
room: z.string().default("lobby").describe("Chat room name. Defaults to lobby."),
|
||||
afterId: z.string().optional().describe("Only return messages after this message id."),
|
||||
@@ -112,13 +104,129 @@ server.registerTool(
|
||||
async ({ room, afterId, limit }) => {
|
||||
const store = await readStore()
|
||||
const roomId = cleanRoom(room)
|
||||
const messages = Array.isArray(store.rooms[roomId]?.messages) ? store.rooms[roomId].messages : []
|
||||
const messages = roomData(store, roomId).messages
|
||||
const start = afterId ? messages.findIndex((message) => message.id === afterId) + 1 : 0
|
||||
const selected = messages.slice(Math.max(0, start)).slice(-limit)
|
||||
return asText({ ok: true, room: roomId, count: selected.length, messages: selected })
|
||||
},
|
||||
)
|
||||
|
||||
server.registerTool(
|
||||
"ack_message",
|
||||
{
|
||||
title: "Acknowledge Operator Message",
|
||||
description: "Acknowledge receipt or handling of an operator-originated chat message. Use this only for messages where origin='operator' and requiresAck=true. Never call this for sandbox-to-sandbox chat messages.",
|
||||
inputSchema: {
|
||||
room: z.string().default("lobby").describe("Chat room name. Defaults to lobby."),
|
||||
messageId: z.string().min(1).describe("Operator message id being acknowledged."),
|
||||
ackToken: z.string().optional().describe("Optional operator ack token. If the message has a token, a provided token must match it."),
|
||||
agentId: z.string().default("anonymous-agent").describe("Stable acknowledging agent id."),
|
||||
sandboxId: z.string().optional().describe("Stable sandbox id or sandbox name for UI grouping."),
|
||||
status: z.enum(["received", "processed", "failed"]).default("received").describe("Use received immediately after seeing the operator message, then processed or failed after acting on it."),
|
||||
note: z.string().max(1000).optional().describe("Optional short machine-readable or human-readable note."),
|
||||
},
|
||||
},
|
||||
async ({ room, messageId, ackToken, agentId, sandboxId, status, note }) => {
|
||||
return asText(await ackChatMessage({ room, messageId, ackToken, agentId, sandboxId, status, note }))
|
||||
},
|
||||
)
|
||||
|
||||
server.registerTool(
|
||||
"claim_operator_messages",
|
||||
{
|
||||
title: "Claim Operator Messages",
|
||||
description: "Return only new targeted operator messages for an agent/sandbox and optionally mark them received. Use this instead of polling read_messages from an LLM loop. Broadcast lobby messages are ignored unless includeBroadcast=true; messages in a room named for the sandbox are considered targeted.",
|
||||
inputSchema: {
|
||||
room: z.string().default("lobby").describe("Chat room name. Defaults to lobby."),
|
||||
agentId: z.string().default("anonymous-agent").describe("Stable claiming agent id."),
|
||||
sandboxId: z.string().optional().describe("Stable sandbox id for cursoring and receipt grouping."),
|
||||
sandboxName: z.string().optional().describe("Sandbox name for target matching."),
|
||||
limit: z.number().int().min(1).max(50).default(5).describe("Maximum number of new operator messages to claim."),
|
||||
includeBroadcast: z.boolean().default(false).describe("When true, untargeted operator messages in the room are also claimable."),
|
||||
autoAck: z.boolean().default(true).describe("When true, writes a received receipt before returning messages."),
|
||||
},
|
||||
},
|
||||
async ({ room, agentId, sandboxId, sandboxName, limit, includeBroadcast, autoAck }) => {
|
||||
return asText(await claimOperatorMessages({ room, agentId, sandboxId, sandboxName, limit, includeBroadcast, autoAck }))
|
||||
},
|
||||
)
|
||||
|
||||
server.registerTool(
|
||||
"get_message_receipts",
|
||||
{
|
||||
title: "Get Operator Message Receipts",
|
||||
description: "Return parseable acknowledgement state for an operator message. This is intended for operator UIs and orchestration; sandbox-to-sandbox messages normally have no receipts.",
|
||||
inputSchema: {
|
||||
room: z.string().default("lobby").describe("Chat room name. Defaults to lobby."),
|
||||
messageId: z.string().min(1).describe("Message id to inspect."),
|
||||
expectedAgents: z.array(z.string()).default([]).describe("Optional agent or sandbox ids expected to acknowledge the operator message."),
|
||||
},
|
||||
},
|
||||
async ({ room, messageId, expectedAgents }) => {
|
||||
const store = await readStore()
|
||||
const roomId = cleanRoom(room)
|
||||
const currentRoom = roomData(store, roomId)
|
||||
const message = currentRoom.messages.find((entry) => entry.id === messageId) || null
|
||||
const receipts = currentRoom.receipts[messageId] && typeof currentRoom.receipts[messageId] === "object"
|
||||
? currentRoom.receipts[messageId]
|
||||
: {}
|
||||
const expected = Array.from(new Set((expectedAgents || []).map((entry) => cleanText(entry)).filter(Boolean)))
|
||||
const pendingAgents = expected.filter((agent) => !receipts[agent])
|
||||
return asText({
|
||||
ok: true,
|
||||
room: roomId,
|
||||
messageId,
|
||||
requiresAck: messageNeedsAck(message),
|
||||
ackToken: message?.ackToken || null,
|
||||
receiptCount: Object.keys(receipts).length,
|
||||
receipts,
|
||||
expectedAgents: expected,
|
||||
pendingAgents,
|
||||
acknowledged: expected.length > 0 ? pendingAgents.length === 0 : Object.keys(receipts).length > 0,
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
server.registerTool(
|
||||
"list_operator_ack_status",
|
||||
{
|
||||
title: "List Operator Ack Status",
|
||||
description: "List recent operator messages with acknowledgement status for dashboards. Sandbox-originated messages are intentionally excluded because they do not require acknowledgements.",
|
||||
inputSchema: {
|
||||
room: z.string().default("lobby").describe("Chat room name. Defaults to lobby."),
|
||||
limit: z.number().int().min(1).max(100).default(50).describe("Maximum number of recent operator messages to inspect."),
|
||||
expectedAgents: z.array(z.string()).default([]).describe("Optional agent or sandbox ids expected to acknowledge each operator message."),
|
||||
},
|
||||
},
|
||||
async ({ room, limit, expectedAgents }) => {
|
||||
const store = await readStore()
|
||||
const roomId = cleanRoom(room)
|
||||
const currentRoom = roomData(store, roomId)
|
||||
const expected = Array.from(new Set((expectedAgents || []).map((entry) => cleanText(entry)).filter(Boolean)))
|
||||
const operatorMessages = currentRoom.messages
|
||||
.filter(messageNeedsAck)
|
||||
.slice(-limit)
|
||||
.map((message) => {
|
||||
const receipts = currentRoom.receipts[message.id] && typeof currentRoom.receipts[message.id] === "object"
|
||||
? currentRoom.receipts[message.id]
|
||||
: {}
|
||||
const pendingAgents = expected.filter((agent) => !receipts[agent])
|
||||
return {
|
||||
messageId: message.id,
|
||||
ackToken: message.ackToken || null,
|
||||
at: message.at,
|
||||
sender: message.sender,
|
||||
message: message.message,
|
||||
receiptCount: Object.keys(receipts).length,
|
||||
receipts,
|
||||
pendingAgents,
|
||||
acknowledged: expected.length > 0 ? pendingAgents.length === 0 : Object.keys(receipts).length > 0,
|
||||
}
|
||||
})
|
||||
return asText({ ok: true, room: roomId, count: operatorMessages.length, expectedAgents: expected, operatorMessages })
|
||||
},
|
||||
)
|
||||
|
||||
server.registerTool(
|
||||
"list_rooms",
|
||||
{
|
||||
@@ -129,18 +237,7 @@ server.registerTool(
|
||||
},
|
||||
},
|
||||
async () => {
|
||||
const store = await readStore()
|
||||
const rooms = Object.entries(store.rooms)
|
||||
.map(([room, value]) => ({
|
||||
room,
|
||||
updatedAt: value?.updatedAt || null,
|
||||
messageCount: Array.isArray(value?.messages) ? value.messages.length : 0,
|
||||
latestMessageId: Array.isArray(value?.messages) && value.messages.length > 0
|
||||
? value.messages[value.messages.length - 1].id
|
||||
: null,
|
||||
}))
|
||||
.sort((a, b) => String(b.updatedAt || "").localeCompare(String(a.updatedAt || "")))
|
||||
return asText({ ok: true, rooms })
|
||||
return asText({ ok: true, rooms: await listRooms() })
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
#!/usr/bin/env node
|
||||
import { spawn, execFile } from "node:child_process"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { existsSync } from "node:fs"
|
||||
import net from "node:net"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { promisify } from "node:util"
|
||||
import { WebSocket } from "ws"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const DASHBOARD_PORT_BASE = Number.parseInt(process.env.OPENCLAW_SANDBOX_DASHBOARD_PORT_BASE || "19000", 10)
|
||||
const DASHBOARD_PORT_RANGE = Number.parseInt(process.env.OPENCLAW_SANDBOX_DASHBOARD_PORT_RANGE || "2000", 10)
|
||||
const REMOTE_DASHBOARD_PORT = Number.parseInt(process.env.OPENCLAW_SANDBOX_DASHBOARD_REMOTE_PORT || "18789", 10)
|
||||
const OPENSHELL_GATEWAY = process.env.OPENSHELL_GATEWAY || "nemoclaw"
|
||||
const CONTROL_UI_ORIGIN = process.env.OPENCLAW_SANDBOX_CONTROL_UI_ORIGIN || "http://127.0.0.1:18789"
|
||||
const CONNECT_TIMEOUT_MS = Number.parseInt(process.env.INTER_SANDBOX_CHAT_OPENCLAW_CONNECT_TIMEOUT_MS || "15000", 10)
|
||||
const SEND_TIMEOUT_MS = Number.parseInt(process.env.INTER_SANDBOX_CHAT_OPENCLAW_SEND_TIMEOUT_MS || "120000", 10)
|
||||
const SESSION_KEY = process.env.INTER_SANDBOX_CHAT_OPENCLAW_SESSION_KEY || "inter-sandbox-chat"
|
||||
|
||||
function firstExisting(candidates, fallback) {
|
||||
return candidates.find((candidate) => candidate && existsSync(candidate)) || fallback
|
||||
}
|
||||
|
||||
const OPENSHELL_BIN = firstExisting([
|
||||
process.env.OPENSHELL_BIN,
|
||||
path.join(os.homedir(), ".local/bin/openshell"),
|
||||
"/usr/local/bin/openshell",
|
||||
"/opt/homebrew/bin/openshell",
|
||||
], "openshell")
|
||||
|
||||
function cleanText(value, fallback = "") {
|
||||
return String(value ?? fallback).trim()
|
||||
}
|
||||
|
||||
function cleanSandboxName(value) {
|
||||
const sandboxName = cleanText(value)
|
||||
if (!/^[A-Za-z0-9._-]{1,128}$/.test(sandboxName)) {
|
||||
throw new Error("sandbox name is required for OpenClaw dispatch")
|
||||
}
|
||||
return sandboxName
|
||||
}
|
||||
|
||||
function hashSandboxId(value) {
|
||||
let hash = 0
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
hash = ((hash << 5) - hash + value.charCodeAt(index)) | 0
|
||||
}
|
||||
return Math.abs(hash)
|
||||
}
|
||||
|
||||
function getDashboardPort(sandboxName) {
|
||||
return DASHBOARD_PORT_BASE + (hashSandboxId(sandboxName) % DASHBOARD_PORT_RANGE)
|
||||
}
|
||||
|
||||
function buildSandboxSshArgs(sandboxName, extraArgs) {
|
||||
return [
|
||||
"-o", "BatchMode=yes",
|
||||
"-o", "StrictHostKeyChecking=no",
|
||||
"-o", "UserKnownHostsFile=/dev/null",
|
||||
"-o", "GlobalKnownHostsFile=/dev/null",
|
||||
"-o", "LogLevel=ERROR",
|
||||
"-o", `ProxyCommand=${OPENSHELL_BIN} ssh-proxy --gateway-name ${OPENSHELL_GATEWAY} --name ${sandboxName}`,
|
||||
`sandbox@openshell-${sandboxName}`,
|
||||
...extraArgs,
|
||||
]
|
||||
}
|
||||
|
||||
async function execSandboxSsh(sandboxName, command, timeoutMs = 10000) {
|
||||
return await execFileAsync("ssh", buildSandboxSshArgs(sandboxName, [command]), {
|
||||
timeout: timeoutMs,
|
||||
maxBuffer: 2 * 1024 * 1024,
|
||||
env: process.env,
|
||||
})
|
||||
}
|
||||
|
||||
function canConnectPort(port, timeoutMs = 750) {
|
||||
return new Promise((resolve) => {
|
||||
const socket = net.connect({ host: "127.0.0.1", port })
|
||||
const done = (ok) => {
|
||||
socket.removeAllListeners()
|
||||
socket.destroy()
|
||||
resolve(ok)
|
||||
}
|
||||
socket.setTimeout(timeoutMs)
|
||||
socket.once("connect", () => done(true))
|
||||
socket.once("timeout", () => done(false))
|
||||
socket.once("error", () => done(false))
|
||||
})
|
||||
}
|
||||
|
||||
async function waitForPort(port, timeoutMs = 8000) {
|
||||
const deadline = Date.now() + timeoutMs
|
||||
while (Date.now() < deadline) {
|
||||
if (await canConnectPort(port)) return true
|
||||
await new Promise((resolve) => setTimeout(resolve, 250))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
async function ensureRemoteDashboard(sandboxName) {
|
||||
const command = [
|
||||
`curl -fsS --max-time 2 http://127.0.0.1:${REMOTE_DASHBOARD_PORT}/ >/dev/null 2>&1`,
|
||||
"||",
|
||||
`(nohup /usr/local/bin/openclaw gateway run --allow-unconfigured --bind loopback --port ${REMOTE_DASHBOARD_PORT} >/tmp/gateway.log 2>&1 &)`,
|
||||
].join(" ")
|
||||
await execSandboxSsh(sandboxName, command, 15000).catch(() => null)
|
||||
}
|
||||
|
||||
async function ensureDashboardTunnel(sandboxName, port) {
|
||||
if (await canConnectPort(port)) return true
|
||||
await ensureRemoteDashboard(sandboxName)
|
||||
|
||||
const child = spawn("ssh", buildSandboxSshArgs(sandboxName, [
|
||||
"-N",
|
||||
"-L", `127.0.0.1:${port}:127.0.0.1:${REMOTE_DASHBOARD_PORT}`,
|
||||
]), {
|
||||
detached: true,
|
||||
env: process.env,
|
||||
stdio: "ignore",
|
||||
})
|
||||
child.unref()
|
||||
return await waitForPort(port, 8000)
|
||||
}
|
||||
|
||||
async function readGatewayToken(sandboxName) {
|
||||
const script = [
|
||||
'const fs=require("fs")',
|
||||
'const cfg=JSON.parse(fs.readFileSync("/sandbox/.openclaw/openclaw.json","utf8"))',
|
||||
'const token=cfg?.gateway?.auth?.token||cfg?.gateway?.token||""',
|
||||
'if(token) process.stdout.write(String(token))',
|
||||
].join(";")
|
||||
const { stdout } = await execSandboxSsh(sandboxName, `node -e '${script}'`, 8000)
|
||||
const token = cleanText(stdout)
|
||||
if (!token) throw new Error("OpenClaw gateway token was not found in sandbox config")
|
||||
return token
|
||||
}
|
||||
|
||||
async function readStdinJson() {
|
||||
const chunks = []
|
||||
for await (const chunk of process.stdin) chunks.push(chunk)
|
||||
const raw = Buffer.concat(chunks).toString("utf8").trim()
|
||||
if (!raw) throw new Error("dispatch payload is required on stdin")
|
||||
return JSON.parse(raw)
|
||||
}
|
||||
|
||||
function randomId() {
|
||||
return randomUUID()
|
||||
}
|
||||
|
||||
class GatewayClient {
|
||||
constructor({ url, token, sessionKey }) {
|
||||
this.url = url
|
||||
this.token = token
|
||||
this.sessionKey = sessionKey
|
||||
this.ws = null
|
||||
this.pending = new Map()
|
||||
}
|
||||
|
||||
async connect() {
|
||||
this.ws = new WebSocket(this.url, {
|
||||
headers: { origin: CONTROL_UI_ORIGIN },
|
||||
})
|
||||
await new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => reject(new Error(`OpenClaw websocket connect timed out after ${CONNECT_TIMEOUT_MS}ms`)), CONNECT_TIMEOUT_MS)
|
||||
this.ws.once("open", () => {
|
||||
clearTimeout(timeout)
|
||||
resolve()
|
||||
})
|
||||
this.ws.once("error", (error) => {
|
||||
clearTimeout(timeout)
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
this.ws.on("message", (data) => this.handleMessage(data))
|
||||
await this.request("connect", {
|
||||
minProtocol: 3,
|
||||
maxProtocol: 3,
|
||||
client: {
|
||||
id: "openclaw-control-ui",
|
||||
version: "openshell-inter-sandbox-chat-sidecar",
|
||||
platform: "node",
|
||||
mode: "webchat",
|
||||
instanceId: "openshell-inter-sandbox-chat-sidecar",
|
||||
},
|
||||
role: "operator",
|
||||
scopes: ["operator.admin", "operator.read", "operator.write", "operator.approvals", "operator.pairing"],
|
||||
caps: ["tool-events"],
|
||||
auth: { token: this.token },
|
||||
userAgent: "openshell-controller/inter-sandbox-chat-sidecar",
|
||||
locale: "en-US",
|
||||
}, CONNECT_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
handleMessage(data) {
|
||||
let message
|
||||
try {
|
||||
message = JSON.parse(String(data))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
if (message.type !== "res") return
|
||||
const pending = this.pending.get(message.id)
|
||||
if (!pending) return
|
||||
this.pending.delete(message.id)
|
||||
if (message.ok) pending.resolve(message.payload)
|
||||
else {
|
||||
const detail = message.error?.message || message.error?.code || "OpenClaw request failed"
|
||||
const error = new Error(detail)
|
||||
error.details = message.error
|
||||
pending.reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
request(method, params, timeoutMs = SEND_TIMEOUT_MS) {
|
||||
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
||||
return Promise.reject(new Error("OpenClaw websocket is not connected"))
|
||||
}
|
||||
|
||||
const id = randomId()
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
this.pending.delete(id)
|
||||
reject(new Error(`${method} timed out after ${timeoutMs}ms`))
|
||||
}, timeoutMs)
|
||||
this.pending.set(id, {
|
||||
resolve: (value) => {
|
||||
clearTimeout(timeout)
|
||||
resolve(value)
|
||||
},
|
||||
reject: (error) => {
|
||||
clearTimeout(timeout)
|
||||
reject(error)
|
||||
},
|
||||
})
|
||||
})
|
||||
this.ws.send(JSON.stringify({ type: "req", id, method, params }))
|
||||
return promise
|
||||
}
|
||||
|
||||
async sendChat(message, idempotencyKey) {
|
||||
return await this.request("chat.send", {
|
||||
sessionKey: this.sessionKey,
|
||||
message,
|
||||
deliver: false,
|
||||
idempotencyKey,
|
||||
}, SEND_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
close() {
|
||||
this.ws?.close(1000, "done")
|
||||
this.ws = null
|
||||
}
|
||||
}
|
||||
|
||||
function buildOpenClawMessage(payload) {
|
||||
const rawMessage = cleanText(payload?.message?.message)
|
||||
if (process.env.INTER_SANDBOX_CHAT_OPENCLAW_RAW_MESSAGE === "1") return rawMessage
|
||||
|
||||
const room = cleanText(payload?.room || payload?.message?.room, "lobby")
|
||||
const sender = cleanText(payload?.message?.sender, "operator")
|
||||
const sandboxLabel = cleanText(payload?.sandboxName || payload?.sandboxId, "this sandbox")
|
||||
return [
|
||||
"Inter-Sandbox Chat message",
|
||||
`Room: ${room}`,
|
||||
`From: ${sender}`,
|
||||
`Origin: ${cleanText(payload?.message?.origin, "sandbox")}`,
|
||||
"",
|
||||
rawMessage,
|
||||
"",
|
||||
`Please handle this as a direct message for ${sandboxLabel}. This dispatch contains only the newest claimed chat message, not the whole room history. If the Inter-Sandbox Chat MCP server is available and a shared-room reply is appropriate, post your reply with post_message to room "${room}" and target the intended sandbox.`,
|
||||
].join("\n")
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const payload = await readStdinJson()
|
||||
const sandboxName = cleanSandboxName(payload.sandboxName || payload.sandboxId)
|
||||
const message = buildOpenClawMessage(payload)
|
||||
if (!message) throw new Error("message text is required")
|
||||
|
||||
const port = getDashboardPort(sandboxName)
|
||||
const tunnelReady = await ensureDashboardTunnel(sandboxName, port)
|
||||
if (!tunnelReady) throw new Error(`OpenClaw dashboard tunnel did not become ready on 127.0.0.1:${port}`)
|
||||
|
||||
const token = await readGatewayToken(sandboxName)
|
||||
const client = new GatewayClient({
|
||||
url: `ws://127.0.0.1:${port}/`,
|
||||
token,
|
||||
sessionKey: SESSION_KEY,
|
||||
})
|
||||
|
||||
try {
|
||||
await client.connect()
|
||||
const result = await client.sendChat(message, payload.message?.id || randomId())
|
||||
process.stdout.write(`${JSON.stringify({
|
||||
status: "processed",
|
||||
note: `sent to OpenClaw chat session ${SESSION_KEY}`,
|
||||
openclaw: {
|
||||
sessionKey: SESSION_KEY,
|
||||
runId: result?.runId || null,
|
||||
port,
|
||||
},
|
||||
})}\n`)
|
||||
} finally {
|
||||
client.close()
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
process.stdout.write(`${JSON.stringify({
|
||||
status: "failed",
|
||||
note: error instanceof Error ? error.message : "OpenClaw dispatch failed",
|
||||
})}\n`)
|
||||
})
|
||||
@@ -0,0 +1,464 @@
|
||||
#!/usr/bin/env node
|
||||
import { spawn } from "node:child_process"
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import {
|
||||
ackChatMessage,
|
||||
claimOperatorMessages,
|
||||
claimTargetedMessages,
|
||||
cleanText,
|
||||
listRooms,
|
||||
postChatMessage,
|
||||
recordChatMessageReceipt,
|
||||
} from "./inter-sandbox-chat-core.mjs"
|
||||
|
||||
const STATE_DIR = process.env.NEMOCLAW_DASHBOARD_STATE_DIR || path.join(os.homedir(), ".nemoclaw-dashboard")
|
||||
const MCP_SERVER_STORE_PATH = path.join(STATE_DIR, "mcp-servers.json")
|
||||
const MCP_BROKER_SESSIONS_PATH = path.join(STATE_DIR, "mcp-broker-sessions.json")
|
||||
const DEFAULT_OPENCLAW_DISPATCH_SCRIPT = fileURLToPath(new URL("./inter-sandbox-chat-openclaw-dispatch.mjs", import.meta.url))
|
||||
const CHAT_SERVER_ID = "inter-sandbox-chat"
|
||||
const SIDECAR_AGENT_PREFIX = "inter-sandbox-chat-sidecar"
|
||||
const MAX_DISPATCH_OUTPUT_BYTES = 64 * 1024
|
||||
|
||||
function parsePositiveInt(value, fallback, max = Number.MAX_SAFE_INTEGER) {
|
||||
const parsed = Number.parseInt(String(value || ""), 10)
|
||||
if (!Number.isFinite(parsed) || parsed < 1) return fallback
|
||||
return Math.min(parsed, max)
|
||||
}
|
||||
|
||||
function parseBoolean(value, fallback = false) {
|
||||
if (typeof value !== "string") return fallback
|
||||
const normalized = value.trim().toLowerCase()
|
||||
if (!normalized) return fallback
|
||||
if (["1", "true", "yes", "on"].includes(normalized)) return true
|
||||
if (["0", "false", "no", "off"].includes(normalized)) return false
|
||||
return fallback
|
||||
}
|
||||
|
||||
function parseDispatchArgs() {
|
||||
const raw = process.env.INTER_SANDBOX_CHAT_DISPATCH_ARGS_JSON?.trim()
|
||||
if (!raw) return []
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!Array.isArray(parsed)) return []
|
||||
return parsed.map((entry) => String(entry))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
const POLL_MS = parsePositiveInt(process.env.INTER_SANDBOX_CHAT_SIDECAR_POLL_MS, 5000)
|
||||
const CLAIM_LIMIT = parsePositiveInt(process.env.INTER_SANDBOX_CHAT_SIDECAR_LIMIT, 5, 50)
|
||||
const DISPATCH_TIMEOUT_MS = parsePositiveInt(process.env.INTER_SANDBOX_CHAT_DISPATCH_TIMEOUT_MS, 120000)
|
||||
const CUSTOM_DISPATCH_COMMAND = cleanText(process.env.INTER_SANDBOX_CHAT_DISPATCH_COMMAND)
|
||||
const DISPATCH_COMMAND = CUSTOM_DISPATCH_COMMAND || process.execPath
|
||||
const DISPATCH_ARGS = CUSTOM_DISPATCH_COMMAND ? parseDispatchArgs() : [DEFAULT_OPENCLAW_DISPATCH_SCRIPT]
|
||||
const DISPATCH_KIND = CUSTOM_DISPATCH_COMMAND ? "custom-command" : "openclaw-chat"
|
||||
const POST_REPLIES = parseBoolean(process.env.INTER_SANDBOX_CHAT_SIDECAR_POST_REPLIES, true)
|
||||
const PROCESS_BROADCAST = parseBoolean(process.env.INTER_SANDBOX_CHAT_SIDECAR_PROCESS_BROADCAST, false)
|
||||
const RELAY_SANDBOX_MESSAGES = parseBoolean(process.env.INTER_SANDBOX_CHAT_SIDECAR_RELAY_SANDBOX_MESSAGES, true)
|
||||
const SANDBOX_RELAY_LATEST_ONLY = parseBoolean(process.env.INTER_SANDBOX_CHAT_SIDECAR_SANDBOX_LATEST_ONLY, true)
|
||||
|
||||
let stopping = false
|
||||
let timer = null
|
||||
let lastIdleKey = ""
|
||||
const activeDispatches = new Set()
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString()
|
||||
}
|
||||
|
||||
function log(event, fields = {}) {
|
||||
const payload = Object.entries(fields)
|
||||
.filter(([, value]) => value !== undefined && value !== null && value !== "")
|
||||
.map(([key, value]) => `${key}=${JSON.stringify(value)}`)
|
||||
.join(" ")
|
||||
console.log(`[inter-sandbox-chat-sidecar] ts=${nowIso()} event=${event}${payload ? ` ${payload}` : ""}`)
|
||||
}
|
||||
|
||||
function logIdle(key, event, fields = {}) {
|
||||
if (lastIdleKey === key) return
|
||||
lastIdleKey = key
|
||||
log(event, fields)
|
||||
}
|
||||
|
||||
function clearIdle() {
|
||||
lastIdleKey = ""
|
||||
}
|
||||
|
||||
async function readJson(pathname, fallback) {
|
||||
try {
|
||||
const parsed = JSON.parse(await readFile(pathname, "utf8"))
|
||||
return parsed && typeof parsed === "object" ? parsed : fallback
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeStringArray(value) {
|
||||
if (!Array.isArray(value)) return []
|
||||
return Array.from(new Set(value.map((entry) => cleanText(entry)).filter(Boolean)))
|
||||
}
|
||||
|
||||
async function readChatPolicy() {
|
||||
const store = await readJson(MCP_SERVER_STORE_PATH, { servers: {} })
|
||||
const server = store.servers?.[CHAT_SERVER_ID]
|
||||
if (!server || typeof server !== "object") {
|
||||
return { active: false, reason: "not-installed", accessMode: "disabled", allowedSandboxIds: [] }
|
||||
}
|
||||
|
||||
const accessMode = server.accessMode === "allow_all" || server.accessMode === "allow_only"
|
||||
? server.accessMode
|
||||
: "disabled"
|
||||
const allowedSandboxIds = normalizeStringArray(server.allowedSandboxIds)
|
||||
if (!server.enabled) return { active: false, reason: "disabled", accessMode, allowedSandboxIds }
|
||||
if (accessMode === "disabled") return { active: false, reason: "access-disabled", accessMode, allowedSandboxIds }
|
||||
if (accessMode === "allow_only" && allowedSandboxIds.length === 0) {
|
||||
return { active: false, reason: "allow-list-empty", accessMode, allowedSandboxIds }
|
||||
}
|
||||
return { active: true, reason: "enabled", accessMode, allowedSandboxIds }
|
||||
}
|
||||
|
||||
function sessionIsUsable(session) {
|
||||
if (!session || typeof session !== "object") return false
|
||||
if (!session.enabled) return false
|
||||
if (!cleanText(session.sandboxId)) return false
|
||||
if (session.expiresAt && Date.parse(session.expiresAt) <= Date.now()) return false
|
||||
return true
|
||||
}
|
||||
|
||||
async function readBrokerSessions() {
|
||||
const store = await readJson(MCP_BROKER_SESSIONS_PATH, { sessions: {} })
|
||||
return Object.values(store.sessions || {}).filter(sessionIsUsable)
|
||||
}
|
||||
|
||||
function targetFromSession(session) {
|
||||
const sandboxId = cleanText(session.sandboxId)
|
||||
const sandboxName = cleanText(session.sandboxName)
|
||||
return {
|
||||
sandboxId,
|
||||
sandboxName: sandboxName || sandboxId,
|
||||
agentId: `${SIDECAR_AGENT_PREFIX}:${sandboxId}`,
|
||||
source: "broker-session",
|
||||
}
|
||||
}
|
||||
|
||||
function targetFromAllowedId(id) {
|
||||
const sandboxId = cleanText(id)
|
||||
return {
|
||||
sandboxId,
|
||||
sandboxName: sandboxId,
|
||||
agentId: `${SIDECAR_AGENT_PREFIX}:${sandboxId}`,
|
||||
source: "allow-list",
|
||||
}
|
||||
}
|
||||
|
||||
function targetKey(target) {
|
||||
return cleanText(target.sandboxId) || cleanText(target.sandboxName) || cleanText(target.agentId)
|
||||
}
|
||||
|
||||
function sessionMatchesAllowedId(session, allowedId) {
|
||||
const allowed = cleanText(allowedId)
|
||||
return Boolean(
|
||||
allowed &&
|
||||
(allowed === cleanText(session.sandboxId) || allowed === cleanText(session.sandboxName)),
|
||||
)
|
||||
}
|
||||
|
||||
function resolveTargets(policy, sessions) {
|
||||
const targets = []
|
||||
if (policy.accessMode === "allow_all") {
|
||||
targets.push(...sessions.map(targetFromSession))
|
||||
} else {
|
||||
for (const allowedId of policy.allowedSandboxIds) {
|
||||
const matchingSession = sessions.find((session) => sessionMatchesAllowedId(session, allowedId))
|
||||
targets.push(matchingSession ? targetFromSession(matchingSession) : targetFromAllowedId(allowedId))
|
||||
}
|
||||
}
|
||||
|
||||
const seen = new Set()
|
||||
return targets.filter((target) => {
|
||||
const key = targetKey(target)
|
||||
if (!key || seen.has(key)) return false
|
||||
seen.add(key)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
function appendLimited(current, chunk) {
|
||||
const next = current + chunk.toString("utf8")
|
||||
return next.length > MAX_DISPATCH_OUTPUT_BYTES ? next.slice(-MAX_DISPATCH_OUTPUT_BYTES) : next
|
||||
}
|
||||
|
||||
function dispatchEnv(payload) {
|
||||
return {
|
||||
...process.env,
|
||||
INTER_SANDBOX_CHAT_ROOM: payload.room,
|
||||
INTER_SANDBOX_CHAT_MESSAGE_ID: payload.message.id,
|
||||
INTER_SANDBOX_CHAT_MESSAGE: payload.message.message,
|
||||
INTER_SANDBOX_CHAT_SENDER: payload.message.sender,
|
||||
INTER_SANDBOX_CHAT_ACK_TOKEN: payload.message.ackToken || "",
|
||||
INTER_SANDBOX_CHAT_SANDBOX_ID: payload.sandboxId || "",
|
||||
INTER_SANDBOX_CHAT_SANDBOX_NAME: payload.sandboxName || "",
|
||||
INTER_SANDBOX_CHAT_AGENT_ID: payload.agentId || "",
|
||||
}
|
||||
}
|
||||
|
||||
async function runDispatch(payload) {
|
||||
if (!DISPATCH_COMMAND) return { ok: false, error: "dispatch command is not configured" }
|
||||
|
||||
return await new Promise((resolve) => {
|
||||
let stdout = ""
|
||||
let stderr = ""
|
||||
let settled = false
|
||||
let timedOut = false
|
||||
const child = spawn(DISPATCH_COMMAND, DISPATCH_ARGS, {
|
||||
cwd: process.cwd(),
|
||||
env: dispatchEnv(payload),
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
})
|
||||
activeDispatches.add(child)
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
timedOut = true
|
||||
if (child.exitCode === null && child.signalCode === null) child.kill("SIGTERM")
|
||||
setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL")
|
||||
}, 2500).unref()
|
||||
}, DISPATCH_TIMEOUT_MS)
|
||||
|
||||
child.stdout.on("data", (chunk) => {
|
||||
stdout = appendLimited(stdout, chunk)
|
||||
})
|
||||
child.stderr.on("data", (chunk) => {
|
||||
stderr = appendLimited(stderr, chunk)
|
||||
})
|
||||
child.once("error", (error) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
activeDispatches.delete(child)
|
||||
resolve({ ok: false, error: error instanceof Error ? error.message : "dispatch failed", stderr })
|
||||
})
|
||||
child.once("exit", (code, signal) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
activeDispatches.delete(child)
|
||||
if (code === 0 && !timedOut) {
|
||||
resolve({ ok: true, stdout: stdout.trim(), stderr: stderr.trim() })
|
||||
return
|
||||
}
|
||||
const reason = timedOut
|
||||
? `dispatch timed out after ${DISPATCH_TIMEOUT_MS}ms`
|
||||
: `dispatch exited with code ${code ?? "null"}${signal ? ` signal ${signal}` : ""}`
|
||||
resolve({ ok: false, error: reason, stderr: stderr.trim() })
|
||||
})
|
||||
|
||||
child.stdin.end(`${JSON.stringify(payload)}\n`)
|
||||
})
|
||||
}
|
||||
|
||||
function parseDispatchOutput(output) {
|
||||
const text = cleanText(output)
|
||||
if (!text) return { reply: "", status: "processed", note: "dispatch completed without output" }
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(text)
|
||||
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
||||
const status = cleanText(parsed.status).toLowerCase()
|
||||
return {
|
||||
reply: cleanText(parsed.reply ?? parsed.message),
|
||||
status: status === "failed" ? "failed" : "processed",
|
||||
note: cleanText(parsed.note ?? parsed.summary ?? parsed.status) || "dispatch completed",
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Plain text stdout is treated as the sandbox reply.
|
||||
}
|
||||
|
||||
return { reply: text, status: "processed", note: "dispatch returned plain text" }
|
||||
}
|
||||
|
||||
async function processClaimedMessage(target, room, message) {
|
||||
const payload = {
|
||||
room,
|
||||
message,
|
||||
sandboxId: target.sandboxId,
|
||||
sandboxName: target.sandboxName,
|
||||
agentId: target.agentId,
|
||||
}
|
||||
log("dispatch-start", {
|
||||
room,
|
||||
messageId: message.id,
|
||||
sandboxId: target.sandboxId,
|
||||
sandboxName: target.sandboxName,
|
||||
})
|
||||
|
||||
const result = await runDispatch(payload)
|
||||
if (!result.ok) {
|
||||
const note = [result.error, result.stderr].filter(Boolean).join(": ")
|
||||
const recordReceipt = message.origin === "operator" ? ackChatMessage : recordChatMessageReceipt
|
||||
await recordReceipt({
|
||||
room,
|
||||
messageId: message.id,
|
||||
ackToken: message.ackToken,
|
||||
agentId: target.agentId,
|
||||
sandboxId: target.sandboxId,
|
||||
status: "failed",
|
||||
note,
|
||||
})
|
||||
log("dispatch-failed", {
|
||||
room,
|
||||
messageId: message.id,
|
||||
sandboxId: target.sandboxId,
|
||||
reason: result.error,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const parsed = parseDispatchOutput(result.stdout)
|
||||
let postedReplyId = null
|
||||
if (POST_REPLIES && parsed.status !== "failed" && parsed.reply) {
|
||||
const posted = await postChatMessage({
|
||||
room,
|
||||
sender: target.sandboxName || target.sandboxId || target.agentId,
|
||||
message: parsed.reply,
|
||||
origin: "sandbox",
|
||||
})
|
||||
postedReplyId = posted.message?.id || null
|
||||
}
|
||||
|
||||
const recordReceipt = message.origin === "operator" ? ackChatMessage : recordChatMessageReceipt
|
||||
await recordReceipt({
|
||||
room,
|
||||
messageId: message.id,
|
||||
ackToken: message.ackToken,
|
||||
agentId: target.agentId,
|
||||
sandboxId: target.sandboxId,
|
||||
status: parsed.status,
|
||||
note: parsed.note,
|
||||
})
|
||||
log("dispatch-complete", {
|
||||
room,
|
||||
messageId: message.id,
|
||||
sandboxId: target.sandboxId,
|
||||
status: parsed.status,
|
||||
postedReplyId,
|
||||
})
|
||||
}
|
||||
|
||||
async function pollOnce() {
|
||||
const policy = await readChatPolicy()
|
||||
if (!policy.active) {
|
||||
logIdle(`inactive:${policy.reason}`, "inactive", { reason: policy.reason })
|
||||
return
|
||||
}
|
||||
|
||||
const sessions = await readBrokerSessions()
|
||||
const targets = resolveTargets(policy, sessions)
|
||||
if (targets.length === 0) {
|
||||
logIdle(`no-targets:${policy.accessMode}`, "no-targets", {
|
||||
accessMode: policy.accessMode,
|
||||
sessionCount: sessions.length,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const rooms = await listRooms()
|
||||
if (rooms.length === 0) {
|
||||
logIdle("no-rooms", "no-rooms", { targetCount: targets.length })
|
||||
return
|
||||
}
|
||||
|
||||
clearIdle()
|
||||
let claimedCount = 0
|
||||
for (const target of targets) {
|
||||
if (stopping) return
|
||||
for (const room of rooms) {
|
||||
if (stopping) return
|
||||
const claimed = await claimOperatorMessages({
|
||||
room: room.room,
|
||||
agentId: target.agentId,
|
||||
sandboxId: target.sandboxId,
|
||||
sandboxName: target.sandboxName,
|
||||
limit: CLAIM_LIMIT,
|
||||
includeBroadcast: PROCESS_BROADCAST,
|
||||
autoAck: true,
|
||||
})
|
||||
for (const message of claimed.messages || []) {
|
||||
claimedCount += 1
|
||||
await processClaimedMessage(target, room.room, message)
|
||||
}
|
||||
if (!RELAY_SANDBOX_MESSAGES) continue
|
||||
const relayed = await claimTargetedMessages({
|
||||
room: room.room,
|
||||
agentId: target.agentId,
|
||||
sandboxId: target.sandboxId,
|
||||
sandboxName: target.sandboxName,
|
||||
limit: CLAIM_LIMIT,
|
||||
includeBroadcast: PROCESS_BROADCAST,
|
||||
autoAck: true,
|
||||
origins: ["sandbox"],
|
||||
excludeSelf: true,
|
||||
latestOnly: SANDBOX_RELAY_LATEST_ONLY,
|
||||
cursorId: `${target.agentId}:sandbox-relay`,
|
||||
receiptNote: SANDBOX_RELAY_LATEST_ONLY
|
||||
? "claimed latest sandbox message by inter-sandbox chat sidecar"
|
||||
: "claimed sandbox message by inter-sandbox chat sidecar",
|
||||
})
|
||||
for (const message of relayed.messages || []) {
|
||||
claimedCount += 1
|
||||
await processClaimedMessage(target, room.room, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (claimedCount > 0) {
|
||||
log("poll-complete", { claimedCount, targetCount: targets.length, roomCount: rooms.length })
|
||||
}
|
||||
}
|
||||
|
||||
async function loop() {
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
await pollOnce()
|
||||
} catch (error) {
|
||||
log("poll-error", {
|
||||
reason: error instanceof Error ? error.message : "unknown error",
|
||||
})
|
||||
}
|
||||
|
||||
if (stopping) return
|
||||
const delay = Math.max(1000, POLL_MS - (Date.now() - startedAt))
|
||||
timer = setTimeout(loop, delay)
|
||||
}
|
||||
|
||||
function stop(exitCode = 0) {
|
||||
if (stopping) return
|
||||
stopping = true
|
||||
process.exitCode = exitCode
|
||||
if (timer) clearTimeout(timer)
|
||||
for (const child of activeDispatches) {
|
||||
if (!child.killed) child.kill("SIGTERM")
|
||||
}
|
||||
log("stopping", { exitCode, activeDispatches: activeDispatches.size })
|
||||
}
|
||||
|
||||
process.once("SIGINT", () => stop(130))
|
||||
process.once("SIGTERM", () => stop(143))
|
||||
|
||||
log("started", {
|
||||
pollMs: POLL_MS,
|
||||
claimLimit: CLAIM_LIMIT,
|
||||
dispatchConfigured: Boolean(DISPATCH_COMMAND),
|
||||
dispatchKind: DISPATCH_KIND,
|
||||
processBroadcast: PROCESS_BROADCAST,
|
||||
postReplies: POST_REPLIES,
|
||||
relaySandboxMessages: RELAY_SANDBOX_MESSAGES,
|
||||
sandboxRelayLatestOnly: SANDBOX_RELAY_LATEST_ONLY,
|
||||
})
|
||||
|
||||
await loop()
|
||||
Reference in New Issue
Block a user