Mona commited on
Commit ·
abec589
1
Parent(s): 7323d61
feat: docker platform protocol — register, chat RPC, LLM proxy
Browse filesThe daemon now speaks the local Docker control plane's native protocol:
- register on connect (flat message, agentId in WS query)
- dashboard chat messages map to run commands, replies via chat:response
- llm:request/llm:response RPC proxies LLM calls through the platform
vault (keys stay in the cloud), provider/model from MONA_LLM_PROVIDER/
MONA_LLM_MODEL (default openai/gpt-4o-mini)
- live status broadcasts with metrics; sngine protocol untouched
Fixes: platform detection uses hostname (host includes the port),
DEFAULTS.llm added. New docker-control test suite (24 tests total).
- README.md +2 -0
- package.json +1 -1
- src/agent.js +34 -20
- src/config.js +9 -4
- src/control.js +81 -17
- test/docker-control.test.mjs +99 -0
README.md
CHANGED
|
@@ -141,6 +141,8 @@ Without arguments, auto-detects: GUI if terminal, headless otherwise.
|
|
| 141 |
| `MONA_ALLOW_CMDS` | `df,uptime,uname,...` | Shell command allowlist |
|
| 142 |
| `MONA_SHELL_UNSAFE` | — | Set to `1` for unrestricted shell |
|
| 143 |
| `MONA_WORKSPACE` | `~/.mona-agent/workspace` | File tool sandbox directory |
|
|
|
|
|
|
|
| 144 |
|
| 145 |
## Project Structure
|
| 146 |
|
|
|
|
| 141 |
| `MONA_ALLOW_CMDS` | `df,uptime,uname,...` | Shell command allowlist |
|
| 142 |
| `MONA_SHELL_UNSAFE` | — | Set to `1` for unrestricted shell |
|
| 143 |
| `MONA_WORKSPACE` | `~/.mona-agent/workspace` | File tool sandbox directory |
|
| 144 |
+
| `MONA_LLM_PROVIDER` | `openai` | Docker platform: LLM provider (openai, anthropic, google, deepseek, openrouter) |
|
| 145 |
+
| `MONA_LLM_MODEL` | `gpt-4o-mini` | Docker platform: default model |
|
| 146 |
|
| 147 |
## Project Structure
|
| 148 |
|
package.json
CHANGED
|
@@ -10,7 +10,7 @@
|
|
| 10 |
"start": "node bin/mona-agent.js start",
|
| 11 |
"gui": "node bin/mona-agent.js gui",
|
| 12 |
"login": "node bin/mona-agent.js login",
|
| 13 |
-
"test": "node --test test/agent.test.mjs test/control.test.mjs"
|
| 14 |
},
|
| 15 |
"engines": {
|
| 16 |
"node": ">=20"
|
|
|
|
| 10 |
"start": "node bin/mona-agent.js start",
|
| 11 |
"gui": "node bin/mona-agent.js gui",
|
| 12 |
"login": "node bin/mona-agent.js login",
|
| 13 |
+
"test": "node --test test/agent.test.mjs test/control.test.mjs test/docker-control.test.mjs"
|
| 14 |
},
|
| 15 |
"engines": {
|
| 16 |
"node": ">=20"
|
src/agent.js
CHANGED
|
@@ -8,6 +8,7 @@ import { think } from './cloud.js';
|
|
| 8 |
import { ControlChannel } from './control.js';
|
| 9 |
import { tools } from './tools/index.js';
|
| 10 |
import { security as shellSecurity } from './tools/shell.js';
|
|
|
|
| 11 |
import { log } from './log.js';
|
| 12 |
|
| 13 |
export class AgentDaemon extends EventEmitter {
|
|
@@ -97,26 +98,35 @@ export class AgentDaemon extends EventEmitter {
|
|
| 97 |
this.#messages.push({ role: 'user', content: task });
|
| 98 |
|
| 99 |
let answer = '';
|
| 100 |
-
let tokenCount = 0;
|
| 101 |
|
| 102 |
try {
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
this.
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
} catch (err) {
|
| 117 |
this.#stats.errors++;
|
| 118 |
this.#currentTask = null;
|
| 119 |
-
this.#control.
|
|
|
|
| 120 |
this.#control.result(runId, { error: err.message });
|
| 121 |
this.emit('task:error', err);
|
| 122 |
log.error(`Think failed: ${err.message}`);
|
|
@@ -125,13 +135,17 @@ export class AgentDaemon extends EventEmitter {
|
|
| 125 |
|
| 126 |
this.#messages.push({ role: 'assistant', content: answer });
|
| 127 |
this.#stats.tasks++;
|
| 128 |
-
this.#stats.tokens +=
|
| 129 |
|
| 130 |
this.#currentTask = null;
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
}
|
| 136 |
|
| 137 |
// ── Tool execution ──────────────────────────────────────────────
|
|
|
|
| 8 |
import { ControlChannel } from './control.js';
|
| 9 |
import { tools } from './tools/index.js';
|
| 10 |
import { security as shellSecurity } from './tools/shell.js';
|
| 11 |
+
import { CLOUD, DEFAULTS } from './config.js';
|
| 12 |
import { log } from './log.js';
|
| 13 |
|
| 14 |
export class AgentDaemon extends EventEmitter {
|
|
|
|
| 98 |
this.#messages.push({ role: 'user', content: task });
|
| 99 |
|
| 100 |
let answer = '';
|
|
|
|
| 101 |
|
| 102 |
try {
|
| 103 |
+
if (CLOUD.platform === 'docker') {
|
| 104 |
+
// Docker platform: LLM call is proxied over the control channel.
|
| 105 |
+
const res = await this.#control.llmRequest({
|
| 106 |
+
provider: DEFAULTS.llm.provider,
|
| 107 |
+
model: DEFAULTS.llm.model,
|
| 108 |
+
messages: this.#messages,
|
| 109 |
+
});
|
| 110 |
+
answer = res.content || '';
|
| 111 |
+
} else {
|
| 112 |
+
answer = await think({
|
| 113 |
+
apiKey: this.#creds.apiKey,
|
| 114 |
+
messages: this.#messages,
|
| 115 |
+
tools: tools.list(),
|
| 116 |
+
onChunk: (delta) => {
|
| 117 |
+
this.#control.token(delta, runId);
|
| 118 |
+
this.emit('task:token', delta, runId);
|
| 119 |
+
},
|
| 120 |
+
onUsage: (usage) => {
|
| 121 |
+
this.emit('task:usage', usage);
|
| 122 |
+
},
|
| 123 |
+
});
|
| 124 |
+
}
|
| 125 |
} catch (err) {
|
| 126 |
this.#stats.errors++;
|
| 127 |
this.#currentTask = null;
|
| 128 |
+
if (CLOUD.platform === 'docker') this.#control.chatResponse(runId, `Error: ${err.message}`);
|
| 129 |
+
else this.#control.step('task.error', { error: err.message });
|
| 130 |
this.#control.result(runId, { error: err.message });
|
| 131 |
this.emit('task:error', err);
|
| 132 |
log.error(`Think failed: ${err.message}`);
|
|
|
|
| 135 |
|
| 136 |
this.#messages.push({ role: 'assistant', content: answer });
|
| 137 |
this.#stats.tasks++;
|
| 138 |
+
this.#stats.tokens += answer.length;
|
| 139 |
|
| 140 |
this.#currentTask = null;
|
| 141 |
+
if (CLOUD.platform === 'docker') {
|
| 142 |
+
this.#control.chatResponse(runId, answer);
|
| 143 |
+
} else {
|
| 144 |
+
this.#control.result(runId, { text: answer });
|
| 145 |
+
this.#control.step('task.done', { runId, tokens: answer.length, chars: answer.length });
|
| 146 |
+
}
|
| 147 |
+
this.emit('task:done', { answer, tokens: answer.length, runId });
|
| 148 |
+
log.info(`Task complete`, { tokens: answer.length, chars: answer.length });
|
| 149 |
}
|
| 150 |
|
| 151 |
// ── Tool execution ──────────────────────────────────────────────
|
src/config.js
CHANGED
|
@@ -21,11 +21,11 @@ const baseUrl = process.env.MONA_CLOUD || 'https://agent.mona.expert';
|
|
| 21 |
// Auto-detect platform type from URL
|
| 22 |
function detectPlatform(url) {
|
| 23 |
try {
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
| 25 |
// Sngine-based: agent.mona.expert (and subdomains)
|
| 26 |
-
if (host.includes('mona.expert') && !url.includes(':4300')) return 'sngine';
|
| 27 |
-
// Docker platform: localhost:4300
|
| 28 |
-
if (url.includes(':4300')) return 'docker';
|
| 29 |
return 'sngine'; // default
|
| 30 |
} catch { return 'sngine'; }
|
| 31 |
}
|
|
@@ -83,6 +83,11 @@ export const DEFAULTS = Object.freeze({
|
|
| 83 |
reconnectMinMs: 1_000,
|
| 84 |
reconnectMaxMs: 30_000,
|
| 85 |
version: '1.2.0',
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
});
|
| 87 |
|
| 88 |
// ── Credential management ─────────────────────────────────────────
|
|
|
|
| 21 |
// Auto-detect platform type from URL
|
| 22 |
function detectPlatform(url) {
|
| 23 |
try {
|
| 24 |
+
// hostname, not host: host includes the port (127.0.0.1:4300).
|
| 25 |
+
const host = new URL(url).hostname;
|
| 26 |
+
// Local control planes (Docker platform, local dev): localhost / 127.0.0.1 / :4300
|
| 27 |
+
if (host === 'localhost' || host === '127.0.0.1' || url.includes(':4300')) return 'docker';
|
| 28 |
// Sngine-based: agent.mona.expert (and subdomains)
|
|
|
|
|
|
|
|
|
|
| 29 |
return 'sngine'; // default
|
| 30 |
} catch { return 'sngine'; }
|
| 31 |
}
|
|
|
|
| 83 |
reconnectMinMs: 1_000,
|
| 84 |
reconnectMaxMs: 30_000,
|
| 85 |
version: '1.2.0',
|
| 86 |
+
// LLM defaults for the docker platform (sngine brain decides its own model).
|
| 87 |
+
llm: Object.freeze({
|
| 88 |
+
provider: process.env.MONA_LLM_PROVIDER || 'openai',
|
| 89 |
+
model: process.env.MONA_LLM_MODEL || 'gpt-4o-mini',
|
| 90 |
+
}),
|
| 91 |
});
|
| 92 |
|
| 93 |
// ── Credential management ─────────────────────────────────────────
|
src/control.js
CHANGED
|
@@ -47,6 +47,7 @@ export class ControlChannel extends EventEmitter {
|
|
| 47 |
#capabilities;
|
| 48 |
#ws = null;
|
| 49 |
#queue = [];
|
|
|
|
| 50 |
#metricsTimer = null;
|
| 51 |
#metricsIntervalMs;
|
| 52 |
#backoff = DEFAULTS.reconnectMinMs;
|
|
@@ -66,7 +67,11 @@ export class ControlChannel extends EventEmitter {
|
|
| 66 |
connect() {
|
| 67 |
if (this.#closing || this.#stopped) return this;
|
| 68 |
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
log.debug(`Connecting to ${url}`);
|
| 71 |
|
| 72 |
this.#ws = new WebSocket(url, {
|
|
@@ -81,16 +86,21 @@ export class ControlChannel extends EventEmitter {
|
|
| 81 |
this.#backoff = DEFAULTS.reconnectMinMs;
|
| 82 |
log.info(`Connected to ${new URL(url).host}`);
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
this.#flush();
|
| 95 |
this.#startMetrics();
|
| 96 |
this.emit('connected');
|
|
@@ -100,8 +110,13 @@ export class ControlChannel extends EventEmitter {
|
|
| 100 |
let msg;
|
| 101 |
try { msg = JSON.parse(raw.toString()); } catch { return; }
|
| 102 |
|
| 103 |
-
if (msg.type === '
|
|
|
|
|
|
|
| 104 |
this.emit('command', msg);
|
|
|
|
|
|
|
|
|
|
| 105 |
} else if (msg.type === 'ping') {
|
| 106 |
this.#send('pong', {});
|
| 107 |
} else {
|
|
@@ -154,6 +169,16 @@ export class ControlChannel extends EventEmitter {
|
|
| 154 |
}
|
| 155 |
}
|
| 156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
#flush() {
|
| 158 |
while (this.#queue.length && this.#ws?.readyState === WebSocket.OPEN) {
|
| 159 |
this.#ws.send(this.#queue.shift());
|
|
@@ -161,10 +186,42 @@ export class ControlChannel extends EventEmitter {
|
|
| 161 |
}
|
| 162 |
|
| 163 |
// ── Public emitters (all consumed by the website dashboard) ─────
|
| 164 |
-
step(name, detail) { this.#send('agent.step', { name, detail }); }
|
| 165 |
-
token(delta, runId) { this.#send('agent.token', { delta, runId }); }
|
| 166 |
-
result(runId, output) { this.#send('agent.result', { runId, output }); }
|
| 167 |
-
log(level, message) { this.#send('agent.log', { level, message }); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
/** Current connection state. */
|
| 170 |
get connected() {
|
|
@@ -196,7 +253,12 @@ export class ControlChannel extends EventEmitter {
|
|
| 196 |
uptimeSeconds: os.uptime(),
|
| 197 |
cpus: cpus.length,
|
| 198 |
};
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
this.emit('metrics', metrics);
|
| 201 |
}, this.#metricsIntervalMs);
|
| 202 |
}
|
|
@@ -213,6 +275,8 @@ export class ControlChannel extends EventEmitter {
|
|
| 213 |
this.#closing = true;
|
| 214 |
clearTimeout(this.#reconnectTimer);
|
| 215 |
this.#stopMetrics();
|
|
|
|
|
|
|
| 216 |
if (this.#ws) {
|
| 217 |
this.#ws.removeAllListeners('close');
|
| 218 |
this.#ws.close(1000, 'agent shutdown');
|
|
|
|
| 47 |
#capabilities;
|
| 48 |
#ws = null;
|
| 49 |
#queue = [];
|
| 50 |
+
#llmPending = new Map();
|
| 51 |
#metricsTimer = null;
|
| 52 |
#metricsIntervalMs;
|
| 53 |
#backoff = DEFAULTS.reconnectMinMs;
|
|
|
|
| 67 |
connect() {
|
| 68 |
if (this.#closing || this.#stopped) return this;
|
| 69 |
|
| 70 |
+
let url = CLOUD.wsUrl;
|
| 71 |
+
// Docker platform registers agents by agentId in the query string.
|
| 72 |
+
if (CLOUD.platform === 'docker') {
|
| 73 |
+
url += (url.includes('?') ? '&' : '?') + `agentId=${encodeURIComponent(this.#agentId || 'agent-1')}`;
|
| 74 |
+
}
|
| 75 |
log.debug(`Connecting to ${url}`);
|
| 76 |
|
| 77 |
this.#ws = new WebSocket(url, {
|
|
|
|
| 86 |
this.#backoff = DEFAULTS.reconnectMinMs;
|
| 87 |
log.info(`Connected to ${new URL(url).host}`);
|
| 88 |
|
| 89 |
+
if (CLOUD.platform === 'docker') {
|
| 90 |
+
// Docker platform protocol: flat register message, no hello handshake.
|
| 91 |
+
this.#sendFlat('register', { name: os.hostname(), model: `mona-agent/${DEFAULTS.version}` });
|
| 92 |
+
} else {
|
| 93 |
+
this.#send('hello', {
|
| 94 |
+
agentId: this.#agentId,
|
| 95 |
+
host: os.hostname(),
|
| 96 |
+
platform: os.platform(),
|
| 97 |
+
arch: os.arch(),
|
| 98 |
+
cpus: os.cpus().length,
|
| 99 |
+
mem: os.totalmem(),
|
| 100 |
+
version: DEFAULTS.version,
|
| 101 |
+
capabilities: this.#capabilities,
|
| 102 |
+
});
|
| 103 |
+
}
|
| 104 |
this.#flush();
|
| 105 |
this.#startMetrics();
|
| 106 |
this.emit('connected');
|
|
|
|
| 110 |
let msg;
|
| 111 |
try { msg = JSON.parse(raw.toString()); } catch { return; }
|
| 112 |
|
| 113 |
+
if (msg.type === 'llm:response' || msg.type === 'llm:error') {
|
| 114 |
+
this.#resolveLlm(msg);
|
| 115 |
+
} else if (msg.type === 'command') {
|
| 116 |
this.emit('command', msg);
|
| 117 |
+
} else if (CLOUD.platform === 'docker' && msg.type === 'chat') {
|
| 118 |
+
// Docker dashboard chat → same run flow as a command.
|
| 119 |
+
this.emit('command', { action: 'run', runId: msg.requestId, payload: { task: msg.message } });
|
| 120 |
} else if (msg.type === 'ping') {
|
| 121 |
this.#send('pong', {});
|
| 122 |
} else {
|
|
|
|
| 169 |
}
|
| 170 |
}
|
| 171 |
|
| 172 |
+
/** Send a flat protocol message (docker platform: fields at top level). */
|
| 173 |
+
#sendFlat(type, obj) {
|
| 174 |
+
const msg = JSON.stringify({ type, ts: Date.now(), ...obj });
|
| 175 |
+
if (this.#ws?.readyState === WebSocket.OPEN) {
|
| 176 |
+
this.#ws.send(msg);
|
| 177 |
+
} else {
|
| 178 |
+
this.#queue.push(msg);
|
| 179 |
+
}
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
#flush() {
|
| 183 |
while (this.#queue.length && this.#ws?.readyState === WebSocket.OPEN) {
|
| 184 |
this.#ws.send(this.#queue.shift());
|
|
|
|
| 186 |
}
|
| 187 |
|
| 188 |
// ── Public emitters (all consumed by the website dashboard) ─────
|
| 189 |
+
step(name, detail) { if (CLOUD.platform !== 'docker') this.#send('agent.step', { name, detail }); }
|
| 190 |
+
token(delta, runId) { if (CLOUD.platform !== 'docker') this.#send('agent.token', { delta, runId }); }
|
| 191 |
+
result(runId, output) { if (CLOUD.platform !== 'docker') this.#send('agent.result', { runId, output }); }
|
| 192 |
+
log(level, message) { if (CLOUD.platform !== 'docker') this.#send('agent.log', { level, message }); }
|
| 193 |
+
|
| 194 |
+
// ── Docker platform protocol ────────────────────────────────────
|
| 195 |
+
|
| 196 |
+
/** Reply to a dashboard chat message (docker platform). */
|
| 197 |
+
chatResponse(requestId, message) {
|
| 198 |
+
this.#sendFlat('chat:response', { requestId, message });
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
/**
|
| 202 |
+
* Proxy an LLM call through the docker platform (request/response RPC).
|
| 203 |
+
* @returns {Promise<{content:string, usage?:object, model?:string, finishReason?:string}>}
|
| 204 |
+
*/
|
| 205 |
+
llmRequest({ provider = null, model = null, messages, temperature = 0.7, maxTokens = null }) {
|
| 206 |
+
const requestId = `req_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
| 207 |
+
return new Promise((resolve, reject) => {
|
| 208 |
+
const timeout = setTimeout(() => {
|
| 209 |
+
this.#llmPending.delete(requestId);
|
| 210 |
+
reject(new Error('LLM request timed out after 120s'));
|
| 211 |
+
}, 120_000);
|
| 212 |
+
this.#llmPending.set(requestId, { resolve, reject, timeout });
|
| 213 |
+
this.#sendFlat('llm:request', { requestId, provider, model, messages, temperature, maxTokens });
|
| 214 |
+
});
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
#resolveLlm(msg) {
|
| 218 |
+
const p = this.#llmPending.get(msg.requestId);
|
| 219 |
+
if (!p) return;
|
| 220 |
+
clearTimeout(p.timeout);
|
| 221 |
+
this.#llmPending.delete(msg.requestId);
|
| 222 |
+
if (msg.type === 'llm:error') p.reject(new Error(msg.error));
|
| 223 |
+
else p.resolve({ content: msg.content, usage: msg.usage, model: msg.model, finishReason: msg.finishReason });
|
| 224 |
+
}
|
| 225 |
|
| 226 |
/** Current connection state. */
|
| 227 |
get connected() {
|
|
|
|
| 253 |
uptimeSeconds: os.uptime(),
|
| 254 |
cpus: cpus.length,
|
| 255 |
};
|
| 256 |
+
if (CLOUD.platform === 'docker') {
|
| 257 |
+
// Docker dashboard shows live agent status from these broadcasts.
|
| 258 |
+
this.#sendFlat('status', { status: 'online', details: metrics });
|
| 259 |
+
} else {
|
| 260 |
+
this.#send('device.metrics', metrics);
|
| 261 |
+
}
|
| 262 |
this.emit('metrics', metrics);
|
| 263 |
}, this.#metricsIntervalMs);
|
| 264 |
}
|
|
|
|
| 275 |
this.#closing = true;
|
| 276 |
clearTimeout(this.#reconnectTimer);
|
| 277 |
this.#stopMetrics();
|
| 278 |
+
for (const [, p] of this.#llmPending) { clearTimeout(p.timeout); p.reject(new Error('closed')); }
|
| 279 |
+
this.#llmPending.clear();
|
| 280 |
if (this.#ws) {
|
| 281 |
this.#ws.removeAllListeners('close');
|
| 282 |
this.#ws.close(1000, 'agent shutdown');
|
test/docker-control.test.mjs
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Docker-platform protocol tests: flat register, chat mapping, llm:request RPC.
|
| 2 |
+
// Run: node --test test/docker-control.test.mjs
|
| 3 |
+
|
| 4 |
+
import { describe, it, before, after } from 'node:test';
|
| 5 |
+
import assert from 'node:assert/strict';
|
| 6 |
+
import { WebSocketServer } from 'ws';
|
| 7 |
+
|
| 8 |
+
// Start the fake platform first, then import ControlChannel with the env pointing at it.
|
| 9 |
+
const server = new WebSocketServer({ port: 0 });
|
| 10 |
+
const port = server.address().port;
|
| 11 |
+
process.env.MONA_CLOUD = `http://127.0.0.1:${port}`;
|
| 12 |
+
process.env.MONA_CLOUD_WS = `ws://127.0.0.1:${port}/ws`;
|
| 13 |
+
const { ControlChannel } = await import('../src/control.js');
|
| 14 |
+
|
| 15 |
+
const received = [];
|
| 16 |
+
const connections = [];
|
| 17 |
+
server.on('connection', (ws) => {
|
| 18 |
+
connections.push(ws);
|
| 19 |
+
ws.on('message', (raw) => {
|
| 20 |
+
const msg = JSON.parse(raw.toString());
|
| 21 |
+
received.push(msg);
|
| 22 |
+
if (msg.type === 'llm:request') {
|
| 23 |
+
if (msg.model === 'bad') {
|
| 24 |
+
ws.send(JSON.stringify({ type: 'llm:error', requestId: msg.requestId, error: 'no key for provider' }));
|
| 25 |
+
} else {
|
| 26 |
+
ws.send(JSON.stringify({
|
| 27 |
+
type: 'llm:response', requestId: msg.requestId,
|
| 28 |
+
content: 'hello from fake platform', usage: { inputTokens: 5, outputTokens: 3 },
|
| 29 |
+
}));
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
});
|
| 33 |
+
});
|
| 34 |
+
|
| 35 |
+
const waitFor = (pred, ms = 3000) => new Promise((resolve, reject) => {
|
| 36 |
+
const t0 = Date.now();
|
| 37 |
+
const iv = setInterval(() => {
|
| 38 |
+
const hit = pred();
|
| 39 |
+
if (hit) { clearInterval(iv); resolve(hit); }
|
| 40 |
+
else if (Date.now() - t0 > ms) { clearInterval(iv); reject(new Error('timeout waiting for condition')); }
|
| 41 |
+
}, 20);
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
describe('docker platform protocol', () => {
|
| 45 |
+
before(() => {});
|
| 46 |
+
after(() => server.close());
|
| 47 |
+
|
| 48 |
+
it('connects and sends a flat register message', async () => {
|
| 49 |
+
const ch = new ControlChannel('key', 'agent-1');
|
| 50 |
+
ch.on('error', () => {});
|
| 51 |
+
ch.connect();
|
| 52 |
+
const reg = await waitFor(() => received.find(m => m.type === 'register'));
|
| 53 |
+
assert.ok(reg);
|
| 54 |
+
assert.equal(reg.type, 'register');
|
| 55 |
+
assert.ok(reg.name);
|
| 56 |
+
assert.ok(reg.model.includes('mona-agent'));
|
| 57 |
+
ch.close();
|
| 58 |
+
});
|
| 59 |
+
|
| 60 |
+
it('proxies llm:request and resolves llm:response', async () => {
|
| 61 |
+
const ch = new ControlChannel('key', 'agent-1');
|
| 62 |
+
ch.on('error', () => {});
|
| 63 |
+
ch.connect();
|
| 64 |
+
const p = ch.llmRequest({ messages: [{ role: 'user', content: 'hi' }] });
|
| 65 |
+
const res = await Promise.race([
|
| 66 |
+
p,
|
| 67 |
+
new Promise((_, reject) => setTimeout(() => reject(new Error('no llm response')), 3000)),
|
| 68 |
+
]);
|
| 69 |
+
assert.equal(res.content, 'hello from fake platform');
|
| 70 |
+
assert.deepEqual(res.usage, { inputTokens: 5, outputTokens: 3 });
|
| 71 |
+
ch.close();
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
it('rejects when the platform answers llm:error', async () => {
|
| 75 |
+
const ch = new ControlChannel('key', 'agent-1');
|
| 76 |
+
ch.on('error', () => {});
|
| 77 |
+
ch.connect();
|
| 78 |
+
await assert.rejects(
|
| 79 |
+
ch.llmRequest({ model: 'bad', messages: [] }),
|
| 80 |
+
/no key for provider/
|
| 81 |
+
);
|
| 82 |
+
ch.close();
|
| 83 |
+
});
|
| 84 |
+
|
| 85 |
+
it('maps inbound chat messages to run commands', async () => {
|
| 86 |
+
const ch = new ControlChannel('key', 'agent-1');
|
| 87 |
+
ch.on('error', () => {});
|
| 88 |
+
const cmd = new Promise((resolve) => ch.on('command', resolve));
|
| 89 |
+
ch.connect();
|
| 90 |
+
// Wait for the connection to be open before pushing a chat message.
|
| 91 |
+
await waitFor(() => ch.connected);
|
| 92 |
+
connections.at(-1).send(JSON.stringify({ type: 'chat', requestId: 'req_42', message: 'do the thing' }));
|
| 93 |
+
const m = await Promise.race([cmd, new Promise((_, reject) => setTimeout(() => reject(new Error('no command')), 3000))]);
|
| 94 |
+
assert.equal(m.action, 'run');
|
| 95 |
+
assert.equal(m.runId, 'req_42');
|
| 96 |
+
assert.equal(m.payload.task, 'do the thing');
|
| 97 |
+
ch.close();
|
| 98 |
+
});
|
| 99 |
+
});
|